blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
05d715abff41adc3596e2562f61612eeab2c0272
|
Swift
|
jmgawecki/QuickTweetsApp
|
/TwitterApp/TwitterApp/Custom Views/View Controllers/TweetAlertVC.swift
|
UTF-8
| 3,543
| 2.65625
| 3
|
[] |
no_license
|
//
// TweetAlertVC.swift
// TwitterApp
//
// Created by Jakub Gawecki on 24/01/2021.
//
import UIKit
final class TweetAlertVC: UIViewController {
//MARK: - Declarations
let containerView = AlertContainerView()
let titleLabel = TwitInfoHeaderTitleLabel()
let messageLabel = TwitInfoHeaderBodyLabel(textAlignment: .center)
let actionButton = TwitButton(backgroundColor: ColorsTwitter.twitterBlue, fontSize: 15, message: "Ok")
var alertTitle: String?
var message: String?
var buttonTitle: String?
let padding: CGFloat = 20
//MARK: - Initialisers
init(title: String, message: String, buttonTitle: String) {
super.init(nibName: nil, bundle: nil)
self.alertTitle = title
self.message = message
self.buttonTitle = buttonTitle
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
layoutUI()
configureUIElements()
}
//MARK: - Objectives
@objc func dismissVC() { dismiss(animated: true) }
//MARK: - Layout configurations
private func configureUIElements() {
view.backgroundColor = UIColor.black.withAlphaComponent(0.75)
titleLabel.text = alertTitle ?? "Something went wrong"
messageLabel.text = message ?? "Unable to complete request"
messageLabel.numberOfLines = 4
actionButton.setTitle(buttonTitle ?? "Ok", for: .normal)
actionButton.addTarget(self, action: #selector(dismissVC), for: .touchUpInside)
}
private func layoutUI() {
view.addSubviews(containerView, titleLabel, actionButton, messageLabel)
NSLayoutConstraint.activate([
containerView.centerYAnchor.constraint (equalTo: view.centerYAnchor),
containerView.centerXAnchor.constraint (equalTo: view.centerXAnchor),
containerView.widthAnchor.constraint (equalToConstant: 280),
containerView.heightAnchor.constraint (equalToConstant: 220),
titleLabel.topAnchor.constraint (equalTo: containerView.topAnchor, constant: padding),
titleLabel.leadingAnchor.constraint (equalTo: containerView.leadingAnchor, constant: padding),
titleLabel.trailingAnchor.constraint (equalTo: containerView.trailingAnchor, constant: -padding),
titleLabel.heightAnchor.constraint (equalToConstant: 28),
actionButton.bottomAnchor.constraint (equalTo: containerView.bottomAnchor, constant: -padding),
actionButton.leadingAnchor.constraint (equalTo: containerView.leadingAnchor, constant: padding),
actionButton.trailingAnchor.constraint (equalTo: containerView.trailingAnchor, constant: -padding),
actionButton.heightAnchor.constraint (equalToConstant: 44),
messageLabel.topAnchor.constraint (equalTo: titleLabel.bottomAnchor, constant: 8),
messageLabel.leadingAnchor.constraint (equalTo: containerView.leadingAnchor, constant: padding),
messageLabel.trailingAnchor.constraint (equalTo: containerView.trailingAnchor, constant: -padding),
messageLabel.bottomAnchor.constraint (equalTo: actionButton.topAnchor, constant: -12)
])
}
}
| true
|
0288baa3290f9a5652ca21690d01950a40a99045
|
Swift
|
TOBI-AB/TMDBAPISwiftUI
|
/TMDBAPI/UIKit components/TextView.swift
|
UTF-8
| 673
| 2.78125
| 3
|
[] |
no_license
|
//
// TextView.swift
// TMDBAPI
//
// Created by Ghaff Ett on 04/10/2019.
// Copyright © 2019 GhaffMac. All rights reserved.
//
import SwiftUI
struct TextView: UIViewRepresentable {
typealias UIViewType = UITextView
let text: String
func makeUIView(context: UIViewRepresentableContext<TextView>) -> UITextView {
let textView = UITextView(frame: .zero)
return textView
}
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<TextView>) {
uiView.isEditable = false
let attributes = detectData(in: self.text)
uiView.attributedText = attributes
}
}
| true
|
2673540bd11d09e90fe8fb8809b75feb7ba5e85b
|
Swift
|
Neelpatel2112/baseproject
|
/BaseApp/View/TryAgainPopup/TryAgainPopupViewController.swift
|
UTF-8
| 1,787
| 2.671875
| 3
|
[] |
no_license
|
//
// TryAgainPopupViewController.swift
// Dilango-Rider
//
// Created by iMac on 06/04/21.
// Copyright © 2021 PC. All rights reserved.
//
import UIKit
protocol tryAgainTapProtocol:AnyObject {
func popupTryAgainClick()
func closePopupClick()
}
class TryAgainPopupViewController: UIViewController {
@IBOutlet weak var viewTitle: UIView!
@IBOutlet weak var viewPopup: UIView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var btnTryAgain: UIButton!
@IBOutlet weak var lblMessage: UILabel!
@IBOutlet weak var btnClose: UIButton!
var popupTitle: String?
var message:String?
weak var delegate:tryAgainTapProtocol?
override func viewDidLoad() {
super.viewDidLoad()
SetupUI()
setupData()
}
private func setupData() {
lblTitle.text = popupTitle
lblMessage.text = message
}
private func SetupUI() {
viewTitle.setGradientBackground(topColor: UIColor.APP_GradiantDarkBlue, bottomColor: UIColor.App_GradientLightBlue)
lblTitle.font = UIFont.Body_Bold
lblMessage.font = UIFont.Body_2
lblTitle.textColor = .white
lblMessage.textColor = .black
btnTryAgain.setTitle(ButtonTitle.tryAgain.rawValue, for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
viewPopup.cornerRadius = viewPopup.frame.width * 0.05
viewPopup.clipsToBounds = true
btnTryAgain.circleCorner = true
}
@IBAction func btnClickClose(_ sender: UIButton) {
delegate?.closePopupClick()
self.dismiss(animated: false, completion: nil)
}
@IBAction func btnClickTryAgain(_ sender: UIButton) {
delegate?.popupTryAgainClick()
dismiss(animated: false, completion: nil)
}
}
| true
|
c2cda59f67378ab31b22d20c45f1650622f3eb61
|
Swift
|
ddianella/100-days-of-SwiftUI
|
/Project 9. Drawing/Drawing/Blend modes .swift
|
UTF-8
| 563
| 3.109375
| 3
|
[] |
no_license
|
//
// Blend modes .swift
// Drawing
//
// Created by Prince$$ Di on 08.04.2021.
//
import SwiftUI
struct Blend_modes_: View {
var body: some View {
ZStack {
Image("Diana")
Rectangle()
.fill(Color.purple)
.blendMode(.screen)
}
.frame(width: 400, height: 500)
.clipped()
// Image("Diana")
// .colorMultiply(.purple)
}
}
struct Blend_modes__Previews: PreviewProvider {
static var previews: some View {
Blend_modes_()
}
}
| true
|
122a6fd258365de35418455c2810d6294e05845e
|
Swift
|
Nhong/KFC
|
/KFC/Services/Promotion/PromotionAPIManager.swift
|
UTF-8
| 1,320
| 2.875
| 3
|
[] |
no_license
|
//
// PromotionAPIManager.swift
// KFC
//
// Created by Kittinun Chobtham on 18/4/2563 BE.
// Copyright © 2563 Kittinun Chobtham. All rights reserved.
//
import Foundation
protocol PromotionAPIManager {
func getCurrentPromotion()
func setPromotionAPIManagerDelegate(_ delegate: PromotionAPIManagerDelegate)
}
protocol PromotionAPIManagerDelegate {
func didGetPromotionCompletion(promotion: Promotion)
func didGetPromotionFailure(error: Error)
}
final class PromotionAPIManagerImplementation: PromotionAPIManager {
let apiClient: PromotionAPIClient
var delegate: PromotionAPIManagerDelegate?
init(apiClient: PromotionAPIClient = PromotionAPIClientImplementation()) {
self.apiClient = apiClient
}
func setPromotionAPIManagerDelegate(_ delegate: PromotionAPIManagerDelegate) {
self.delegate = delegate
}
func getCurrentPromotion() {
apiClient.getCurrentPromotion { (optionalPromotion, optionalError) in
if let error = optionalError {
self.delegate?.didGetPromotionFailure(error: error)
return
}
if let promotion = optionalPromotion {
self.delegate?.didGetPromotionCompletion(promotion: promotion)
}
}
}
}
| true
|
12cfc5859e1e7fa1907ec9a697a42d958520bbd0
|
Swift
|
vikashideveloper/PushNotification_customUIDemo
|
/NotificationContentEx/NotificationViewController.swift
|
UTF-8
| 2,014
| 2.59375
| 3
|
[] |
no_license
|
//
// NotificationViewController.swift
// NotificationContentEx
//
// Created by Vikash Kumar on 04/04/17.
// Copyright © 2017 Vikash Kumar. All rights reserved.
//
import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var label: UILabel?
@IBOutlet var lbl2: UILabel?
@IBOutlet var lbl3: UILabel?
@IBOutlet var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
print("NotificationController")
}
func didReceive(_ notification: UNNotification) {
let userinfo = notification.request.content.userInfo
self.label?.text = notification.request.content.body
self.lbl2?.text = userinfo["detail"] as? String
self.lbl3?.text = userinfo["address"] as? String
if let attachment = notification.request.content.attachments.first {
if attachment.url.startAccessingSecurityScopedResource() {
print(attachment.url.path)
let image = UIImage(contentsOfFile: attachment.url.path)
image?.imageFlippedForRightToLeftLayoutDirection()
self.imgView.image = image
print("notificaiton received")
attachment.url.stopAccessingSecurityScopedResource()
}
}
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "accept" {
completion(.dismissAndForwardAction)
} else if response.actionIdentifier == "invitationReply" {
if let textResponse = response as? UNTextInputNotificationResponse {
lbl3?.text = textResponse.userText
}
} else {
completion(.dismiss)
}
}
}
| true
|
d15bacc7b6fcaee154415b91be2ace9d714163ae
|
Swift
|
KKANG00/Watpago
|
/Watpago WatchKit Extension/Model/defaultLanguages.swift
|
UTF-8
| 496
| 2.71875
| 3
|
[] |
no_license
|
//
// defaultLanguages.swift
// Watpago WatchKit Extension
//
// Created by KKANG on 2021/07/27.
//
import Foundation
struct defaultLanguages {
static let Languages = [("English", "en", "en-US"), ("French", "fr", "fr-FR"), ("Chinese", "zh-CN", "zh-CN"), ("Russian", "ru", "ru-RU"),
("Thai", "th", "th-TH"), ("Indonesian", "id", "id-ID"), ("German", "de", "de-DE"), ("Italian", "it", "it-IT")]
.sorted(by: { return $0.0 < $1.0 })
}
| true
|
c95fa49b8fd4dbd8d1da68b15eb82a3645a8659a
|
Swift
|
galbernator/SportsNews
|
/SportsNews/Protocols/Headlineable.swift
|
UTF-8
| 227
| 2.546875
| 3
|
[] |
no_license
|
//
// SportResult.swift
// SportsNews
//
// Created by Steve Galbraith on 11/13/20.
//
import Foundation
protocol Headlineable {
var publicationDate: Date { get }
var headline: String { get }
var sport: Sport { get }
}
| true
|
b4d97983f55f6d05525702eff4c424de834048b2
|
Swift
|
uny/Longing
|
/Longing/Models/Keyword.swift
|
UTF-8
| 1,936
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
//
// Keyword.swift
// Longing
//
// Created by Yuki Nagai on 10/18/14.
// Copyright (c) 2014 Yuki Nagai. All rights reserved.
//
import Foundation
let keywordsKey = "keywords"
let keywordsMax = 6
class Keyword {
class func lettersMax() -> Int {
return 10
}
class func count() -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults()
if let keywords = userDefaults.arrayForKey(keywordsKey) {
return keywords.count
}
return 0
}
class func isFull() -> Bool {
return keywordsMax <= count()
}
class func all() -> [String] {
let userDefaults = NSUserDefaults.standardUserDefaults()
var keywords = userDefaults.arrayForKey(keywordsKey)
if keywords == nil {
keywords = [String]()
}
return keywords as [String]
}
class func intersect(target: [String]) -> [String] {
var result = [String]()
let source = Keyword.all()
for a in source {
for b in target {
if a == b && !contains(result, a) {
result.append(a)
}
}
}
return result
}
class func add(text: String) {
let trimmed = text.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
if trimmed == "" {
return
}
var keywords = all()
keywords.append(trimmed as NSString)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(keywords, forKey: keywordsKey)
userDefaults.synchronize()
}
class func removeAt(index : Int) {
var keywords = all()
keywords.removeAtIndex(index)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(keywords, forKey: keywordsKey)
userDefaults.synchronize()
}
}
| true
|
95f66ee8c836a4febb764105a202ec63a81049cd
|
Swift
|
PabloRb2X/CVChallegeG
|
/CVChallenge/Utils/CustomView.swift
|
UTF-8
| 1,340
| 2.71875
| 3
|
[] |
no_license
|
//
// RoundableView.swift
// CVChallenge
//
// Created by Pablo Ramirez on 7/14/19.
// Copyright © 2019 Pablo Ramirez. All rights reserved.
//
import UIKit
@IBDesignable
class CustomView: UIView {
@IBInspectable var cornerRadius : CGFloat = 0.0{
didSet{
self.applyCornerRadius()
}
}
@IBInspectable var shadowColor : UIColor = UIColor.clear{
didSet{
self.applyCornerRadius()
}
}
@IBInspectable var shadowOpacity : Float = 0.0{
didSet{
self.applyCornerRadius()
}
}
@IBInspectable var shadowOffset : CGSize = .zero{
didSet{
self.applyCornerRadius()
}
}
@IBInspectable var shadowRadius : CGFloat = 0.0{
didSet{
self.applyCornerRadius()
}
}
func applyCornerRadius()
{
self.layer.cornerRadius = cornerRadius
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowOffset = shadowOffset
self.layer.shadowRadius = shadowRadius
}
override func awakeFromNib() {
super.awakeFromNib()
self.applyCornerRadius()
}
override func layoutSubviews() {
super.layoutSubviews()
applyCornerRadius()
}
}
| true
|
8aa7d002b6449a97932acb6caf22ba0cf9bc9a7d
|
Swift
|
ejjonny/alpacka
|
/Sources/Alpacka/CGExtensions/Point+CGPoint.swift
|
UTF-8
| 388
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
//
//
// Created by Ethan John on 11/29/20.
//
#if os(macOS)
import AppKit
#elseif os(iOS)
import UIKit
#endif
extension Alpacka.Point {
init(_ point: CGPoint) {
x = Double(point.x)
y = Double(point.y)
}
}
extension CGPoint: OriginConvertible {
public init(_ point: Alpacka.Point) {
self.init(x: point.x, y: point.y)
}
}
| true
|
27e0798a0a19b872bf5918ef47b8f72a102036e3
|
Swift
|
paveliOS/Contacts
|
/Contacts/contact/ContactViewData.swift
|
UTF-8
| 1,091
| 2.78125
| 3
|
[] |
no_license
|
struct ContactViewData {
let firstName: String
let lastName: String
let phoneNumber: String?
let streetAddress1: String?
let streetAddress2: String?
let city: String?
let state: String?
let zipCode: String?
init(firstName: String, lastName: String, phoneNumber: String?, streetAddress1: String?, streetAddress2: String?, city: String?, state: String?, zipCode: String?) {
self.firstName = firstName
self.lastName = lastName
self.phoneNumber = phoneNumber
self.streetAddress1 = streetAddress1
self.streetAddress2 = streetAddress2
self.city = city
self.state = state
self.zipCode = zipCode
}
init(contact: Contact) {
self.firstName = contact.firstName
self.lastName = contact.lastName
self.phoneNumber = contact.phoneNumber
self.streetAddress1 = contact.streetAddress1
self.streetAddress2 = contact.streetAddress2
self.city = contact.city
self.state = contact.state
self.zipCode = contact.zipCode
}
}
| true
|
65da14a4b0edc7ac47f8f47c70a596676b343876
|
Swift
|
weiran/Hackers
|
/App/Services/NavigationService.swift
|
UTF-8
| 900
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// NavigationService.swift
// Hackers
//
// Created by Weiran Zhang on 06/06/2020.
// Copyright © 2020 Weiran Zhang. All rights reserved.
//
import UIKit
class NavigationService {
weak var mainSplitViewController: MainSplitViewController?
func showPost(id: Int) {
if let splitViewController = mainSplitViewController,
let navController = viewController(for: "PostViewNavigationController") as? UINavigationController,
let controller = navController.children.first as? CommentsViewController {
controller.postId = id
splitViewController.showDetailViewController(navController, sender: self)
}
}
private func viewController(for identifier: String) -> UIViewController? {
let storyboard = UIStoryboard(name: "Main", bundle: .main)
return storyboard.instantiateViewController(identifier: identifier)
}
}
| true
|
c288aae3229fee10b645af0edc2a47e8b36911da
|
Swift
|
JasonChene/PLApp
|
/pianoLearningApp/BookCardView.swift
|
UTF-8
| 1,425
| 2.8125
| 3
|
[] |
no_license
|
//
// BookCardView.swift
// pianoLearningApp
//
// Created by 黃恩祐 on 2018/10/22.
// Copyright © 2018年 ENYUHUANG. All rights reserved.
//
import UIKit
@IBDesignable
class BookCardView: UIView {
@IBOutlet var view: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var title: UILabel!
@IBInspectable var image: UIImage?
@IBInspectable var name: String?
override func draw(_ rect: CGRect) {
super.draw(rect)
imageView.contentMode = .scaleAspectFit
imageView.image = image
title.text = name
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
fatalError("init(coder:) has not been implemented")
}
func setup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth,
UIViewAutoresizing.flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
| true
|
e4a387a68be2d2581db17b7868c57b97aa1af24c
|
Swift
|
fpg1503/ComeHome
|
/GGJ19/Map.swift
|
UTF-8
| 9,781
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import AVFoundation
import UIKit
struct Point: Hashable {
let x: Int
let y: Int
init?(x: Int, y: Int) {
guard x >= 0 && y >= 0 else { return nil }
self.x = x
self.y = y
}
func distance(to otherPoint: Point) -> Double {
let xDist = self.x - otherPoint.x
let yDist = self.y - otherPoint.y
return sqrt(Double((xDist * xDist) + (yDist * yDist)))
}
}
struct Sound: Hashable {
let name: String
}
struct AudioSource {
let origin: Point
let sound: Sound
var player: AVAudioPlayer {
guard let player = ViewController.audioSourcePlayers[sound] else {
let url = URL(string: Bundle.main.path(forResource: sound.name, ofType: "aac")!)!
let newPlayer = try! AVAudioPlayer(contentsOf: url)
ViewController.audioSourcePlayers[sound] = newPlayer
return newPlayer
}
return player
}
}
struct Map {
let height: UInt
let width: UInt
let warning: [Point]
let path: [Point]
let destination: Point
let startPoint: Point
func isValid(point: Point) -> Bool {
return point.x < width &&
point.y < height &&
(warning.contains(point) ||
path.contains(point) ||
startPoint == point ||
destination == point)
}
static func from(grid: Grid) -> Map {
let string = grid.toString()
var warnings: [Point] = []
var path: [Point] = []
var destination: Point!
var startPoint: Point!
let lines = string.components(separatedBy: .newlines).filter { !$0.isEmpty }
for (y, line) in lines.enumerated() {
for (x, character) in line.enumerated() {
let point = Point(x: x, y: y)!
switch String(character) {
case "X": warnings.append(point)
case "L": path.append(point)
case "S": startPoint = point
case "G": destination = point
default: continue
}
}
}
let width = UInt(lines[0].count)
let height = UInt(lines.count)
return Map(height: height,
width: width,
warning: warnings,
path: path,
destination: destination,
startPoint: startPoint)
}
var initialState: State {
return State(map: self,
currentLocation: startPoint,
audioSources: [AudioSource(origin: destination, sound: Sound(name: "goodboy"))], heading: .up)
}
}
struct State {
let map: Map
let currentLocation: Point
let audioSources: [AudioSource]
let heading: Direction
}
enum Direction {
case up, down, left, right
var opposite: Direction {
return self + .down
}
}
func + (lhs: Point, rhs: Direction) -> Point? {
switch rhs {
case .up:
return Point(x: lhs.x, y: lhs.y - 1)
case .down:
return Point(x: lhs.x, y: lhs.y + 1)
case .left:
return Point(x: lhs.x - 1, y: lhs.y)
case .right:
return Point(x: lhs.x + 1, y: lhs.y)
}
}
func + (lhs: Direction, rhs: Direction) -> Direction {
switch rhs {
case .up: return lhs
case .down:
switch lhs {
case .up: return .down
case .down: return .up
case .left: return .right
case .right: return .left
}
case .left:
switch lhs {
case .up: return .left
case .down: return .right
case .left: return .down
case .right: return .up
}
case .right:
switch lhs {
case .up: return .right
case .down: return .left
case .left: return .up
case .right: return .down
}
}
}
func walk(direction: Direction, state: State) -> State {
// Walking is rotating and moving to the new forward
// Set new heading
let newHeading = direction == .down ? state.heading : state.heading + direction
// Translate desired movement to north-heading
// If left or right, just rotate heading!
guard direction == .up || direction == .down else {
AudioPlayer.sharedInstance.rotate()
let newState = State(map: state.map,
currentLocation: state.currentLocation,
audioSources: state.audioSources,
heading: newHeading)
loopWarning(newState, state.currentLocation, rotating: true)
return newState
}
let translatedDirection = direction == .down ? newHeading.opposite : newHeading
guard let newPoint = state.currentLocation + translatedDirection,
state.map.isValid(point: newPoint) else {
alert()
//Back to home
ViewController.warning.pause()
return State(map: state.map,
currentLocation: state.map.startPoint,
audioSources: state.audioSources,
heading: .up)
}
if state.map.destination == newPoint { yes() }
loopWarning(state, newPoint, rotating: false)
AudioPlayer.sharedInstance.walk()
return State(map: state.map,
currentLocation: newPoint,
audioSources: state.audioSources,
heading: newHeading)
}
func pan(for state: State, audioSource: AudioSource) -> Float {
let audioX = audioSource.origin.x
let myX = state.currentLocation.x
if myX == audioX {
return 0
} else if myX < audioX {
// Left
let maximumLeftDistance = audioX
let myDistance = audioX - myX
let myRelativeDistance = Float(myDistance) / Float(maximumLeftDistance)
return myRelativeDistance
} else {
// Right
let maximumRightDistance = Int(state.map.width) - audioX
let myDistance = myX - audioX
let myRelativeDistance = Float(myDistance) / Float(maximumRightDistance)
return myRelativeDistance
}
}
func volume(for state: State, audioSource: AudioSource) -> Float {
let maxDistanceToListen: Float = 5
let myDistance = audioSource.origin.distance(to: state.currentLocation)
let relativeAudio = max(0, (maxDistanceToListen - Float(myDistance)) / maxDistanceToListen)
return relativeAudio
}
func loopWarning(_ state: State, _ newPoint: Point, rotating: Bool) {
// Count dogs!
let upIsDog = Point(x: newPoint.x, y: newPoint.y - 1).map { !state.map.isValid(point: $0) } ?? true
let downIsDog = Point(x: newPoint.x, y: newPoint.y + 1).map { !state.map.isValid(point: $0) } ?? true
let leftIsDog = Point(x: newPoint.x - 1, y: newPoint.y).map { !state.map.isValid(point: $0) } ?? true
let rightIsDog = Point(x: newPoint.x + 1, y: newPoint.y).map { !state.map.isValid(point: $0) } ?? true
let dogCount = [upIsDog, downIsDog, leftIsDog, rightIsDog].map { $0 ? 1 : 0 }.reduce(0, +)
ViewController.sharedInstance.dogCount = dogCount
let volume = dogCount == 0 ? 0 : 0.25 + (Float(dogCount) * 0.25)
// Balance
// Convert directions to player heading!
let myLeftIsDog: Bool
let myRightIsDog: Bool
switch state.heading {
case .up:
myLeftIsDog = leftIsDog
myRightIsDog = rightIsDog
case .down:
myLeftIsDog = rightIsDog
myRightIsDog = leftIsDog
case .left:
myLeftIsDog = downIsDog
myRightIsDog = upIsDog
case .right:
myLeftIsDog = upIsDog
myRightIsDog = downIsDog
}
let pan: Float
switch (myLeftIsDog, myRightIsDog) {
case (false, false): pan = 0
case (false, true): pan = 0.75
case (true, false): pan = -0.75
case (true, true): pan = 0
}
vibrate(dogCount, rotating)
print("Dogs: \(dogCount) - Volume: \(volume) - Pan: \(pan) L: \(myLeftIsDog ? "T" : "F") R: \(myRightIsDog ? "T" : "F")")
if !ViewController.warning.isPlaying {
ViewController.warning.currentTime = 0
ViewController.warning.play()
}
ViewController.warning.pan = pan
if !ViewController.warning2.isPlaying {
ViewController.warning2.currentTime = 0
ViewController.warning2.play()
}
ViewController.warning2.pan = pan
if volume > 0 {
ViewController.warning.setVolume(volume, fadeDuration: 0.2)
ViewController.warning2.setVolume(volume, fadeDuration: 0.2)
} else {
ViewController.warning.volume = 0
ViewController.warning2.volume = 0
}
}
func vibrate(_ dogs: Int, _ rotating: Bool) {
guard dogs > 0, !rotating else { return }
if (UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0) >= 2 {
switch dogs {
case 1: AudioServicesPlaySystemSound(1519)
case 2: AudioServicesPlaySystemSound(1520)
case 3: AudioServicesPlaySystemSound(1521)
default: break
}
} else {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
}
func alert() {
ViewController.always.setVolume(0, fadeDuration: 3)
let url = URL(string: Bundle.main.path(forResource: "death", ofType: "aac")!)!
let player = try! AVAudioPlayer(contentsOf: url)
ViewController.players.append(player)
player.play()
ViewController.sharedInstance.performSegue(withIdentifier: "lose", sender: nil)
}
func yes() {
ViewController.always.setVolume(0, fadeDuration: 3)
let url = URL(string: Bundle.main.path(forResource: "goodboy", ofType: "aac")!)!
let player = try! AVAudioPlayer(contentsOf: url)
ViewController.players.append(player)
player.play()
ViewController.sharedInstance.performSegue(withIdentifier: "win", sender: nil)
}
| true
|
1e2a2627071db97f69952d793ff043fc2647c767
|
Swift
|
CISTeamTeam/frontend
|
/Frontend/Activities/Comments/Views/CommentList.swift
|
UTF-8
| 885
| 3.109375
| 3
|
[] |
no_license
|
//
// CommentList.swift
// Frontend
//
import SwiftUI
/// A view that shows all of the comments on a post
struct CommentList: View {
/// The ID of the post
let postID: ID
/// The IDs of the comments on the post
let commentIDs: [ID]
/// The contents of the view
var body: some View {
ScrollView {
LazyVStack {
ForEach(commentIDs, id: \.self) { commentID in
CommentView(commentID: commentID)
.padding(.vertical, 5)
}
}
}
.overlay(
NewComment(postID: postID)
.alignedVertically(to: .bottom)
)
}
}
struct CommentList_Previews: PreviewProvider {
static var previews: some View {
CommentList(postID: Placeholders.aPost.id, commentIDs: Placeholders.comments.map(\.id))
}
}
| true
|
49e48fc4d8e5fa8123c9bd0b66c4fd9b4b2dcd71
|
Swift
|
HVHMobileDeveloper/MVVM
|
/MVVM/ViewModel/UserModel.swift
|
UTF-8
| 811
| 2.84375
| 3
|
[] |
no_license
|
//
// UserModel.swift
// MVVM
//
// Created by mobileteam on 2/18/20.
// Copyright © 2020 mobileteam. All rights reserved.
//
import Foundation
class UserModel {
var userName : String!
var id : Int!
init() {
self.userName = ""
self.id = 0
}
init(object : Any) {
if let dic : Dictionary<String ,Any> = object as? Dictionary<String, Any> {
if let userName = dic["login"] as? String {
self.userName = userName
}else{
self.userName = ""
}
if let id = dic["id"] as? Int {
self.id = id
}else{
self.id = 0
}
}else{
self.userName = ""
self.id = 0
}
}
}
| true
|
19e9483ee2440b744704816b1153d52b40010086
|
Swift
|
kuanh/AllDemo
|
/TongKetTatCaCacBai/Demo/TonghopBa/TonghopBa/Mydata.swift
|
UTF-8
| 2,107
| 3.125
| 3
|
[] |
no_license
|
//
// Mydata.swift
// TonghopBa
//
// Created by KuAnh on 25/10/2017.
// Copyright © 2017 KuAnh. All rights reserved.
//
import UIKit
class MyData1: NSObject, UITableViewDelegate, UITableViewDataSource {
var number = [Int](0...10)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.separatorStyle = .none
return number.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "123", for: indexPath)
cell.textLabel?.text = "\(number[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
class MyData2: NSObject, UITableViewDelegate, UITableViewDataSource {
var textString: [String] = ["Hai","Ba"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.separatorStyle = .none
return textString.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "123", for: indexPath)
cell.textLabel?.text = textString[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
| true
|
0916543e4da6a855ba6f4a1fc3060b48c9876cc3
|
Swift
|
sbooker/Nifty
|
/Sources/rmap.swift
|
UTF-8
| 2,645
| 3.125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* rmap.swift
*
* This file provides functionality for remapping a number to a new range.
*
* Author: Philip Erickson
* Creation Date: 1 May 2016
* Contributors:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2016 Philip Erickson
******************************************************************************/
/// Maps a number linearly from one range to another.
///
/// - Parameters:
/// - x: number to map
/// - from: original range
/// - to: target range
/// - Returns: re-mapped number
func rmap(_ x: Double, from: Range<Int>, to: Range<Int>) -> Double
{
let fromLow = Double(from.lowerBound)
let fromHigh = Double(from.upperBound-1)
let toLow = Double(to.lowerBound)
let toHigh = Double(to.upperBound-1)
return rmap(x, l: fromLow, h: fromHigh, tl: toLow, th: toHigh)
}
// TODO: should overloads get a comment header?
// Check out how doc tool (e.g. jazzy) handles this
func rmap(_ x: Int, from: Range<Int>, to: Range<Int>) -> Double
{
// FIXME: check whether this upperBound-1 makes sense (hold over from Swift 2.2)
let fromLow = Double(from.lowerBound)
let fromHigh = Double(from.upperBound-1)
let toLow = Double(to.lowerBound)
let toHigh = Double(to.upperBound-1)
return rmap(Double(x), l: fromLow, h: fromHigh, tl: toLow, th: toHigh)
}
func rmap(_ x: Double, from: ClosedRange<Double>,
to: ClosedRange<Double>) -> Double
{
let fromLow = from.lowerBound
let fromHigh = from.upperBound
let toLow = to.lowerBound
let toHigh = to.upperBound
return rmap(x, l: fromLow, h: fromHigh, tl: toLow, th: toHigh)
}
func rmap(_ x: Int, from: ClosedRange<Double>,
to: ClosedRange<Double>) -> Double
{
let fromLow = from.lowerBound
let fromHigh = from.upperBound
let toLow = to.lowerBound
let toHigh = to.upperBound
return rmap(Double(x), l: fromLow, h: fromHigh, tl: toLow, th: toHigh)
}
private func rmap(_ x: Double, l: Double, h: Double, tl: Double,
th: Double) -> Double
{
return (x-l) * (th-tl)/(h-l) + tl
}
| true
|
2153224927b25ce29ed249eacbdd28a9a417840a
|
Swift
|
etwmc/DataCruncher
|
/Cruncher Studio/CruncherPortTableViewCell.swift
|
UTF-8
| 1,494
| 2.96875
| 3
|
[] |
no_license
|
//
// CruncherPortTableViewCell.swift
// Data Crunchers
//
// Created by Wai Man Chan on 11/3/15.
//
//
import UIKit
enum CCPortConnectionState {
case NotConnected
case Connecting
case Connected
}
class Port {
var name: String = ""
var connection: CCPortConnectionState = CCPortConnectionState.Connected
}
class InputPort: Port {}
class OutputPort: Port {}
class CruncherPortTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(port: Port) {
let image: UIImage
switch (port.connection) {
case .Connected:
image = UIImage(named: "ConnectedIndicator")!
break
case .Connecting:
image = UIImage(named: "ConnectingIndicator")!
break
case .NotConnected:
image = UIImage(named: "EmptyIndicator")!
break
}
if let _ = port as? InputPort {
self.imageView?.image = image
} else {
self.accessoryView = UIImageView(image: image)
self.accessoryView?.frame = CGRectMake(0, 0, self.frame.size.height, self.frame.size.height)
}
self.layer.borderWidth = 1;
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public var port: Port?
}
| true
|
8f3ba5dea6ef90971fc6ea4028b584a81b5325e7
|
Swift
|
ProjectsHTinc/HSTiOS6
|
/OPS/Presenter/LikeandSharePresenter.swift
|
UTF-8
| 1,412
| 2.5625
| 3
|
[] |
no_license
|
//
// LikeandSharePresenter.swift
// OPS
//
// Created by Apple on 30/11/20.
//
import UIKit
struct LikeandShareData {
let msg: String
let status: String
}
protocol LikeandShareView : NSObjectProtocol {
func startLoading()
func finishLoading()
func setValue(msg:String,status:String)
func setEmpty(errorMessage:String)
}
class LikeandSharePresenter: NSObject {
private let likeandShareService:LikeandShareService
weak private var likeandShareView : LikeandShareView?
init(likeandShareService:LikeandShareService) {
self.likeandShareService = likeandShareService
}
func attachView(view:LikeandShareView) {
likeandShareView = view
}
func detachViewClientUrl() {
likeandShareView = nil
}
func getRespLikeandShare(from:String,user_id:String,newsfeed_id:String) {
self.likeandShareView?.startLoading()
likeandShareService.callAPILikeAndShare(
from:from,user_id:user_id,newsfeed_id:newsfeed_id, onSuccess: { (resp) in
self.likeandShareView?.setValue(msg: resp.msg!, status: resp.status!)
self.likeandShareView?.finishLoading()
},
onFailure: { (errorMessage) in
self.likeandShareView?.setEmpty(errorMessage: errorMessage)
self.likeandShareView?.finishLoading()
}
)
}
}
| true
|
bcf0c7009b4448536b9da9c04034bd7846b5d604
|
Swift
|
PPTaa/swift_study
|
/StartSwiftUI/ContentView.swift
|
UTF-8
| 1,743
| 3.265625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// StartSwiftUI
//
// Created by 맥북에어 on 2020/12/02.
//
import SwiftUI
struct ContentView: View {
@State // 값의 변화를 감지 -> 처음부터 view애 적용
private var isActivate: Bool = false
// body
var body: some View {
NavigationView{
VStack {
HStack {
MyVstackView(isActivated: $isActivate)
MyVstackView(isActivated: $isActivate)
MyVstackView(isActivated: $isActivate)
}// Hstack
.padding(isActivate ? 50.0 : 10.0)
//
.background(isActivate ? Color.yellow: Color.blue)
// 탭 제스쳐 추가
.onTapGesture {
print("hstack click")
// 애니메이션 추가
withAnimation{
// toggle() 알아서 t/f 변경
self.isActivate.toggle()
}
} // hstack end
//navi 버튼 링크
NavigationLink(destination: MyTextView(isActivated: $isActivate) ) {
Text("네비게이션 버튼")
.fontWeight(.heavy)
.font(.system(size: 40))
.padding(10)
.background(Color.green)
.foregroundColor(Color.white)
.cornerRadius(30)
}
}
} // navigationview
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
48b2df136c31e0a47e4732dcf09805ed3892f457
|
Swift
|
SDGGiesbrecht/SDGCornerstone
|
/Sources/SDGMathematicsTestUtilities/Float.swift
|
UTF-8
| 13,589
| 2.78125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
Float.swift
This source file is part of the SDGCornerstone open source project.
https://sdggiesbrecht.github.io/SDGCornerstone
Copyright ©2018–2023 Jeremy David Giesbrecht and the SDGCornerstone project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import SDGMathematics
import SDGLocalization
import SDGTesting
/// Checks whether the two values are approximately equal.
///
/// - Parameters:
/// - precedingValue: A value to compare.
/// - followingValue: Another value to compare.
@inlinable public func ≈ <T>(precedingValue: T, followingValue: T) -> Bool
where T: ExpressibleByFloatLiteral, T: FloatingPoint, T: Subtractable {
#if !PLATFORM_LACKS_SWIFT_FLOAT_16
if #available(tvOS 14, iOS 14, watchOS 7, *),
precedingValue is Float16
{
return precedingValue ≈ followingValue ± 0.01
}
#endif
return precedingValue ≈ followingValue ± 0.000_01
}
// MARK: - Methods
// #documentation(SDGCornerstone.test(method:of:returns:))
/// Tests a method, verifying that it returns the expected result.
///
/// - Parameters:
/// - method: The method to test.
/// - instance: The instance on which to call the method.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<T, R>(
method: (call: (_ methodInstance: T) -> () throws -> R, name: String),
of instance: T,
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let methodCall = method.call(instance)
let result = try methodCall()
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(instance).\(method.name)() → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(method:of:with:returns:))
/// Tests a method, verifying that it returns the expected result.
///
/// - Parameters:
/// - method: The method to test.
/// - instance: The instance on which to call the method.
/// - argument: The argument to pass to the method.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<T, A, R>(
method: (call: (_ methodInstance: T) -> (_ methodArgument: A) throws -> R, name: String),
of instance: T,
with argument: A,
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let methodCall = method.call(instance)
let result = try methodCall(argument)
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(instance).\(method.name)(\(argument)) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(mutatingMethod:of:resultsIn:))
/// Tests a method, verifying that it returns the expected result.
///
/// - Parameters:
/// - method: The method to test.
/// - instance: The instance on which to call the method.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<T>(
mutatingMethod method: (call: (_ methodInstance: inout T) throws -> Void, name: String),
of instance: T,
resultsIn expectedResult: T,
file: StaticString = #filePath,
line: UInt = #line
) where T: ExpressibleByFloatLiteral, T: FloatingPoint, T: Subtractable {
do {
var copy = instance
try method.call(©)
test(
copy ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(instance).\(method.name)() → \(copy) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(mutatingMethod:of:with:resultsIn:))
/// Tests a method, verifying that it returns the expected result.
///
/// - Parameters:
/// - method: The method to test.
/// - instance: The instance on which to call the method.
/// - argument: The argument to pass to the method.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<T, A>(
mutatingMethod method: (
call: (_ methodInstance: inout T, _ methodArgument: A) throws -> Void, name: String
),
of instance: T,
with argument: A,
resultsIn expectedResult: T,
file: StaticString = #filePath,
line: UInt = #line
) where T: ExpressibleByFloatLiteral, T: FloatingPoint, T: Subtractable {
do {
var copy = instance
try method.call(©, argument)
test(
copy ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(instance).\(method.name)(\(argument)) → \(copy) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// MARK: - Functions
// #documentation(SDGCornerstone.test(function:on:returns:))
/// Tests a function, verifying that it returns the expected result.
///
/// - Parameters:
/// - function: The function to test.
/// - argument: The argument to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<A, R>(
function: (call: (_ functionArgument: A) throws -> R, name: String),
on argument: A,
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let result = try function.call(argument)
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(function.name)(\(argument)) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(function:on:(2)returns:))
/// Tests a function, verifying that it returns the expected result.
///
/// - Parameters:
/// - function: The function to test.
/// - arguments: The arguments to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<A, B, R>(
function: (
call: (_ firstFunctionArgument: A, _ secondFunctionArgument: B) throws -> R, name: String
),
on arguments: (A, B),
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let result = try function.call(arguments.0, arguments.1)
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(function.name)(\(arguments.0), \(arguments.1)) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(function:on:returns:))
/// Tests a function, verifying that it returns the expected result.
///
/// - Parameters:
/// - function: The function to test.
/// - argument: The argument to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<A>(
function: (call: (_ functionArgument: A) throws -> Angle<A>, name: String),
on argument: A,
returns expectedResult: Angle<A>,
file: StaticString = #filePath,
line: UInt = #line
) where A: FloatingPoint {
do {
let result = try function.call(argument)
test(
result.rawValue ≈ expectedResult.rawValue,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(function.name)(\(argument)) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// MARK: - Operators
// #documentation(SDGCornerstone.test(operator:on:returns:))
/// Tests an infix operator, verifying that it returns the expected result.
///
/// - Parameters:
/// - operator: The operator function to test.
/// - operands: The operands to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<P, F, R>(
operator: (function: (_ precedingOperand: P, _ followingOperand: F) throws -> R, name: String),
on operands: (precedingValue: P, followingValue: F),
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let result = try `operator`.function(operands.precedingValue, operands.followingValue)
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(operands.precedingValue) \(`operator`.name) \(operands.followingValue) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(prefixOperator:on:returns:))
/// Tests a prefix operator, verifying that it returns the expected result.
///
/// - Parameters:
/// - operator: The operator function to test.
/// - operand: The operand to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<O, R>(
prefixOperator operator: (function: (_ functionOperand: O) throws -> R, name: String),
on operand: O,
returns expectedResult: R,
file: StaticString = #filePath,
line: UInt = #line
) where R: ExpressibleByFloatLiteral, R: FloatingPoint, R: Subtractable {
do {
let result = try `operator`.function(operand)
test(
result ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(`operator`.name)\(operand) → \(result) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// #documentation(SDGCornerstone.test(postfixAssignmentOperator:with:resultsIn:))
/// Tests a postfix assignment operator, verifying that the mutated value matches the expected result.
///
/// - Parameters:
/// - operator: The operator function to test.
/// - operand: The operand to pass to the function.
/// - expectedResult: The expected result.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
@inlinable public func test<O>(
postfixAssignmentOperator operator: (
function: (_ functionOperand: inout O) throws -> Void, name: String
),
with operand: O,
resultsIn expectedResult: O,
file: StaticString = #filePath,
line: UInt = #line
) where O: ExpressibleByFloatLiteral, O: FloatingPoint, O: Subtractable {
do {
var copy = operand
try `operator`.function(©)
test(
copy ≈ expectedResult,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(operand)\(`operator`.name) → \(copy) ≠ \(expectedResult)"
}(),
file: file,
line: line
)
} catch {
fail("\(error)", file: file, line: line)
}
}
// MARK: - Global Variables
// #documentation(SDGCornerstone.test(variable:is:))
/// Tests a variable, verifying that it contains the expected value.
///
/// - Parameters:
/// - variable: The variable to test.
/// - expectedValue: The expected property value.
/// - file: Optional. A different source file to associate with any failures.
/// - line: Optional. A different line to associate with any failures.
public func test<V>(
variable: (contents: V, name: String),
is expectedValue: V,
file: StaticString = #filePath,
line: UInt = #line
) where V: ExpressibleByFloatLiteral, V: FloatingPoint, V: Subtractable {
test(
variable.contents ≈ expectedValue,
{ // @exempt(from: tests)
return // @exempt(from: tests)
"\(variable.name) → \(variable.contents) ≠ \(expectedValue)"
}(),
file: file,
line: line
)
}
| true
|
858b23b7e12c1e2924fb052cc24fdd5ecf48745a
|
Swift
|
johndpope/LinkX
|
/LinkX/ViewControllers/Tables/ActivityTableViewController.swift
|
UTF-8
| 1,674
| 2.53125
| 3
|
[] |
no_license
|
//
// ActivityTableViewController.swift
// LinkX
//
// Created by Rodney Gainous Jr on 7/1/19.
// Copyright © 2019 CodeSigned. All rights reserved.
//
import UIKit
class ActivityTableViewController: UITableViewController {
let activities = [LXConstants.CONTRIBUTE_INVESTOR]
var activitySelected: ((Activity) -> ())?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "ActivityTableViewCell", bundle: nil), forCellReuseIdentifier: "ActivityTableViewCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 77.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell =
tableView.dequeueReusableCell(withIdentifier: "ActivityTableViewCell", for: indexPath) as? ActivityTableViewCell else {
return UITableViewCell()
}
cell.configure(activity: activities[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row < activities.count else {
return
}
tableView.deselectRow(at: indexPath, animated: false)
activitySelected?(activities[indexPath.row])
}
}
| true
|
00bbf72e2c60335fc53201268a6d5629af4c7ab3
|
Swift
|
taroyuyu/ShapeScript
|
/Viewer/Utilities.swift
|
UTF-8
| 2,802
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// Utilities.swift
// Viewer
//
// Created by Nick Lockwood on 22/12/2018.
// Copyright © 2018 Nick Lockwood. All rights reserved.
//
import AppKit
import Euclid
import ShapeScript
// MARK: General
let isHighSierra: Bool = {
let os = ProcessInfo.processInfo.operatingSystemVersion
return os.majorVersion == 10 && os.minorVersion == 13
}()
let useOpenGL = isHighSierra
func isImageFile(_ url: URL) -> Bool {
[
"webp",
"png",
"jpg", "jpeg", "jpe", "jif", "jfif", "jfi",
"tiff", "tif",
"psd",
"raw", "arw", "cr2", "nrw", "k25",
"bmp", "dib",
"heif", "heic",
"ind", "indd", "indt",
"jp2", "j2k", "jpf", "jpx", "jpm", "mj2",
].contains(url.pathExtension.lowercased())
}
func showSheet(_ alert: NSAlert, in window: NSWindow?,
_ handler: ((NSApplication.ModalResponse) -> Void)? = nil)
{
if let window = window {
alert.beginSheetModal(for: window, completionHandler: handler)
} else {
let response = alert.runModal()
handler?(response)
}
}
func showSheet(_ dialog: NSSavePanel, in window: NSWindow?,
_ handler: @escaping (NSApplication.ModalResponse) -> Void)
{
if let window = window {
dialog.beginSheetModal(for: window, completionHandler: handler)
} else {
let response = dialog.runModal()
handler(response)
}
}
// MARK: Editor selection
func configureEditorPopup(_ popup: NSPopUpButton) {
let selectedEditor = Settings.shared.selectedEditor ?? Settings.shared.defaultEditor
popup.removeAllItems()
for app in Settings.shared.editorApps {
popup.addItem(withTitle: app.name)
if app == selectedEditor {
popup.select(popup.menu?.items.last)
}
}
popup.menu?.addItem(.separator())
popup.addItem(withTitle: "Other…")
}
func handleEditorPopupAction(for popup: NSPopUpButton, in window: NSWindow?) {
let index = popup.indexOfSelectedItem
if index < Settings.shared.editorApps.count {
Settings.shared.selectedEditor = Settings.shared.editorApps[index]
return
}
let appDirectory = NSSearchPathForDirectoriesInDomains(.allApplicationsDirectory, .systemDomainMask, true).first
let dialog = NSOpenPanel()
dialog.title = "Select App"
dialog.showsHiddenFiles = false
dialog.directoryURL = appDirectory.map { URL(fileURLWithPath: $0) }
dialog.allowedFileTypes = ["app"]
showSheet(dialog, in: window) { response in
guard response == .OK, let url = dialog.url else {
if let editor = Settings.shared.selectedEditor?.name {
popup.selectItem(withTitle: editor)
}
return
}
Settings.shared.selectedEditor = EditorApp(url)
}
}
| true
|
68d4ea7c1cb9679eea053b2d9435d12c23b68fc9
|
Swift
|
heji233/LiteChart
|
/Sources/Color/UIColor+Utilities.swift
|
UTF-8
| 314
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// UIColor+Utilities.swift
//
//
// Created by 刘洋 on 2020/6/4.
//
import UIKit
extension UIColor {
internal convenience init(sRGB3PRed red: Int, green: Int, blue: Int) {
self.init(displayP3Red: CGFloat(red) / 255 , green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1)
}
}
| true
|
36565b3c14f2541b68f5fe2b1dd16f7597dd98a2
|
Swift
|
dev-yong/NAVER-CSS-Clova-Speech-Synthesis
|
/NAVER Clova Speech Synthesis/ViewController.swift
|
UTF-8
| 6,044
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// NAVER Clova Speech Synthesis
//
// Created by 이광용 on 2018. 8. 1..
// Copyright © 2018년 이광용. All rights reserved.
//
import UIKit
import AVFoundation
import Alamofire
//http://docs.ncloud.com/ko/naveropenapi_v2/naveropenapi-4-2.html
//https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html
//https://developer.apple.com/documentation/uikit/uipickerview
//https://developer.apple.com/documentation/uikit/uislider
enum Gender: Int, EnumCollection {
case male, female
var description: String {
switch self {
case .male:
return "Male"
case .female:
return "Female"
}
}
}
enum Language: Int, EnumCollection {
var description: String {
switch self {
case .korean:
return "한국어"
case .english:
return "English"
case .japanese:
return "日本語"
case .chinese:
return "中文"
case .spanish:
return "Español"
}
}
case korean, english, japanese, chinese, spanish
func speaker(gender: Gender) -> String {
switch self {
case .korean:
return gender == .male ? "jinho" : "mijin"
case .english:
return gender == .male ? "matt" : "clara"
case .japanese:
return gender == .male ? "shinji" : "yuri"
case .chinese:
return gender == .male ? "liangliang" : "meimei"
case .spanish:
return gender == .male ? "jose" : "carmen"
}
}
}
class ViewController: UIViewController {
var audio: AVAudioPlayer?
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var ttsButton: UIButton!
@IBOutlet weak var picker: UIPickerView!
@IBOutlet weak var slider: UISlider!
let languages: [Language] = Language.allCases
let genders: [Gender] = Gender.allCases
var language: Language = .korean
var gender: Gender = .female
var speed = 0
override func viewDidLoad() {
super.viewDidLoad()
self.picker.dataSource = self
self.picker.delegate = self
self.slider.minimumValue = -5
self.slider.maximumValue = 5
self.slider.value = 0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.picker.selectRow(self.language.rawValue, inComponent: 0, animated: true)
self.picker.selectRow(self.gender.rawValue, inComponent: 1, animated: true)
}
@IBAction func touchUpTTSButton(_ sender: UIButton) {
guard let text = self.textView.text else {return}
requestTTS(language: self.language, gender: self.gender, speed: self.speed, text: text)
}
//음성 재생 속도. -5 에서 5 사이의 정수 값이며, -5 이면 0.5 배 빠른 속도이고 5 이면 0.5 배 느린 속도입니다. 0 이면 정상 속도의 목소리로 음성을 합성합니다.
@IBAction func valueChanged(_ sender: UISlider) {
self.speed = Int(sender.value)
}
func requestTTS(language: Language, gender: Gender, speed: Int, text: String) {
let header = [ "X-NCP-APIGW-API-KEY-ID": "[Client ID]",
"X-NCP-APIGW-API-KEY": "[Client Secret]"]
let parameter: [String: Any] = ["speaker": language.speaker(gender: gender),
"speed": 0,
"text": text]
Alamofire.request("https://naveropenapi.apigw.ntruss.com/voice/v1/tts",
method: HTTPMethod.post,
parameters: parameter,
headers: header).responseData { (response) in
switch response.result {
case .success :
guard let statusCode = response.response?.statusCode as Int? else {return}
switch statusCode {
case 200..<400 :
guard let data = response.data else {return}
self.play(data: data)
default :
print(statusCode)
}
case .failure(let error) :
print(error.localizedDescription)
}
}
}
func play(data: Data) {
do {
audio = try AVAudioPlayer(data: data)
audio?.prepareToPlay()
audio?.play()
} catch {
print(error.localizedDescription)
}
}
func saveAudio(data: Data) {
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("voice.mp3")
do {
try data.write(to: fileURL, options: .atomic)
}
catch {
print(error.localizedDescription)
}
}
}
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return languages.count
case 1:
return genders.count
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0:
return languages[row].description
case 1:
return genders[row].description
default:
return ""
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
self.language = self.languages[row]
case 1:
self.gender = self.genders[row]
default:
break
}
}
}
| true
|
6b3da8648c58580fa2ffa6c43719150fcc2bf17d
|
Swift
|
ChrisRhode/ToDoSwift
|
/ToDoSwift/MainTableViewController.swift
|
UTF-8
| 12,344
| 2.59375
| 3
|
[] |
no_license
|
//
// MainTableViewController.swift
// ToDoSwift
//
// Created by Christopher Rhode on 2/27/20.
// Copyright © 2020 Christopher Rhode. All rights reserved.
//
import UIKit
// ** should search mode focus within current level or continue to be global?
class MainTableViewController: UITableViewController, DatePickerPassbackDelegate, UITextFieldDelegate {
let ugbl : Utility
let db : DBWrapper
// ** program for forceReload / natural calls / viewWillAppear
var forceReload: Bool = true
var searchadd : UITextField? = nil
// ** all special handling based on search mode
var isSearchMode : Bool = false
var currParentItemID : Int = 0
var currParentItemText : String = "$(root)"
//var recordList: [[String]] = []
var itemsAtThisLevel : [ToDoItem] = []
// ** all of the above have to be initialized in an init, cannot do in viewDidLoad etc
// ** may be required to define all possible init methods, definmitely the one used to create it
override init(style:UITableView.Style)
{
ugbl = Utility()
db = DBWrapper.init(forDbFile: "ToDoSwift")
super.init(style:style)
}
required init?(coder: NSCoder)
{
//ugbl = Utility()
//db = DBWrapper.init(forDbFile: "ToDoSwift")
//super.init(coder:coder)
fatalError("init(coder:) not supported")
}
override func viewDidLoad() {
// ** have to initialize to empty in caller!
super.viewDidLoad()
// get all the items at the root level
// search/add text entry box
searchadd = UITextField(frame: CGRect(x:0,y:0,width:320,height:44))
searchadd?.delegate = self
searchadd?.borderStyle = UITextField.BorderStyle.roundedRect
searchadd?.clearButtonMode = UITextField.ViewMode.whileEditing
searchadd?.placeholder = "(search/add)"
self.tableView.tableHeaderView = searchadd
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
// ** this suffices to create the instance
// ugbl = Utility()
// testing
//var x = ugbl.dateHumanToSortable(sourceDate: "03/02/2020")
//x = ugbl.dateSortableToHuman(sourceDate: x)
// var x = ugbl.doesContainValidNonNegativeInteger(theString: "ABC")
//
self.title = ugbl.currDateInHumanFormat()
let _ = db.openDB()
let _ = db.executeSQLCommand(theSQL: "CREATE TABLE IF NOT EXISTS Items (ItemID INTEGER NOT NULL, ParentItemID INTEGER NOT NULL, ChildCount INTEGER NOT NULL, ItemText TEXT NOT NULL, Notes TEXT, BumpCount INTEGER NOT NULL, DateOfEvent TEXT,BumpToTopDate TEXT, isGrayedOut INTEGER NOT NULL, isDeleted INTEGER NOT NULL, PRIMARY KEY (ItemID));")
db.closeDB()
// testing
// let _ = db.openDB()
// let _ = db.executeSQLCommand(theSQL: "INSERT INTO Items VALUES (1,1,0,0,'Hello World',NULL,0,NULL,0,0);")
// let _ = db.executeSQLCommand(theSQL: "INSERT INTO Items VALUES (1,2,0,0,'Second Record',NULL,0,NULL,0,0);")
// let _ = db.doSelect(sql: "SELECT * FROM Items", records: &recordList)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (forceReload)
{
forceReload = false
loadCurrentChildren()
self.tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return (itemsAtThisLevel.count)+1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// ** code for reusable cells
// let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "MainListCell")
cell.accessoryType = .none
let thisRow = indexPath.row
//let thisItemID = Int(recordList[thisRow][0])
//let thisItem = ToDoItem(requestedItemID: thisItemID!)
if (thisRow == 0)
{
if (isSearchMode)
{
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
}
else
{
var theValue = currParentItemText
if (currParentItemID != 0)
{
theValue = "<- " + theValue
}
cell.textLabel?.text = theValue
cell.detailTextLabel?.text = ""
}
}
else
{
let thisItem = itemsAtThisLevel[thisRow-1]
cell.textLabel?.text = thisItem.itemText
cell.detailTextLabel?.text = ""
if (thisItem.childCount > 0)
{
cell.accessoryType = .disclosureIndicator
}
}
// Configure the cell...
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let thisRow = indexPath.row
if (thisRow == 0)
{
if (!isSearchMode)
{
if (currParentItemID != 0)
{
// repopulate based on parent node
let currParentItem = ToDoItem(requestedItemID: currParentItemID)
let newParentItemID = currParentItem.parentItemID
currParentItemID = newParentItemID
if (newParentItemID == 0)
{
currParentItemText = "$(root)"
}
else
{
let newParentItem = ToDoItem(requestedItemID: currParentItem.parentItemID)
currParentItemText = newParentItem.itemText
}
loadCurrentChildren()
self.tableView.reloadData()
}
}
}
else
{
let thisItem = itemsAtThisLevel[thisRow-1]
currParentItemID = thisItem.itemID
currParentItemText = thisItem.itemText
if (isSearchMode)
{
isSearchMode = false
searchadd?.text = ""
}
loadCurrentChildren()
self.tableView.reloadData()
}
// selectedRow = indexPath.row
// edit the date
// let tmp = DatePicker(CurrentHumanDate: dateValue, ItemDescription: "Test Date")
// tmp.delegate = self
// self.navigationController?.pushViewController(tmp, animated: true)
}
func doDatePickerPassBack(theHumanDate: String, didTapCancel: Bool)
{
if (didTapCancel == false)
{
//dateValue = theHumanDate
forceReload = true
}
self.navigationController?.popViewController(animated: false)
}
// UITextField delegate implementations
func textFieldDidChangeSelection(_ textField: UITextField) {
let currentTextFieldValue = textField.text
// ** currentTextFieldValue?.count does not work
if (currentTextFieldValue!.count >= 2)
{
var recordList : [[String]] = []
var thisItemID : Int?
// instate search mode based on characters entered so far
isSearchMode = true
// ** code for parameterized select, to protect against SQL injection
let sql = "SELECT ItemID FROM Items WHERE (ItemText LIKE '%" + currentTextFieldValue! + "%')"
let _ = db.openDB()
let _ = db.doSelect(sql: sql, records: &recordList)
// ** commonize this with regular load
db.closeDB()
let lastNdx = recordList.count - 1
var ndx = 0
// ***** keepingCapacity?
itemsAtThisLevel.removeAll()
while (ndx <= lastNdx)
{
thisItemID = Int(recordList[ndx][0])
itemsAtThisLevel.append(ToDoItem(requestedItemID: thisItemID!))
ndx += 1
}
}
else
{
// restore to normal mode
isSearchMode = false
loadCurrentChildren()
}
self.tableView.reloadData()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// hitting RETURN vs clearing the box or defocusing the box is treated as ADD
let finalTextFieldValue = textField.text
if (finalTextFieldValue?.count == 0)
{
ugbl.popUpSimpleAlert(alertMessage: "Item text cannot be empty", withTypeOfAlert: .isError)
return false
}
let theNewItem = ToDoItem()
theNewItem.itemText = finalTextFieldValue!
theNewItem.saveNew(withParentItemID: currParentItemID)
textField.text = ""
loadCurrentChildren()
self.tableView.reloadData()
return false
}
// load items at current level
func loadCurrentChildren()
{
var recordList : [[String]] = []
var ndx : Int
var lastNdx : Int
var thisItemID : Int?
let sql = "SELECT ItemID FROM Items WHERE (ParentItemID = \(currParentItemID)) ORDER BY ItemID DESC"
let _ = db.openDB()
let _ = db.doSelect(sql: sql, records: &recordList)
db.closeDB()
lastNdx = recordList.count - 1
ndx = 0
// ***** keepingCapacity?
itemsAtThisLevel.removeAll()
while (ndx <= lastNdx)
{
thisItemID = Int(recordList[ndx][0])
itemsAtThisLevel.append(ToDoItem(requestedItemID: thisItemID!))
ndx += 1
}
}
// template code after this line
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
bc6075acd6ab2a7188a573a183af7791bd06bfd0
|
Swift
|
appcoda/PhotosApp
|
/PhotosApp/Photo Handling/PhotoHelper.swift
|
UTF-8
| 3,886
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// PhotoHelper.swift
// PhotosApp
//
// Created by Gabriel Theodoropoulos.
// Copyright © 2019 Appcoda. All rights reserved.
//
import Cocoa
class PhotoHelper {
// MARK: - Properties
static let shared = PhotoHelper()
private(set) var photosToProcess = [PhotoInfo]()
private var progressHandler: ((_ current: Int) -> Void)?
var queue: DispatchQueue?
// MARK: - Init
private init() {
}
// MARK: - Custom Methods
func createThumbnails(for photos: [PhotoInfo],
desiredSize size: NSSize,
progress: @escaping (_ currentPhoto: Int) -> Void,
completion: @escaping () -> Void) {
progressHandler = progress
photosToProcess = photos
queue = DispatchQueue(label: "createThumbnailsQueue", qos: .utility)
queue?.async {
self.createThumbnail(fromPhotoURLAt: 0, resizeTo: size) {
completion()
}
}
}
func importPhotoURLs(from selectedURL: URL, to collection: inout [PhotoInfo]) {
guard let enumerator = FileManager.default.enumerator(at: selectedURL,
includingPropertiesForKeys: [.isDirectoryKey, .nameKey],
options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles],
errorHandler: nil) else { return }
enumerator.forEach { (url) in
guard let url = url as? URL else { return }
do {
guard let isDir = try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory else { return }
if !isDir {
let allowedPhotoExtensions = ["png", "jpg", "jpeg", "JPG", "PNG"]
if allowedPhotoExtensions.contains(url.pathExtension) {
collection.append(PhotoInfo(with: url))
}
}
} catch { print(error.localizedDescription) }
}
}
// MARK: - Private Methods
private func createThumbnail(fromPhotoURLAt index: Int, resizeTo size: NSSize, completion: @escaping () -> Void) {
if index < photosToProcess.count {
createThumbnail(fromPhotoURLAt: index + 1, resizeTo: size) {
self.queue?.asyncAfter(deadline: .now() + 0.001) {
self.progressHandler?(self.photosToProcess.count - index)
let photoIndex = self.photosToProcess.count - index - 1
self.photosToProcess[photoIndex].thumbnail = self.resize(photoAt: self.photosToProcess[photoIndex].url, to: size)
completion()
}
}
} else {
completion()
}
}
private func resize(photoAt url: URL?, to size: NSSize) -> NSImage? {
if let url = url, let photo = NSImage(contentsOf: url) {
let ratio = photo.size.width > photo.size.height ? size.width / photo.size.width : size.height / photo.size.height
var rect = NSRect(origin: .zero, size: NSSize(width: photo.size.width * ratio, height: photo.size.height * ratio))
rect.origin = NSPoint(x: (size.width - rect.size.width)/2, y: (size.height - rect.size.height)/2)
let thumbnail = NSImage(size: size)
thumbnail.lockFocus()
photo.draw(in: rect,
from: NSRect(origin: .zero, size: photo.size),
operation: .copy, fraction: 1.0)
thumbnail.unlockFocus()
return thumbnail
}
return nil
}
}
| true
|
19fac9d967214260e5e2fab8c29044e517579380
|
Swift
|
InvadingOctopus/octopuskit
|
/Sources/OctopusKit/Support & Utility/Data Structures/AcceleratedValue.swift
|
UTF-8
| 4,045
| 3.46875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//
// AcceleratedValue.swift
// OctopusKit
//
// Created by ShinryakuTako@invadingoctopus.io on 2019/12/05.
// Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt)
//
import Foundation
/// Represents a scalar with a base value that may increase or decrease by the specified amount per frame or per second.
public struct AcceleratedValue <Number: Numeric & Comparable> {
// TODO: Non-linear acceleration
// DECIDE: Should this be a @propertyWrapper?
// DESIGN: As of Swift 5.1 2019-12-05, the current property wrapper syntax and synthesis may not be suitable for the intended use cases.
/// The base value.
public var base: Number
/// The current value with cumulative `acceleration` applied.
public var current: Number
/// The maximum permitted value for `current` including accumulated `acceleration`.
public var maximum: Number
/// The minimum permitted value for `current` including accumulated de-`acceleration`.
public var minimum: Number
/// The amount to change (or decrease, if negative) the `current` value by on every update.
public var acceleration: Number
/// `true` if the `current` value is greater than `minimum` and less than `maximum`.
@inlinable
public var isWithinBounds: Bool {
// CHECK: PERFORMANCE: Should this be set whenever `current` is modified, or is it better to check this only when the bounds are important?
current > minimum
&& current < maximum
}
/// - Parameters:
/// - base: The base value, without any `acceleration`. Default: `1`
/// - current: The initial value to start with. Default: `base`
/// - maximum: The upper bound for `current` including accumulated `acceleration`. Default: `base`
/// - minimum: The lower bound for `current` including accumulated deceleration, if `acceleration` is a negative amount. Default: `base`
/// - acceleration: Specify a negative amount to decelerate. Default: `0`
public init(base: Number = 1,
current: Number? = nil,
maximum: Number? = nil,
minimum: Number? = nil,
acceleration: Number = 0)
{
self.base = base
self.current = current ?? base
self.maximum = maximum ?? base
self.minimum = minimum ?? base
self.acceleration = acceleration
}
/// Adds `acceleration` to the `current` value. Does *not* check for `minimum` or `maximum`; call `clamp()` to limit the value within those bounds.
///
/// - Returns: `self` which may then be chained with `.clamp()`.
@inlinable
public mutating func update() {
current += acceleration
}
/// Adds `acceleration` × `deltaTime` to the `current` value. Does *not* check for `minimum` or `maximum`; call `clamp()` to limit the value within those bounds.
///
/// - Returns: `self` which may then be chained with `.clamp()`.
@inlinable
public mutating func update(deltaTime: Number) {
current += acceleration * deltaTime
}
/// Applies `acceleration` to the `current` value, scaling `acceleration` by `deltaTime` if `timeStep` is `perSecond`.Does *not* check for `minimum` or `maximum`; call `clamp()` to limit the value within those bounds.
@inlinable
public mutating func update(timeStep: TimeStep, deltaTime: Number) {
timeStep.apply(acceleration, to: ¤t, deltaTime: deltaTime)
}
/// If `current` is less than `minimum`, sets it to `minimum`, or if `current` is greater than `maximum`, sets it to `maximum` (checked in that order.)
@inlinable
public mutating func clamp() {
if current < minimum {
current = minimum
} else if current > maximum {
current = maximum
}
}
/// Sets `current` to `base`.
@inlinable
public mutating func reset() {
current = base
}
}
| true
|
944af02204952f2ab4669643011c53e9b1373180
|
Swift
|
AnastasiaTetyueva/test_game
|
/test_game/ViewController.swift
|
UTF-8
| 1,083
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// test_game
//
// Created by Anastasia Tetyueva on 03.09.2021.
// Copyright © 2021 Anastasia Tetyueva. All rights reserved.
//
import UIKit
import SnapKit
class GameStartVC: UIViewController {
lazy var startButton: UIButton = {
var l = UIButton()
l.setTitle("Start New Game", for: .normal)
l.backgroundColor = UIColor.orange
l.showsTouchWhenHighlighted = true
l.layer.cornerRadius = 5
l.addTarget(self, action: #selector(pushStartButton), for: .touchUpInside)
return l
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "gameName"
self.view.backgroundColor = UIColor.white
self.view.addSubview(startButton)
startButton.snp.makeConstraints { (constraint) in
constraint.centerX.equalToSuperview()
constraint.bottom.equalToSuperview().offset(-50)
constraint.width.equalTo(160)
constraint.height.equalTo(30)
}
}
@objc func pushStartButton() {
}
}
| true
|
6ca17eb622881c32bdcd2029a769ac650089bb72
|
Swift
|
Huluk/Scribit
|
/Scribit/SelectionView.swift
|
UTF-8
| 890
| 3.03125
| 3
|
[] |
no_license
|
//
// SelectionView.swift
// Scribit
//
// Created by Lars Hansen on 2016-04-13.
// Copyright © 2016 Lars Hansen. All rights reserved.
//
import Cocoa
class SelectionView: NSView {
let borderColor = NSColor.blueColor()
let fillColor = NSColor.clearColor()
var dashPattern:CGFloat = 5
var origin = NSPoint()
var selection = NSRect()
func selectTo(point: NSPoint) {
let minX = min(origin.x, point.x)
let minY = min(origin.y, point.y)
selection = NSMakeRect(minX, minY, max(origin.x, point.x)-minX, max(origin.y, point.y)-minY)
needsDisplay = true
}
override func drawRect(dirtyRect: NSRect) {
let path = NSBezierPath(rect: selection)
path.setLineDash(&dashPattern, count: 1, phase: 0)
borderColor.setStroke()
path.stroke()
fillColor.setFill()
path.fill()
}
}
| true
|
b6f296211828bf9612f0481c28593dd053823267
|
Swift
|
taketo1024/LinAlgSample
|
/LinAlg/Views/VectorView.swift
|
UTF-8
| 3,008
| 2.734375
| 3
|
[] |
no_license
|
//
// VectorView.swift
// LinAlg
//
// Created by Taketo Sano on 2019/02/26.
// Copyright © 2019 Taketo Sano. All rights reserved.
//
import UIKit
protocol VectorViewDelegate: class {
func vectorViewUpdated(_ v: VectorView)
func vectorView(_ v: VectorView, dragged amount: CGPoint)
}
class VectorView: UIView {
var vector: Vec2 = .zero {
didSet {
if vector != oldValue {
setNeedsDisplay()
delegate?.vectorViewUpdated(self)
}
}
}
var color: UIColor = .black
var lineWidth: CGFloat = 2
var headRadius: CGFloat { return lineWidth * 2.5 }
var dragging: Bool = false
weak var delegate: VectorViewDelegate?
weak var related: VectorView?
var headCenter: CGPoint {
let r = headRadius * (dragging ? 1.5 : 1.0)
let t = -vector.asCGPoint.arg
return -r * CGPoint.unit(arg: t)
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
if isUserInteractionEnabled {
let alpha: CGFloat = dragging ? 0.5 : 0.1
ctx.setFillColor(color.withAlphaComponent(alpha).cgColor)
ctx.fillEllipse(in: bounds)
}
ctx.setFillColor(color.cgColor)
let r = headRadius * (dragging ? 1.5 : 1.0)
if vector == .zero {
let c = bounds.center
ctx.fillEllipse(in: CGRect(c.x - r, c.y - r, 2 * r, 2 * r))
} else {
let π = CGFloat.pi
let u = CGPoint.unit
let t = -vector.asCGPoint.arg
let c = bounds.center + headCenter
ctx.beginPath()
ctx.move(to: c + r * u(t))
ctx.addLine(to: c + r * u(t + 2 * π / 3))
ctx.addLine(to: c + r * u(t + 4 * π / 3))
ctx.closePath()
ctx.fillPath()
}
}
func update() {
if let planeView = superview as? PlaneView {
center = planeView.convertVector(vector)
planeView.setNeedsDisplay()
}
}
private func dragged(_ state: UIGestureRecognizer.State, _ touches: Set<UITouch>) {
dragging = (state == .began || state == .changed)
if let t = touches.first {
let a = t.location(in: self) - t.previousLocation(in: self)
delegate?.vectorView(self, dragged: a)
}
setNeedsDisplay()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dragged(.began, touches)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
dragged(.changed, touches)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
dragged(.cancelled, touches)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
dragged(.ended, touches)
}
}
| true
|
a70759feddd462d8255322c8ade2df736e07ae97
|
Swift
|
zyahs/MyWeiBo
|
/MySinXWeiBo/MySinXWeiBo/Classes/Tools/ZYEmoticonTools.swift
|
UTF-8
| 3,596
| 2.640625
| 3
|
[] |
no_license
|
//
// ZYEmoticonTools.swift
// MySinXWeiBo
//
// Created by 飞奔的羊 on 16/5/21.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
///读取表情数据专用类
class ZYEmoticonTools: NSObject {
///单例全局访问点
static let sharedTools: ZYEmoticonTools = ZYEmoticonTools()
//构造函数私有化
private override init() {
super.init()
}
///创建 emoriconbundlle 对象,因为主要都在这个 bundle
private lazy var emoticonBundle: NSBundle = {
let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
//创建 bundle 对象
let bundle = NSBundle(path: path)!
//返回 bundle 对象
return bundle
}()
///读取默认表情
private lazy var defaultEmoticons: [ZYEmoticon] = {
return self.loadEmoticonWithPath("default/info.plist")
}()
///读取默认表情
private lazy var emojiEmoticons: [ZYEmoticon] = {
return self.loadEmoticonWithPath("emoji/info.plist")
}()
///读取默认表情
private lazy var LxhEmoticons: [ZYEmoticon] = {
return self.loadEmoticonWithPath("lxh/info.plist")
}()
///给表情视图做准备
lazy var allEmoticons: [[[ZYEmoticon]]] = {
//表情视图包含三个种类型的二维数组
return [
self.sectionWithEmoticons(self.defaultEmoticons),
self.sectionWithEmoticons(self.emojiEmoticons),
self.sectionWithEmoticons(self.LxhEmoticons)
]
}()
///抽取读取表情方法
private func loadEmoticonWithPath(subPath: String) -> [ZYEmoticon] {
//pathForResource 如果不知道路径取得就是 Resources 路径
let path = self.emoticonBundle.pathForResource(subPath, ofType: nil)!
//加载 plist 资源数据
let array = NSArray(contentsOfFile: path)!
var tempArray = [ZYEmoticon]()
//遍历数组转模型
for dic in array
{
let emoticon = ZYEmoticon(dic: dic as! [String: AnyObject])
//判断是否是图片
if emoticon.type == "0" {
//给我们 path 拼接路径
//获取图片名字
let png = emoticon.png!
//把路径里面的最后一部分干掉
let subPath = (path as NSString).stringByDeletingLastPathComponent
//图片的全路径
emoticon.path = subPath + "/" + png
}
tempArray.append(emoticon)
}
return tempArray
}
///计算页数,截取数据
private func sectionWithEmoticons(emoticons: [ZYEmoticon]) -> [[ZYEmoticon]] {
//计算页数
let pageCount = (emoticons.count - 1) / 20 + 1
var tempArray: [[ZYEmoticon]] = [[ZYEmoticon]]()
//遍历页数计算截取
for i in 0..<pageCount
{
//计算当前截取的索引
let locaction = i * 20
var length = 20
//如果数组越界,重写计算截取个数
if locaction + length > emoticons.count {
length = emoticons.count - locaction
}
//截取数组元素
let subArray = (emoticons as NSArray).subarrayWithRange(NSMakeRange(locaction, length)) as! [ZYEmoticon]
tempArray.append(subArray)
}
return tempArray
}
///通过表情字符串 查找表情模型
func emoticonWithEmoticonStr(emoticonStr: String) -> ZYEmoticon? {
//另一种方法
// if let defaultEmoticon = defaultEmoticons.filter({$0.chs == emoticonStr}).first {
// return defaultEmoticon
// }
// if let lxhEmoticon = lxhEmoticons.filter({$0.chs == emoticonStr}).first {
// return lxhEmoticon
// }
//
//先从默认数组中查找
for value in defaultEmoticons
{
if value.chs == emoticonStr {
return value
}
}
//从浪小花数组中查找
for value in LxhEmoticons
{
if value.chs == emoticonStr {
return value
}
}
return nil
}
}
| true
|
0d187c4e636e9957f7cad1ce4c550bc2d35f81e8
|
Swift
|
st-small/CombineSwift
|
/Projects/02 HandlingErrors/HandlingErrors/BigButton.swift
|
UTF-8
| 1,073
| 2.765625
| 3
|
[] |
no_license
|
//
// BigButton.swift
// HandlingErrors
//
// Created by Stanly Shiyanovskiy on 23.12.2020.
//
import UIKit
@IBDesignable
class BigButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
setBackgroundImage(image(with: .systemBlue), for: .normal)
setTitleColor(.white, for: .normal)
titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline)
layer.masksToBounds = true
layer.cornerRadius = 12
}
override func prepareForInterfaceBuilder() {
configure()
}
private func image(with color: UIColor) -> UIImage {
let size = CGSize(width: 1, height: 1)
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { (context) in
context.cgContext.setFillColor(color.cgColor)
context.cgContext.fill(CGRect(origin: .zero, size: size))
}
}
}
| true
|
c03b33609fca1a3622b15a3e3781bda447763325
|
Swift
|
AndrewBellamy/Richly
|
/Richly/Richly/AddViewController.swift
|
UTF-8
| 3,885
| 2.578125
| 3
|
[] |
no_license
|
//
// AddViewController.swift
// Richly
//
// Created by Andrew Bellamy : 215240036 on 2/5/17.
// SIT206 Assignment 2
// Copyright © 2017 Andrew Bellamy. All rights reserved.
//
import UIKit
import CoreData
class AddViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
/**
Initialization variables
*/
var parameterToAdd = Int()
var objectForJournal = parameterObject()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let CategoryFarm = categoryFarm()
var currentCategory: [String] = []
/**
In UI controls, set as variables for programmatic use.
*/
@IBOutlet weak var topLabel: UIBarButtonItem!
@IBOutlet weak var categorySelected: UILabel!
@IBOutlet weak var nameEntered: UITextField!
@IBOutlet weak var categoryPicker: UIPickerView!
@IBOutlet weak var doneButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
switch parameterToAdd {
case 0:
topLabel.title = "Add Person"
currentCategory = CategoryFarm.personCategory
case 1:
topLabel.title = "Add Place"
currentCategory = CategoryFarm.placeCategory
case 2:
topLabel.title = "Add Activity"
currentCategory = CategoryFarm.activityCategory
case 3:
topLabel.title = "Add Weather"
currentCategory = CategoryFarm.weatherCategory
case 4:
topLabel.title = "Add Time"
currentCategory = CategoryFarm.timeCategory
case 5:
topLabel.title = "Add Impact"
currentCategory = CategoryFarm.impactCategory
case 6:
topLabel.title = "Add Feeling"
currentCategory = CategoryFarm.feelingCategory
case 7:
topLabel.title = "Add Experience"
currentCategory = CategoryFarm.consumeCategory
default:
cancelAdd((Any).self)
}
categorySelected.text = currentCategory[0]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currentCategory.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currentCategory[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
categorySelected.text = currentCategory[row]
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameEntered {
textField.resignFirstResponder()
return false
}
return true
}
/**
Sets the done button to enabled when text exists in the name input field
- parameters:
- sender: The UITextField for name input
*/
@IBAction func enteredName(_ sender: UITextField) {
if(sender.text != "" || sender.text != nil) {
doneButton.isEnabled = true
}
}
/**
Dismisses the presenting view controller
*/
@IBAction func cancelAdd(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "saveUnwindSegue" {
objectForJournal.name = nameEntered.text
objectForJournal.category = categorySelected.text
objectForJournal.section = parameterToAdd
}
}
}
| true
|
ad5f8418e08dc21a5b41e8f65ade5949f4339eb0
|
Swift
|
dali-lab/DALI-Framework
|
/Example/DALI/FoodViewController.swift
|
UTF-8
| 1,172
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// FoodViewController.swift
// DALI
//
// Created by John Kotz on 9/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import DALI
class FoodViewController: UIViewController {
@IBOutlet weak var foodTextField: UITextField!
@IBOutlet weak var foodLabel: UILabel!
@IBOutlet weak var connectionLabel: UILabel!
var observer: Observation?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
connectionLabel.text = "Connecting..."
foodLabel.text = "Loading..."
observer = DALIFood.observeFood { (food) in
DispatchQueue.main.async {
self.connectionLabel.text = "Connected"
self.foodLabel.text = food ?? "No food tonight"
}
}
}
override func viewWillDisappear(_ animated: Bool) {
observer?.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submit(_ sender: UIButton) {
DALIFood.setFood(food: foodTextField.text!) { (success) in
print(success)
}
}
}
| true
|
ec69a1ad9d54c4c69e80addf0d448bd61f0d9473
|
Swift
|
bviertel/snapchat
|
/Snapchat/SelectUserViewController.swift
|
UTF-8
| 3,920
| 2.90625
| 3
|
[] |
no_license
|
//
// SelectUserViewController.swift
// Snapchat
//
// Created by Ann Marie Seyerlein on 5/18/17.
// Copyright © 2017 Brandon. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import FirebaseStorage
// Need to set up numrowssection and cellforrowat as well as delegate and datasource otherwise error will be thrown
class SelectUserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var imageURL : String = ""
var desc : String = ""
var uuid : String = ""
var users : [User] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
// Populate Table View after Picture has been selected from the Picture View Controller
// Observe allows us to get the data or look at it
// NOTE THE FORMAT WITH OBSERVE!!!! BUG IN SYSTEM? WEIRD...
Database.database().reference().child("users").observe(DataEventType.childAdded, with: { DataSnapshot in
// print(DataSnapshot) // <--- Uncomment for detailed info in command window
// Gets the value specified from the dictionary key
let user = User()
// *** Should check to see if 'nil' first ***
// Create a Response Variable to hold the DataSnapChat response from Fire Base
let fireBaseResponse = DataSnapshot.value! as! NSDictionary
// Have to specify to String
// Note optional items (!,?)
// Set User Email to Email Value as String from the Fire Base Response
user.email = fireBaseResponse["email"] as! String
user.userName = fireBaseResponse["username"] as! String
// Set User ID to the Key of the DataSnapShot, does NOT need to be from the Fire Base Response
user.uid = DataSnapshot.key
// Add user to array in local program
// Self because it's inside a completion block
self.users.append(user)
// Reload the Table View to show Users
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let user = users[indexPath.row]
// Gets information from the User class that we made!
cell.textLabel?.text = user.userName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = users[indexPath.row]
// Creates dictionary for information regarding the User
// Got data from previous VC. Retrieved it by creating vars in current VC and assigning them in the previous VC
// Note the current user in from!
let snap = ["fromEmail":Auth.auth().currentUser!.email, "fromUserName":user.userName, "fromUserID":user.uid, "description":desc, "imageURL":imageURL, "uuid":uuid]
// Assigns the Snap information to the database
// Note the childByAutoId!
// Also setValue as dictionary
Database.database().reference().child("users").child(user.uid).child("snaps").childByAutoId().setValue(snap)
navigationController!.popToRootViewController(animated: true)
}
}
| true
|
7a843585ebc0e62360607c1bf24f2d73d10544fc
|
Swift
|
jadeocr/jadeocr-ios
|
/jadeocr/Controllers/Flashcards/Learn/LearnViewController.swift
|
UTF-8
| 1,998
| 2.578125
| 3
|
[] |
no_license
|
//
// LearnViewController.swift
// jadeocr
//
// Created by Jeremy Tow on 4/15/21.
//
import UIKit
class LearnViewController: Flashcards {
@IBOutlet var learnView: UIView!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
var scramble: Bool?
var repetitions: Int?
override func viewDidLoad() {
super.viewDidLoad()
backButton.isExclusiveTouch = true
nextButton.isExclusiveTouch = true
if handwriting ?? false {
cardHeightMultiplier = 0.3
cardYAnchorMultiplier = 0.5
AnchorButtonsViewToBottom.isActive = false
createHandwritingView(parentView: learnView)
}
createCardsBasedOnRepetitions(repetitions: repetitions ?? 0, parentView: learnView)
countLabel.text = "0/" + String(cardArray.count)
if scramble ?? false {
cardArray.shuffle()
}
super.showNextCard() //bypass sliding animation
}
override func showNextCard() {
slideOut(childView: cardArray[count].view, parentView: learnView, completion: {
super.showNextCard()
})
}
@IBAction func nextButtonPressed(_ sender: Any) {
guard count < cardArray.count - 1 else {
self.finishedLearn()
return
}
showNextCard()
}
@IBAction func backButtonPressed(_ sender: Any) {
guard count > 0 else {
return
}
showLastCard()
slideIn(childView: cardArray[count].view, parentView: learnView, completion: {})
}
func finishedLearn() {
if self.studentDelegate == nil {
self.performSegue(withIdentifier: "unwindToDeckInfo", sender: self)
} else {
self.performSegue(withIdentifier: "unwindToStudentView", sender: self)
}
studentDelegate?.submit(resultsForQuiz: [])
}
}
| true
|
9c72498dbdebedd7cde1f868d934a3c2ebf10c11
|
Swift
|
smrchrdsn/CuriousNature
|
/CuriousNature/Model/Flock.swift
|
UTF-8
| 2,929
| 3.234375
| 3
|
[] |
no_license
|
//
// Flock.swift
// CuriousNature
//
// Created by Sam Richardson on 4/7/18.
// Copyright © 2018 Sam Richardson. All rights reserved.
//
//
// Flock contains an array of Peas, methods for populating and managing the array, and methods to have the peas interact
//
import Foundation
class Flock {
// MARK: - Properties
var peas: [Pea]
var currentInteractions: Int
var colors: [CGColor] = [
CGColor(red: 0.83, green: 0.3, blue: 0.31, alpha: 1.0),
CGColor(red: 0.83, green: 0.3, blue: 0.31, alpha: 1.0),
CGColor(red: 0.06, green: 0.53, blue: 0.52, alpha: 1.0),
CGColor(red: 0.06, green: 0.53, blue: 0.52, alpha: 1.0),
CGColor(red: 0.25, green: 0.54, blue: 0.0, alpha: 1.0),
CGColor(red: 0.52, green: 0.53, blue: 0.03, alpha: 1.0)
]
// MARK: - Initializers
init() {
peas = [Pea]()
currentInteractions = 0
populate()
}
// MARK: - Methods
func populate() {
for _ in 0..<state.population {
peas.append(Pea(color: colors.randomItem()!))
}
}
func changePopulation() {
let difference = state.population - peas.count
if difference > 0 {
addPeas(count: difference)
print("Added", difference, "peas")
} else if difference < 0 {
removePeas(count: abs(difference))
print("Removed", abs(difference), "peas")
}
}
func addPeas(count: Int) {
for _ in 0..<count {
peas.append(Pea(color: colors.randomItem()!))
}
}
func removePeas(count: Int) {
peas.removeLast(count)
}
// Give peas new depths
func updateDepth() {
for pea in peas {
pea.depth = CGFloat.random(from: state.minDepth, to: state.maxDepth)
}
}
// Give peas a singular color
func color(_ color: CGColor) {
for pea in peas {
pea.color = color
}
}
// Give peas a random color from an array
func color(_ colors: [CGColor]) {
if !colors.isEmpty {
for pea in peas {
pea.color = colors.randomItem()!
}
}
}
// Recolor peas from state
func color() {
for i in 0..<peas.count {
peas[i].color = CGColor.random()
}
}
// MARK: - Updater
// Update peas based on interactions
func updateFlock(to context: CGContext) {
currentInteractions = 0
for pea in peas {
pea.update(seeking: peas)
currentInteractions += pea.currentInteractions
pea.drawInteractionsWithPolygons(to: context, peas: peas)
pea.drawPath(to: context)
}
// Peas interact in pairs, so halve the counted interactions
currentInteractions /= 2
//print(currentInteractions, "current interactions")
}
}
| true
|
be60e5dcf5ae164d05d1adf249e1f6bba882d7ab
|
Swift
|
markcadag/GithubSearchSwift
|
/technicalexam/Utilities/With.swift
|
UTF-8
| 837
| 3.359375
| 3
|
[] |
no_license
|
//
// With.swift
// technicalexam
//
// Created by iOS on 04/25/21.
// Copyright © 2021 iOS. All rights reserved.
//
import Foundation
import UIKit
protocol With { }
extension With where Self: Any {
/**
allows you to update the callee with changes in the supplied closure
let foo = SomeType().with {
$0.text = "Hello World"
$0.number = 1
}
- parameter update: the closure that will make the change
- returns: for value types, a copy of the callee with the changes in the closure applied.
For reference types, the callee with the changes in the closure applied
*/
func with(_ update: (inout Self) -> Void) -> Self {
var copy = self
update(©)
return copy
}
}
extension UIView: With { }
extension UIBarItem: With { }
| true
|
3b162806a71660dbd2b727aada140429d754b6ee
|
Swift
|
Otlichnick/Streaming
|
/Streaming/PresentationLayer/MainModule/MainPresenter.swift
|
UTF-8
| 3,292
| 2.75
| 3
|
[] |
no_license
|
//
// MainPresenter.swift
// Aster
//
// Created by Daniil Miroshnichenko on 14.03.21.
//
import UIKit
struct MainDataSource {
let section: String
let rows: [String]
}
final class MainPresenter: MainPresenterProtocol {
private weak var view: MainViewProtocol?
private let interactor: MainInteractorProtocol
private var playerManager: PlayerManagerProtocol
var dataSource = [MainDataSource]()
var playerViewHeight: CGFloat {
return playerManager.playerWindow.initialHeight
}
var currentStreamKey: String {
get {
return interactor.currentStream?.stream_key ?? ""
}
}
init(
view: MainViewProtocol,
interactor: MainInteractorProtocol,
playerManager: PlayerManagerProtocol
) {
self.view = view
self.interactor = interactor
self.playerManager = playerManager
self.playerManager.delegate = self
}
// MARK: MainPresenterProtocol
func didLoadView() {
fillDataSource()
view?.renderUI(with: "HOME")
view?.reloadData()
playerManager.playerWindow.showLoader()
interactor.fetchPlaybackURL { result in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
switch result {
case .success(let playbackURL):
self.playerManager.play(url: playbackURL)
self.playerManager.playerWindow.hideLoader()
case .failure:
self.playerManager.playerWindow.hideLoader()
}
}
}
}
func viewWillDisappear() {
playerManager.playerWindow.setPosition(.small)
}
func viewDidAppear() {
playerManager.playerWindow.setPosition(.default)
}
}
// MARK: - PlayerManagerDelegate
extension MainPresenter: PlayerManagerDelegate {
func didFinishStreaming() {
playerManager.playerWindow.showLoader()
interactor.fetchPlaybackURL { result in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
switch result {
case .success(let playbackURL):
self.playerManager.play(url: playbackURL)
self.playerManager.playerWindow.hideLoader()
case .failure:
self.playerManager.playerWindow.hideLoader()
}
}
}
}
}
// MARK: - Private methods
extension MainPresenter {
private func fillDataSource() {
dataSource = [(MainDataSource(section: "Sample Title", rows: [textStub()]))]
}
private func textStub() -> String {
return """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
}
}
| true
|
6a5d87d868154cbfb9ae7dbb8379c83ffd144f72
|
Swift
|
iMartin111/Avengers
|
/Avengers/Avengers/Models/Movie.swift
|
UTF-8
| 731
| 3.09375
| 3
|
[] |
no_license
|
//
// Movie.swift
// Avengers
//
// Created by Yan Akhrameev on 04/10/21.
//
import Foundation
class Movie: Avenger {
let description: String
var favorite: Bool = false
init(id: String, name: String, image: String, description: String) {
self.description = description
super.init(id: id, name: name, image: image)
}
}
var movies: [Movie] = [
Movie(id: "01", name: "Thor Ragnarok", image: "thorRagnarokImage", description: "Very good movie"),
Movie(id: "02", name: "Spiderman Far from Home", image: "spidermanFarFromHomeImage", description: "Very enjoyable as well."),
Movie(id: "03", name: "Iron Man 3", image: "ironMan3Image", description: "too much, it was better never to meke it.")
]
| true
|
0cccdafc68d99ff3fa91e12ed52e62cee0ec79b2
|
Swift
|
frimpongopoku/LocationHandler-plus-firebase-swift-test
|
/View Models/AuthViewModel.swift
|
UTF-8
| 1,388
| 3
| 3
|
[] |
no_license
|
import Foundation
import Firebase
class AuthViewModel : ObservableObject {
@Published var mode : String = "Login Mode"
@Published var email : String = ""
@Published var password : String = ""
@Published var hasError = false
@Published var error = ""
@Published var regMode = false
{
didSet{
if(regMode){
self.mode = "Registration Mode"
}else{
self.mode = "Login Mode"
}
}
}
func authenticate(){
Auth.auth().signIn(withEmail: self.email, password: self.password) { [weak self] response, error in
guard error == nil else {
self!.hasError = true
self!.error = error?.localizedDescription ?? "An error occured"
print (error?.localizedDescription ?? "Something happened here bro")
return
}
print("Successfully signed in bro! ")
print("Je suis le response ----> \(String(describing: response.currentUser()))")
}
}
func registerWithEmailAndPassword(){
Auth.auth().createUser(withEmail: email, password: password) { [weak self] (response, error) in
guard error == nil else {
self!.hasError = true
self!.error = error?.localizedDescription ?? "An error occured"
print (error?.localizedDescription ?? "Something happened here bro")
return
}
print("Successfully Created User in bro! ")
print("Je suis register le response ----> \(String(describing: response))")
}
}
}
| true
|
8709ba456c173b253b3aa7f78c393deca8891d84
|
Swift
|
andreap007/DogYears
|
/DogYears/ViewController.swift
|
UTF-8
| 1,616
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DogYears
//
// Created by Andrea on 31/10/2019.
// Copyright © 2019 Andrea P. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let backgroundImageView = UIImageView()
@IBOutlet weak var dogAge: UITextField!
@IBOutlet weak var label: UILabel!
@IBAction func buttonPressed(_ sender: UIButton) {
if let age = dogAge.text {
if let ageNumber = Int(age) {
let dogAgeNumber = ageNumber * 7
label.text = "Your dog is \(dogAgeNumber) years old."
}
}
}
func setBackground() {
view.addSubview(backgroundImageView)
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
backgroundImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
backgroundImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
backgroundImageView.image = UIImage(named: "cuteDog")
view.sendSubviewToBack(backgroundImageView)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setBackground()
}
}
| true
|
1ab925c70cfa910226724278ad0fdb60f2014d0d
|
Swift
|
depromeet/9th_muyaho_iOS
|
/9th_muyaho_iOS/models/AuthResponse.swift
|
UTF-8
| 460
| 2.8125
| 3
|
[] |
no_license
|
//
// AuthResponse.swift
// 9th_muyaho_iOS
//
// Created by Hyun Sik Yoo on 2021/05/01.
//
struct AuthResponse: Decodable {
let sessionId: String
enum CodingKeys: String, CodingKey {
case sessionId = "sessionId"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
sessionId = try values.decodeIfPresent(String.self, forKey: .sessionId) ?? ""
}
}
| true
|
d736ba0516a9cf48d186631ba00ca08fd6d1038f
|
Swift
|
Atoroe/WeeklyFinder
|
/WeeklyFinder/ViewController.swift
|
UTF-8
| 1,365
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WeeklyFinder
//
// Created by Artiom Poluyanovich on 26.04.21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var dayTextField: UITextField!
@IBOutlet weak var monthTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func findDayTapped() {
guard let day = dayTextField.text,
let month = monthTextField.text,
let year = yearTextField.text else {
return
}
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.day = Int(day)
dateComponents.month = Int(month)
dateComponents.year = Int(year)
let dateFormater = DateFormatter()
dateFormater.locale = Locale(identifier: "ru_Ru")
dateFormater.dateFormat = "EEEE"
guard let date = calendar.date(from: dateComponents) else { return }
let weekday = dateFormater.string(from: date)
let capitalizedWeekday = weekday.capitalized
resultLabel.text = capitalizedWeekday
}
}
extension ViewController: UITextFieldDelegate {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
| true
|
d31923da93d30b097a596dd6f7de5a60b394f1cc
|
Swift
|
igorzharii/ios-code-example
|
/Models/List.swift
|
UTF-8
| 800
| 3.015625
| 3
|
[] |
no_license
|
enum ListType: String, Codable {
case own
case room
}
class List: Codable {
var id: String = ""
var index: Int = 0
var name: String = ""
var type: ListType = .own
var songs: [RadioSong] = [RadioSong]() {
didSet {
Lister.shared.update(list: self)
}
}
init(id: String, name: String, type: ListType = .own) {
self.id = id
self.name = name
self.type = type
}
func add(_ song: RadioSong) {
if !contains(song) { songs.append(song) }
}
func remove(_ song: RadioSong) {
if contains(song) { songs = songs.filter({ $0.title != song.title }) }
}
func contains(_ song: RadioSong) -> Bool {
return songs.contains(where: { $0.title == song.title })
}
}
| true
|
7b4671e9b578c7c99eb3a8819c8459f3816c6b47
|
Swift
|
olgusirman/TwitterClient
|
/VNGRSTwitterClient/Infrastructure/Router/APIManager.swift
|
UTF-8
| 2,413
| 2.8125
| 3
|
[] |
no_license
|
//
// APIManager.swift
// HayatKurtar
//
// Created by Olgu SIRMAN on 17/04/2017.
// Copyright © 2017 Olgu Sirman. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
final public class APIManager {
// Handler typealiases
typealias success = ( ( _ responseObject : Any) -> Void )
typealias failure = ( ( _ error : Error? ) -> Void )
// MARK: - Properties
static let shared = APIManager() // Use dependency injection later instead
fileprivate lazy var manager: Alamofire.SessionManager = {
let manager = SessionManager.default
if let authToken = UserDefaults.standard.string(forKey: APIConstants.accessToken) { // Use keychain for that "access_token"
manager.adapter = AccessTokenAdapter(accessToken: authToken)
}
return manager
}()
// MARK: - Functions
func authentication(successHandler : @escaping success , failure : @escaping failure) {
Alamofire.request(Router.authentication()).validate().responseCodable { (response: DataResponse<AuthObject>) in
switch response.result {
case .success:
// Serialize
if let accessToken = response.value?.accessToken {
debugPrint("Successfully Authhenticate 👍")
UserDefaults.standard.set(accessToken, forKey: APIConstants.accessToken)
successHandler(accessToken)
} else {
//not Mapped
}
case .failure(let error):
print(error)
failure(error)
}
}
}
func search( searchRouterObject: SearchRouterObject, successHandler : @escaping ( (_ tweets : [Tweet]?) -> Void ) , failure : @escaping failure) {
manager.request(Router.search(searchRouterObject: searchRouterObject)).responseJSON { (dataResponse) in
ErrorManager.error(with: dataResponse)
switch dataResponse.result {
case .success:
if let base = Mapper<BaseObject>().map(JSONObject: dataResponse.result.value) {
successHandler(base.statuses)
}
case .failure(let error):
print(error)
ErrorManager.error(with: dataResponse)
failure(error)
}
}
}
}
| true
|
103d7357cfa1b0a9cdf526b036cc0ab91d28e5cc
|
Swift
|
jackcook/pointrun
|
/PointRun/util/Achievement.swift
|
UTF-8
| 1,687
| 2.71875
| 3
|
[] |
no_license
|
//
// Achievement.swift
// PointRun
//
// Created by Jack Cook on 9/30/14.
// Copyright (c) 2014 CosmicByte. All rights reserved.
//
import Foundation
import GCHelper
func checkAchievement(_ achievement: PRAchievement) {
let value = defaults.double(forKey: achievement.rawValue + "Default")
var percent: Double = 0
switch achievement {
case PRAchievement.MarathonMan:
percent = value * 0.002
case PRAchievement.HatTrick:
if defaults.bool(forKey: achievement.rawValue + "Completed") {
return
}
percent = value == 3 ? 100 : 0
case PRAchievement.k100:
percent = value
case PRAchievement.Addicted:
percent = value * 5
case PRAchievement.BadLuck:
percent = value * 5
case PRAchievement.Evader:
if defaults.bool(forKey: achievement.rawValue + "Completed") {
return
}
percent = value >= 100 ? 100 : 0
}
GCHelper.sharedInstance.reportAchievementIdentifier(gameCenterID(achievement), percent: percent)
defaults.set(percent >= 100, forKey: achievement.rawValue)
}
enum PRAchievement: String {
case MarathonMan = "MarathonMan",
HatTrick = "HatTrick",
k100 = "100",
Addicted = "Addicted",
BadLuck = "BadLuck",
Evader = "Evader"
}
func gameCenterID(_ achievement: PRAchievement) -> String {
switch achievement {
case .MarathonMan:
return "marathonman"
case .HatTrick:
return "hattrick"
case .k100:
return "100"
case .Addicted:
return "addicted"
case .BadLuck:
return "badluck"
case .Evader:
return "evader"
}
}
| true
|
8c513be9260a9bd05d3be456d98cfe8ecd51221b
|
Swift
|
jaycdave88/Say-It
|
/My Sound Board/NewSoundViewController.swift
|
UTF-8
| 3,835
| 2.6875
| 3
|
[] |
no_license
|
//
// NewSoundViewController.swift
// My Sound Board
//
// Created by DEV MODE on 6/7/15.
// Copyright (c) 2015 DEV MODE. All rights reserved.
//
import UIKit
import AVFoundation
import CoreData
class newSoundViewContoller : UIViewController{
required init(coder aDecoder: NSCoder) {
var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
self.audioURL = NSUUID().UUIDString + ".m4a"
var pathComponents = [baseString, self.audioURL]
var audioNSURL = NSURL.fileURLWithPathComponents(pathComponents)
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
var recordSettings: [NSObject : AnyObject] = Dictionary()
recordSettings[AVFormatIDKey] = kAudioFormatMPEG4AAC
recordSettings[AVSampleRateKey] = 44100.0
recordSettings[AVNumberOfChannelsKey] = 2
self.audioRecorder = AVAudioRecorder(URL: audioNSURL, settings: recordSettings, error: nil)
self.audioRecorder.meteringEnabled = true
self.audioRecorder.prepareToRecord()
// super init is below
super.init(coder: aDecoder )
}
@IBOutlet weak var soundTextName: UITextField!
@IBOutlet weak var recordButton: UIButton! // record button
@IBOutlet weak var textWord: UILabel! // label for user knowing
var audioRecorder: AVAudioRecorder // creating a property that has the recorder
var audioURL: String
var soundListViewController = SoundListViewController()
override func viewDidLoad() {
super.viewDidLoad()
// go n code
}
@IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil )
}
@IBAction func save(sender: AnyObject) {
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! // finding the core data
// first create a sound object
var sound = NSEntityDescription.insertNewObjectForEntityForName("Sound", inManagedObjectContext: context) as! Sound
sound.name = self.soundTextName.text // display name
sound.url = self.audioURL
// save sound to coredata
if (sound.name == ""){
alertMessage()
}else {
context.save(nil)
// dismiss this view controller
self.dismissViewControllerAnimated(true, completion: nil ) // dismiss
}
}
@IBAction func record(sender: AnyObject) {
if self.audioRecorder.recording{
self.textWord.text = "Finished Recording!" // prints message to textWord label
self.audioRecorder.stop() // if someone is already recording ... stop
// self.recordButton.setTitle("RECORD", forState: UIControlState.Normal)// changing text to record
} else {
var sessions = AVAudioSession.sharedInstance() // if no one is recording start recording
sessions.setActive(true, error: nil)
self.textWord.text = "Recording ..."
self.audioRecorder.record()
}
}
func alertMessage(){
let title = "Oops!"
let message = "Looks like you didn't add a name for your sound!"
let okayText = "OK"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayButton = UIAlertAction(title: okayText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okayButton)
presentViewController(alert, animated: true, completion: nil)
}
}
| true
|
20a844cec812eb04f3b23dbaf31df2686710bc34
|
Swift
|
RufusMall/UIKitPractice
|
/FacebookApp/Facebook/CircleImageView.swift
|
UTF-8
| 498
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// CircleImageView.swift
// Facebook
//
// Created by Rufus on 22/11/2019.
// Copyright © 2019 Rufus. All rights reserved.
//
import Foundation
import UIKit
class CircleImageView: UIImageView {
required init(image: UIImage?, diameter: CGFloat) {
super.init(image: image)
contentMode = .scaleAspectFill
layer.cornerRadius = diameter / 2
clipsToBounds = true
}
required init?(coder: NSCoder) {
fatalError("Not Implemented")
}
}
| true
|
20380ea90ab69a66a139f3f409ce48dcfd4bae49
|
Swift
|
mc3747/19_SwiftBase
|
/5_SwiftUIKit-Demo/SwiftUIKit-Demo/18_刷新组件/MJRefreshVC.swift
|
UTF-8
| 2,410
| 2.59375
| 3
|
[] |
no_license
|
//
// MJRefreshDemo.swift
// SwiftUIKit-Demo
//
// Created by 马成 on 2021/1/5.
// Copyright © 2021 马成. All rights reserved.
//
import Foundation
import UIKit
import MJRefresh
class MJRefreshVC: BaseViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
var index = 0
var data = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "RefreshLoadDemo"
self.view.backgroundColor = .white
tableView = UITableView(frame: self.view.frame)
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
self.tableView.mj_header = RefreshHeader(refreshingBlock: {
[weak self] () -> Void in
self?.headerRefresh()
})
self.tableView.mj_footer = RefreshFooter(refreshingBlock: {
[weak self] () -> Void in
self?.footerRefresh()
})
// 默认刷新一下数据
self.tableView.mj_header?.beginRefreshing()
}
@objc func headerRefresh() {
self.data.removeAll()
index = 0
self.tableView.mj_footer?.resetNoMoreData()
for _ in 0..<20 {
data.append(Int(arc4random()))
}
Thread.sleep(forTimeInterval: 1)
self.tableView.reloadData()
self.tableView.mj_header?.endRefreshing()
}
@objc func footerRefresh() {
for _ in 0..<10 {
data.append(Int(arc4random()))
}
Thread.sleep(forTimeInterval: 1)
self.tableView.reloadData()
self.tableView.mj_footer?.endRefreshing()
index = index + 1
if index > 2 {
self.tableView.mj_footer?.endRefreshingWithNoMoreData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = String(data[indexPath.row])
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
0e6b756d99e7cc4cc1bb56e911ade02e4c681641
|
Swift
|
zladzeyka/TestImportLastFMAlbums
|
/LastFMProject/Helpers&Managers/AppNavigator.swift
|
UTF-8
| 2,661
| 2.796875
| 3
|
[] |
no_license
|
//
// AppNavigator.swift
// LastFMProject
//
// Created by Nadzeya Karaban on 09.12.19.
// Copyright © 2019 Nadzeya Karaban. All rights reserved.
//
import Foundation
import UIKit
class AppNavigator: Navigator {
struct Constants {
static let searchController = "searchArtistController"
static let topAlbumsController = "albumsController"
static let albumInfoController = "albumInfoController"
static let savedAlbumsController = "savedAlbumsController"
static let mainStoryboard = "Main"
}
enum Destination {
case search
case savedAlbumDetails(albumInfo: AlbumInfo)
case topAlbums(artistName: String)
case albumDetails(album: AlbumInfo, state : ButtonState)
}
static let shared = AppNavigator()
static let window = UIApplication.shared.windows.first { $0.isKeyWindow }
var naviController = window!.rootViewController as! UINavigationController
// MARK: - Navigator
func navigate(to destination: Destination) {
let viewController = makeViewController(for: destination)
naviController.pushViewController(viewController, animated: true)
}
// MARK: - Private
private func makeViewController(for destination: Destination) -> LastFMViewController {
var identifier = ""
switch destination {
case .savedAlbumDetails(let albumInfo):
identifier = Constants.albumInfoController
let vc = UIStoryboard(name: Constants.mainStoryboard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! AlbumInfoController
vc.buttonState = .delete
vc.albumInfo = albumInfo
return vc
case .search:
identifier = Constants.searchController
return UIStoryboard(name: Constants.mainStoryboard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! LastFMViewController
case .topAlbums(let artistName):
identifier = Constants.topAlbumsController
let vc = UIStoryboard(name: Constants.mainStoryboard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! AlbumsController
vc.artistName = artistName
return vc
case .albumDetails(let album, let state):
identifier = Constants.albumInfoController
let vc = UIStoryboard(name: Constants.mainStoryboard, bundle: nil).instantiateViewController(withIdentifier: identifier) as! AlbumInfoController
vc.buttonState = state
vc.albumInfo = album
return vc
}
}
}
| true
|
ce134e55d23fa0e1663ce9767c095e527566a033
|
Swift
|
Yaruki00/TouchShooting
|
/TouchShooting/StartGameScene.swift
|
UTF-8
| 1,568
| 2.65625
| 3
|
[] |
no_license
|
//
// StartGameScene.swift
// TouchShooting
//
// Created by Yuta Kawabe on 2015/06/22.
// Copyright (c) 2015年 Yaruki00. All rights reserved.
//
import UIKit
import SpriteKit
class StartGameScene: SKScene {
override func didMove(to view: SKView) {
// StartScene settings
backgroundColor = SKColor.black
// title label
let title = SKLabelNode(fontNamed: "Chalkduster")
title.text = "TouchShooting"
title.fontSize = 40
title.fontColor = SKColor.yellow
title.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(title)
// message label
let message = SKLabelNode(fontNamed: "MarkerFelt-Thin")
message.text = "Touch Screen to Start!!"
message.fontSize = 25
message.fontColor = SKColor.brown
message.position = CGPoint(x: size.width/2, y: size.height/4)
addChild(message)
// flashing message label
message.run(SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.5),
SKAction.hide(),
SKAction.wait(forDuration: 0.5),
SKAction.unhide()
])))
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// transit to GameScene
let gameScene = GameScene(size: size)
gameScene.scaleMode = scaleMode
let transitionType = SKTransition.doorway(withDuration: 2.0)
view?.presentScene(gameScene, transition: transitionType)
}
}
| true
|
e7998b93099ae6ccbe3975397108aef9feb4e2f3
|
Swift
|
ourialkada/Dijkstra-Swift-Project
|
/dijexstra/ViewController.swift
|
UTF-8
| 5,511
| 2.953125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// dijexstra
//
// Created by Ouri -Live Care on 8/30/19.
// Copyright © 2019 Ouri Alkada. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var startSelect: UILabel!
@IBOutlet weak var answer: UILabel!
@IBOutlet weak var stopSelect: UILabel!
let firstNode = MyNode(name: "firstNode")
let secondNode = MyNode(name: "secondNode")
let thirdNode = MyNode(name: "thirdNode")
let fourthNode = MyNode(name: "fourthNode")
let fifthNode = MyNode(name: "fifthNode")
override func viewDidLoad() {
super.viewDidLoad()
// Add all nodes
// add all connections
firstNode.connections.append(Connection(to: secondNode, weight: 1))
secondNode.connections.append(Connection(to: thirdNode, weight: 3))
thirdNode.connections.append(Connection(to: fourthNode, weight: 1))
secondNode.connections.append(Connection(to: fifthNode, weight: 1))
fifthNode.connections.append(Connection(to: thirdNode, weight: 1))
}
func shortestPath(source: Node, destination: Node) -> Path? {
var frontier: [Path] = [] {
didSet { frontier.sort { return $0.cumulativeWeight < $1.cumulativeWeight } } // the frontier has to be always ordered
}
frontier.append(Path(to: source)) // the frontier is made by a path that starts nowhere and ends in the source
while !frontier.isEmpty {
let cheapestPathInFrontier = frontier.removeFirst() // getting the cheapest path available
guard !cheapestPathInFrontier.node.visited else { continue } // making sure we haven't visited the node already
if cheapestPathInFrontier.node === destination {
return cheapestPathInFrontier // found the cheapest path 😎
}
cheapestPathInFrontier.node.visited = true
for connection in cheapestPathInFrontier.node.connections where !connection.to.visited { // adding new paths to our frontier
frontier.append(Path(to: connection.to, via: connection, previousPath: cheapestPathInFrontier))
}
} // end while
return nil // we didn't find a path 😣
}
@IBAction func start(_ sender: UIButton) {
startSelect.text = "Selected: " + sender.title(for: .normal)!
}
@IBAction func End(_ sender: UIButton) {
stopSelect.text = "Selected: " + sender.title(for: .normal)!
}
@IBAction func Go(_ sender: Any) {
var sourceNode = firstNode
var destinationNode = fourthNode
switch (startSelect.text)
{
case "firstNode":
sourceNode = firstNode
break;
case "secondNode":
sourceNode = secondNode
break;
case "thirdNode":
sourceNode = thirdNode
break;
case "fourthNode":
sourceNode = fourthNode
break;
case "fifthNode":
sourceNode = fifthNode
break;
case .none:
break
case .some(_): break
}
switch (stopSelect.text)
{
case "firstNode":
destinationNode = firstNode
break;
case "secondNode":
destinationNode = secondNode
break;
case "thirdNode":
destinationNode = thirdNode
break;
case "fourthNode":
destinationNode = fourthNode
break;
case "fifthNode":
destinationNode = fifthNode
break;
case .none:
break;
case .some(_): break
}
if startSelect.text == "Selected:"
{
let alert = UIAlertController(title: "Click a start node", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
else if stopSelect.text == "Selected:"
{
let alert = UIAlertController(title: "Click a end node", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
else
{
var path = shortestPath(source: sourceNode, destination: destinationNode)
if let succession: [String] = path?.array.reversed().flatMap({ $0 as? MyNode}).map({$0.name}) {
print("🏁 Quickest path: \(succession)")
answer.text = "Quickest path: \(succession)"
} else {
print("💥 No path between \(sourceNode.name) & \(destinationNode.name)")
answer.text = "No path between \(sourceNode.name) & \(destinationNode.name)"
}
}
}
}
extension Path {
var array: [Node] {
var array: [Node] = [self.node]
var iterativePath = self
while let path = iterativePath.previousPath {
array.append(path.node)
iterativePath = path
}
return array
}
}
| true
|
7d721f91d1afc20fd28363d9bead3d13d1abf2ac
|
Swift
|
XYXiaoYuan/Leetcode
|
/Nowcoder_HW.playground/Pages/OD测试一星普通题二.xcplaygroundpage/Contents.swift
|
UTF-8
| 553
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
let string1: String? = "8"
let string2: String? = "123 124 125 121 119 122 126 123"
if let line = string1, let num = Int(line), let line = string2 {
let array: [Int] = line.split(separator: " ").map { Int($0)! }
print(array)
var result: [Int] = [Int].init(repeating: 0, count: num)
for (i, val) in array.enumerated() {
for j in (i + 1)..<num where val < array[j] {
result[i] = j
break
}
}
print(result)
// print(result.map { "\($0)" }.joined(separator: " ") )
}
| true
|
8db783f92376d9f7fc79b02dbef95363d150643b
|
Swift
|
wintelsui/LearnSwiftUI
|
/LearnSwiftUI/Routes/Simple/SimpleView.swift
|
UTF-8
| 4,441
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// SimpleView.swift
// LearnSwiftUI
//
// Created by apple on 2019/6/10.
// Copyright © 2019 wintelsui. All rights reserved.
//
import SwiftUI
struct SimpleView : View {
//状态属性参数
@State private var alertHello = false
@State private var toggleHello = false
@State private var sliderHelloValue: Double = 0.0
@State private var textFieldHello: String = ""
@State private var secureFieldHello: String = ""
@State private var datePickerHello = Date()
@State private var pickerHelloIndex: Int = 1
@State private var stepperHello: Int = 0
private let pickerHelloList = ["P1", "P2", "P3"]
var body: some View {
ScrollView(Axis.Set.vertical, showsIndicators: true) {
VStack(spacing: 10.0) {
HStack {
Image(systemName: "person.fill")
Image("aragaki")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 64.0,height: 64.0)
.clipped()
.clipShape(Circle())
Text("Hello Text!")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(Color.white)
.padding(.init(top: 0.0, leading: 10.0, bottom: 0.0, trailing: 10.0))
.multilineTextAlignment(.center)
.background(Color.yellow)
}
//按钮
Button(action: helloButtonPressed) {
Text("Hello Button!").alert(isPresented: $alertHello) { () -> Alert in
Alert(title: Text("Hello Alert:Toggle will \(toggleHello == true ? "turn on" : "turn off")"))
}
}
Toggle(isOn: $toggleHello) {
Text("Hello Toggle!")
}
HStack {
Text("TextField:").foregroundColor(.gray)
TextField("Text Placeholder",
text: $textFieldHello,
onEditingChanged: { changed in
print(" onEditingChanged:\(self.textFieldHello)")
}, onCommit: helloTextFieldonCommit).textFieldStyle(RoundedBorderTextFieldStyle())
.multilineTextAlignment(.center)
}
HStack {
//这里我暂时无法理解,为什么用String(format: "%.2f", self.sliderHelloValue)会报错
Text("Hello Slider:\(getSliderHelloString())")
Slider(value: $sliderHelloValue)
}
DatePicker(selection: $datePickerHello,
displayedComponents: [.date]){
Text("Date Picker")
}
Text("Hello DatePicker:\(getDatePickerDateString())")
Stepper(onIncrement: {
self.stepperHello += 1
}, onDecrement: {
self.stepperHello -= 1
}, label: { Text("Stepper: \(stepperHello)") })
}
}.navigationBarTitle(Text("Simple UIs"), displayMode: .inline)
}
func helloTextFieldonCommit() {
print("helloTextFieldonCommit:\(self.textFieldHello)")
UIApplication.shared.keyWindow?.endEditing(true)
}
func helloButtonPressed() {
alertHello = true
if self.toggleHello {
//Toggle无动画
self.toggleHello = !self.toggleHello
}else{
//Toggle有动画
withAnimation{
self.toggleHello.toggle()
}
}
}
func getSliderHelloString() -> String {
let number = self.sliderHelloValue
return String(format: "%.2f", number)
}
func getDatePickerDateString() -> String {
let dateformatter = DateFormatter()
dateformatter.timeZone = TimeZone.current
dateformatter.dateFormat = "YYYY/MM/dd"
let dateString = dateformatter.string(from: datePickerHello)
return dateString
}
}
#if DEBUG
struct SimpleView_Previews : PreviewProvider {
static var previews: some View {
SimpleView()
}
}
#endif
| true
|
a4a91964a85b694ca5d1b5e8cefb3aa306f71123
|
Swift
|
nelglez/LineInBottomOfViewSwiftUI
|
/LineInBottomOfViewSwiftUI/LineView.swift
|
UTF-8
| 666
| 2.984375
| 3
|
[] |
no_license
|
//
// LineView.swift
// LineInBottomOfViewSwiftUI
//
// Created by Nelson Gonzalez on 1/11/20.
// Copyright © 2020 Nelson Gonzalez. All rights reserved.
//
import SwiftUI
struct LineView: View {
var lineColor: Color
var height: CGFloat
var lineWidth: CGFloat
var body: some View {
HStack {
//This only show for active button. Width of button
Rectangle().frame(width: self.lineWidth, height: self.height).foregroundColor(self.lineColor).padding(.top, 0)
}
}
}
struct LineView_Previews: PreviewProvider {
static var previews: some View {
LineView(lineColor: Color.green, height: 1, lineWidth: 260)
}
}
| true
|
9aca3c324b4d545d5b022393f32f133dabccc4f7
|
Swift
|
MikeTheGreat/TechEase_Sprint_1
|
/TechEase/ContentView.swift
|
UTF-8
| 1,815
| 3.5625
| 4
|
[] |
no_license
|
//
// ContentView.swift
// TechEase
//
// Created by Arica Conrad, Mackenzie Fear,
// Hans Mandt, and Natalman Nahm on 4/17/21.
//
import SwiftUI
struct CascadiaCourse : Identifiable {
let id = UUID()
let img: String
let title: String
}
struct CourseRow: View {
let whichCourse: CascadiaCourse
var body: some View {
HStack {
Image(systemName: whichCourse.img)
Button(whichCourse.title){
print("button pressed")
}
}
}
}
struct ContentView: View {
let courseList = [
CascadiaCourse(img: "text.bubble.fill", title: "Texting"),
CascadiaCourse(img: "envelope.fill", title: "Email"),
CascadiaCourse(img: "phone.circle.fill", title: "Some other phone thing")
]
var body: some View {
VStack {
NavigationView {
Text("Sample Tutorials:").font(.title)
.navigationBarTitle("TechEase", displayMode: .inline)
.navigationBarItems(trailing:
HStack{
Button("back"){
print("back")
}
Button("home"){
print("home")
}
}
)
}
.frame(height: 100.0)
List(courseList) { aCourse in
CourseRow(whichCourse:aCourse)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
57d67e7c748d0069464731c6aba50a19e00f4e31
|
Swift
|
DeVitoC/ios-afternoon-project-custom-controls
|
/StarRating/StarRating/View Controllers/ViewController.swift
|
UTF-8
| 562
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// StarRating
//
// Created by Lambda_School_Loaner_259 on 3/19/20.
// Copyright © 2020 DeVitoC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func updateRating(_ ratingControl: CustomControl) {
if CustomControl.value == 1 {
title = "User Rating: 1 star"
} else {
title = "User Rating: \(CustomControl.value) stars"
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "User Rating:"
}
}
| true
|
94719dd4d23208d1976661929843d2e62aedfdf4
|
Swift
|
8secz-johndpope/DownloadingFileAsset
|
/Example/DownloadingFileAsset/SampleDataReader.swift
|
UTF-8
| 1,347
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// SampleDataReader.swift
// DownloadingFileAsset_Example
//
// Created by HANAI Tohru on 2019/07/08.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import AVFoundation
public func readSampleData(asset: AVAsset, readHandler: @escaping (_ read: TimeInterval, _ total: TimeInterval) -> Void) {
guard
let track = asset.tracks.first,
let reader = try? AVAssetReader(asset: asset)
else {
NSLog("Cannot read sample data")
return
}
let readerOutput = AVAssetReaderTrackOutput(track: track, outputSettings: nil)
readerOutput.alwaysCopiesSampleData = false
reader.add(readerOutput)
// 16-bit samples
reader.startReading()
defer { reader.cancelReading() }
var readDuration: TimeInterval = 0
var totalDuration: TimeInterval?
// var remainBytes = Int(ceil(duration.duration.seconds * Double(sampleRate))) * channelCount * MemoryLayout<Int16>.size
while let sample = readerOutput.copyNextSampleBuffer(), CMSampleBufferIsValid(sample) {
readDuration += CMSampleBufferGetDuration(sample).seconds
CMSampleBufferInvalidate(sample)
if let totalDuration = totalDuration {
readHandler(readDuration, totalDuration)
} else if 0 < asset.duration.seconds {
totalDuration = asset.duration.seconds
readHandler(readDuration, totalDuration!)
}
}
NSLog("read done")
}
| true
|
8d36f549762c8811b8ebf263e9bd50a6904d6f91
|
Swift
|
DavidonRails/InstaChain_iOS
|
/InstaChain/Generated/Colors.swift
|
UTF-8
| 3,014
| 2.65625
| 3
|
[] |
no_license
|
// swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSColor
internal typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIColor
internal typealias Color = UIColor
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Colors
// swiftlint:disable identifier_name line_length type_body_length
internal struct ColorName {
internal let rgbaValue: UInt32
internal var color: Color { return Color(named: self) }
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#25272a"></span>
/// Alpha: 100% <br/> (0x25272aff)
internal static let tabBarBackdrop = ColorName(rgbaValue: 0x25272aff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#161819"></span>
/// Alpha: 100% <br/> (0x161819ff)
internal static let tabBarHighlightBackdrop = ColorName(rgbaValue: 0x161819ff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span>
/// Alpha: 100% <br/> (0xffffffff)
internal static let tabBarHighlightIcon = ColorName(rgbaValue: 0xffffffff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#a5a5a5"></span>
/// Alpha: 100% <br/> (0xa5a5a5ff)
internal static let tabBarIcon = ColorName(rgbaValue: 0xa5a5a5ff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#115688"></span>
/// Alpha: 100% <br/> (0x115688ff)
internal static let tabBarSpecialBackdrop = ColorName(rgbaValue: 0x115688ff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#161819"></span>
/// Alpha: 100% <br/> (0x161819ff)
internal static let tabBarSpecialHighlightBackdrop = ColorName(rgbaValue: 0x161819ff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span>
/// Alpha: 100% <br/> (0xffffffff)
internal static let tabBarSpecialHighlightIcon = ColorName(rgbaValue: 0xffffffff)
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span>
/// Alpha: 100% <br/> (0xffffffff)
internal static let tabBarSpecialIcon = ColorName(rgbaValue: 0xffffffff)
}
// swiftlint:enable identifier_name line_length type_body_length
// MARK: - Implementation Details
// swiftlint:disable operator_usage_whitespace
internal extension Color {
convenience init(rgbaValue: UInt32) {
let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0
let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0
let blue = CGFloat((rgbaValue >> 8) & 0xff) / 255.0
let alpha = CGFloat((rgbaValue ) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
// swiftlint:enable operator_usage_whitespace
internal extension Color {
convenience init(named color: ColorName) {
self.init(rgbaValue: color.rgbaValue)
}
}
| true
|
06b11399dc38e78dcb6a2d69a701e63153c7823d
|
Swift
|
zigmuntb/cv
|
/MyCV/MyCV/MyCV/SectionsTableView/InfoModel.swift
|
UTF-8
| 2,989
| 2.921875
| 3
|
[] |
no_license
|
//
// InfoModel.swift
// MyCV
//
// Created by Arsenkin Bogdan on 4/19/19.
// Copyright © 2019 Arsenkin Bogdan. All rights reserved.
//
import UIKit
class InfoModel {
var contacts = ["Phone", "E-mail", "Telegram"]
var contactsInfo = ["+38(067)3534792", "zigmuntb@gmail.com", "@bodivan1"]
var info = """
Arsenkin Bogdan
14.02.1995
Single
No children
Tel : +38(067)353-47-92
E-mail: zigmuntb@gmail.com
Skype: zigmuntb
SKILLS:
SWIFT (Junior)
Currently learning Swift and on the road of becoming a proficient specialist.
Secondary skills:
Interface builder
COCOA PODS
Web services
REST APIs
GIT
XCode
UIKit
Sketch/Photoshop
HTML/CSS
CRM’s (Jira, future simple, amo)
MS Office programs
Sales
TRAININGS, SEMINARS, COURSES
25.02.2019 (2 months)
• Finished Web Academy courses (iOS DEVELOPMENT FOR BEGINNERS [SWIFT])
Learning materials:
Ray wenderlich (ios apprentice/ swift apprentice)
Lets build that app (youtube)
Ios development Blogs/Vlogs
Communication:
Able to ask, explain and participate in group conversations.
Desire to learn:
Huge desire to learn new and to sharpen my current programming skills.
PERSONAL QUALITIES:
• Initiative
• Energetic
• Stress-resistant
• Multitasking
PROFESSIONAL EXPERIENCE
09.2017–04.2018
Maya Gold Trading
Maya Gold Trading is an organic food product trading company specialised in sourcing the highest quality organic products from around the world.
International B2B sales
Sales representative. Reported to CEO and to a responsible sales manager.
Tasks and responsibilities:
● Lead scoring, phone sales (USA,Europe)
● Cold calls
● Hot calls
● Visiting european trade shows
● Push sales
● Direct sales
● Margin calculation
● Assisting client from the beginning till the moment when the product arrives
Achievements:
● Visiting international trade shows.
● Closing deals
● Training in Amsterdam office
● Selling to a client who previously declined our offers
05.2018–01.2019
Yabloko Ideas Studio
Branding agency.
Client service manager (sales representative)
Reported to CEO.
Tasks and responsibilities:
● Lead scoring
● Cold calls
● Hot calls
● Visiting trade shows
● Push sales
● Direct sales
● Follow up calls
● Project manager (1 month)
● Market research
Achievements:
● Closing deals
● Quick learner. Did different tasks, because the company is new, so there was a lot of side work that had to be done. From translations to replacing a project manager while the company was on the lookout for another one.
EDUCATION
09.2014 - 06.2017
КРОК
Export oriented management Bachelor
LANGUAGES: English (Advanced) Russian (fluent) Ukrainian (fluent)
"""
}
| true
|
9f5447328f70924c90aba767393bf58b43ddb653
|
Swift
|
Eomkicheol/RibsDaumImageSearch
|
/RibsExample/RibsExample/Scene/RIBs/RootBuilder.swift
|
UTF-8
| 1,294
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// RootBuilder.swift
// RibsExample
//
// Created by Hanzo on 2020/11/30.
//
import RIBs
protocol RootDependency: Dependency {}
final class RootComponent: Component<RootDependency> {
let rootViewController: RootViewController
init(dependency: RootDependency, rootViewController: RootViewController) {
self.rootViewController = rootViewController
super.init(dependency: dependency)
}
}
// MARK: - Builder
protocol RootBuildable: Buildable {
func build() -> (launchRouter: LaunchRouting, urlHandler: UrlHandler)
}
final class RootBuilder: Builder<RootDependency>, RootBuildable {
override init(dependency: RootDependency) {
super.init(dependency: dependency)
}
func build() -> (launchRouter: LaunchRouting, urlHandler: UrlHandler) {
let viewController = RootViewController()
let component = RootComponent(dependency: self.dependency, rootViewController: viewController)
let interactor = RootInteractor(presenter: viewController)
let homeBuilder = HomeBuilder(dependency: component)
let router = RootRouter(
interactor: interactor,
viewController: viewController,
homeBuilder: homeBuilder
)
return (router, interactor)
}
}
| true
|
457eb1353a9e06d1c129deb1b6be039cc228f411
|
Swift
|
AfaqYousafzai/TheHitchhikerProphecyTask
|
/The Hitchhiker Prophecy/Modules/Home/Home Scene/Views/HomeSceneViewController.swift
|
UTF-8
| 2,802
| 2.703125
| 3
|
[] |
no_license
|
//
// HomeSceneViewController.swift
// The Hitchhiker Prophecy
//
// Created by Mohamed Matloub on 6/10/20.
// Copyright © 2020 SWVL. All rights reserved.
//
import UIKit
class HomeSceneViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var charactersList: UICollectionView!
// MARK: - Instance variables
var interactor: HomeSceneBusinessLogic?
var router: HomeSceneRoutingLogic?
var homeCustomCollectionManager: HomeCustomCollection?
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
interactor?.fetchCharacters()
self.setupInitalView()
}
}
extension HomeSceneViewController: HomeSceneDisplayView {
func didFetchCharacters(viewModel: [HomeScene.Search.ViewModel]) {
// TODO: Implement
// here we assigned received viewmodels to out data source and delegate object and reload collection
self.homeCustomCollectionManager?.viewModels = viewModel
// to reload the collection view after the data source is ready
self.homeCustomCollectionManager?.reloadCollection()
}
func failedToFetchCharacters(error: Error) {
// TODO: Implement
print(error.localizedDescription)
// just incae we recieve error from server a ui alertview will be presented for user info
let alert = UIAlertController(title: "The Hitchhiker Prophecy", message: "Sorry we are unable to load data", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
@unknown default:
print("Will b use in future IA")
}
}))
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - Helper MEthods extension
extension HomeSceneViewController {
// To setup the inital settting of view controller
func setupInitalView() {
homeCustomCollectionManager = HomeCustomCollection(with: self.charactersList, router: self.router)
let button = UIBarButtonItem(image: nil, style: .plain, target: homeCustomCollectionManager, action: #selector(homeCustomCollectionManager?.changeLayoutButtonPressed(_:)))
button.title = "Change Layout"
button.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = button
charactersList.delegate = homeCustomCollectionManager
charactersList.dataSource = homeCustomCollectionManager
}
}
| true
|
46d97f068496950b68179b98f9b2c291e0ef9442
|
Swift
|
mohsinalimat/ZATCA
|
/ZATCA/ContentView.swift
|
UTF-8
| 1,868
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ContentView.swift
// ZATCA
//
// Created by Ahmed Abduljawad on 23/11/2021.
//
import SwiftUI
struct ContentView: View {
var qrCodegenerator = ZatcaQRCodeGenerator(tags: [
ZatcaQRCodeTag(tag: .SellerNameTag, value: "Jawad"),
ZatcaQRCodeTag(tag: .VatIdTag, value: "123456789"),
ZatcaQRCodeTag(tag: .DateTimeTag, value: "2021-11-24T11:11:11Z"),
ZatcaQRCodeTag(tag: .InvoiceTotalWithVatTag, value: "100.00"),
ZatcaQRCodeTag(tag: .InvoiceVatTag, value: "15.00"),
])
var body: some View {
GeometryReader { proxy in
VStack(spacing: 50) {
Spacer()
VStack(spacing: 20) {
Text("ZATCA QR CODE")
.font(.headline)
if qrCodegenerator.qrCodeImage != nil {
Image(systemName: "qrcode.viewfinder")
.resizable()
.frame(width: proxy.size.width - 60, height: proxy.size.height * 0.5)
} else {
Image(systemName: "qrcode.viewfinder")
.resizable()
.frame(width: 300, height: 300)
}
}
VStack(alignment: .leading, spacing: 20){
Text("Base64 Encoded String:")
HStack {
Text(qrCodegenerator.base64EncodedString ?? "⚠️")
.foregroundColor(Color.secondary)
Image(systemName: "doc.on.clipboard")
}
}
Spacer()
}
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
ef78dc565fb053689c89c7b0426c0f1323a0ad80
|
Swift
|
rshafto/ChitChat
|
/ChitChat/MessageInteractions.swift
|
UTF-8
| 1,926
| 2.875
| 3
|
[] |
no_license
|
//
// MessageInteractions.swift
// ChitChat
//
// Created by Shafto, Robin on 4/18/18.
// Copyright © 2018 Shafto, Robin. All rights reserved.
//
import Foundation
import Alamofire
import CoreLocation
func sendMessage(message: String, sendLocation: Bool) {
var lat: String = ""
var lon: String = ""
if sendLocation {
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation: CLLocation!
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){
currentLocation = locManager.location
lon = "1.2" //"\(currentLocation.coordinate.longitude)"
lat = "2.3" //"\(currentLocation.coordinate.latitude)"
}
//if (CLLocationManager.locationServicesEnabled()) {
currentLocation = locManager.location
locManager.desiredAccuracy = 1.0 // Who really knows what values these need?
locManager.distanceFilter = 1.0
locManager.startUpdatingLocation()
if locManager.location != nil {
lon = "\(currentLocation.coordinate.longitude)"
lat = "\(currentLocation.coordinate.latitude)"
}
locManager.stopUpdatingLocation()
//}*/
}
//let formattedMessage = message.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
//var url: String = "https://www.stepoutnyc.com/chitchat?key=735e6cff-5205-49b7-be80-7ec57c083aac&client=robin.shafto@mymail.champlain.edu&message="+formattedMessage!
//url += "&lat="+lat+"&lon="+lon
let url: String = "https://www.stepoutnyc.com/chitchat"
Alamofire.request(url, method: .post , parameters: ["key" : UserDefaults.standard.string(forKey: "lastUsedKey")!, "client" : UserDefaults.standard.string(forKey: "lastUsedEmail")!, "message" : message, "lat" : lat, "lon" : lon])
}
| true
|
506633ad2a1026fb98c662367c3e444fbd47ba80
|
Swift
|
alvin-martin-lee/TownHunt
|
/TownHunt-iOSApp-v2.3/TownHunt/Sound.swift
|
UTF-8
| 986
| 3.328125
| 3
|
[] |
no_license
|
//
// Sound.swift
// TownHunt App
//
// Created by Alvin Lee.
// Copyright © 2017 Alvin Lee. All rights reserved.
//
import AVFoundation // AVFoundation contains the sound management interface
import UIKit // UIKit constructs and manages the app's UI
// Equips the app with an audio player
var audioPlayer = AVAudioPlayer()
// Class which holds and plays a sound file
class Sound{
// Method which plays a specified sound file from the sound resource files
func playSound(_ soundName: String){
// Retrieves the sound file
let soundFile = URL(fileURLWithPath: Bundle.main.path(forResource: soundName, ofType: "mp3")!)
do{ // Attempts to load the sound file into the sound player
audioPlayer = try AVAudioPlayer(contentsOf: soundFile)
// Plays the sound
audioPlayer.play()
} catch{ // If sound couldn't be loaded then an error is printed
print("Error getting the audio file")
}
}
}
| true
|
2bcfd813362d9b1e166ab4569a2717623b5b6979
|
Swift
|
Macky-iOS/Trivia
|
/Trivia/Enums and Modals/Modals.swift
|
UTF-8
| 1,717
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
struct Questions{
var question: String?
var option1: String?
var option2: String?
var option3: String?
var option4: String?
var singleSelection: Bool?
init(data: [String: Any]) {
question = data["question"] as? String ?? ""
option1 = data["option1"] as? String ?? ""
option2 = data["option2"] as? String ?? ""
option3 = data["option3"] as? String ?? ""
option4 = data["option4"] as? String ?? ""
singleSelection = data["singleSelection"] as? Bool ?? false
}
}
class GameResult{
var name = String()
var questionSet = [QuestionAnswerSet]()
var date = String()
var time = String()
convenience init(data: [String: Any]){
self.init()
name = data["name"] as? String ?? ""
date = data["date"] as? String ?? ""
time = data["time"] as? String ?? ""
let set = data["questonSet"] as? [[String: Any]] ?? []
for each in set{
var question = QuestionAnswerSet()
question.question = each["question"] as? String ?? ""
question.answer = each["answer"] as? String ?? ""
questionSet.append(question)
}
}
func convertToDict() -> [String: Any]{
var dictQuestions = [[String: Any]]()
for each in questionSet{
let dict: [String: Any] = ["question": each.question, "answer": each.answer]
dictQuestions.append(dict)
}
let param: [String: Any] = ["name": name, "questonSet": dictQuestions, "date": date, "time": time]
return param
}
}
struct QuestionAnswerSet{
var question = String()
var answer = String()
}
| true
|
9a8767d6824f1ffdae011327ca089a8b5995b4f2
|
Swift
|
pz2372/EllerbeCreek
|
/EllerbeCreek/Features/Sighting/SightingNavigator.swift
|
UTF-8
| 1,559
| 2.78125
| 3
|
[] |
no_license
|
//
// SightingNavigator.swift
// Ellerbe Creek
//
// Created by Ryan Anderson on 2/14/20.
// Copyright © 2020 Ryan Anderson. All rights reserved.
//
import UIKit
class SightingNavigator: Navigator {
enum Destination {
case gameMap
case sightingDetail(_ sighting: Sighting)
}
var dependencyContainer: CoreDependencyContainer & KeyValueStorable
init(dependencyContainer: CoreDependencyContainer & KeyValueStorable) {
self.dependencyContainer = dependencyContainer
}
func navigate(to destination: SightingNavigator.Destination) {
let viewController = makeViewController(for: destination)
dependencyContainer.navigationController.viewControllers = [viewController]
}
func present(_ destination: Destination, with presentationStyle: UIModalPresentationStyle = .fullScreen) {
if let rootController = dependencyContainer.navigationController.viewControllers.first {
let viewController = makeViewController(for: destination)
viewController.modalPresentationStyle = presentationStyle
rootController.present(viewController, animated: true, completion: nil)
}
}
private func makeViewController(for destination: Destination) -> UIViewController {
switch destination {
case .gameMap:
return dependencyContainer.makeGameMapViewController()
case .sightingDetail(let sighting):
return dependencyContainer.makeSightingDetailViewController(sighting: sighting)
}
}
}
| true
|
02bcf297595b00595662484435511d2e1fdce1cc
|
Swift
|
Nag91777/DiSYS
|
/DiSYS/NewsDataModel.swift
|
UTF-8
| 987
| 2.96875
| 3
|
[] |
no_license
|
//
// NewsDataModel.swift
// HGS
//
// Copyright © 2019 DEFTeam. All rights reserved.
//
import Foundation
class NewsDataModel {
var title: String = ""
var date: String = ""
var desc: String = ""
var imgUrl: String = ""
class func getNewsDataModel(dict: [String: Any]) -> NewsDataModel {
let newsDataModel = NewsDataModel()
newsDataModel.title = String.giveMeProperString(str: dict["title"])
newsDataModel.desc = String.giveMeProperString(str: dict["description"])
newsDataModel.date = String.giveMeProperString(str: dict["date"])
newsDataModel.imgUrl = String.giveMeProperString(str: dict["image"])
return newsDataModel
}
class func getAllNewsModelsData(arr: [[String: Any]]) -> [NewsDataModel] {
var newsModels = [NewsDataModel]()
for dict in arr {
newsModels.append(NewsDataModel.getNewsDataModel(dict: dict))
}
return newsModels
}
}
| true
|
86c296d886234cbc898086963cad79e5eff50ce7
|
Swift
|
nuclearace/playground
|
/Sources/Playground/string.swift
|
UTF-8
| 4,065
| 2.9375
| 3
|
[] |
no_license
|
//
// Created by Erik Little on 2019-03-19.
//
import Foundation
public extension String {
private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)")
var isPalindrome: Bool { Playground.isPalindrome(self) }
func splitOnChanges() -> [String] {
guard !isEmpty else {
return []
}
var res = [String]()
var workingChar = first!
var workingStr = "\(workingChar)"
for char in dropFirst() {
if char != workingChar {
res.append(workingStr)
workingStr = "\(char)"
workingChar = char
} else {
workingStr += String(char)
}
}
res.append(workingStr)
return res
}
func textBetween(_ startDelim: String, and endDelim: String) -> String {
precondition(!startDelim.isEmpty && !endDelim.isEmpty)
let startIdx: String.Index
let endIdx: String.Index
if startDelim == "start" {
startIdx = startIndex
} else if let r = range(of: startDelim) {
startIdx = r.upperBound
} else {
return ""
}
if endDelim == "end" {
endIdx = endIndex
} else if let r = self[startIdx...].range(of: endDelim) {
endIdx = r.lowerBound
} else {
endIdx = endIndex
}
return String(self[startIdx..<endIdx])
}
func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String {
guard separator != "" else {
return self
}
let sep = Array(separator)
let startIdx = index(startIndex, offsetBy: start)
let matches = String.commaReg.matches(in: self, range: NSRange(startIdx..., in: self))
guard !matches.isEmpty else {
return self
}
let fullMatch = String(self[Range(matches.first!.range(at: 0), in: self)!])
let splits = fullMatch.components(separatedBy: ".")
var ip = splits[0]
if ip.count > period {
var builder = Array(ip.reversed())
for i in stride(from: (ip.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
ip = String(builder.reversed())
}
if fullMatch.contains(".") {
var dp = splits[1]
if dp.count > period {
var builder = Array(dp)
for i in stride(from: (dp.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
dp = String(builder)
}
ip += "." + dp
}
return String(prefix(start)) + String(dropFirst(start)).replacingOccurrences(of: fullMatch, with: ip)
}
func tokenize(separator: Character, escape: Character) -> [String] {
var token = ""
var tokens = [String]()
var chars = makeIterator()
while let char = chars.next() {
switch char {
case separator:
tokens.append(token)
token = ""
case escape:
if let next = chars.next() {
token.append(next)
}
case _:
token.append(char)
}
}
tokens.append(token)
return tokens
}
}
@inlinable
public func isPalindrome<T: CustomStringConvertible>(_ x: T) -> Bool {
let asString = String(describing: x)
for (c, c1) in zip(asString, asString.reversed()) where c != c1 {
return false
}
return true
}
extension String {
public func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) {
var matches = [Substring]()
var matched = [(String, (String.Index, String.Index))]()
var i = startIndex
var lastMatch = startIndex
main: while i != endIndex {
for sep in seps where self[i...].hasPrefix(sep) {
if i > lastMatch {
matches.append(self[lastMatch..<i])
} else {
matches.append("")
}
lastMatch = index(i, offsetBy: sep.count)
matched.append((sep, (i, lastMatch)))
i = lastMatch
continue main
}
i = index(i, offsetBy: 1)
}
if i > lastMatch {
matches.append(self[lastMatch..<i])
}
return (matches, matched)
}
}
| true
|
35d5a7935e343d1b3998f39f9c0aca2e4a7bf503
|
Swift
|
psotoulloa/Todoey
|
/Todoey/Models/Item.swift
|
UTF-8
| 235
| 2.59375
| 3
|
[] |
no_license
|
//
// Item.swift
// Todoey
//
// Created by Patricio Soto on 3/4/19.
// Copyright © 2019 Patricio Soto. All rights reserved.
//
import Foundation
class Item: Encodable , Decodable{
var title : String = ""
var done : Bool = false
}
| true
|
47922b65743e46e24ae2f432c426cce0d9f8816f
|
Swift
|
raunakp/RPDownloadManager
|
/Example/RPDownloadManager/JSONUtils.swift
|
UTF-8
| 634
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// JSONUtils.swift
// CacheDemoTests
//
// Created by Raunak Poddar on 14/10/19.
// Copyright © 2019 Raunak. All rights reserved.
//
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
| true
|
7178588997638da688036bd0ac7727e7ab278419
|
Swift
|
Zuping/LeetCode-swift
|
/LeetCode/UnitTest/Solution300Test.swift
|
UTF-8
| 656
| 2.546875
| 3
|
[] |
no_license
|
//
// Solution300Test.swift
// LeetCodeTest
//
// Created by zuping on 10/21/18.
// Copyright © 2018 zuping. All rights reserved.
//
import XCTest
class Solution300Test: XCTestCase {
func test1() {
let result = Solution300().lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])
assert(result == 4)
}
func test2() {
let result = Solution300().lengthOfLIS([])
assert(result == 0)
}
func test3() {
let result = Solution300().lengthOfLIS([1, 2])
assert(result == 2)
}
func test4() {
let result = Solution300().lengthOfLIS([-2, -1])
assert(result == 2)
}
}
| true
|
a0e05a28bc20b2a9766df5077870070009c7ee4b
|
Swift
|
hoyinc/Swift-Hackaton
|
/Numero/GameOverViewController.swift
|
UTF-8
| 819
| 2.921875
| 3
|
[] |
no_license
|
//
// GameOverViewController.swift
// Numero
//
// Created by Sunny Cheung on 22/11/14.
// Copyright (c) 2014 Ho Yin Cheung. All rights reserved.
//
import UIKit
class GameOverViewController: UIViewController {
var score:Int!
@IBOutlet var scoreLabel:UILabel!
var delegate:GameOverDelegate!
override func viewDidLoad() {
super.viewDidLoad()
self.scoreLabel.text = NSString(format: "%d/10", score)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func newGame() {
self.delegate.restartGame()
self.dismissViewControllerAnimated(true , completion: nil)
}
func updateScore(score:Int) {
self.score = score
}
}
protocol GameOverDelegate {
func restartGame()
}
| true
|
44567a2ae6b23ac0a26ed7f22eeed829c4569c56
|
Swift
|
rhayes22/SampleCode2021
|
/Memory/Memory/Views/GuessButtonView.swift
|
UTF-8
| 855
| 3.140625
| 3
|
[] |
no_license
|
//
// GuessButtonView.swift
// Memory
//
// Created by jjh9 on 9/1/20.
// Copyright © 2020 jjh9. All rights reserved.
//
import SwiftUI
struct GuessButtonView : View {
@EnvironmentObject var memoryViewModel : MemoryManager
let index : Int //specifies which button
let labelFontSize : CGFloat = 100
var body: some View {
let gamePiece = memoryViewModel.gamePieceFor(index: index)
return Button(action: {memoryViewModel.nextGuess(guess: index)}) {
GamePieceView(gamePiece: gamePiece, fontSize: labelFontSize)
}
.disabled(memoryViewModel.shouldDisableGuessButton)
}
}
struct ColorButtonView_Previews: PreviewProvider {
static var previews: some View {
GuessButtonView(index: 0)
.environmentObject(MemoryManager())
}
}
| true
|
28799fe105f1dd5e6d6a944a1c83de302ac7ff0b
|
Swift
|
olinaser/final
|
/Final Project/SlotsViewController.swift
|
UTF-8
| 6,444
| 2.59375
| 3
|
[] |
no_license
|
//
// SlotsViewController.swift
// Final Project
//
// Created by oliver naser on 12/3/17.
// Copyright © 2017 oliver naser. All rights reserved.
//
import UIKit
import AVFoundation
class SlotsViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var balance : Int!
@IBOutlet weak var slotOne: UIImageView!
@IBOutlet weak var slotTwo: UIImageView!
@IBOutlet weak var slotThree: UIImageView!
@IBOutlet weak var resultsLabel: UILabel!
@IBOutlet weak var currentBalanceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
print("\(balance)")
updateCurrentBalanceLabel()
}
func updateCurrentBalanceLabel() {
currentBalanceLabel.text = String(balance)
}
func playSound(soundName: String, audioPlayer: inout AVAudioPlayer) {
if let sound = NSDataAsset(name: soundName) {
do {
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.play()
} catch {
print("ERROR: Data from \(soundName) could not be played as an audio file")
}
} else {
print("ERROR: Could not load datea from file \(soundName)")
}
}
func animateSlotOne() {
let bounds = self.slotOne.bounds
let shrinkValue: CGFloat = 60
self.slotOne.bounds = CGRect(
x: self.slotOne.bounds.origin.x + shrinkValue,
y: self.slotOne.bounds.origin.y + shrinkValue, width: self.slotOne.bounds.size.width - shrinkValue, height: self.slotOne.bounds.size.height - shrinkValue)
UIView.animate(withDuration: 1, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { self.slotOne.bounds = bounds }, completion: nil)
}
func animateSlotTwo() {
let bounds = self.slotTwo.bounds
let shrinkValue: CGFloat = 60
self.slotTwo.bounds = CGRect(
x: self.slotTwo.bounds.origin.x + shrinkValue,
y: self.slotTwo.bounds.origin.y + shrinkValue, width: self.slotTwo.bounds.size.width - shrinkValue, height: self.slotTwo.bounds.size.height - shrinkValue)
UIView.animate(withDuration: 1, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { self.slotTwo.bounds = bounds }, completion: nil)
}
func animateSlotThree() {
let bounds = self.slotThree.bounds
let shrinkValue: CGFloat = 60
self.slotThree.bounds = CGRect(
x: self.slotThree.bounds.origin.x + shrinkValue,
y: self.slotThree.bounds.origin.y + shrinkValue, width: self.slotThree.bounds.size.width - shrinkValue, height: self.slotThree.bounds.size.height - shrinkValue)
UIView.animate(withDuration: 1, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { self.slotThree.bounds = bounds }, completion: nil)
}
@IBAction func slotRolled(_ sender: Any) {
var slotRandomOne = arc4random_uniform(3)
var slotRandomTwo = arc4random_uniform(3)
var slotRandomThree = arc4random_uniform(3)
var BCLogoCount = 0
var sevenCount = 0
var letterXCount = 0
switch slotRandomOne {
case 0:
slotOne.image = UIImage(named:"BCLogo")
BCLogoCount += 1
case 1:
slotOne.image = UIImage(named: "seven")
sevenCount += 1
case 2:
slotOne.image = UIImage(named:"letterX")
letterXCount += 1
default:
print("whoops")
}
switch slotRandomTwo {
case 0:
slotTwo.image = UIImage(named:"BCLogo")
BCLogoCount += 1
case 1:
slotTwo.image = UIImage(named: "seven")
sevenCount += 1
case 2:
slotTwo.image = UIImage(named:"letterX")
letterXCount += 1
default:
print("whoops")
}
switch slotRandomThree {
case 0:
slotThree.image = UIImage(named:"BCLogo")
BCLogoCount += 1
case 1:
slotThree.image = UIImage(named: "seven")
sevenCount += 1
case 2:
slotThree.image = UIImage(named:"letterX")
letterXCount += 1
default:
print("whoops")
}
if BCLogoCount == 2 {
resultsLabel.text = "Congrats, you won 3 coins"
balance = balance + 3
playSound(soundName: "appluaseSound", audioPlayer: &audioPlayer)
} else if BCLogoCount == 3 {
resultsLabel.text = "Congrats, you won 8 coins"
balance = balance + 8
playSound(soundName: "appluaseSound", audioPlayer: &audioPlayer)
animateSlotOne()
animateSlotTwo()
animateSlotThree()
}
if sevenCount == 2 {
resultsLabel.text = "Congrats, you won 1 coin"
balance = balance + 1
playSound(soundName: "appluaseSound", audioPlayer: &audioPlayer)
} else if sevenCount == 3 {
resultsLabel.text = "Jackpot!!! 20 Coins!!!"
balance = balance + 20
playSound(soundName: "jackpotSound", audioPlayer: &audioPlayer)
animateSlotOne()
animateSlotTwo()
animateSlotThree()
}
if sevenCount == 1 && BCLogoCount == 1 && letterXCount == 1 {
resultsLabel.text = "try again!"
} else if letterXCount == 2 {
resultsLabel.text = "Tough luck, -10 coin!"
balance = balance - 10
playSound(soundName: "loseSound", audioPlayer: &audioPlayer)
} else if letterXCount == 3 {
resultsLabel.text = "Ouch! -25 coins!"
balance = balance - 25
playSound(soundName: "loseSound", audioPlayer: &audioPlayer)
}
letterXCount = 0
sevenCount = 0
BCLogoCount = 0
updateCurrentBalanceLabel()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! BalanceVC
destination.balance = balance
}
}
| true
|
e7422e79bcbd46c73c5d62d31baf7b23c844ed8a
|
Swift
|
DaRkViRuS2012/Emall
|
/E-MALL/PageCell.swift
|
UTF-8
| 4,664
| 2.640625
| 3
|
[] |
no_license
|
//
// PageCell.swift
// Audible
//
// Created by Nour on 12/8/16.
// Copyright © 2016 Nour . All rights reserved.
//
import UIKit
class PageCell: UICollectionViewCell {
var ratio = 0.566
var bgColor:UIColor = UIColor.red{
didSet{
self.backgroundColor = bgColor
}
}
var page:Page?{
didSet{
guard let page = page else {
return
}
imageview.image = UIImage(named: "\(page.image)")
// let color = UIColor(white: 0.2, alpha: 1)
let attributedtext = NSMutableAttributedString(string: page.title, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium)
,NSForegroundColorAttributeName: UIColor.black])
attributedtext.append(NSAttributedString(string: "\n\n\(page.message)", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName:UIColor.black]))
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let length = attributedtext.string.characters.count
attributedtext.addAttributes([NSParagraphStyleAttributeName : paragraph], range: NSRange(location:0,length:length))
textview.attributedText = attributedtext
// textview.text = page.title + "\n\n" + page.message
}
}
override init(frame: CGRect) {
super.init(frame: frame)
ratio = Double(UIScreen.main.bounds.width / 750)
prepareView()
}
func injected() {
prepareView()
print("I've been injected: \(self)")
}
let textview:UITextView = {
let tv = UITextView()
tv.isEditable = false
tv.contentInset = UIEdgeInsets(top: 24, left: 0, bottom: 0, right: 0)
tv.textColor = .black
tv.backgroundColor = .white
return tv
}()
let overlay:UIView = {
let v = UIView()
v.backgroundColor = UIColor(white: 0, alpha: 0.2)
return v
}()
let container:UIView = {
let iv = UIView()
// iv.layer.cornerRadius = 10
iv.layer.masksToBounds = true
iv.layer.borderColor = UIColor.lightGray.cgColor
iv.layer.borderWidth = 0.5
iv.layer.shadowColor = UIColor.black.cgColor
iv.layer.shadowOpacity = 1
iv.layer.shadowOffset = CGSize(width: -15, height: 20)
iv.layer.shadowRadius = 10
iv.layer.shadowPath = UIBezierPath(rect: iv.bounds).cgPath
iv.layer.shouldRasterize = true
return iv
}()
let lineView:UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.9, alpha: 1)
return view
}()
let imageview:UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.image = UIImage(named: "page1")
iv.clipsToBounds = true
return iv
}()
func prepareView() {
addSubview(container)
container.addSubview(imageview)
// container.addSubview(overlay)
container.addSubview(textview)
container.addSubview(lineView)
_ = container.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: CGFloat(0 * ratio), leftConstant: CGFloat(0 * ratio), bottomConstant: 0, rightConstant: 0, widthConstant: CGFloat(0 * ratio), heightConstant: CGFloat(0 * ratio))
// overlay.anchorToTop(container.topAnchor, left: container.leftAnchor, bottom: container.bottomAnchor, right: container.rightAnchor)
imageview.anchorToTop(container.topAnchor, left: container.leftAnchor, bottom: textview.topAnchor, right: container.rightAnchor)
textview.anchorToTop(nil, left: container.leftAnchor, bottom: container.bottomAnchor, right: container.rightAnchor)
textview.heightAnchor.constraint(equalTo: container.heightAnchor , multiplier: 0.33).isActive = true
lineView.anchorToTop(nil, left: container.leftAnchor, bottom: textview.topAnchor, right: container.rightAnchor)
lineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
e6cfec423eff2b084b600bd9e95e9b7582e11d06
|
Swift
|
RickBr0wn/Ultimate-Gaming-Quiz
|
/Ultimate Gaming Quiz/Views/Sub Views/HeaderView.swift
|
UTF-8
| 1,380
| 3.265625
| 3
|
[] |
no_license
|
//
// HeaderView.swift
// Ultimate Gaming Quiz
//
// Created by Rick Brown on 11/03/2021.
//
import SwiftUI
struct HeaderView: View {
let score: Int
let questionNumber: Int
let font = Constants.primaryFont.rawValue
let fontSize: CGFloat = 28
let numberOfQuestions = Settings.shared.numberOfQuestions
var body: some View {
ZStack {
HStack {
Text("\(score)")
.font(.custom(font, size: fontSize))
Spacer()
Text("\(questionNumber)/\(numberOfQuestions.rawValue)")
.font(.custom(font, size: fontSize))
}
.padding()
.font(.custom(font, size: 22))
.foregroundColor(.mainDarkColor)
.frame(width: 350, height: 50, alignment: .center)
.background(Color.backgroundColor)
Circle()
.frame(width: 62, height: 62, alignment: .center)
Circle()
.fill(Color.backgroundColor.opacity(0.9))
.frame(width: 50, height: 50, alignment: .center)
Text("\(numberOfQuestions.rawValue)")
.font(.custom(font, size: 26))
.fontWeight(.bold)
.foregroundColor(.mainDarkColor)
}
.cornerRadius(200)
.shadow(radius: 10)
}
}
struct HeaderView_Previews: PreviewProvider {
static var previews: some View {
HeaderView(score: 5, questionNumber: 1)
.previewLayout(.sizeThatFits)
}
}
| true
|
bacd0310a2c428e6490d97d4780ad17bfa37e285
|
Swift
|
antochan/Celeste-Private-iOS
|
/Celeste/Celeste/View/GiftCouponView.swift
|
UTF-8
| 3,699
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// GiftCouponView.swift
// Celeste
//
// Created by Antonio Chan on 2020/9/12.
// Copyright © 2020 Antonio Chan. All rights reserved.
//
import UIKit
import TextFieldEffects
class GiftCouponView: UIView {
private let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .carosMedium(size: 21)
label.textColor = UIColor.AppColors.black
label.text = "Gift a Coupon"
label.textAlignment = .center
return label
}()
let couponTitleTextField: HoshiTextField = {
let textfield = HoshiTextField()
textfield.translatesAutoresizingMaskIntoConstraints = false
textfield.borderInactiveColor = .gray
textfield.borderActiveColor = .black
textfield.font = .caros(size: 15)
textfield.placeholder = "Coupon Title"
textfield.placeholderColor = .gray
return textfield
}()
let couponDescriptionTextField: HoshiTextField = {
let textfield = HoshiTextField()
textfield.translatesAutoresizingMaskIntoConstraints = false
textfield.borderInactiveColor = .gray
textfield.borderActiveColor = .black
textfield.font = .caros(size: 15)
textfield.placeholder = "Coupon Description"
textfield.placeholderColor = .gray
return textfield
}()
let submitButton: ButtonComponent = {
let button = ButtonComponent()
button.translatesAutoresizingMaskIntoConstraints = false
button.apply(viewModel: ButtonComponent.ViewModel(style: .primary, text: "Submit"))
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - Private
private extension GiftCouponView {
func commonInit() {
backgroundColor = .white
configureSubviews()
configureLayout()
}
func configureSubviews() {
addSubviews(titleLabel, couponTitleTextField, couponDescriptionTextField, submitButton)
}
func configureLayout() {
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 60.0),
titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
couponTitleTextField.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: Spacing.sixteen),
couponTitleTextField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Spacing.twentyFour),
couponTitleTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Spacing.twentyFour),
couponTitleTextField.heightAnchor.constraint(equalToConstant: 60),
couponDescriptionTextField.topAnchor.constraint(equalTo: couponTitleTextField.bottomAnchor, constant: Spacing.sixteen),
couponDescriptionTextField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Spacing.twentyFour),
couponDescriptionTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Spacing.twentyFour),
couponDescriptionTextField.heightAnchor.constraint(equalToConstant: 60),
submitButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Spacing.fortyEight),
submitButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Spacing.twentyFour),
submitButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Spacing.twentyFour),
])
}
}
| true
|
19f1264a309e3ec6c5b916e87d3fe819e3b8b6d1
|
Swift
|
brianhawking/Mad107-2
|
/week6/Arrays.playground/Contents.swift
|
UTF-8
| 2,852
| 4.65625
| 5
|
[] |
no_license
|
// Playground - noun: a place where people can play
import UIKit
var str = "Welcome to the Array playground"
// Array Literals
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
// Accessing and Moditying Arrays
print("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."
// Empty?
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// prints "The shopping list is not empty."
// Append Item - using methood
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes
print(shoppingList.count)
// using assignment operator
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
print(shoppingList.count)
// append an array of compatible items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
print(shoppingList.count)
// retrieve items in an array
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"
// change an existing value
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"
// change a bunch of values
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
print(shoppingList.count)
// put something in a specific spot
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
print(shoppingList[0])
// remove something
let mapleSyrup = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string
print(shoppingList.count)
// remove the last item
let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no cheese
// the apples constant is now equal to the removed "Apples" string
print(shoppingList.count)
// Iterating thru an array
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
// Creating and Initializing arrays
// Empty
var someInts = [Int]()
print("someInts is of type Int[] with \(someInts.count) items.")
// prints "someInts is of type Int[] with 0 items."
// Size & Type
var threeDoubles = [Double](repeating: 0.0, count: 3)
// threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]
// Adding Arrays
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as Double[], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
| true
|
6b554266b9ddab9eb2ed0b23a27ad441129bb1d9
|
Swift
|
ArturRuZ/Phonebook
|
/Phonebook/Services/InternetService/InternetService.swift
|
UTF-8
| 1,596
| 2.921875
| 3
|
[] |
no_license
|
//
// InternetService.swift
// Phonebook
//
// Created by Артур on 26/07/2019.
// Copyright © 2019 Артур. All rights reserved.
//
import Foundation
final class InternetService {
// MARK: - Properties
private var downloadQueue = OperationQueue()
// MARK: - Initialization
init() {
downloadQueue.name = "Download queue"
downloadQueue.maxConcurrentOperationCount = 1
}
// MARK: - Private methods
private func parse<T>(data: Data, container: T.Type, completion: @escaping (Result<T>) -> Void) where T: Codable {
do {
let response = try JSONDecoder().decode(container, from: data)
DispatchQueue.main.async {
completion(Result(value: response))
}
} catch {
completion (Result(error: error))
}
}
}
// MARK: - InternetServiceProtocol implementation
extension InternetService: InternetServiceProtocol {
func downloadData<T>(fromURL: URL?, parseInto container: T.Type, completion: @escaping (Result<T>) -> Void) where T: Codable {
guard let url = fromURL else {
completion(Result(error: ErrorsList.urlIsIncorrect))
return
}
downloadQueue.cancelAllOperations()
downloadQueue.addOperation (
DownloadOperation(url: url, completion: { [weak self] result in
guard let self = self else { return }
if let error = result.error {
completion(Result(error: error))
} else {
guard let data = result.success else { return }
self.parse(data: data, container: container, completion: completion)
}
})
)
}
}
| true
|
629f27415d3ca6301974bb0711cbe36f7f0113e7
|
Swift
|
VikashHart/PhotoBooth
|
/PhotoBooth/Components/Extensions/UIView+Shimmer.swift
|
UTF-8
| 3,049
| 2.828125
| 3
|
[] |
no_license
|
import UIKit
class TripleStripeMaskLayer: CAShapeLayer {
func drawPath() {
let mutablePath = CGMutablePath()
mutablePath.addPath(firstStripePath())
mutablePath.addPath(secondStripePath())
mutablePath.addPath(thirdStripePath())
self.path = mutablePath
}
private func firstStripePath() -> CGPath {
let points: [CGPoint] = [
CGPoint(x: 0, y: 0),
CGPoint(x: frame.width * 0.1, y: 0),
CGPoint(x: frame.width * 0.4, y: frame.height),
CGPoint(x: frame.width * 0.3, y: frame.height)
]
return path(with: points)
}
private func secondStripePath() -> CGPath {
let points: [CGPoint] = [
CGPoint(x: frame.width * 0.2, y: 0),
CGPoint(x: frame.width * 0.4, y: 0),
CGPoint(x: frame.width * 0.7, y: frame.height),
CGPoint(x: frame.width * 0.5, y: frame.height)
]
return path(with: points)
}
private func thirdStripePath() -> CGPath {
let points: [CGPoint] = [
CGPoint(x: frame.width * 0.6, y: 0),
CGPoint(x: frame.width * 0.7, y: 0),
CGPoint(x: frame.width, y: frame.height),
CGPoint(x: frame.width * 0.9, y: frame.height)
]
return path(with: points)
}
private func path(with corners: [CGPoint]) -> CGPath {
let path = UIBezierPath()
guard let first = corners.first else {
return path.cgPath
}
path.move(to: first)
for point in corners[1...] {
path.addLine(to: point)
}
path.addLine(to: first)
return path.cgPath
}
}
extension UIView {
func animateShimmer(withMask mask: UIView,
shimmerWidth: CGFloat,
maskColor: UIColor,
duration: CFTimeInterval = 0.6,
repeatCount: Float = 1,
insertionPoint: Int = 0) {
mask.backgroundColor = maskColor
let maskheight = mask.frame.height
let stripeLayer = TripleStripeMaskLayer() //CAShapeLayer()
stripeLayer.frame = CGRect(x: -shimmerWidth, y: 0, width: shimmerWidth, height: maskheight)
mask.layer.mask = stripeLayer
self.insertSubview(mask, at: insertionPoint)
stripeLayer.drawPath()
stripeLayer.fillColor = UIColor.blue.cgColor
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = stripeLayer.position
animation.toValue = CGPoint(x: mask.frame.maxX + shimmerWidth / 2,
y: mask.frame.midY)
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animation.duration = duration
animation.repeatCount = repeatCount
CATransaction.setCompletionBlock {
mask.removeFromSuperview()
}
stripeLayer.add(animation, forKey: "shimmer")
CATransaction.commit()
}
}
| true
|
3d4f3fbc83df078507250ed383d94d27a4c96bca
|
Swift
|
konstatinblagok/react-native-OnDemand-app
|
/Plumbal/Plumbal/SearchBarTableViewCell.swift
|
UTF-8
| 1,656
| 2.640625
| 3
|
[] |
no_license
|
//
// SearchBarTableViewCell.swift
// Plumbal
//
// Created by Casperon iOS on 15/12/2016.
// Copyright © 2016 Casperon Tech. All rights reserved.
//
import UIKit
class SearchBarTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//MARK: - Function
func configureCellWith(searchTerm:String, cellText:String){
var pattern = searchTerm.replacingOccurrences(of: " ", with: "|")
pattern.insert("(", at: pattern.startIndex)
pattern.insert(")", at: pattern.endIndex)
do {
let regEx = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive,
.allowCommentsAndWhitespace])
let range = NSRange(location: 0, length: cellText.count)
let displayString = NSMutableAttributedString(string: cellText)
let highlightColour = PlumberThemeColor
regEx.enumerateMatches(in: cellText, options: .withTransparentBounds, range: range, using: { (result, flags, stop) in
if result?.range != nil {
// displayString.setAttributes([NSBackgroundColorAttributeName:highlightColour], range: result!.range)
}
})
self.textLabel?.attributedText = displayString
} catch
{
self.textLabel?.text = cellText
}
}
}
| true
|
63d1905e1db7db375bb8678fb5ef742b43a9037d
|
Swift
|
YusufCakan/Compiler-Deconstruction
|
/Oberon-0-AST/Oberon Compiler Unit Tests/ParsingTests/Statements/ParsingIfStatement_UnitTests.swift
|
UTF-8
| 3,385
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
// Copyright 2019 Chip Jarred
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
// ----------------------------------
class ParsingIfStatement_UnitTests: XCTestCase
{
// ----------------------------------
func test_parses_simple_if_statement()
{
let code =
"""
IF x = y THEN
x := y + 1
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {x = (y + 1)}, {}}")
}
// ----------------------------------
func test_parses_simple_if_statement_with_else()
{
let code =
"""
IF x = y THEN
x := y + 1
ELSE
y := y DIV 2;
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {x = (y + 1)}, {y = (y DIV 2)}}")
}
// ----------------------------------
func test_parses_simple_if_statement_with_elsif()
{
let code =
"""
IF x = y THEN
x := y + 1
ELSIF x < y THEN
y := y DIV 2;
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {x = (y + 1)}, ELSIF{(x < y), {y = (y DIV 2)}, {}}}")
}
// ----------------------------------
func test_parses_simple_if_statement_with_elsif_and_else()
{
let code =
"""
IF x = y THEN
x := y + 1
ELSIF x < y THEN
y := y DIV 2
ELSE
y := y * 2
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {x = (y + 1)}, ELSIF{(x < y), {y = (y DIV 2)}, {y = (y * 2)}}}")
}
// ----------------------------------
func test_parses_if_statement_nested_in_then_block()
{
let code =
"""
IF x = y THEN
IF a > b THEN
x := a
ELSE
x := b
END
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {IF{(a > b), {x = a}, {x = b}}}, {}}")
}
// ----------------------------------
func test_parses_if_statement_nested_in_else_block()
{
let code =
"""
IF x = y THEN
x := y + 1
ELSE
IF a > b THEN
x := a
ELSE
x := b
END
END;
"""
guard let ast = parseStatement(code) else { return }
let result = "\(ast)"
XCTAssertEqual(result, "IF{(x = y), {x = (y + 1)}, {IF{(a > b), {x = a}, {x = b}}}}")
}
}
| true
|
1efcb4c4ab646cb145ef909ab61870f1b2a693c3
|
Swift
|
cobreti/MasterProject
|
/projects/iOS/ProjectFV/ProjectFV/Stories/SchematicView/SchematicViewTBController.swift
|
UTF-8
| 1,454
| 2.609375
| 3
|
[] |
no_license
|
//
// SchematicViewTBController.swift
// ProjectFV
//
// Created by Danny Thibaudeau on 2015-09-13.
// Copyright (c) 2015 Danny Thibaudeau. All rights reserved.
//
import Foundation
import UIKit
class SchematicViewTBController : UIViewController {
typealias RecenterDelegate = () -> Void
typealias ShowQuestionRechercheDelegate = () -> Void
var recenterDelegate : RecenterDelegate! {
get {
return _recenterDelegate
}
set(delegate) {
_recenterDelegate = delegate
}
}
var showQuestionRechercheDelegate: ShowQuestionRechercheDelegate! {
get {
return _showQuestionRechercheDelegate
}
set(delegate) {
_showQuestionRechercheDelegate = delegate
}
}
var diagramName : String! {
get {
return _diagramNameLabel?.text
}
set (value) {
if let text = value {
_diagramNameLabel?.text = text
}
else {
_diagramNameLabel?.text = ""
}
}
}
@IBAction func onRecenter(_ sender: AnyObject) {
_recenterDelegate?()
}
@IBAction func onShowQuestion(_ sender: AnyObject) {
_showQuestionRechercheDelegate?()
}
@IBOutlet weak var _diagramNameLabel: UILabel!
var _recenterDelegate : RecenterDelegate!
var _showQuestionRechercheDelegate : ShowQuestionRechercheDelegate!
}
| true
|
1e9a2d9be85d1ee37fb39b8b20a860c3a51064fa
|
Swift
|
Weizilla/advent-of-code
|
/swift/2020/advent-of-code/advent-of-code/day-09.swift
|
UTF-8
| 2,097
| 3.5625
| 4
|
[] |
no_license
|
import Foundation
func day09Part1() -> Int {
let input = readInputInt(9)
let preamble = 25
var window = Window()
return findInvalid(preamble: preamble, window: window, input: input)
}
func day09Part2() -> Int {
let input = readInputInt(9)
let preamble = 25
var window = Window()
let invalid = findInvalid(preamble: preamble, window: window, input: input)
print(invalid)
var window2 = Window()
var window2Index = 0
while (window2.sum() != invalid) {
if (window2.sum() < invalid) {
window2.add(input[window2Index])
window2Index += 1
} else {
window2.dropFirst()
}
// print(window2)
}
let finalValues = window2.values.sorted()
return finalValues.first! + finalValues.last!
}
func findInvalid(preamble: Int, window: Window, input: [Int]) -> Int {
for i in 0..<preamble {
window.add(input[i])
}
for i in preamble..<input.count {
let curr = input[i]
let isValid = window.canAdd(curr)
if isValid {
window.dropFirst()
window.add(curr)
} else {
return curr
}
}
return 0
}
class Window : CustomStringConvertible {
var values: [Int] = []
var valuesCount: [Int:Int] = [:]
func dropFirst() {
let first = values.first!
let count = valuesCount[first]! - 1
if count == 0 {
valuesCount.removeValue(forKey: first)
} else {
valuesCount[first] = count
}
values.removeFirst()
}
func add(_ input: Int) {
values.append(input)
valuesCount.merge([input: 1], uniquingKeysWith: +)
}
func canAdd(_ input: Int) -> Bool {
for v in values {
let diff = input - v
if diff > 0 && valuesCount[diff] != nil {
return true
}
}
return false
}
func sum() -> Int {
values.reduce(0, +)
}
var description: String {
"----------------\n\(values)\n\(valuesCount)"
}
}
| true
|
7233325ddd35f80ed3ace33771f390acfee387fe
|
Swift
|
Zfalgout/DropBoxer
|
/DropBoxer/Views/InitalVC.swift
|
UTF-8
| 1,613
| 2.734375
| 3
|
[] |
no_license
|
import UIKit
import Photos
class InitalVC: UIViewController {
let photoLibrary = PhotoLibraryVM()
var imagesFromLibrary: [StatefulImage] = []
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var deniedMessage: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//Get the authroization status of the photo library.
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
self.requestAuthorization()
} else if photos == .authorized {
self.goToCollectionView()
} else if photos == .denied {
self.requestAuthorization()
}
}
//Function to fire off the showCollection segue. It has to be done on the UI thread. Removing the call to the main thread causes issues with the label in the SavedPhotosVC.
private func goToCollectionView() {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showCollection", sender: self)
}
}
private func requestAuthorization() {
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
DispatchQueue.main.async {
self.goToCollectionView()
}
} else {
//The status has been set to denied, show a popup letting the user know how to give access to DropBoxer for their photos.
DispatchQueue.main.async {
self.deniedMessage.isHidden = false
}
}
})
}
}
| true
|
75cd1294a1f7f1cf64c1f6a20e9e5afffc119060
|
Swift
|
jauharibill/pickle-jones
|
/AnimationInSwift/SwipeGestureViewController.swift
|
UTF-8
| 1,029
| 2.6875
| 3
|
[] |
no_license
|
//
// SwipeGestureViewController.swift
// AnimationInSwift
//
// Created by Bill Tanthowi Jauhari on 18/05/19.
// Copyright © 2019 Batavia Hack Town. All rights reserved.
//
import UIKit
class SwipeGestureViewController: UIViewController {
@IBOutlet weak var objectGame: UIView!
@IBOutlet var swipeGesture: UISwipeGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
objectGame.layer.cornerRadius = 50
print(swipeGesture.direction.rawValue)
// Do any additional setup after loading the view.
}
@IBAction func swipeGestureAction(_ sender: UISwipeGestureRecognizer) {
print(sender.direction.rawValue)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
3fed0c505d12f6c723c0a46ecb61f7cf04e3061d
|
Swift
|
sherefshokry/PrayerTimeWidget
|
/PrayerTimeWidget/Views/PrayerTimeView.swift
|
UTF-8
| 998
| 3.046875
| 3
|
[] |
no_license
|
//
// PrayerTimeView.swift
// PrayerTime
//
// Created by SherifShokry on 08/09/2021.
//
import WidgetKit
import SwiftUI
struct MediumPrayerTimeView : View {
var imageName = "sun"
var prayerName = "Fajr"
var prayerTime = "0:00"
init(imageName : String = "sun" , prayerName : String = "Fajr" , prayerTime : String = "0:00") {
self.imageName = imageName
self.prayerName = prayerName
self.prayerTime = prayerTime
}
var body: some View {
VStack(spacing: 8){
Image(imageName)
.foregroundColor(.white)
.scaledToFit()
VStack{
Text(prayerTime)
.font(Font.system(size: 13.0))
.foregroundColor(Color.white)
Text(prayerName)
.font(Font.system(size: 13.0))
.foregroundColor(Color.white)
}
}
}
}
| true
|
056f07f0414262cf8e56fe6c511051119c400bb6
|
Swift
|
ValeriyaTarasenko/ios-playgrounds
|
/18/18.playground/Contents.swift
|
UTF-8
| 2,619
| 4.03125
| 4
|
[] |
no_license
|
//1
class Artist {
var name: String
var surname: String
func action() {
print("Artist \(name) \(surname) perfomens")
}
init(name: String, surname: String) {
self.name = name
self.surname = surname
}
}
class Dancer: Artist {
override func action() {
print("Dancer \(name) \(surname) perfomens")
}
}
class Painter: Artist {
override func action() {
self.name = "Painter"
self.surname = "Painter"
print("\(name) \(surname) perfomens")
}
}
var artist = Artist(name: "Vasya", surname: "Sidorov")
var danser = Dancer(name: "Kolya", surname: "Ivanov")
var painter = Painter(name: "Lesha", surname: "Petrov")
for i in [artist, danser, painter] {
i.action()
}
//2
class Vehicle {
var speed: Int {return 150}
var capacity: Int {return 200}
var cost: Int {return 50}
func calculation(people: Int, distance: Int) {
let time = distance/speed // * (people/capacity==1 ? 1 : (people/capacity)*2)
let allCost = people * cost
print("Count people \(people) costs \(allCost) time \(time)")
}
}
class Plane: Vehicle {
override var speed: Int { return 700 }
override var capacity: Int { return 300 }
override var cost: Int { return 150 }
}
class Car: Vehicle {
override var speed: Int { return 120 }
override var capacity: Int { return 5 }
override var cost: Int { return 30 }
}
class Train: Vehicle {
override var speed: Int { return 250 }
override var capacity: Int { return 300 }
override var cost: Int { return 10 }
}
var transport = [Plane(), Car(), Train()]
for i in transport {
i.calculation(people: 100, distance: 1000)
}
//3
class Creature {}
class Animal: Creature {}
class Reptile: Animal {}
class Quadruped: Animal {}
class Crocodile: Reptile {}
class Human: Quadruped {}
class Dog: Quadruped {}
class Lizard: Reptile {}
class Giraffe: Quadruped {}
class Monkey: Quadruped {}
var cr1 = Crocodile()
var cr2 = Lizard()
var cr3 = Human()
var cr4 = Human()
var cr5 = Dog()
var cr6 = Dog()
var cr7 = Giraffe()
var cr8 = Giraffe()
var cr9 = Lizard()
var cr10 = Lizard()
var creatures : [Creature] = [cr1,cr2,cr3,cr4,cr5,cr6,cr7,cr8,cr9,cr10]
//var creatures = [Crocodile(),Lizard(),Human(),Human(),Dog(),Dog(),Giraffe(),Giraffe(),Lizard(),Lizard()]
var quad = 0
var an = 0
var cr = 0
for i in creatures {
if i is Quadruped {
quad = quad + 1
}
if i is Animal {
an = an + 1
}
if i is Creature {
cr = cr + 1
}
}
print("creatures - \(cr), animals - \(an), quadruped - \(quad)")
| true
|
b700483b0888a7fd92c91a7b734a15c5fd8504fa
|
Swift
|
igyvigy/QuBar
|
/QuBar/Extensions.swift
|
UTF-8
| 378
| 3.125
| 3
|
[] |
no_license
|
//
// Extensions.swift
// QuBar
//
// Created by Andrii Narinian on 2/15/17.
// Copyright © 2017 Andrii. All rights reserved.
//
import Foundation
extension Int {
var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
| true
|
099b5657065f80a438016efe7719a2731631f9a5
|
Swift
|
BozhkoAlexander/VideoLibrary
|
/VideoLibrary/Classes/Video+Container.swift
|
UTF-8
| 6,209
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// Video+Container.swift
// video app
//
// Created by Alexander Bozhko on 20/08/2018.
// Copyright © 2018 Filmgrail AS. All rights reserved.
//
import Foundation
import AVKit
public extension Notification.Name {
static let VideoBuffered = Notification.Name("videoview-buffering")
static let VideoTimer = Notification.Name("videoview-timer")
static let VideoPlayPressed = Notification.Name("videoview-play")
static let VideoPausePressed = Notification.Name("videoview-pause")
static let VideoStop = Notification.Name("videoview-stop")
static let VideoResync = Notification.Name("videoview-resync")
static let VideoFullscreenPressed = Notification.Name("videoview-fullscreen")
}
/** AVPlayer video loading callback
- parameters:
@param container
Container object (optional) with additional info
@param isCached
if video received from cache the true, otherwise - false
@param error
Error object (optional) if an error occurs
*/
public extension Video {
/** Video status */
enum Status {
case empty
case loading
case playing
case stopped
case paused
case ended
}
/**
AVPlayer video loading callback
- Parameters:
- container: Container object (optional) with additional info
- isCached: if video received from cache the true, otherwise - false
- error: Error object (optional) if an error occurs
*/
typealias Callback = (_ container: Container?, _ isCached: Bool, _ error: Error?) -> Void
/** The object which is sent in VideoTimer notification */
typealias TimerInfo = (Container, String)
/** Returns video container if exist by video link. */
func container(for link: String?) -> Container? {
guard let link = link else { return nil }
return Cache.videos.value(forKey: link) as? Container
}
/** Video containter */
class Container: NSObject {
// MARK: - Properties
public var isPlaying = true // if true then it needs to play video asap, else it needs to pause video
public var player: AVPlayer
public var item: AVPlayerItem
private var timer: Any! = nil
// MARK: - KVO
private var bufferKVO: NSKeyValueObservation! = nil
private var buffer2KVO: NSKeyValueObservation! = nil
private var statusKVO: NSKeyValueObservation! = nil
private var timeControlKVO: NSKeyValueObservation! = nil
private func kvoChangeHandler() {
NotificationCenter.default.post(name: .VideoBuffered, object: self)
}
// MARK: - Life cycle
public init(player: AVPlayer, item: AVPlayerItem) {
self.player = player
self.item = item
super.init()
addObservers()
}
deinit {
removeObservers()
}
private func addObservers() {
statusKVO = item.observe(\.status, options: .initial, changeHandler: { [weak self] (_, _) in
self?.kvoChangeHandler()
})
if #available(iOS 10.0, *) {
timeControlKVO = player.observe(\.timeControlStatus, options: .initial, changeHandler: { [weak self] (_, _) in
self?.kvoChangeHandler()
})
} else {
bufferKVO = item.observe(\.isPlaybackBufferEmpty, options: .initial, changeHandler: { [weak self] (_, _) in
self?.kvoChangeHandler()
})
buffer2KVO = item.observe(\.isPlaybackLikelyToKeepUp, options: .initial, changeHandler: { [weak self] (_, _) in
self?.kvoChangeHandler()
})
}
timer = player.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 1), queue: .main) { [weak self] (time) in
guard let this = self else { return }
guard time != CMTime.zero else { return }
this.postTimeNotification(for: time)
}
}
private func postTimeNotification(for time: CMTime) {
let remain = item.duration.seconds - time.seconds
guard !remain.isNaN && !remain.isZero else { return }
let minutes = Int(remain) / 60
let seconds = Int(remain) % 60
let string = String(format: "%02i:%02i", minutes, seconds)
let info: TimerInfo = (self, string)
NotificationCenter.default.post(name: .VideoTimer, object: info)
}
private func removeObservers() {
statusKVO = nil
timeControlKVO = nil
bufferKVO = nil
buffer2KVO = nil
timer = nil
}
// MARK: - Player interaction
public func play() {
isPlaying = true
self.player.play()
let time = self.player.currentTime()
postTimeNotification(for: time)
}
public func stop() {
isPlaying = false
self.player.seek(to: CMTime.zero)
self.player.pause()
}
public func pause() {
isPlaying = false
self.player.pause()
}
public func bufferingStatus() -> Status? {
guard item.status != .failed else { return .empty }
if #available(iOS 10.0, *) {
switch player.timeControlStatus {
case .waitingToPlayAtSpecifiedRate: return .loading
case .paused: return item.currentTime() == CMTime.zero ? .stopped : .paused
case .playing: return .playing
@unknown default: return .empty
}
} else {
if isPlaying { // if we want to play video
return .playing
} else {
return item.currentTime() == CMTime.zero ? .stopped : .paused
}
}
}
}
}
| true
|
7b4bd8f855c266a3ab23f26d4ed14fbe4b2c38e4
|
Swift
|
ninayang036/guessnumber
|
/guessnumber/ABViewController.swift
|
UTF-8
| 3,391
| 2.796875
| 3
|
[] |
no_license
|
//
// ABViewController.swift
// guessnumber
//
// Created by Yang Nina on 2021/4/8.
//
import UIKit
import GameplayKit
class ABViewController: UIViewController {
@IBOutlet weak var tmp: UILabel!
@IBOutlet weak var moodImg: UIImageView!
@IBOutlet weak var goBtn: UIButton!
@IBOutlet weak var guessBtn: UIButton!
@IBOutlet weak var againBtn: UIButton!
@IBOutlet var guessNumText: [UITextField]!
@IBOutlet weak var showLabel: UILabel!
@IBOutlet weak var titleImg: UIImageView!
@IBOutlet weak var recordTextView: UITextView!
var enter = ""
var correctNum:[String] = ["","","",""]
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
reset()
}
@IBAction func start(_ sender: UIButton) {
for i in 0...3{
guessNumText[i].placeholder = "0"
guessNumText[i].isEnabled = true
}
moodImg.image = UIImage(named: "artist")
goBtn.isHidden = true
guessBtn.isHidden = false
titleImg.isHidden = true
}
@IBAction func guess(_ sender: UIButton) {
var a = 0
var b = 0
for i in 0...3{
if correctNum[i] == guessNumText[i].text{
a += 1
}
else if correctNum.contains(guessNumText[i].text!){
b += 1
}
enter.append(guessNumText[i].text!)
guessNumText[i].placeholder = "0"
guessNumText[i].text = ""
}
if a == 4{
againBtn.isHidden = false
guessBtn.isHidden = true
showLabel.text = "猜對啦~再來玩一次吧^^"
moodImg.image = UIImage(named: "sing")
}
else if a == 3{
count += 1
recordTextView.text += "[\(count)]: \(enter) \(a)A\(b)B\r\n"
showLabel.text = "差一點點而已!加油!!"
}
else{
count += 1
recordTextView.text += "[\(count)]: \(enter) \(a)A\(b)B\r\n"
let cheer:[String] = ["還要加把勁唷@@","太可惜啦!","再試試看吧!!"]
showLabel.text = cheer.randomElement()
}
enter = ""
self.view.endEditing(true)
}
@IBAction func again(_ sender: UIButton) {
reset()
}
func creatnum(){
let randomNum = GKShuffledDistribution(lowestValue: 0, highestValue: 9)
for i in 0...3{
correctNum[i] = "\(randomNum.nextInt())"
}
}
func reset(){
for i in 0...3{
guessNumText[i].placeholder = "?"
guessNumText[i].text = ""
guessNumText[i].isEnabled = false
}
creatnum()
moodImg.image = UIImage(named: "drawing")
goBtn.isHidden = false
guessBtn.isHidden = true
againBtn.isHidden = true
titleImg.isHidden = false
showLabel.text = "一起來猜猜看!"
recordTextView.text = ""
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
39556883122fa194fe3b8f9d17b61dc02752ac5a
|
Swift
|
JonathonJames/CodeTest
|
/Job Search/Job Search/JobListingSearchViewController.swift
|
UTF-8
| 8,763
| 2.609375
| 3
|
[] |
no_license
|
//
// JobListingSearchViewController.swift
// Job Search
//
// Created by Jonathon James on 11/08/2021.
//
import UIKit
import Combine
/// Describes a cell which displays a preview for a job listing.
final class JobListingTableViewCell: UITableViewCell {
@IBOutlet private var jobTitleLabel: UILabel!
func bind(to viewModel: JobListing) {
self.jobTitleLabel.text = viewModel.jobTitle
self.jobTitleLabel.sizeToFit()
}
}
/// A wrapper around all the input parameters required to construct a query.
private struct InputParameters {
// Publishes keyword search parameters.
let keyword: AnyPublisher<String, Never>
// Publishes pagination parameters.
let pagination: AnyPublisher<Int64, Never>
#warning("TODO: Add other filter parameters")
}
/// Describes a view controller which allows for the search and display of `JobListing`s.
final class JobListingSearchViewController: UIViewController {
final class ViewModel {
fileprivate let repository: JobSearchRepository
fileprivate var previousQuery: JobSearchQuery = .init()
fileprivate var query: JobSearchQuery = .init()
private var cancellables: [AnyCancellable] = []
init(repository: JobSearchRepository) {
self.repository = repository
}
fileprivate func process(input: InputParameters) -> AnyPublisher<JobListingSearchState, Never> {
self.cancellables.forEach { $0.cancel() }
self.cancellables.removeAll()
let keywordInput = input.keyword
.debounce(for: .milliseconds(300), scheduler: RunLoop.main)
.removeDuplicates()
.filter({ !$0.isEmpty })
let paginationInput = input.pagination
.debounce(for: .milliseconds(300), scheduler: RunLoop.main)
.removeDuplicates()
let asyncSearch = Publishers.CombineLatest(keywordInput, paginationInput)
.flatMap({ [unowned self] (keywords, page) -> AnyPublisher<Result<JobListingSearchResult, Error>, Never> in
var query = self.query
query.keywords = keywords
query.resultsToSkip = page * (query.resultsToTake ?? 25)
self.previousQuery = query
self.query = query
return self.repository.performSearch(query)
})
.map { result -> JobListingSearchState in
switch result {
case .success(let searchResults):
return .loaded(.init(result: searchResults))
case .failure(let error):
return .error(error)
}
}
.eraseToAnyPublisher()
let initialState: AnyPublisher<JobListingSearchState, Never> = Just(.idle).eraseToAnyPublisher()
let emptySearchString: AnyPublisher<JobListingSearchState, Never> = keywordInput.filter({ $0.isEmpty }).map({ _ in .idle }).eraseToAnyPublisher()
let idle: AnyPublisher<JobListingSearchState, Never> = Publishers.Merge(initialState, emptySearchString).eraseToAnyPublisher()
return Publishers.Merge(idle, asyncSearch).removeDuplicates().eraseToAnyPublisher()
}
}
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
private let keywordSearchPublisher: PassthroughSubject<String, Never> = .init()
private let paginationPublisher: CurrentValueSubject<Int64, Never> = .init(0)
private var cancellables: [AnyCancellable] = []
let viewModel: ViewModel! = {
let config: URLSessionConfiguration = .ephemeral
config.httpAdditionalHeaders = ["Authorization" : "Basic YmI2YjM3MTgtOTA2YS00NTJlLWEwMmEtY2RiMjVlNDU2NDIyIDo="]
return .init(
repository: .init(
api: JobSearchNetworkingDomain(
baseURL: "https://www.reed.co.uk/api/1.0/",
session: URLSession(configuration: config)
)
)
)
}()
private lazy var datasource: UITableViewDiffableDataSource<JobListingSearchState.DataSections, JobListing> = {
let retval: UITableViewDiffableDataSource<JobListingSearchState.DataSections, JobListing> = .init(
tableView: tableView,
cellProvider: { tableView, indexPath, model in
guard let cell = tableView.dequeueReusableCell(withIdentifier: "JobListingTableViewCell") as? JobListingTableViewCell else {
assertionFailure("Failed to dequeue JobListingTableViewCell")
return UITableViewCell()
}
#warning("TODO: Setup accessibility identifier")
cell.bind(to: model)
return cell
}
)
var snapshot = retval.snapshot()
snapshot.appendSections(JobListingSearchState.DataSections.allCases)
retval.apply(snapshot, animatingDifferences: false)
return retval
}()
override func viewDidLoad() {
super.viewDidLoad()
// Setup the table view's datasource and search bar's delegate.
self.tableView.dataSource = self.datasource
self.tableView.delegate = self
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 42
self.searchBar.delegate = self
/// Bind the publisher(s) to the view.
self.cancellables.forEach { $0.cancel() }
self.cancellables.removeAll()
self.viewModel.process(
input: InputParameters(
keyword: self.keywordSearchPublisher.eraseToAnyPublisher(),
pagination: self.paginationPublisher.eraseToAnyPublisher()
)
)
.sink(receiveValue: {[unowned self] state in
switch state {
case .idle:
#warning("TODO: Prompt the user to do something. Give them an example search query, perhaps.")
break
case .loading:
#warning("TODO: Display a loading indicator.")
break
case .error(let error):
#warning("TODO: Inform the user of the error.")
print("An error occured when performing search: \(error)")
case .loaded(let data):
DispatchQueue.main.async {
var snapshot: NSDiffableDataSourceSnapshot<JobListingSearchState.DataSections, JobListing>
if (self.viewModel.query.resultsToSkip == nil || self.viewModel.previousQuery.resultsToSkip! == 0) ||
(self.viewModel.query.keywords != self.viewModel.previousQuery.keywords) {
snapshot = .init()
snapshot.appendSections(JobListingSearchState.DataSections.allCases)
} else {
snapshot = self.datasource.snapshot()
}
JobListingSearchState.DataSections.allCases.forEach { section in
snapshot.appendItems(data.data[section] ?? [], toSection: section)
}
self.datasource.apply(snapshot, animatingDifferences: true)
}
}
}).store(in: &cancellables)
}
}
extension JobListingSearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.keywordSearchPublisher.send(searchText)
}
}
extension JobListingSearchViewController: UITableViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if targetContentOffset.pointee.y >= scrollView.contentSize.height - (scrollView.visibleSize.height * 1.5) {
#warning("TODO: Only try and paginate if there's more data to fetch")
self.paginationPublisher.send(self.paginationPublisher.value + 1)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let listing: JobListing = self.datasource.itemIdentifier(for: indexPath) else {
#warning("TODO: Display an error here. The selected listing can't be found.")
return
}
self.navigationController?.pushViewController(
JobDetailsViewController.newInstance(viewModel: .init(listing: listing)),
animated: true
)
}
}
| true
|
e463be871ee69514b4e1e0389c78ba3c2ec2ebdc
|
Swift
|
BrunoMichelotti/swinx
|
/Swinx/Swinx/Feature/Functionary/ListFunctionary/Model/FunctionaryModel.swift
|
UTF-8
| 1,437
| 2.546875
| 3
|
[] |
no_license
|
//
// FunctionaryModel.swift
// Swinx
//
// Created by Any Ambria on 24/04/21.
// Copyright © 2021 Swinx. All rights reserved.
//
import Foundation
struct Functionary: Codable {
let data: FunctionaryDataClass?
}
// MARK: - DataClass
struct FunctionaryDataClass: Codable {
let funcionarios: [Funcionario]?
}
// MARK: - Funcionario
struct Funcionario: Codable {
let nome, codProjetoJira, pre, funcional: String?
let racf, email, squadProfissional, cargo: String?
let dataInicio, dataFim, status, cpf: String?
let rg, matriculaGeco, numeroMAC, celularCorporativo: String?
let telefone, emailCliente, aniversario, shadow: String?
let tecnologia, pontoFocal, tl, pl: String?
let gerente, servico: String?
enum CodingKeys: String, CodingKey {
case nome
case codProjetoJira = "cod_projeto_jira"
case pre, funcional
case racf = "RACF"
case email
case squadProfissional = "squad_profissional"
case cargo
case dataInicio = "data_inicio"
case dataFim = "data_fim"
case status, cpf, rg
case matriculaGeco = "matricula_geco"
case numeroMAC = "numero_mac"
case celularCorporativo = "celular_corporativo"
case telefone
case emailCliente = "email_cliente"
case aniversario, shadow, tecnologia
case pontoFocal = "ponto_focal"
case tl, pl, gerente, servico
}
}
| true
|
251f8c706350503e861af89f1f6b08f539ce93a2
|
Swift
|
kzkunuzbam/youtube-onedaybuild
|
/youtube-onedaybuild/Helpers/CacheManager.swift
|
UTF-8
| 417
| 2.65625
| 3
|
[] |
no_license
|
//
// CacheManager.swift
// youtube-onedaybuild
//
// Created by Murat Kunuzbayev on 6/17/20.
// Copyright © 2020 Murat Kunuzbayev. All rights reserved.
//
import Foundation
class CacheManager {
static var cache = [String:Data]()
static func setVideoCache(_ url: String, _ data:Data?) {
cache[url] = data
}
static func getVideoCache(_ url:String) -> Data? {
return cache[url]
}
}
| true
|
60af2b1c174832f27831e69f4ee8384f8d803612
|
Swift
|
kothihaaung/animations
|
/ViewControllerTransition(CircularAnimation)/ViewControllerTransition(CircularAnimation)/ViewController.swift
|
UTF-8
| 1,488
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ViewControllerTransition(CircularAnimation)
//
// Created by Thiha Aung on 2019/06/01.
// Copyright © 2019 Thiha Aung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var openButton: UIButton!
let transition = CircularTransition()
override func viewDidLoad() {
super.viewDidLoad()
openButton.layer.cornerRadius = openButton.frame.size.width / 2
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nextVc = segue.destination as! NextViewController
nextVc.transitioningDelegate = self
nextVc.modalPresentationStyle = .custom
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .present
transition.startingPoint = openButton.center
transition.circleColor = openButton.backgroundColor!
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .dismiss
transition.startingPoint = openButton.center
transition.circleColor = openButton.backgroundColor!
return transition
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.