text
stringlengths
8
1.32M
// ZJaDe: gyb自动生成 // swiftlint:disable colon public protocol ExpressibleValueProtocol: ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, ExpressibleByNilLiteral { init(booleanLiteral value: Bool) init(integerLiteral value: Int) init(floatLiteral value: Double) init(stringLiteral value: String) init(nilLiteral: ()) } extension ExpressibleValueProtocol { public init(_ value: Bool?) { if let value = value { self.init(booleanLiteral: value) } else { self.init(nilLiteral: ()) } } public init(_ value: Int?) { if let value = value { self.init(integerLiteral: value) } else { self.init(nilLiteral: ()) } } public init(_ value: Double?) { if let value = value { self.init(floatLiteral: value) } else { self.init(nilLiteral: ()) } } public init(_ value: String?) { if let value = value { self.init(stringLiteral: value) } else { self.init(nilLiteral: ()) } } } extension IntegerLiteralTypeValueProtocol where Self: ExpressibleValueProtocol { public init(booleanLiteral value: Bool) { self.init(value: value.toInt) } public init(integerLiteral value: Int) { self.init(value: value.toInt) } public init(floatLiteral value: Double) { self.init(value: value.toInt) } public init(stringLiteral value: String) { self.init(value: value.toInt) } public init(nilLiteral: ()) { self.init(value: nil) } } extension FloatLiteralTypeValueProtocol where Self: ExpressibleValueProtocol { public init(booleanLiteral value: Bool) { self.init(value: value.toDouble) } public init(integerLiteral value: Int) { self.init(value: value.toDouble) } public init(floatLiteral value: Double) { self.init(value: value.toDouble) } public init(stringLiteral value: String) { self.init(value: value.toDouble) } public init(nilLiteral: ()) { self.init(value: nil) } } extension StringLiteralTypeValueProtocol where Self: ExpressibleValueProtocol { public init(booleanLiteral value: Bool) { self.init(value: value.toString) } public init(integerLiteral value: Int) { self.init(value: value.toString) } public init(floatLiteral value: Double) { self.init(value: value.toString) } public init(stringLiteral value: String) { self.init(value: value.toString) } public init(nilLiteral: ()) { self.init(value: nil) } } extension BooleanLiteralTypeValueProtocol where Self: ExpressibleValueProtocol { public init(booleanLiteral value: Bool) { self.init(value: value.toBool) } public init(integerLiteral value: Int) { self.init(value: value.toBool) } public init(floatLiteral value: Double) { self.init(value: value.toBool) } public init(stringLiteral value: String) { self.init(value: value.toBool) } public init(nilLiteral: ()) { self.init(value: nil) } }
// // SettingsViewController.swift // Rectangle // // Created by Ryan Hanson on 8/24/19. // Copyright © 2019 Ryan Hanson. All rights reserved. // import Cocoa import ServiceManagement import Sparkle class SettingsViewController: NSViewController { static let allowAnyShortcutNotificationName = Notification.Name("allowAnyShortcutToggle") static let windowSnappingNotificationName = Notification.Name("windowSnappingToggle") static let changeDefaultsNotificationName = Notification.Name("changeDefaults") @IBOutlet weak var launchOnLoginCheckbox: NSButton! @IBOutlet weak var versionLabel: NSTextField! @IBOutlet weak var windowSnappingCheckbox: NSButton! @IBOutlet weak var hideMenuBarIconCheckbox: NSButton! @IBOutlet weak var subsequentExecutionCheckbox: NSButton! @IBOutlet weak var allowAnyShortcutCheckbox: NSButton! @IBOutlet weak var checkForUpdatesAutomaticallyCheckbox: NSButton! @IBOutlet weak var checkForUpdatesButton: NSButton! @IBAction func toggleLaunchOnLogin(_ sender: NSButton) { let newSetting: Bool = sender.state == .on let smLoginSuccess = SMLoginItemSetEnabled(AppDelegate.launcherAppId as CFString, newSetting) if !smLoginSuccess { Logger.log("Unable to set launch at login preference. Attempting one more time.") SMLoginItemSetEnabled(AppDelegate.launcherAppId as CFString, newSetting) } Defaults.launchOnLogin.enabled = newSetting } @IBAction func toggleWindowSnapping(_ sender: NSButton) { let newSetting: Bool = sender.state == .on Defaults.windowSnapping.enabled = newSetting NotificationCenter.default.post(name: SettingsViewController.windowSnappingNotificationName, object: newSetting) } @IBAction func toggleHideMenuBarIcon(_ sender: NSButton) { let newSetting: Bool = sender.state == .on Defaults.hideMenuBarIcon.enabled = newSetting RectangleStatusItem.instance.refreshVisibility() } @IBAction func toggleSubsequentExecutionBehavior(_ sender: NSButton) { Defaults.subsequentExecutionMode.value = sender.state == .on ? .acrossMonitor : .resize } @IBAction func toggleAllowAnyShortcut(_ sender: NSButton) { let newSetting: Bool = sender.state == .on Defaults.allowAnyShortcut.enabled = newSetting NotificationCenter.default.post(name: SettingsViewController.allowAnyShortcutNotificationName, object: newSetting) } @IBAction func checkForUpdates(_ sender: Any) { SUUpdater.shared()?.checkForUpdates(sender) } @IBAction func restoreDefaults(_ sender: Any) { WindowAction.active.forEach { UserDefaults.standard.removeObject(forKey: $0.name) } let currentDefaults = Defaults.alternateDefaultShortcuts.enabled ? "Rectangle" : "Spectacle" let response = AlertUtil.twoButtonAlert(question: "Default Shortcuts", text: "You are currently using \(currentDefaults) defaults.\n\nSelect your defaults. ", confirmText: "Rectangle", cancelText: "Spectacle") let rectangleDefaults = response == .alertFirstButtonReturn if rectangleDefaults != Defaults.alternateDefaultShortcuts.enabled { Defaults.alternateDefaultShortcuts.enabled = rectangleDefaults NotificationCenter.default.post(name: Self.changeDefaultsNotificationName, object: nil) } } override func awakeFromNib() { if Defaults.launchOnLogin.enabled { launchOnLoginCheckbox.state = .on } if Defaults.hideMenuBarIcon.enabled { hideMenuBarIconCheckbox.state = .on } if Defaults.subsequentExecutionMode.value == .acrossMonitor { subsequentExecutionCheckbox.state = .on } if Defaults.allowAnyShortcut.enabled { allowAnyShortcutCheckbox.state = .on } if Defaults.windowSnapping.enabled == false { windowSnappingCheckbox.state = .off } if let updater = SUUpdater.shared() { checkForUpdatesAutomaticallyCheckbox.bind(.value, to: updater, withKeyPath: "automaticallyChecksForUpdates", options: nil) } let appVersionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String versionLabel.stringValue = "v" + appVersionString + " (" + buildString + ")" checkForUpdatesButton.title = NSLocalizedString("HIK-3r-i7E.title", tableName: "Main", value: "Check for Updates…", comment: "") } } extension SettingsViewController { static func freshController() -> SettingsViewController { let storyboard = NSStoryboard(name: "Main", bundle: nil) let identifier = "SettingsViewController" guard let viewController = storyboard.instantiateController(withIdentifier: identifier) as? SettingsViewController else { fatalError("Unable to find ViewController - Check Main.storyboard") } return viewController } }
// // CFNetworker + Extension.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/12. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import UIKit extension CFNetworker { /// 加载微博数据字典数组 /// /// - Parameters: /// - since_id: 返回比since_id大的微博 /// - max_id: 返回ID小于或等于max_id的微博 /// - completion: 完成回调 func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String : AnyObject]]?, _ isSuccess: Bool) -> ()) { let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" // Swift中Int类型可以直接转换成AnyObject 但是Int64不行 let parameters = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)"] // 请求数据 CFNetworker.shared.tokenRequest(URLString: urlString, parameters: parameters as [String : AnyObject]?){(json: Any? , isSuccess: Bool) in let response = json as AnyObject? let result = response?["statuses"] as? [[String : AnyObject]] completion(result, isSuccess) } } func unreadCount(completion: @escaping (_ count: Int) -> ()) { guard let uid = userAccount.uid else { return } let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json" let parameters = ["uid": uid as AnyObject] as [String : AnyObject] CFNetworker.shared.tokenRequest(URLString: urlString, parameters: parameters) { (json, isSuccess) in let dict = json as? [String: AnyObject] let count = dict?["status"] as? Int completion(count ?? 0) } } } // MARK: - 加载用户信息 extension CFNetworker { /// 加载当前用户信息,用户登录成功后立即执行 func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject]) -> ()) { guard let uid = userAccount.uid else { NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUserShoudLoginNotification), object: "bad token") return } let urlString = "https://api.weibo.com/2/users/show.json" let parameters = ["uid": uid] tokenRequest(URLString: urlString, parameters: parameters as [String : AnyObject]?) { (json, isSuccess) in print(json ?? "登录失败") completion(json as? [String: AnyObject] ?? [:]) } } } // MARK: - 发微博 extension CFNetworker { func postStatus(text: String, image: UIImage? = nil, completion: @escaping (_ dict: [String: AnyObject]?, _ isSuccess: Bool) -> ()) { var urlString: String = "https://api.weibo.com/2/statuses/update.json" var name: String? var data: Data? if let image = image { // 上传图片 urlString = "https://upload.api.weibo.com/2/statuses/upload.json" name = "pic" data = UIImagePNGRepresentation(image) } let parameters = ["status": text] tokenRequest(method: .POST, URLString: urlString, parameters: parameters as [String : AnyObject]?, name: name, data: data) { (json, isSuccess) in completion(json as? [String: AnyObject], isSuccess) } } } // MARK: - OAuth相关方法 extension CFNetworker { /// 请求AccessToken func requestToken(code: String, completion:@escaping (_ isSuccess: Bool) ->()) { let urlString = "https://api.weibo.com/oauth2/access_token" let parameters = [ "client_id": SinaAppKey, "client_secret": SinaAppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": SinaRedirectURI ] request(method: .POST, URLString: urlString, parameters: parameters as [String : AnyObject]?) { (json, isSuccess) in print(json ?? "") // 字典转模型 self.userAccount.yy_modelSet(with: json as? [String : AnyObject] ?? [:]) // 加载当前用户信息 self.loadUserInfo(completion: { (dict) in // 设置昵称,头像地址 self.userAccount.yy_modelSet(with: dict) // 保存用户信息 self.userAccount.saveAccount() print(self.userAccount) // 用户信息加载完毕再请求 completion(isSuccess) }) } } }
// // ARSceneKitViewController.swift // HelloARKit // // CCreated by Dion Larson on 1/20/18. // Copyright © 2018 Make School. All rights reserved. // import UIKit import SceneKit import ARKit class ARSceneKitViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // Set the scene to the view sceneView.scene = scene sceneView.debugOptions = ARSCNDebugOptions.showFeaturePoints } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal // find a flat horizontal plane and add a node or an anchor configuration.isLightEstimationEnabled = true // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK: - ARSCNViewDelegate // gets call when recognizing a flat surface func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { let waterScene = SKScene(fileNamed: "PondScene-Water") let waterNode = self.createPlaneNode(center: planeAnchor.center, extent: planeAnchor.extent, contents: waterScene) node.addChildNode(waterNode) let pondScene = SKScene(fileNamed: "PondScene-Main") pondScene?.didMove(to: SKView()) pondScene?.isPaused = false let pondNode = self.createPlaneNode(center: planeAnchor.center, extent: planeAnchor.extent, contents: pondScene, yOffset: 0.025) node.addChildNode(pondNode) let plantsScene = SKScene(fileNamed: "PondScene-Plants") let plantsNode = self.createPlaneNode(center: planeAnchor.center, extent: planeAnchor.extent, contents: plantsScene, yOffset: 0.05) node.addChildNode(plantsNode) } } } func createPlaneNode(center: vector_float3, extent: vector_float3, contents: Any? = UIColor.blue.withAlphaComponent(0.4), yOffset: Float = 0) -> SCNNode { let plane = SCNPlane(width: CGFloat(extent.x), height: CGFloat(extent.z)) let planeMaterial = SCNMaterial() planeMaterial.diffuse.contents = contents plane.materials = [planeMaterial] let planeNode = SCNNode(geometry: plane) planeNode.transform = SCNMatrix4MakeRotation(-Float.pi/2, 1, 0, 0) planeNode.position = SCNVector3Make(center.x, yOffset, center.z) return planeNode } /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } }
// // Extensions.swift // TMDb // // Created by Dmitriy Pak on 10/17/18. // Copyright © 2018 Dmitriy Pak. All rights reserved. // import UIKit extension UIView{ @IBInspectable var cornerRadius: CGFloat{ get { return 0.0 } set(cornerRadius) { self.layer.cornerRadius = cornerRadius } } } extension String { func convertToURL() -> String{ let stringUrl = Helper.current.imageStaticUrl + self let url = stringUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! return url } func getDatefromTimeStamp (strdateFormat: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone let date = dateFormatter.date(from: self) dateFormatter.dateFormat = strdateFormat let datestr = dateFormatter.string(from: date!) return datestr } } extension UIViewController { class func storyboardInstance(storyboardId: String, restorationId: String) -> UIViewController { let storyboard = UIStoryboard(name: storyboardId, bundle: nil) return storyboard.instantiateViewController(withIdentifier: restorationId) } }
// // UIViews.swift // simpleSavings // // Created by Stephenson Ang on 1/12/20. // Copyright © 2020 Stephenson Ang. All rights reserved. // import UIKit extension UIView { func universalViewDesign() { self.backgroundColor = .white self.layer.shadowRadius = 5.0 self.layer.shadowOpacity = 0.25 self.layer.cornerRadius = 10.0 } }
// // UiImage+extension.swift // weiboTest // // Created by OceanDeep on 15/5/12. // Copyright (c) 2015年 OceanDeep. All rights reserved. // 扩展方法 import UIKit /** * image扩展方法 */ extension UIImage { func resizedImageWithName(name:String)->UIImage { var image=UIImage(named: name) var leftCapWidth:Int = Int(image!.size.width * 0.5) var topCapHeight:Int = Int(image!.size.height * 0.5) return image!.stretchableImageWithLeftCapWidth(leftCapWidth, topCapHeight: topCapHeight) } func aa(ss:String)->String { return "s" } }
// // GameScene.swift // Pop the Box // // Created by Lucia Reynoso on 9/20/18. // Copyright © 2018 Lucia Reynoso. All rights reserved. // import Foundation import SpriteKit import GameplayKit class GameScene: SKScene { let squareSize = CGSize(width: 40, height: 40) let scoreLabel = ScoreLabel(font: "Helvetica", fontColor: .white, fontSize: 30) var counter: Int = 0 enum GameState { case run, gameOver } var state: GameState = .run override func didMove(to view: SKView) { self.backgroundColor = .black // position score label, add it to the scene scoreLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height - 35) addChild(scoreLabel) } override func update(_ currentTime: TimeInterval) { if state == .run { // check loss condition if scoreLabel.actualScore < 0 { gameOver() } // check if we need to make a box if counter <= 0 { makeBox() counter = 15 * Int.random(in: 1...4) } else { counter -= 1 } } scoreLabel.updateDisplay() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if state == .gameOver { if let view = self.view { state = .run // Load the SKScene from 'GameScene.sks' let scene = GameScene(size: view.bounds.size) // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } if state == .run { if let touch = touches.first { let touchedNode = self.atPoint(touch.location(in: self)) if touchedNode.name == "box" { // remove the box from the screen and give the player some points touchedNode.removeFromParent() scoreLabel.updateScore(score: 100) // pop up a little score label to show how many points the box was worth let tinyLabel = TinyLabel(score: 100) tinyLabel.position = touch.location(in: self) addChild(tinyLabel) tinyLabel.floatUp() } } } } func makeBox() { // create random color and starting position let color = UIColor(hue: CGFloat.random(in: 0...1), saturation: 1, brightness: 1, alpha: 1) // make a new box let box = Box(squareSize: squareSize, color: color, name: "box", screenSize: self.size) // add the box to the screen addChild(box) // zoom! zoom(box) } func zoom(_ node: SKSpriteNode) { let moveUp = SKAction.moveTo(y: self.size.height, duration: Double(Int.random(in: 1...6))) let seq = SKAction.sequence([moveUp, .removeFromParent()]) node.run(seq) { // this only runs if the SKAction sequence is allowed to finish. if it is interrupted // by something, like the node being removed by a player touch, it won't run. so // the player can only lose points if the box makes it to the top of the screen and disappears. self.scoreLabel.updateScore(score: -100) } } func gameOver() { state = .gameOver self.removeAllChildren() let gameOverLabel = SKLabelNode(fontNamed: "Helvetica") gameOverLabel.text = "Game Over!" gameOverLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2) gameOverLabel.fontColor = .white gameOverLabel.fontSize = 45 addChild(gameOverLabel) } }
// // ViewController.swift // CollectionPaging // // Created by sanjay kumar chaurasia on 21/04/18. // Copyright © 2018 sanjay kumar chaurasia. All rights reserved. // import UIKit import FAPaginationLayout class ViewController: UIViewController { @IBOutlet weak var collectionView:UICollectionView! @IBOutlet weak var ht_const: NSLayoutConstraint! var value = 0 let ht = UIScreen.main.bounds.height let width = UIScreen.main.bounds.width override func viewDidLoad() { super.viewDidLoad() collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) collectionView.decelerationRate = UIScrollViewDecelerationRateFast collectionView.reloadData() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit{ print("in deinit method") } @IBAction func test(_ sender: UIBarButtonItem) { value += 1 if(value%2 == 0){ self.ht_const.constant = ht-64 } else{ self.ht_const.constant = ht/2-64 } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let layout = collectionView.collectionViewLayout as! FAPaginationLayout layout.itemSize = CGSize(width: width, height: self.ht_const.constant) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) collectionView.collectionViewLayout = layout self.collectionView.reloadData() } } extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell cell.imageView.image = UIImage(named: "\(indexPath.item)") return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var cellSize: CGSize = collectionView.bounds.size //cellSize.width -= collectionView.contentInset.left // cellSize.width -= collectionView.contentInset.right // cellSize.height = cellSize.width return cellSize } }
// // ConditionsView.swift // Freesurf // // Created by Sahand Nayebaziz on 9/20/16. // Copyright © 2016 Sahand Nayebaziz. All rights reserved. // import UIKit class ConditionsView: UIView, SpotDataDelegate { let directionLabel = UILabel() let periodLabel = UILabel() let conditionsLabel = UILabel() let windLabel = UILabel() init() { super.init(frame: CGRect.zero) let labelsStackView = UIStackView() let valuesStackView = UIStackView() for stackView in [labelsStackView, valuesStackView] { stackView.axis = .vertical stackView.alignment = .leading stackView.distribution = .fill stackView.spacing = 5 addSubview(stackView) } labelsStackView.snp.makeConstraints { make in make.left.equalTo(0) make.top.equalTo(0) make.width.equalTo(100) } valuesStackView.snp.makeConstraints { make in make.left.equalTo(120) make.top.equalTo(0) make.width.equalTo(120) } for metric in ["Direction", "Period", "Condition", "Wind"] { let label = UILabel() label.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular) label.textAlignment = .left label.text = metric label.textColor = Colors.blue labelsStackView.addArrangedSubview(label) } for valueLabel in [directionLabel, periodLabel, conditionsLabel, windLabel] { valueLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular) valueLabel.textAlignment = .left valueLabel.textColor = UIColor.white valuesStackView.addArrangedSubview(valueLabel) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func did(updateSpot spot: SpotData) { conditionsLabel.text = spot.conditionString } func did(updateCounty county: CountyData) { directionLabel.text = county.significantSwell?.direction periodLabel.text = county.periodString windLabel.text = county.windString } }
// // AppColors.swift // EasyGitHubSearch // // Created by Yevhen Triukhan on 11.10.2020. // Copyright © 2020 Yevhen Triukhan. All rights reserved. // import UIKit enum AppColor { public static var mainBackground: UIColor { if #available(iOS 13, *) { return .systemBackground } return .white // return #available(iOS13, #) ? .systemBackground : .white } public static var mainText: UIColor { if #available(iOS 13, *) { return .label } return .black } } enum AppColorName: String { // hex color example case purpleDark = "#492584" case tangerine = "#FF998A" } extension UIColor { convenience init(name: AppColorName, alpha: CGFloat? = nil) { self.init(name.rawValue, alpha: alpha)! } static var purpleDark: UIColor { return UIColor(name: .purpleDark) } static var tangerine: UIColor { return UIColor(name: .tangerine) } }
// // AppDependency.swift // VCamera // // Created by VassilyChi on 2020/8/11. // Copyright © 2020 VassilyChi. All rights reserved. // import Foundation import Swinject import AVFoundation import Galilei import Vincent class AppDependency { static let shared = AppDependency() private let container: Container private init() { container = .init(parent: nil, defaultObjectScope: .container, behaviors: [], registeringClosure: { _ in }) container.register(RenderDeivceResource.self) { _ in return sharedRenderResource } container.register(CameraManager.self) { _ in let devices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDualCamera, .builtInTrueDepthCamera], mediaType: .video, position: .unspecified).devices return CameraManager(devices: devices) } } func makeChildContainer(objectScrope: ObjectScope = .graph) -> Container { return .init(parent: self.container, defaultObjectScope: objectScrope, behaviors: [], registeringClosure: { _ in }) } }
// // main.swift // Notify // // Created by Charles Kenney on 12/13/17. // Copyright © 2017 Charles Kenney. All rights reserved. // import Foundation import Cocoa autoreleasepool { let app = NSApplication.shared let delegate = AppDelegate() app.delegate = delegate app.run() }
import Foundation extension Integer { init(bytes: [UInt8]) { precondition(bytes.count == MemoryLayout<Self>.size, "incorrect number of bytes") self = bytes.withUnsafeBufferPointer() { $0.baseAddress!.withMemoryRebound(to: Self.self, capacity: 1) { //(ptr) -> Result in return $0.pointee } } } init(data: Data) { self.init(bytes: Array(data)) } } extension UnsignedInteger { var bytes: Data { var copy = self // is this a good solution regarding LE/BE? return withUnsafePointer(to: &copy) { Data(Data(bytes: $0, count: MemoryLayout<Self>.size).reversed()) } } }
// // Errors.swift // StellarErrors // // Created by Kin Foundation. // Copyright © 2018 Kin Foundation. All rights reserved. // import Foundation public enum StellarError: Error { case memoTooLong(Any?) case missingBalance case urlEncodingFailed case dataEncodingFailed case dataDecodingFailed } extension StellarError: LocalizedError { public var errorDescription: String? { return String("\(self)") } }
// // AbilityVoew.swift // PocketDex // // Created by Thomas Tenzin on 6/22/20. // Copyright © 2020 Thomas Tenzin. All rights reserved. // import SwiftUI struct AbilityView: View { @EnvironmentObject var selectedVersion: UserVersion var pokemonList: [Pokemon] var pokemonFormsList: [Pokemon_Forms] var pokemonTypeList: [PokemonType] var moveList: [Move] var moveEffectList: [MoveEffectProse] var typeList: [Type] var abilityList: [Ability] var abilityProseList: [AbilityProse] var pokemonAbilitiesList: [PokemonAbilities] var itemList: [Item] enum SortType: String, CaseIterable { case number, name } enum OrderType: String, CaseIterable { case forward, backward } @State private var showSheetView = false @State private var searchAbilityText : String = "" @State var sorting: SortType @State var order: OrderType @State var genFilter: Int = 1 @State var showingGenFilter = false @State var showingConquestFilter = false @State var inclusiveGenFilter = false var filteredAbilityList_Gen: [Ability] { if showingGenFilter { if inclusiveGenFilter { return Array(abilityList).filter{$0.generation_id ?? 100 <= self.selectedVersion.versionGen} } else { return Array(abilityList).filter{$0.generation_id == self.selectedVersion.versionGen} } } else { return Array(abilityList).filter{$0.generation_id ?? 100 <= self.selectedVersion.versionGen} } } var filteredAbilityList_Conquest: [Ability] { if showingConquestFilter { return filteredAbilityList_Gen } else { return Array(filteredAbilityList_Gen).filter{$0.is_main_series == 1} } } var sortedAbilityList: [Ability] { switch sorting { case .number: return filteredAbilityList_Conquest.sorted{$0.id < $1.id} case .name: return filteredAbilityList_Conquest.sorted{$0.wrappedName < $1.wrappedName} } } var orderedAbilityList: [Ability] { switch order { case .forward: return sortedAbilityList case .backward: return sortedAbilityList.reversed() } } var body: some View { // NavigationView { VStack { SearchBar(text: $searchAbilityText) .padding(.horizontal, 4) List(orderedAbilityList.filter{ self.searchAbilityText.isEmpty ? true : $0.identifier.contains(self.searchAbilityText) }) { ability in Section { NavigationLink(destination: AbilityDetailView(pokemonList:pokemonList, pokemonFormsList: pokemonFormsList, pokemonTypeList:pokemonTypeList, moveList:moveList, moveEffectList:moveEffectList, typeList:typeList, abilityList:abilityList, abilityProseList:abilityProseList, pokemonAbilitiesList:pokemonAbilitiesList, itemList: itemList, ability: ability)) { HStack { // Display the ability name Text("\(ability.wrappedName)") } } } } .id(UUID()) } .navigationBarTitle("Ability List") .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { self.showSheetView.toggle() }) { Label("Filter List", systemImage: "arrow.up.arrow.down.circle.fill") } } } .sheet( isPresented: self.$showSheetView) { NavigationView { Form { Section(header: Text("Order...")) { Picker(selection: self.$order, label: Text("Ordering: ")) { ForEach(OrderType.allCases, id: \.self) { Text("\($0.rawValue)") } } .pickerStyle(SegmentedPickerStyle()) } Section(header: Text("Sort by...")) { Picker(selection: self.$sorting, label: Text("Choose to sort by: ")) { ForEach(SortType.allCases, id: \.self) { Text("\($0.rawValue)") } } .pickerStyle(SegmentedPickerStyle()) } Section(header: Text("Filter by...")) { Toggle(isOn: self.$showingGenFilter.animation()) { Text("Filter by Generation?") } if self.showingGenFilter { Picker(selection: self.$genFilter, label: EmptyView()) { ForEach(3...7, id: \.self) { Text("Gen \($0)") } } .pickerStyle(WheelPickerStyle()) Toggle(isOn: self.$inclusiveGenFilter) { Text("Include previous generations?") } } } Section(header: Text("Defaults")) { Button(action: { self.order = OrderType.forward self.sorting = SortType.number self.showingGenFilter = false self.inclusiveGenFilter = false self.showSheetView = false }) { HStack { Spacer() Text("Set to default") .fontWeight(.semibold) Spacer() } .padding() } } } .navigationBarTitle(Text("Sort and Filter"), displayMode: .inline) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { self.showSheetView = false }) { Text("Done").bold() } } } } .navigationViewStyle(StackNavigationViewStyle()) } } }
// // ViewController.swift // rentaTest // // Created by Egor Vdovin on 21/09/2019. // Copyright © 2019 Egor Vdovin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var dateLabel: UILabel! var photo: Photo? var index: Int? let cache = NSCache<NSString, AnyObject>() override func viewDidLoad() { super.viewDidLoad() setInfo() } private func setInfo() { guard let photo = photo else { return } if let cachedImage = photo.largeImage { DispatchQueue.main.async { self.imageView.image = cachedImage if let date = photo.date { self.dateLabel.text = date } } } else { ImageLoader.init(url: photo.largeImageUrl).loadImage { (image) in photo.largeImage = image photo.date = Date().description self.cache.setObject(photo, forKey: (self.index ?? 0) as NSString) DispatchQueue.main.async { self.imageView.image = image if let date = photo.date { self.dateLabel.text = date } } } } } }
// // Side.swift // Side // // Created by Truong Son Nguyen on 10/26/17. // Copyright © 2017 Truong Son Nguyen. All rights reserved. // import XCTest import EarlGrey class Side: XCTestCase { func testBasicSelectionAndAction() { // Select and tap the button with Accessibility ID "Sign". EarlGrey.select(elementWithMatcher: grey_accessibilityID("Sign")) .perform(grey_tap()) } func testExample() { EarlGrey.select(elementWithMatcher: grey_keyWindow()) .assert(grey_sufficientlyVisible()) // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testBasicSelectionAndAssert() { // Select the button with Accessibility ID "clickMe" and assert it's visible. EarlGrey.select(elementWithMatcher: grey_accessibilityID("Sign")) .assert(with: grey_sufficientlyVisible()) } func testBasicSelectionActionAssert() { // Select and tap the button with Accessibility ID "clickMe", then assert it's visible. EarlGrey.select(elementWithMatcher: grey_accessibilityID("Member")) .perform(grey_tap()) .assert(with: grey_sufficientlyVisible()) } }
// // NetworkingManagerAlamofire.swift // JustTest // // Created by Stanislav Dymedyuk on 1/30/17. // Copyright © 2017 JustStan. All rights reserved. // import UIKit import Alamofire class NetworkingManagerAlamofire: NSObject, NetworkManagerProtocol { func request(_ requestURL: String, params: [String: Any], callback: @escaping ([String: Any]?, Error?) -> (Void)) { Alamofire.request(requestURL, parameters: params) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON { response in if let json = response.result.value as? Dictionary<String, Any> { callback(json,nil) } else { callback(nil,response.result.error) } } } }
// // ViewController.swift // googleSignin // // Created by Sujeet.Kumar on 27/02/20. // Copyright © 2020 Cuddle. All rights reserved. // import UIKit import GoogleSignIn import MSAL /// See this as a loginViewController. class ViewController: UIViewController,MicrosoftLoginServiceDelegate,GoogleSiginServiceDelegate,PingFederateSigninProtocol { @IBOutlet weak var signInButton: GIDSignInButton! { didSet { // signInButton.set } } @IBOutlet weak var microsoftLoginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setUpGoogleSigin() setUpMicrsoftSigin() setUpPingFederateSignIn() } static func instance() -> ViewController? { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) guard let detailController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController else {return nil} return detailController } private func launchDetailController() { //launch the detail AppDelegate.getAppDelegate().launchDetailController() } //MARK:- Google func setUpGoogleSigin() { GoogleSiginService.shared.setUp(presentingViewController: self, delegate: self) } //MARK:- GoogleSiginServiceDelegate func didGoogleSignIn(user:GIDGoogleUser?, error:Error?) { if let error = error { if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue { print("The user has not signed in before or they have since signed out.") } else { print("\(error.localizedDescription)") } return } // //setup signin mode info SignInMode.setPersistentSignMode(mode:.google) // Perform any operations on signed in user here. let userId = user?.userID // For client-side use only! let idToken = user?.authentication.idToken // Safe to send to the server let fullName = user?.profile.name let givenName = user?.profile.givenName // let familyName = user.profile.familyName let email = user?.profile.email print(""" Google User detail = \(userId), \(idToken), \(fullName), \(givenName), \(email) """) self.launchDetailController() } //MARK::- PingFederate var pingFederateService:PingFederateLoginService? @IBAction func pingFederateLoginAction(_ sender: Any) { self.pingFederateService?.actionSignIn() } func setUpPingFederateSignIn() { pingFederateService = PingFederateLoginService.shared pingFederateService?.setUp(withConfig: PingFederateConfig(), presentingController: self, delegate: self) } func didSignin(withToken token: String?, error: PingFederateLoginError?) { } func didGetUserDetail(user: Any?, error: PingFederateLoginError?) { guard let userDetail = user else { print("Got error \(error)") return } guard let userInfo = userDetail as? [String:Any] else {return} print("UserInfo Email = \(userInfo["email"])") //setup signin mode info SignInMode.setPersistentSignMode(mode:.pingFederate) let token = pingFederateService?.accessToken ?? "" print("token = \(String(describing: token))") self.launchDetailController() } //MARK:- MICROSOFT var micrsoftService:MicrosoftLoginService? func setUpMicrsoftSigin() { micrsoftService = MicrosoftLoginService.shared micrsoftService?.setUp(withParentController:self,delegate:self) } @IBAction func MicrosoftLoginAction(_ sender: Any) { self.micrsoftService?.callGraphAPI(sender as! UIButton) } //MARK:- MicrosoftLoginServiceDelegate func didAquireToken(token:String?, errror:MicroSoftLoginError?) { if let loginError = errror { //error found print("microsoft Error = \(loginError)") } else { //login successful //setup signin mode info SignInMode.setPersistentSignMode(mode:.microsoft) print("token = \(String(describing: token))") self.launchDetailController() } } func didGetUserDetail(user: Any?, error: MicroSoftLoginError?) { } }
// // tables.swift // OS Helper 2 // // Created by Alan Brooks on 5/2/16. // Copyright © 2016 Chips & Ink. All rights reserved. // import Foundation struct codeDescription { let code: String let description: String }
import Foundation final class ContinentListCoordinator: BaseCoordinator { private var viewModel: ContinentListViewModelProtocol private var countryCoordinator: BaseCoordinator? override init(router: AppRouterProtocol) { viewModel = ContinentListViewModel() super.init(router: router) } init(router: AppRouterProtocol, viewModel: ContinentListViewModelProtocol, countryCoordinator: BaseCoordinator) { self.viewModel = viewModel self.countryCoordinator = countryCoordinator super.init(router: router) } override func start(onFinish: (() -> ())? = nil) { viewModel.coordinatorDelegate = self let viewController = ContinentListViewController(viewModel: viewModel) router.push(viewController, isAnimated: true, onNavigateBack: onFinish) } } extension ContinentListCoordinator: ContinentListCoordinatorDelegate { func startCountryListScene(continent: ContinentListQuery.Data.Continent) { let countryCoordinator = self.countryCoordinator ?? CountryListCoordinator(router: router, continent: continent) store(coordinator: countryCoordinator) countryCoordinator.start { [weak self] in self?.free(coordinator: countryCoordinator) } } }
// // SecretWordCellViewCollectionViewCell.swift // DragAndDrop // // Created by Badre DAHA BELGHITI on 08/12/2019. // Copyright © 2019 BadNetApps. All rights reserved. // import UIKit class SecretWordCellView: UICollectionViewCell { @IBOutlet var secretWordLabel: UILabel! @IBOutlet var numberWordIncrementLabel: UILabel! var secretWord: String = ""{ didSet{ updateSecretWord() } } var numberWordIncrement: String = ""{ didSet{ updateNumber() } } private func updateSecretWord(){ self.secretWordLabel.text = secretWord } private func updateNumber(){ self.numberWordIncrementLabel.text = numberWordIncrement } }
// // CustomViews.swift // Example // // Created by Ben Guo on 9/8/18. // Copyright © 2018 Stripe. All rights reserved. // import UIKit import Static open class RedButtonCell: ButtonCell { // MARK: - Initializers public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) tintColor = UIColor.red } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) tintColor = UIColor.red } } open class MethodStartCell: UITableViewCell, Cell { public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) self.textLabel?.font = UIFont(name: "Menlo", size: UIFont.smallSystemFontSize) self.backgroundColor = UIColor.groupTableViewBackground } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } open class LogEventCell: UITableViewCell, Cell { public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) self.detailTextLabel?.textColor = UIColor.gray if let size = self.detailTextLabel?.font.pointSize { self.detailTextLabel?.font = UIFont(name: "Menlo", size: size) } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class AmountInputView: TextFieldView, UITextFieldDelegate { var amount: UInt { if let text = textField.text, let amount = UInt(text) { return amount } return 0 } var amountString: String { var doubleAmount = Double(amount) if !StripeCurrencies.isNoDecimalCurrency(currency: self.numberFormatter.currencyCode) { doubleAmount = Double(amount)/Double(100) } return numberFormatter.string(from: NSNumber(value: doubleAmount)) ?? "" } var onAmountUpdated: (String) -> Void = { _ in } var numberFormatter = NumberFormatter() private let defaultAmount: UInt = 100 convenience init() { self.init(text: "Amount", footer: "") textField.text = String(defaultAmount) textField.delegate = self textField.keyboardType = .numberPad numberFormatter.currencyCode = "usd" numberFormatter.numberStyle = .currency } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let newText = text.replacingCharacters(in: textRange, with: string) if newText.count < 9 { textField.text = newText } } onAmountUpdated(amountString) return false } func textFieldDidEndEditing(_ textField: UITextField) { textField.text = String(amount) } } class CurrencyInputView: TextFieldView, UIPickerViewDelegate, UIPickerViewDataSource { /// A lowercased representation of the currently selected currency code. /// /// "usd" or "cad" would both be possible values here; "GBP" or /// "Singapore Dollars" would not be. var currency: String { if let text = textField.text { return text.lowercased() } return "usd" } var onCurrencyUpdated: (String) -> Void = { _ in } let pickerView = UIPickerView(frame: CGRect.zero) convenience init() { self.init(text: "Currency", footer: "") textField.text = StripeCurrencies.supported.first textField.keyboardType = .alphabet pickerView.dataSource = self pickerView.delegate = self pickerView.backgroundColor = UIColor.white textField.inputView = pickerView } func initialize() { textField.inputView = pickerView } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return StripeCurrencies.supported.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let currencyCode = StripeCurrencies.supported[row] var title = currencyCode if let localizedString = NSLocale.current.localizedString(forCurrencyCode: currencyCode.uppercased()) { title = "\(title) – \(localizedString)" } return title } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let currency = StripeCurrencies.supported[row] onCurrencyUpdated(currency) textField.text = currency } } class TextFieldView: UIView { lazy var textField: InsetTextField = { let textField = InsetTextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.font = UIFont.systemFont(ofSize: UIFont.labelFontSize) textField.inset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) textField.backgroundColor = UIColor.white return textField }() lazy var footerLabel: InsetLabel = { let label = InsetLabel() label.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false label.inset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) label.backgroundColor = UIColor.groupTableViewBackground label.textColor = UIColor.gray label.isUserInteractionEnabled = true return label }() init(text: String, footer: String) { super.init(frame: .zero) backgroundColor = UIColor.white addSubview(textField) footerLabel.text = footer addSubview(footerLabel) let stack = UIStackView(arrangedSubviews: [ textField, footerLabel ]) stack.axis = .vertical stack.distribution = .equalSpacing addSubview(stack) stack.translatesAutoresizingMaskIntoConstraints = false let insets = UIEdgeInsets.zero if #available(iOS 11.0, *) { stack.anchor(to: safeAreaLayoutGuide, withInsets: insets) } else { stack.anchorToSuperviewAnchors(withInsets: insets) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MonospaceTextView: UIView { private lazy var label: UILabel = { let label = UILabel() label.font = UIFont(name: "Menlo", size: UIFont.systemFontSize) label.numberOfLines = 0 label.textColor = UIColor.darkGray label.translatesAutoresizingMaskIntoConstraints = false return label }() init(text: String) { super.init(frame: .zero) layoutMargins = UIEdgeInsets(top: 20, left: 16, bottom: 20, right: 16) addSubview(label) label.text = text label.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor).isActive = true label.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor).isActive = true label.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true label.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class LinkTextView: UIView { static func buildAttributedString(prefix: String, linkName: String, urlString: String) -> NSAttributedString { let font = UIFont.systemFont(ofSize: UIFont.systemFontSize) let aString = NSMutableAttributedString(string: prefix + linkName) let fullRange = NSRange(location: 0, length: aString.string.count) let prefixRange = NSRange(location: 0, length: prefix.count) aString.addAttribute(.foregroundColor, value: UIColor.gray, range: prefixRange) aString.addAttribute(.font, value: font, range: fullRange) let linkRange = NSRange(location: prefix.count, length: linkName.count) aString.addAttribute(.link, value: urlString, range: linkRange) return aString } private lazy var textView: UITextView = { let view = UITextView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.clear view.isScrollEnabled = false view.isEditable = false return view }() init(prefix: String, linkName: String, urlString: String) { super.init(frame: CGRect.zero) layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) addSubview(textView) textView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor).isActive = true textView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor).isActive = true textView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true textView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true textView.setContentOffset(CGPoint.zero, animated: false) textView.attributedText = LinkTextView.buildAttributedString(prefix: prefix, linkName: linkName, urlString: urlString) textView.sizeToFit() frame = CGRect(x: 0, y: 0, width: 0, height: textView.bounds.height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ActivityIndicatorHeaderView: UIView { let activityIndicator = UIActivityIndicatorView(style: .gray) var title: String { didSet { label.text = title.uppercased() } } private lazy var label: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) label.textColor = UIColor(red: 0.42, green: 0.42, blue: 0.44, alpha: 1.0) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() init(title: String) { self.title = title super.init(frame: .zero) label.text = title.uppercased() // https://useyourloaf.com/blog/stack-views-and-multi-line-labels/ activityIndicator.setContentHuggingPriority(.required - 1, for: .horizontal) let stack = UIStackView(arrangedSubviews: [ label, activityIndicator ]) stack.axis = .horizontal stack.distribution = .fill addSubview(stack) stack.translatesAutoresizingMaskIntoConstraints = false let insets = UIEdgeInsets(top: 14, left: 16, bottom: 6, right: 16) if #available(iOS 11.0, *) { stack.anchor(to: safeAreaLayoutGuide, withInsets: insets) } else { stack.anchorToSuperviewAnchors(withInsets: insets) } bounds.size.height = 50 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class InsetTextField: UITextField { public var inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) { didSet { setNeedsDisplay() } } public override init(frame: CGRect) { super.init(frame: frame) } convenience init() { self.init(frame: .zero) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: inset) } open override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: inset) } open override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: inset) } open override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: inset)) } } open class InsetLabel: UILabel { open var inset: UIEdgeInsets = UIEdgeInsets() { didSet { super.invalidateIntrinsicContentSize() } } open override var intrinsicContentSize: CGSize { var size = super.intrinsicContentSize size.width += inset.left + inset.right size.height += inset.top + inset.bottom return size } override open func drawText(in rect: CGRect) { return super.drawText(in: rect.inset(by: inset)) } } open class LargeTitleNavigationController: UINavigationController { open override func viewDidLoad() { super.viewDidLoad() navigationBar.isTranslucent = false if #available(iOS 11.0, *) { navigationBar.prefersLargeTitles = true } if #available(iOS 13.0, *) { navigationBar.isTranslucent = true } } }
// // FilterViewCell3.swift // UberEATS // // Created by Sean Zhang on 7/23/18. // Copyright © 2018 Sean Zhang. All rights reserved. // import UIKit class FilterViewCell3: UICollectionViewCell { var delegate: FilterSelectDelegate? let dietOptions: [String] = ["Vegetarian", "Vegan", "Gluten-free", "Halal"]; let dietImages:[String] = ["filter_vegetarian", "filter_vegan", "filter_glutenfree", "filter_hala"]; let tableView: UITableView = { let table = UITableView(frame: .zero) table.translatesAutoresizingMaskIntoConstraints = false table.isScrollEnabled = false let imgview = UIImageView() return table }() override init(frame: CGRect) { super.init(frame: frame) setupTableView() setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupTableView() { self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(FilterTableCell.self, forCellReuseIdentifier: "FilterTableCell") self.tableView.separatorColor = .white } fileprivate func setupViews(){ addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: topAnchor, constant: 0), tableView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0), tableView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0), tableView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0) ]) } } extension FilterViewCell3: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FilterTableCell", for: indexPath) as! FilterTableCell cell.tl.text = dietOptions[indexPath.row] cell.iv.image = UIImage(imageLiteralResourceName: dietImages[indexPath.row]) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.selected(section: 2, row: indexPath.row) } }
// // ContentViewController.swift // SwiftSamples // // Created by Tsukasa Hasegawa on 2019/01/02. // Copyright © 2019 Tsukasa Hasegawa. All rights reserved. // import UIKit class ContentViewController: UIViewController { @IBOutlet weak var contentLabel: UILabel! var index: Int? override func viewDidLoad() { super.viewDidLoad() if let index = index { contentLabel.text = PagingMenu.items[index].contentTitle view.backgroundColor = PagingMenu.items[index].themeColor } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // ConfessionGuys.swift // FaceppCLI // // Created by 姜振华 on 2020/3/8. // import Foundation
// // Text_ImportedFont.swift // 100Views // // Created by Mark Moeykens on 9/5/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Text_ImportedFont: View { var body: some View { VStack(spacing: 20) { Text("Text") .font(.largeTitle) Text("Imported Fonts") .font(.title) .foregroundColor(.gray) Text("Use the Font.custom() function to set imported fonts you added to your project.") .padding().layoutPriority(1) .frame(maxWidth: .infinity) .background(Color.green) .foregroundColor(.white) .font(.title) Text("Hello, World!") // Specify the name and size of the font to use // (Note: You can remove "Font." and it'll still work) .font(Font.custom("Nightcall", size: 60)) .padding(.top) } } } struct Text_ImportedFont_Previews: PreviewProvider { static var previews: some View { Text_ImportedFont() } }
// // SeleccionarCorreoViewController.swift // INSSAFI // // Created by Pro Retina on 7/19/18. // Copyright © 2018 Novacomp. All rights reserved. // import UIKit class SeleccionarCorreoViewController: UIViewController,UITableViewDataSource, UITableViewDelegate { typealias JSONStandard = Dictionary<String, Any> var user: User! var favorita:JSONStandard? var vencimiento:JSONStandard? var solicitud:JSONStandard? var solicitudProgramada:JSONStandard? var correos = [String]() var selectedCorreo = "" var subcuenta = "" var operacion:String = "" var referencia:String = "" @IBOutlet weak var tableView: UITableView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var titleImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() user = User.getInstance() obtenerCorreos() } override func viewWillAppear(_ animated: Bool) { if (solicitud != nil) { titleLabel.text = "Solicitudes" titleImageView.image = UIImage(named: "solicitudes2") } else if (solicitudProgramada != nil) { titleLabel.text = "Solicitudes" titleImageView.image = UIImage(named: "solicitudes2") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "ingresarCodigoSegue") { let vc = segue.destination as! IngresarCodigoViewController vc.referencia = referencia vc.subcuenta = subcuenta vc.operacion = operacion } } func obtenerCorreos() { let networkReachability = Reachability.forInternetConnection let networkStatus = networkReachability().currentReachabilityStatus if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) { let alert = Functions.getLoading("Obteniendo información") present(alert!, animated: true, completion: getCorreos) } else { // Mostramos el error //[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"]; } } func getCorreos() { let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_TRAER_CORREOS) let params = ["NI":user.getUser()!,"TK":user.getToken()!] let data = ["pConsulta":params] var dataString = "\(data)" dataString = dataString.replacingOccurrences(of: "[", with: "{") dataString = dataString.replacingOccurrences(of: "]", with: "}") let paramsExtern = ["pJsonString":dataString] NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in self.dismiss(animated: true, completion: nil) let response = data["TraerCorreosPersonaResult"] as! String let dataJson = response.data(using: String.Encoding.utf8) do { let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard print(dataDictionary) let resultado = dataDictionary["Resultado"] as! JSONStandard if let contenido = resultado["Contenido"] as? [JSONStandard] { for correo in contenido { self.correos.append(correo["CO"] as! String) } self.tableView.reloadData() } } catch { } } } func agregarFavorita() { let networkReachability = Reachability.forInternetConnection let networkStatus = networkReachability().currentReachabilityStatus if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) { let alert = Functions.getLoading("Obteniendo información") present(alert!, animated: true, completion:addFavorita) } else { // Mostramos el error //[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"]; } } func addFavorita() { let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_GRABAR_FAVORITA) let moneda = (favorita!["MO"] as! String) == "Colones" ? "COL" : "DOL" let params = ["NI":user.getUser()!, "CU":user.getSelectedCuenta()!, "TV":"C", "CC":favorita!["CC"] as! String, "NO":favorita!["NO"] as! String, "MO":moneda, "CE":(favorita!["CE"] as! NSNumber).stringValue, "IT":favorita!["IC"] as! String, "CO":selectedCorreo, "TK":user.getToken()!] //let params = ["NI":user.getUser()!, "CU":user.getSelectedCuenta()!, "TV":"C", "CC":"CR70015202001142490739", "NO":favorita!["NO"] as! String, "MO":favorita!["MO"] as! String, "CE":(favorita!["CE"] as! NSNumber).stringValue, "IT":favorita!["IC"] as! String, "CO":selectedCorreo, "TK":user.getToken()!] let data = ["pTransaccion":params] var dataString = "\(data)" dataString = dataString.replacingOccurrences(of: "[", with: "{") dataString = dataString.replacingOccurrences(of: "]", with: "}") let paramsExtern = ["pJsonString":dataString] NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in self.dismiss(animated: true, completion: nil) let response = data["GrabarCuentaFavoritaResult"] as! String let dataJson = response.data(using: String.Encoding.utf8) do { let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard print(dataDictionary) let resultado = dataDictionary["Resultado"] as! JSONStandard if let respuesta = resultado["Respuesta"] as? JSONStandard { if( String(describing: respuesta["CodMensaje"]!) != "0") { self.showAlert(title: "", message: respuesta["Mensajes"] as! String) } else { let alertSuccess = UIAlertController(title: "Éxito", message: respuesta["Mensajes"] as? String, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction (title: "OK", style: .default, handler: { (alert: UIAlertAction!) in self.operacion = "C" self.referencia = respuesta["Referencia"] as! String self.performSegue(withIdentifier: "ingresarCodigoSegue", sender: nil) }) alertSuccess.addAction(okAction) self.present(alertSuccess, animated: true, completion: nil) } } } catch { } } } func agregarVencimiento() { let networkReachability = Reachability.forInternetConnection let networkStatus = networkReachability().currentReachabilityStatus if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) { let alert = Functions.getLoading("Obteniendo información") present(alert!, animated: true, completion:addVencimiento) } else { // Mostramos el error //[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"]; } } func addVencimiento() { let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_GRABAR_VENCIMIENTO) var params:JSONStandard = self.solicitud! params["CO"] = selectedCorreo let data = ["pTransaccion":params] var dataString = "\(data)" dataString = dataString.replacingOccurrences(of: "[", with: "{") dataString = dataString.replacingOccurrences(of: "]", with: "}") let paramsExtern = ["pJsonString":dataString] NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in self.dismiss(animated: true, completion: nil) let response = data["GrabarCuentaFavoritaResult"] as! String let dataJson = response.data(using: String.Encoding.utf8) do { let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard print(dataDictionary) let resultado = dataDictionary["Resultado"] as! JSONStandard if let respuesta = resultado["Respuesta"] as? JSONStandard { if( String(describing: respuesta["CodMensaje"]!) != "0") { self.showAlert(title: "", message: respuesta["Mensajes"] as! String) } else { let alertSuccess = UIAlertController(title: "Éxito", message: respuesta["Mensajes"] as? String, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction (title: "OK", style: .default, handler: { (alert: UIAlertAction!) in self.operacion = "V" self.referencia = respuesta["Referencia"] as! String self.performSegue(withIdentifier: "ingresarCodigoSegue", sender: nil) }) alertSuccess.addAction(okAction) self.present(alertSuccess, animated: true, completion: nil) } } } catch { } } } func agregarSolicitud() { let networkReachability = Reachability.forInternetConnection let networkStatus = networkReachability().currentReachabilityStatus if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) { let alert = Functions.getLoading("Obteniendo información") present(alert!, animated: true, completion: { self.addSolicitud() }) } else { // Mostramos el error //[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"]; } } func addSolicitud() { let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_GRABAR_SOLICITUD) var params:JSONStandard = self.solicitud! params["CO"] = selectedCorreo let data = ["pTransaccion":params] var dataString = "\(data)" dataString = dataString.replacingOccurrences(of: "[", with: "{") dataString = dataString.replacingOccurrences(of: "]", with: "}") let paramsExtern = ["pJsonString":dataString] NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in self.dismiss(animated: true, completion: nil) let response = data["GrabarSolicitudesResult"] as! String let dataJson = response.data(using: String.Encoding.utf8) do { let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard print(dataDictionary) let resultado = dataDictionary["Resultado"] as! JSONStandard if let respuesta = resultado["Respuesta"] as? JSONStandard { if(String(describing: respuesta["CodMensaje"]!) != "0") { self.showAlert(title: "", message: respuesta["Mensajes"] as! String) } else { let alertSuccess = UIAlertController(title: "Éxito", message: respuesta["Mensajes"] as? String, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction (title: "OK", style: .default, handler: { (alert: UIAlertAction!) in if(self.solicitud!["TR"] == nil) { self.operacion = "I" } else { self.operacion = "R" } self.referencia = respuesta["Referencia"] as! String self.performSegue(withIdentifier: "ingresarCodigoSegue", sender: nil) }) alertSuccess.addAction(okAction) self.present(alertSuccess, animated: true, completion: nil) } } } catch { } } } func agregarSolicitudProgramada() { let networkReachability = Reachability.forInternetConnection let networkStatus = networkReachability().currentReachabilityStatus if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) { let alert = Functions.getLoading("Obteniendo información") present(alert!, animated: true, completion: { self.addSolicitudProgramada() }) } else { // Mostramos el error //[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"]; } } func addSolicitudProgramada() { let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_GRABAR_INVERSION) var params:JSONStandard = self.solicitudProgramada! params["CO"] = selectedCorreo let data = ["pTransaccion":params] var dataString = "\(data)" dataString = dataString.replacingOccurrences(of: "[", with: "{") dataString = dataString.replacingOccurrences(of: "]", with: "}") let paramsExtern = ["pJsonString":dataString] NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in self.dismiss(animated: true, completion: nil) let response = data["GrabarInversionProgramadaResult"] as! String let dataJson = response.data(using: String.Encoding.utf8) do { let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard print(dataDictionary) let resultado = dataDictionary["Resultado"] as! JSONStandard if let respuesta = resultado["Respuesta"] as? JSONStandard { if(String(describing: respuesta["CodMensaje"]!) != "0") { self.showAlert(title: "", message: respuesta["Mensajes"] as! String) } else { let alertSuccess = UIAlertController(title: "Éxito", message: respuesta["Mensajes"] as? String, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction (title: "OK", style: .default, handler: { (alert: UIAlertAction!) in self.operacion = "P" self.referencia = respuesta["Referencia"] as! String self.performSegue(withIdentifier: "ingresarCodigoSegue", sender: nil) }) alertSuccess.addAction(okAction) self.present(alertSuccess, animated: true, completion: nil) } } } catch { } } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return correos.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 64 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "correoCell") as! CorreoCell cell.correoLabel.text = correos[indexPath.row] return cell } /// Stub for responding to user row selection. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) selectedCorreo = correos[indexPath.row] if (favorita != nil) { agregarFavorita() } else if (solicitud != nil) { agregarSolicitud() } else if (solicitudProgramada != nil) { agregarSolicitudProgramada() } else if (vencimiento != nil) { agregarVencimiento() } } } class CorreoCell: UITableViewCell { @IBOutlet weak var correoLabel: UILabel! }
// // ProfileViewController.swift // ModuleProfile // // Created by 孙梁 on 2021/3/1. // import UIKit import ModuleComm class ProfileViewController: BaseViewController { } extension ProfileViewController { override func setMasterView() { super.setMasterView() title = "我的" view.backgroundColor = UIColor.sl_randomColor() } }
// // DetailViewController.swift // FarmStamp // // Created by CSC-PC on 2016. 6. 6.. // Copyright © 2016년 thatzit. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet var addr: UITextView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // LeetCode509.swift // LeetCode // // Created by 360JR on 2021/1/4. // Copyright © 2021 liangqili.com. All rights reserved. // /** 斐波那契数,通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,F(1) = 1 F(n) = F(n - 1) + F(n - 2),其中 n > 1 给你 n ,请计算 F(n) 。   示例 1: 输入:2 输出:1 解释:F(2) = F(1) + F(0) = 1 + 0 = 1 示例 2: 输入:3 输出:2 解释:F(3) = F(2) + F(1) = 1 + 1 = 2 示例 3: 输入:4 输出:3 解释:F(4) = F(3) + F(2) = 2 + 1 = 3   提示: 0 <= n <= 30 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fibonacci-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ import Foundation class Solution509_1 { func fib(_ n: Int) -> Int { if n < 2 { return n } return fib(n-1)+fib(n-2) } } class Solution509_2 { func fib(_ n: Int) -> Int { if n < 2 { return n } var p = 0, q = 1, r = 1 var index = 3 while index <= n { p = q q = r r = p + q index += 1 } return r } } class Solution509_3 { func fib(_ n: Int) -> Int { var arr = Array(repeating: -1, count: 31) arr[0] = 0 arr[1] = 1 return self.calc(n,&arr) } func calc(_ n: Int, _ arr: inout Array<Int>) -> Int { if arr[n] >= 0 { return arr[n] } let ret = self.calc(n-1, &arr) + self.calc(n-2, &arr) arr[n] = ret return ret } } /** func printTime(_ n : Int) { let slu = Solution509_1() let start = CFAbsoluteTimeGetCurrent() let ret1 = slu.fib(n) let end1 = CFAbsoluteTimeGetCurrent() - start let str = String(format: "%f", end1) print("\(ret1) & \(str)") } func printTime2(_ n : Int) { let slu = Solution509_2() let start = CFAbsoluteTimeGetCurrent() let ret1 = slu.fib(n) let end1 = CFAbsoluteTimeGetCurrent() - start let str = String(format: "%f", end1) print("\(ret1) & \(str)") } func printTime3(_ n : Int) { let slu = Solution509_3() let start = CFAbsoluteTimeGetCurrent() let ret1 = slu.fib(n) let end1 = CFAbsoluteTimeGetCurrent() - start let str = String(format: "%f", end1) print("\(ret1) & \(str)") } printTime(30) printTime2(30) printTime3(30) */
//: Playground - noun: a place where people can play import UIKit //// 定义字符串 //let str = "xiaofan" //// 遍历字符串 //for c in str.characters { //print(c) //} // 字符的拼接 //let str1 = "xiao" //let str2 = "ming" //let str3 = str1 + str2 //// 字符串和其他标识符之间的拼接 //let name = "xiaoming" //let age = 18 //let height = 1.67 //let info = "my name is \(name), my age is \(age), my height is \(height)" //// 拼接字符串时, 字符串的格式化 //let min = 2 //let second = 35 //let timeStr = String(format: "%02d:%02d", arguments: [min, second]) //z 字符串的截取 let urlStr = "www.devxiaofan.com" // 将 String 转成 NSString 再截取 let header = (urlStr as NSString).substringToIndex(3) let middle = (urlStr as NSString).substringWithRange(NSMakeRange(4, 10)) let footer = (urlStr as NSString).substringFromIndex(15)
// // Flat.swift // Staff // // Created by James Bean on 6/14/16. // // import QuartzCore public class Flat: Accidental { public override var description: String { get { return "flat" } } internal var column_up_height: CGFloat { get { return 1.618 * gS } } internal var column_down_height: CGFloat { get { return 0.75 * gS } } internal override var height: CGFloat { get { return column_up_height + column_down_height } } internal override var width: CGFloat { get { return midWidth } } internal override var xRef: CGFloat { get { return 0.5 * midWidth } } internal override var yRef: CGFloat { get { return column_up_height } } public override func createComponents() { addBody() addColumnUp() addColumnDown() } internal func addBody() { body = ComponentBodyFlat( staffSlotHeight: staffSlotHeight, scale: scale, point: CGPoint(x: xRef + 0.4 * thinLineWidth, y: yRef) ) components.append(body!) } internal func addColumnUp() { column_left_up = ComponentColumn( staffSlotHeight: staffSlotHeight, scale: scale, x: 0, y_internal: yRef, y_external: yRef - column_up_height ) components.append(column_left_up!) column_left_up!.alignment = .right } internal func addColumnDown() { column_left_down = ComponentColumn( staffSlotHeight: staffSlotHeight, scale: scale, x: 0, y_internal: yRef, y_external: yRef + column_down_height ) components.append(column_left_down!) column_left_down!.alignment = .left } }
/*: ### UIView contentMode Quick Guide The `contentMode` property of UIView allows you to control how to layout a view when the view's bounds change. The system will not, by default, redraw a view each time the bounds change. That would be wasteful. Instead, depending on the content mode, it can scale, stretch or pin the contents to a fixed position. There are thirteen different content modes but it is easiest to think of three main groups based on the effect: #### Scaling the View (with or without maintaining the aspect ratio) + [Scale To Fill](ScaleToFill) + [Scale Aspect Fit](ScaleAspectFit) + [Scale Aspect Fill](ScaleAspectFill) #### Redrawing the View + [Redraw](Redraw) #### Positioning the View + [Center](Center) + [Top](Top) + [Bottom](Bottom) + [Left](Left) + [Right](Right) + [TopLeft](TopLeft) + [TopRight](TopRight) + [BottomLeft](BottomLeft) + [BottomRight](BottomRight) */
// // ViewController.swift // test001. prueba técnica para domicilios.com // // Creado por Henry Bautista on 22/05/18. // Copyright © 2018 Henry Bautista. Derechos reservados. // import UIKit import LocalAuthentication class ViewController: UIViewController { @IBOutlet weak var mainLogoXConstraint: NSLayoutConstraint! @IBOutlet weak var loginButtonXConstraint: NSLayoutConstraint! var animationPerformOnce = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // esto realiza la animacion de derecha a izquierda mainLogoXConstraint.constant -= view.bounds.width loginButtonXConstraint.constant -= view.bounds.width } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // esto realiza la compensacion de posicion para la animacion de derecha a izquierda if(!animationPerformOnce){ UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: { self.mainLogoXConstraint.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) UIView.animate(withDuration: 0.7, delay: 0.3, options: .curveEaseOut, animations: { self.loginButtonXConstraint.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) animationPerformOnce = true; } } @IBAction func prepareForUnwind(segue: UIStoryboardSegue){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func butAction(_ sender: Any) { beginFaceID() } // esta funcion realiza la validacion de reconocimiento facial y/o la de biometria por touch func beginFaceID() { let laContext = LAContext() var error: NSError? let biometricsPolicy = LAPolicy.deviceOwnerAuthenticationWithBiometrics if (laContext.canEvaluatePolicy(biometricsPolicy, error: &error)) { if let laError = error { print("laError - \(laError)") return } var localizedReason = "Unlock device" if #available(iOS 11.0, *) { switch laContext.biometryType { case .faceID: localizedReason = "Unlock using Face ID"; print("FaceId support") case .touchID: localizedReason = "Unlock using Touch ID"; print("TouchId support") case .none: print("No Biometric support") } } else { // Fallback on earlier versions deshabilidtado ya que este programa no funcionara en iphones menores al 6 } laContext.evaluatePolicy(biometricsPolicy, localizedReason: localizedReason, reply: { (isSuccess, error) in DispatchQueue.main.async(execute: { // se asegura que se ejecute en el tiempo correcto if let laError = error { print("laError - \(laError)") } else { if isSuccess { let alertController = UIAlertController(title: "HB Map Test App", message: "Bienvenido !", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Continuar", style: UIAlertActionStyle.default,handler: self.theAlertHandler)) self.present(alertController, animated: true, completion: nil) print("Exitoso") } } }) }) } } //controla el evento de dar continuar despues de un reconocimiento exitoso func theAlertHandler(alert: UIAlertAction!){ let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let newViewController = storyBoard.instantiateViewController(withIdentifier: "theSecondView") self.present(newViewController, animated: true, completion: nil) } }
// // MapViewController.swift // Skoolivin // // Created by Namrata A on 5/5/18. // Copyright © 2018 Namrata A. All rights reserved. // import UIKit import MapKit import SwiftyJSON class MapViewController: UIViewController { var currAddress: String! var mapView: MKMapView! var locs = [Location]() var currentPlcMark: CLPlacemark? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white mapView = MKMapView() let leftMargin:CGFloat = 10 let topMargin:CGFloat = 60 let mapWidth:CGFloat = view.frame.size.width-20 let mapHeight:CGFloat = 300 mapView.frame = CGRect(x: leftMargin, y: topMargin, width: mapWidth, height: mapHeight) mapView.mapType = MKMapType.standard mapView.isZoomEnabled = true mapView.isScrollEnabled = true mapView.center = view.center view.addSubview(mapView) let initLoc = CLLocation(latitude: 43.0393726, longitude: -76.13024290000001) mapZoom(loc: initLoc) //let initMarker = Location(coordinate: CLLocationCoordinate2D(latitude: 43.0393726, longitude: -76.13024290000001), locName: "College Place, SU") //mapView.addAnnotation(initMarker) fetchData() addDestAnnotation() self.mapView.delegate = self } private let regionRadius: CLLocationDistance = 1000 func addDestAnnotation(){ print("in add dest annotation with location count: ", locs.count) for loc in locs { print("comparing: ", loc.locName as Any, currAddress) if loc.locName == currAddress { let sourceLocation = CLLocationCoordinate2D(latitude: 43.0393726 , longitude: -76.13024290000001) let destinationLocation = loc.coordinate let initMarker = Location(coordinate: sourceLocation, locName: "College Place") mapView.addAnnotation(initMarker) let destMarker = Location(coordinate: destinationLocation, locName: loc.locName!) mapView.addAnnotation(destMarker) let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation) let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation) let directionRequest = MKDirectionsRequest() directionRequest.source = MKMapItem(placemark: sourcePlaceMark) directionRequest.destination = MKMapItem(placemark: destinationPlaceMark) directionRequest.transportType = .automobile let directions = MKDirections(request: directionRequest) directions.calculate { (response, error) in guard let directionResonse = response else { if let error = error { print("we have error getting directions==\(error.localizedDescription)") } return } let route = directionResonse.routes[0] self.mapView.add(route.polyline, level: .aboveRoads) let rect = route.polyline.boundingMapRect self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true) } } } } func mapZoom(loc: CLLocation){ let coordinateReg = MKCoordinateRegionMakeWithDistance(loc.coordinate, regionRadius * 2.0, regionRadius * 2.0) mapView.setRegion(coordinateReg, animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func fetchData() { let fileName = Bundle.main.path(forResource: "Venues", ofType: "json") let filePath = URL(fileURLWithPath: fileName!) var data: Data? do { data = try Data(contentsOf: filePath, options: Data.ReadingOptions(rawValue: 0)) } catch let error { data = nil print("Report error \(error.localizedDescription)") } if let jsonData = data { let json = JSON(jsonData) if json == JSON.null { print("whoops!")} if let locJsons = json["response"]["venues"].array { print("made it to the right path!") for locJSON in locJsons { if let loc = Location.from(json: locJSON) { print("yaayy!! ", loc.locName as Any) self.locs.append(loc) } } } } } } extension MapViewController : MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.blue renderer.lineWidth = 4.0 return renderer } }
// // KataPresenter.swift // KataLogin // // Created by Artur Costa-Pazo on 07/05/2019. // Copyright © 2019 Biometrics Team. All rights reserved. // import Foundation protocol KataView { func showLogInForm() -> Void func showLogOutForm() -> Void func showErrorMessage(message: String) -> Void } class KataPresenter{ var view: KataView; var login: LogIn; var logout: LogOut; init(view: KataView, login: LogIn, logout: LogOut) { self.view = view self.login = login self.logout = logout } func onLogInButtonClick(credentials: Credentials){ let result = login.invoke(credentials: credentials) switch(result){ case .success: view.showLogOutForm() case .invalidUsername: view.showErrorMessage(message: "Invalid Username") case .invalidUsernameAndPassowrd: view.showErrorMessage(message: "Invalid Credentials") } } func onLogOutButtonClick(){ if (logout.invoke()){ view.showLogInForm() } else{ view.showErrorMessage(message: "Log out error") } } }
import Foundation protocol FriendDetailRepositoryProtocol { func setFriend(_ friend: Friend) func getName() -> String func getAwards() -> [Award] func deleteFriend() func takethAway(award: Award) }
// // UCInputView.swift // ZGHFinance // // Created by zhangyr on 16/3/17. // Copyright © 2016年 cjxnfs. All rights reserved. // import UIKit enum UCInputViewType : Int { case Normal case WithButton } @objc protocol UCInputViewDelegate : NSObjectProtocol { optional func inputViewDidChanged(inputView : UCInputView , withInputString string : String) optional func inputViewButtonTap(inputView : UCInputView , actionButton : UIButton) } class UCInputView: UIView , UCInputViewDelegate { var text : String? { get { return textField.text } set { textField.text = newValue } } var iconImage : UIImage? { didSet { icon.image = iconImage } } var textColor : UIColor = UtilTool.colorWithHexString("#666") { didSet { textField.textColor = textColor } } var font : UIFont = UIFont.systemFontOfSize(12) { didSet { textField.font = font } } var placeholder : String = ""{ didSet { textField.placeholder = placeholder } } var secureTextEntry : Bool = false { didSet { textField.secureTextEntry = secureTextEntry } } var keyboardType : UIKeyboardType = .Default { didSet { textField.keyboardType = keyboardType } } var btnTitle : String = "" { didSet { button?.setTitle(btnTitle, forState: UIControlState.Normal) } } private var icon : UIImageView! private var textField : UITextField! private var button : BaseButton? private var sepLine : UIView? private weak var delegate : UCInputViewDelegate? init(type: UCInputViewType , delegate : UCInputViewDelegate? , needLine : Bool) { super.init(frame: CGRectZero) self.delegate = delegate icon = UIImageView() icon.image = iconImage self.addSubview(icon) textField = UITextField() textField.placeholder = placeholder textField.secureTextEntry = secureTextEntry textField.font = font textField.textColor = textColor textField.keyboardType = keyboardType textField.addTarget(self, action: #selector(UCInputView.didChanged(_:)), forControlEvents: UIControlEvents.EditingChanged) self.addSubview(textField) if type == .WithButton { button = BaseButton() button?.backgroundColor = UtilTool.colorWithHexString("#53a0e3") button?.titleLabel?.font = UIFont.systemFontOfSize(10) button?.setTitle(btnTitle, forState: UIControlState.Normal) button?.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) button?.layer.cornerRadius = 4 button?.layer.masksToBounds = true button?.addTarget(self, action: #selector(UCInputView.buttonTap(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(button!) } var offset : CGFloat = 0 if needLine { offset = -1 sepLine = UIView() sepLine?.backgroundColor = UtilTool.colorWithHexString("#ddd") self.addSubview(sepLine!) } icon.mas_makeConstraints { (maker) -> Void in maker.left.equalTo()(self).offset()(16) maker.centerY.equalTo()(self).offset()(offset) maker.width.equalTo()(15) maker.height.equalTo()(19) } button?.mas_makeConstraints({ (maker) -> Void in maker.right.equalTo()(self).offset()(-16) maker.centerY.equalTo()(self.icon) maker.width.equalTo()(80) maker.height.equalTo()(30) }) textField.mas_makeConstraints { (maker) -> Void in maker.left.equalTo()(self.icon.mas_right).offset()(24) maker.centerY.equalTo()(self.icon) if self.button == nil { maker.right.equalTo()(self).offset()(-16) }else{ maker.right.equalTo()(self.button?.mas_left).offset()(-16) } maker.height.equalTo()(self).offset()(offset) } sepLine?.mas_makeConstraints({ (maker) -> Void in maker.left.equalTo()(self) maker.right.equalTo()(self) maker.bottom.equalTo()(self) maker.height.equalTo()(1) }) } @objc private func buttonTap(button : UIButton) { delegate?.inputViewButtonTap?(self, actionButton: button) } @objc private func didChanged(tf : UITextField) { delegate?.inputViewDidChanged?(self, withInputString: tf.text!) } override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // SettingsTableViewController.swift // WarrantyTrackerv0.2 // // Created by Jeff Chimney on 2017-02-19. // Copyright © 2017 Jeff Chimney. All rights reserved. // import Foundation import UIKit import CloudKit import CoreData import EventKit import AVFoundation import StoreKit class SettingsTableViewController: UITableViewController { @IBOutlet weak var logOutButton: UIButton! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var allowDataSyncLabel: UILabel! @IBOutlet weak var allowCameraAccessLabel: UILabel! @IBOutlet weak var allowCalendarAccessLabel: UILabel! @IBOutlet weak var rateUnderWarantyLabel: UILabel! @IBOutlet weak var rateUnderWarrantySubTitle: UILabel! @IBOutlet weak var navBar: UINavigationItem! @IBOutlet weak var cameraSwitch: UISwitch! @IBOutlet weak var calendarSwitch: UISwitch! override func viewDidLoad() { if UserDefaultsHelper.isSignedIn() { logOutButton.setTitle("Sign Out", for:.normal) logOutButton.setTitleColor(UIColor.red, for: .normal) } else { logOutButton.setTitle("Sign In", for:.normal) logOutButton.setTitleColor(usernameLabel.tintColor, for: .normal) } usernameLabel.defaultFont = UIFont(name: "Kohinoor Bangla", size: 17)! allowDataSyncLabel.defaultFont = UIFont(name: "Kohinoor Bangla", size: 17)! allowCameraAccessLabel.defaultFont = UIFont(name: "Kohinoor Bangla", size: 17)! allowCalendarAccessLabel.defaultFont = UIFont(name: "Kohinoor Bangla", size: 17)! rateUnderWarantyLabel.defaultFont = UIFont(name: "Kohinoor Bangla", size: 17)! if EKEventStore.authorizationStatus(for: EKEntityType.event) == .authorized { calendarSwitch.isOn = true } else { calendarSwitch.isOn = false } if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized { cameraSwitch.isOn = true } else { cameraSwitch.isOn = false } } override func viewDidLayoutSubviews() { let defaults = UserDefaults.standard let username = defaults.string(forKey: "username") if username != nil { // user is logged in } let usernameRow = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! UsernamePasswordTableViewCell if UserDefaultsHelper.isSignedIn() { usernameRow.usernameLabel.text = UserDefaultsHelper.getUsername() } else { usernameRow.usernameLabel.text = "N/A" } let toggleRow = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! TitleAndSwitchTableViewCell toggleRow.toggle.isOn = UserDefaultsHelper.canSyncUsingData() } @IBAction func logOutButtonPressed(_ sender: Any) { if UserDefaultsHelper.isSignedIn() { // warn about losing data and prompt if they still want to log out let alertController = UIAlertController(title: "Are you sure you want to Sign Out?", message: "Any records stored locally on your device will be removed. Any changes not yet synced to the cloud will be lost.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert let DestructiveAction = UIAlertAction(title: "Sign Out Anyway", style: UIAlertActionStyle.destructive) { (result : UIAlertAction) -> Void in print("Sign Out Anyway") print("Deleting All Records") CoreDataHelper.deleteAll() print("Records Deleted, Signed Out") UserDefaultsHelper.isSignedIn(bool: false) //go to sign up page let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "AccountQuestionViewController") self.present(vc, animated: true, completion: nil) } // Replace UIAlertActionStyle.Default by UIAlertActionStyle.default let okAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("Cancel") } alertController.addAction(DestructiveAction) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } else { // tell user they won't lose data and log in. let alertController = UIAlertController(title: "Sign In", message: "Once signed in, any records stored locally on your device will be associated with your account and synced to the cloud.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert let DestructiveAction = UIAlertAction(title: "Sign In", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in UserDefaultsHelper.isSignedIn(bool: false) //go to sign up page let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "AccountQuestionViewController") self.present(vc, animated: true, completion: nil) } // Replace UIAlertActionStyle.Default by UIAlertActionStyle.default let okAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("Cancel") } alertController.addAction(DestructiveAction) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } @IBAction func cameraAccessSwitch(_ sender: Any) { guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } @IBAction func calendarAccessSwitch(_ sender: Any) { guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Account" case 1: return "Permissions" case 2: return "Feedback" default: return "" } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 2 { if #available(iOS 10.3, *) { SKStoreReviewController.requestReview() } else { // Fallback on earlier versions } } } }
// // Conductor.swift // GameboyMIDIPlayer // // Created by Evan Murray on 6/17/20. // Copyright © 2020 Evan Murray. All rights reserved. // import AudioKit class Conductor { static let shared = Conductor() var sampler: AKSampler var midiData: AKMIDIFile! var midiFile: AKAppleSequencer! var midiFileDescriptor: MIDIFileDescriptor! var midiFileConnector: AKMIDINode! var importedMIDIURL: URL! var lastMIDINote: Double! init() { AKSettings.enableLogging = true AKAudioFile.cleanTempDirectory() AKSettings.bufferLength = .short sampler = AKSampler() AudioKit.output = sampler do { try AudioKit.start() } catch { AKLog("AudioKit did not start") } } func setupMIDI() { midiFile = AKAppleSequencer(fromURL: importedMIDIURL) midiData = AKMIDIFile(url: importedMIDIURL) midiFileDescriptor = MIDIFileDescriptor(midiFile: midiData) midiFileConnector = AKMIDINode(node: sampler) midiFile.setGlobalMIDIOutput(midiFileConnector.midiIn) //lastMIDINote = midiFileDescriptor.finalNoteList[self.midiFileDescriptor.finalNoteList.count - 1].noteOffPosition } func playSound() { midiFile.play() } func loadSamples() { sampler.loadSFZ2(url: Bundle.main.url(forResource: "Gameboy", withExtension: "sfz")!) } }
// // CharacterTest.swift // Westeros // // Created by Fernando Rodriguez on 7/6/17. // Copyright © 2017 Keepcoding. All rights reserved. // import XCTest @testable import Westeros class PersonTest: XCTestCase { var starkImage : UIImage! var lannisterImage : UIImage! var starkSigil : Sigil! var lannisterSigil : Sigil! var starkHouse : House! var lannisterHouse : House! var robb : Person! var arya : Person! var tyrion : Person! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. starkImage = #imageLiteral(resourceName: "codeIsComing.png") lannisterImage = #imageLiteral(resourceName: "lannister.jpg") starkSigil = Sigil(image: starkImage, description: "Direwolf") lannisterSigil = Sigil(image: lannisterImage, description: "Rampant Lion") let starkUrl = URL(string: "http://awoiaf.westeros.org/index.php/House_Stark")! starkHouse = House(name: "Stark", sigil: starkSigil, words: "Winter is coming!", url: starkUrl) lannisterHouse = House(name: "Lannister", sigil: lannisterSigil, words: "Hear me roar!", url: starkUrl) robb = Person(name: "Edduard", alias: "The hand of the King", house: starkHouse, image: UIImage(named: "edduard_stark.png")!) arya = Person(name: "Arya", alias: "Braavos", house: starkHouse, image: UIImage(named: "arya_stark.png")!) tyrion = Person(name: "Jon Snow", alias: "Commander of the Night's Watch", house: starkHouse, image: UIImage(named: "Jon-Snow_stark.png")!) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPersonExistence(){ XCTAssertNotNil(tyrion) } func testFullName(){ XCTAssertEqual(tyrion.fullName, "Jon Snow Stark") } func testPersonEquality(){ // Identidad XCTAssertEqual(tyrion, tyrion) // Igualdad let imp = Person(name: "Jon Snow", alias: "Commander of the Night's Watch", house: starkHouse, image: UIImage(named: "Jon-Snow_stark.png")!) XCTAssertEqual(imp, tyrion) // Desigualdad XCTAssertNotEqual(tyrion, arya) } }
// // ImportTypes.swift // WavesWallet-iOS // // Created by Prokofev Ruslan on 21/09/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import DomainLayer enum ImportTypes { enum DTO { } } extension ImportTypes.DTO { struct Account { let privateKey: PrivateKeyAccount let password: String let name: String } }
// // Cpf.swift // CPFChain // // Created by Aaron on 2017/11/16. // Copyright © 2017年 ruhnn. All rights reserved. // import Foundation public final class Cpf<Wrapped> { public var wrapped: Wrapped public init(_ wrapped: Wrapped) { self.wrapped = wrapped } }
// // AOCTests.swift // AOCTests // // Created by Philipp Wallrich on 16.12.18. // import XCTest @testable import AOC2018 class Day5Tests: XCTestCase { var sut: Day5! override func setUp() { sut = Day5(with: "dabAcCaCBAcCcaDA") } func testPart1() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssertEqual(sut.part1(), "10") } func testPart2() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssertEqual(sut.part2(), "4") } // func testPerformance() { // sut = Day5() // self.measure { // sut.part2() // } // } }
// // ShippingViewC.swift // MyLoqta // // Created by Ashish Chauhan on 23/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit class ShippingViewC: UIViewController { var viewModel: ShippingVModeling? var dataModel = [[String: String]]() var responseBlock: ((_ param: [String: String]) -> Void)? @IBOutlet weak var tblShipping: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: false) } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: false) } // MARK: - Private functions private func setup() { self.recheckVM() if let array = self.viewModel?.getModel() { self.dataModel.append(contentsOf: array) } self.tblShipping.register(ShippingCell.self) self.tblShipping.reloadData() self.navigationController?.presentTransparentNavigationBar() self.addLeftButton(image: #imageLiteral(resourceName: "arrow_left_black"), target: self, action: #selector(tapBack)) } private func recheckVM() { if self.viewModel == nil { self.viewModel = ShippingVM() } } @objc func tapBack() { self.navigationController?.popViewController(animated: true) } } extension ShippingViewC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataModel.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ShippingCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.configureCell(data: self.dataModel[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("\(self.dataModel[indexPath.row])") if let responseBlock = self.responseBlock { responseBlock(self.dataModel[indexPath.row]) self.navigationController?.popViewController(animated: true) } } }
// // UIViewControllerExtension.swift // final-project // // Created by Jerry Lo on 3/11/18. // Copyright © 2018 Andrew Chiu. All rights reserved. // import Foundation import UIKit extension UIViewController { // Attribution: https://stackoverflow.com/questions/32281651/how-to-dismiss-keyboard-when-touching-anywhere-outside-uitextfield-in-swift func hideKeyboard() { let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
// // DaySixTests.swift // AdventOfCode2017 // // Created by Shawn Veader on 12/6/17. // Copyright © 2017 v8logic. All rights reserved. // import Foundation extension DaySix: Testable { func runTests() { let memory = [0, 2, 7, 0] guard testValue(5, equals: partOne(input: memory)) else { print("Part 1 Tests Failed!") return } guard testValue(4, equals: partTwo(input: memory)) else { print("Part 2 Tests Failed!") return } print("Done with tests... all pass") } }
// // Movie.swift // VNGRS-MovieAPP // // Created by Burak Kelleroğlu on 16.03.2020. // Copyright © 2020 Burak Kelleroğlu. All rights reserved. // import Foundation import RxDataSources struct Movies: Codable { let page, totalResults, totalPages: Int let results: [Movie] enum CodingKeys: String, CodingKey { case page case totalResults = "total_results" case totalPages = "total_pages" case results } } struct Movie: Codable { let id: Int let popularity: Double let voteCount: Int let posterPath: String? let title: String let voteAverage: Double let releaseDate: String enum CodingKeys: String, CodingKey { case id case popularity case voteCount = "vote_count" case posterPath = "poster_path" case title case voteAverage = "vote_average" case releaseDate = "release_date" } } extension Movie: IdentifiableType { var identity: String { "\(id)" } typealias Identity = String } extension Movie: Equatable { }
// // GZEDatesChatViewModel.swift // Gooze // // Created by Yussel on 3/31/18. // Copyright © 2018 Gooze. All rights reserved. // import UIKit import ReactiveSwift import ReactiveCocoa import enum Result.NoError import SwiftOverlays class GZEChatViewModelDates: GZEChatViewModel { // MARK: - GZEChatViewModel var mode: GZEChatViewMode { didSet { changeMode(self.mode) } } let error = MutableProperty<String?>(nil) let username = MutableProperty<String?>(nil) let messages = MutableProperty<[GZEChatMessage]>([]) let backgroundImage = MutableProperty<URLRequest?>(nil) let topButtonTitle = MutableProperty<String>("") let topButtonEnabled = MutableProperty<Bool>(true) let topButtonIsHidden = MutableProperty<Bool>(true) var topButtonAction: CocoaAction<GZEButton>? let topAccessoryButtonEnabled = MutableProperty<Bool>(true) let topAccessoryButtonIsHidden = MutableProperty<Bool>(true) var topAccessoryButtonAction: CocoaAction<UIButton>? let topTextInput = MutableProperty<String?>(nil) let topTextInputIsHidden = MutableProperty<Bool>(true) let topTextInputIsEditing = MutableProperty<Bool>(false) let (topTextInputEndEditingSignal, topTextInputEndEditingObs) = Signal<Void, NoError>.pipe() let inputMessage = MutableProperty<String?>(nil) let sendButtonImage = MutableProperty<UIImage?>(nil) let sendButtonEnabled = MutableProperty<Bool>(true) let sendButtonAction = MutableProperty<CocoaAction<UIButton>?>(nil) var paymentViewModel: GZEPaymentMethodsViewModel? { return getPaymentViewModel() } var mapViewModel: GZEMapViewModel { return GZEMapViewModelDate(dateRequest: self.dateRequest, mode: self.mode) } let (showPaymentViewSignal, showPaymentViewObserver) = Signal<Bool, NoError>.pipe() let (showMapViewSignal, showMapViewObserver) = Signal<Void, NoError>.pipe() let chat: GZEChat func startObservers() { self.setAmount(self.dateRequest.value.amount) self.observeMessages() self.observeRequests() self.observeSocketEvents() self.observeRequestUpdates() } func stopObservers() { self.stopObservingSocketEvents() self.stopObservingRequests() self.stopObservingMessages() self.stopObs.send(value: ()) } func retrieveHistory() { self.retrieveHistoryProducer?.start() } // End GZEChatViewModel protocol // MARK: - private properties // let dateRequestId: String var requestsObserver: Disposable? var messagesObserver: Disposable? var socketEventsObserver: Disposable? var (stopSignal, stopObs) = Signal<Void, NoError>.pipe() var retrieveHistoryProducer: SignalProducer<Void, GZEError>? let setAmountButtonTitle = "vm.datesChat.setAmountButtonTitle".localized().uppercased() let acceptAmountButtonTitle = "vm.datesChat.acceptAmountButtonTitle".localized().uppercased() let dateButtonTitle = "vm.datesChat.dateButtonTitle".localized().uppercased() let errorDigitsOnly = "vm.datesChat.error.digitsOnly".localized() let errorPositiveNumber = "vm.datesChat.error.positiveNumber".localized() let amount = MutableProperty<Decimal?>(nil) let dateRequest: MutableProperty<GZEDateRequest> var sendMessageAction: CocoaAction<UIButton>? var sendAmountAction: CocoaAction<UIButton>? // MARK: - init init(chat: GZEChat, dateRequest: MutableProperty<GZEDateRequest>, mode: GZEChatViewMode, username: String) { self.mode = mode self.chat = chat self.dateRequest = dateRequest self.username.value = username log.debug("\(self) init") log.debug("active request: \(dateRequest)") self.changeMode(self.mode) let topAction = self.createTopAccessoryButtonAction() topAction.values.observeValues{[weak self] dateRequest in guard let this = self else {return} this.dateRequest.value = dateRequest this.setAmount(dateRequest.amount) } self.sendMessageAction = CocoaAction(self.createSendAction()) self.sendAmountAction = CocoaAction(topAction) self.topButtonAction = CocoaAction(self.createTopButtonAction()) self.topAccessoryButtonAction = self.sendAmountAction self.sendButtonAction.value = self.sendMessageAction self.retrieveHistoryProducer = SignalProducer {[weak self] sink, disposable in log.debug("retrieve history producer called") guard let this = self else {return} GZEChatService.shared.retrieveHistory(chatId: this.chat.id) sink.sendCompleted() }.debounce(60, on: QueueScheduler.main) self.sendButtonAction <~ self.topTextInputIsEditing.map{ [weak self] isEditing -> CocoaAction<UIButton>? in guard let this = self else {return nil} if isEditing { return this.sendAmountAction } else { return this.sendMessageAction } } if mode == .gooze { self.amount <~ self.topTextInput.map{[weak self] amountText -> Decimal? in if let amountText = amountText, !amountText.isEmpty { guard let amountDouble = Decimal(string: amountText) else { self?.error.value = self?.errorDigitsOnly return nil } guard amountDouble >= 500 else { self?.error.value = self?.errorPositiveNumber return nil } return amountDouble } else { return nil } } } // self.getUpdatedRequest(dateRequestId) } private func changeMode(_ mode: GZEChatViewMode) { log.debug("changing chat mode: \(mode)") switch mode { case .client: topButtonTitle.value = "" topButtonIsHidden.value = true case .gooze: topButtonTitle.value = setAmountButtonTitle topButtonIsHidden.value = false } } // MARK: - Actions private func createTopButtonAction() -> Action<Void, Bool, GZEError> { return Action(enabledIf: topButtonEnabled) {[weak self] () -> SignalProducer<Bool, GZEError> in guard let this = self else { log.error("self disposed before executing action") return SignalProducer(error: .repository(error: .UnexpectedError)) } guard !this.dateRequest.value.isBlocked else { let error = GZEError.message(text: "vm.datesChat.error.sendMessage.unavailable", args: [this.username.value ?? ""]) this.error.value = error.localizedDescription return SignalProducer(error: error) } if (this.dateRequest.value.date) != nil { this.showMapView() return SignalProducer.empty } log.debug("mode: \(this.mode)") switch this.mode { case .client: this.showPaymentView() case .gooze: this.topTextInputIsHidden.value = false } return SignalProducer.empty } } private func createTopAccessoryButtonAction() -> Action<Void, GZEDateRequest, GZEError> { return Action(enabledIf: topAccessoryButtonEnabled) {[weak self] () -> SignalProducer<GZEDateRequest, GZEError> in guard let this = self else { log.error("self disposed before executing action") return SignalProducer(error: .repository(error: .UnexpectedError)) } this.topTextInputEndEditingObs.send(value: ()) guard let sender = GZEAuthService.shared.authUser else { log.error("sender is nil") return SignalProducer(error: .repository(error: .UnexpectedError)) } guard !this.dateRequest.value.isBlocked else { let error = GZEError.message(text: "vm.datesChat.error.sendMessage.unavailable", args: [this.username.value ?? ""]) this.error.value = error.localizedDescription return SignalProducer(error: error) } guard let amount = this.amount.value else { return SignalProducer(error: .validation(error: .required(fieldName: "amount"))) } guard let username = this.username.value else { return SignalProducer(error: .validation(error: .required(fieldName: "username"))) } switch this.mode { case .client: return SignalProducer.empty case .gooze: return GZEChatService.shared.request( amount: amount, dateRequestId: this.dateRequest.value.id, senderId: sender.id, username: username, chat: this.chat, mode: .client, senderUsername: sender.username ) } } } private func createSendAction() -> Action<Void, Void, GZEError> { return Action(enabledIf: sendButtonEnabled) {[weak self] () -> SignalProducer<Void, GZEError> in guard let this = self else { log.error("self disposed before executing action") return SignalProducer(error: .repository(error: .UnexpectedError)) } guard !this.dateRequest.value.isBlocked else { let error = GZEError.message(text: "vm.datesChat.error.sendMessage.unavailable", args: [this.username.value ?? ""]) this.error.value = error.localizedDescription return SignalProducer(error: error) } guard let messageText = this.inputMessage.value else { return SignalProducer(error: .validation(error: .required(fieldName: "messageText"))) } let messageTextTrim = messageText.trimmingCharacters(in: .whitespacesAndNewlines) guard !messageTextTrim.isEmpty else { return SignalProducer(error: .validation(error: .required(fieldName: "messageText"))) } guard let sender = GZEAuthService.shared.authUser else { log.error("sender is nil") return SignalProducer(error: .repository(error: .UnexpectedError)) } let message = GZEChatMessage( text: messageTextTrim, senderId: sender.id, chatId: this.chat.id ) var mode: GZEChatViewMode switch this.mode { case .client: mode = .gooze case .gooze: mode = .client } GZEChatService.shared.send( message: message, username: sender.username, chat: this.chat, dateRequest: this.dateRequest.value, mode: mode.rawValue ) this.inputMessage.value = "" return SignalProducer.empty } } private func observeRequestUpdates() { if self.mode == .gooze { // validate max double val SignalProducer.combineLatest( self.amount.producer, self.dateRequest.producer ) .take(until: self.stopSignal) .startWithValues{[weak self] (amount, dateRequest) in guard let this = self else {return} if dateRequest.date != nil { this.topAccessoryButtonIsHidden.value = true this.topButtonTitle.value = this.dateButtonTitle } else if let amount = amount, let formattedAmount = GZENumberHelper.shared.currencyFormatter.string(from: NSDecimalNumber(decimal: amount)) { this.topAccessoryButtonIsHidden.value = false this.topButtonTitle.value = "\(formattedAmount) MXN" } else { this.topAccessoryButtonIsHidden.value = true this.topButtonTitle.value = this.setAmountButtonTitle } } } else { SignalProducer.combineLatest( self.amount.producer, self.dateRequest.producer ) .take(until: self.stopSignal) .startWithValues{[weak self] (amount, dateRequest) in guard let this = self else {return} if dateRequest.date != nil { this.topButtonIsHidden.value = false this.topButtonTitle.value = this.dateButtonTitle } else if let amount = amount, let formattedAmount = GZENumberHelper.shared.currencyFormatter.string(from: NSDecimalNumber(decimal: amount)) { this.topButtonIsHidden.value = false this.topButtonTitle.value = "\(String(format: this.acceptAmountButtonTitle, formattedAmount)) MXN" } else { this.topButtonIsHidden.value = true this.topButtonTitle.value = "" } } } } private func observeRequests() { // guard self.mode == .client else {return} self.stopObservingRequests() self.requestsObserver = ( Signal.merge([ GZEDatesService.shared.lastSentRequest.signal, GZEDatesService.shared.lastReceivedRequest.signal ]) .skipNil() .filter{[weak self] in guard let this = self else { return false } log.debug("filter called: \(String(describing: $0.id)) \(String(describing: this.dateRequest.value.id))") return $0.id == this.dateRequest.value.id } .observeValues {[weak self] updatedDateRequest in log.debug("updatedDateRequest: \(String(describing: updatedDateRequest))") guard let this = self else { log.error("self was disposed"); return } this.dateRequest.value = updatedDateRequest this.setAmount(updatedDateRequest.amount) } ) } private func setAmount(_ amount: Decimal?) { self.amount.value = amount if let amount = amount { self.topTextInput.value = "\(amount)" } else { self.topTextInput.value = nil } } private func stopObservingRequests() { self.requestsObserver?.dispose() self.requestsObserver = nil } private func observeMessages() { log.debug("start observing messages") self.stopObservingMessages() self.messagesObserver = self.messages.bindingTarget <~ GZEChatService.shared.messages.map {[weak self] in guard let this = self else { log.error("self was disposed"); return [] } return $0[this.chat.id]?.sorted(by: { $0.createdAt.compare($1.createdAt) == .orderedAscending }) ?? [] } GZEChatService.shared.retrieveHistory(chatId: chat.id) } private func stopObservingMessages() { log.debug("stop observing messages") if self.messagesObserver != nil { GZEChatService.shared.clear(chatId: self.chat.id) self.messagesObserver?.dispose() self.messagesObserver = nil } } private func observeSocketEvents() { log.debug("start observing socket events") stopObservingSocketEvents() self.socketEventsObserver = GZEDatesService.shared.dateSocket? .socketEventsEmitter .signal .skipNil() .filter { $0 == .authenticated } .observeValues {[weak self] _ in guard let this = self else { log.error("self was disposed") return } this.getUpdatedRequest(this.dateRequest.value.id) GZEChatService.shared.retrieveNewMessages(chatId: this.chat.id) } } private func stopObservingSocketEvents() { log.debug("stop observing SocketEvents") if self.socketEventsObserver != nil { self.socketEventsObserver?.dispose() self.socketEventsObserver = nil } } private func getUpdatedRequest(_ dateRequestId: String?) { guard let dateRequestId = dateRequestId else {return} SwiftOverlays.showBlockingWaitOverlay() GZEDatesService.shared.find(byId: dateRequestId) .start{event in log.debug("find request event received: \(event)") SwiftOverlays.removeAllBlockingOverlays() switch event { // case .value(let dateRequest): handled by request observer case .failed(let error): log.error(error.localizedDescription) default: break } } } private func showPaymentView() { self.showPaymentViewObserver.send(value: true) } private func getPaymentViewModel() -> GZEPaymentMethodsViewModelPay? { guard let sender = GZEAuthService.shared.authUser else { log.error("authUser is nil") return nil } guard let amount = self.amount.value else { log.error("amount is nil") return nil } var mode: GZEChatViewMode switch self.mode { case .client: mode = .gooze case .gooze: mode = .client } return GZEPaymentMethodsViewModelPay( amount: amount, dateRequest: self.dateRequest, senderId: sender.id, username: sender.username, chat: self.chat, mode: mode ) } private func showMapView() { self.showMapViewObserver.send(value: ()) } // MARK: - Deinitializers deinit { log.debug("\(self) disposed") } }
// // WorkspaceMetadata.swift // Buildasaur // // Created by Honza Dvorsky on 29/09/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils public enum CheckoutType: String { case SSH = "SSH" // case HTTPS - not yet supported, right now only SSH is supported // (for bots reasons, will be built in when I have time) // case SVN - not yet supported yet } public struct WorkspaceMetadata { public let projectName: String public let projectPath: String public let projectWCCIdentifier: String public let projectWCCName: String public let projectURL: NSURL public let checkoutType: CheckoutType init(projectName: String?, projectPath: String?, projectWCCIdentifier: String?, projectWCCName: String?, projectURLString: String?) throws { let errorForMissingKey: (String) -> ErrorType = { Error.withInfo("Can't find/parse \"\($0)\" in workspace metadata!") } guard let projectName = projectName else { throw errorForMissingKey("Project Name") } guard let projectPath = projectPath else { throw errorForMissingKey("Project Path") } guard let projectWCCIdentifier = projectWCCIdentifier else { throw errorForMissingKey("Project WCC Identifier") } guard let projectWCCName = projectWCCName else { throw errorForMissingKey("Project WCC Name") } guard let projectURLString = projectURLString else { throw errorForMissingKey("Project URL") } guard let checkoutType = WorkspaceMetadata.parseCheckoutType(projectURLString) else { let allowedString = [CheckoutType.SSH].map({ $0.rawValue }).joinWithSeparator(", ") let error = Error.withInfo("Disallowed checkout type, the project must be checked out over one of the supported schemes: \(allowedString)") throw error } //we have to prefix SSH urls with "git@" (for a reason I don't remember) var correctedProjectUrlString = projectURLString if case .SSH = checkoutType where !projectURLString.hasPrefix("git@") { correctedProjectUrlString = "git@" + projectURLString } guard let projectURL = NSURL(string: correctedProjectUrlString) else { throw Error.withInfo("Can't parse url \"\(projectURLString)\"") } self.projectName = projectName self.projectPath = projectPath self.projectWCCIdentifier = projectWCCIdentifier self.projectWCCName = projectWCCName self.projectURL = projectURL self.checkoutType = checkoutType } func duplicateWithForkURL(forkUrlString: String?) throws -> WorkspaceMetadata { return try WorkspaceMetadata(projectName: self.projectName, projectPath: self.projectPath, projectWCCIdentifier: self.projectWCCIdentifier, projectWCCName: self.projectWCCName, projectURLString: forkUrlString) } } extension WorkspaceMetadata { internal static func parseCheckoutType(projectURLString: String) -> CheckoutType? { let urlString = projectURLString let scheme = NSURL(string: projectURLString)!.scheme switch scheme { case "github.com": return CheckoutType.SSH case "https": if urlString.hasSuffix(".git") { //HTTPS git } else { //SVN } Log.error("HTTPS or SVN not yet supported, please create an issue on GitHub if you want it added (czechboy0/Buildasaur)") return nil default: return nil } } }
// // APIURLConstants.swift // FlightsSRPAssignment // // Created by Satyam Sehgal on 08/06/19. // Copyright © 2019 Satyam Sehgal. All rights reserved. // import Foundation struct AppURLConstants { static let basefetchURL = "https://www.ixigo.com/sampleFlightData" }
// // Scenario.swift // Ticket Tap // // Created by Samuel Hoffmann on 2/18/17. // Copyright © 2017 Samuel Hoffmann. All rights reserved. // import Foundation import UIKit import SpriteKit import GameplayKit class Scenario { static let funcky = false static let night = false static let raining = 1 static let coloredCars = true static let rainbowCars = false static let blackAndWhite = false static let snowing = false static let special = false static let joshF = false static var yoelCamp = false static let grass = false static var allwaysSpeeding = false static let solar = false static var inAlert = false static var screenWidth : CGFloat = 0.0 static var globalButton1 = SKSpriteNode() static var globalButton2 = SKSpriteNode() static var globalButton3 = SKSpriteNode() static var globalButton4 = SKSpriteNode() static let version = 2.1 }
// // Request.swift // NSMWebservice // // Created by Marc Bauer on 14.02.18. // Copyright © 2018 nesiumdotcom. All rights reserved. // import Foundation public enum HTTPMethod : String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" internal var hasBody: Bool { switch self { case .get, .delete: return false case .post, .put: return true } } } public struct Request<T> { public let method: HTTPMethod public let path: String public let data: T? public let parameters: [URLQueryItem]? public let headerFields: [String: String]? public let timeoutInterval: TimeInterval private let bodyDataEncoder: (T) throws -> Data? private init( _ method: HTTPMethod, _ path: String, data: T?, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30, bodyDataEncoder: @escaping (T) throws -> Data?) { self.method = method self.path = path self.data = data self.parameters = parameters self.headerFields = headerFields self.timeoutInterval = timeoutInterval self.bodyDataEncoder = bodyDataEncoder } public static func get( _ path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<Void> { return Request<Void>( .get, path, data: nil, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval ) { _ in nil } } public static func delete( _ path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<Void> { return Request<Void>( .delete, path, data: nil, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval ) { _ in nil } } public static func post( to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<Void> { return Request<Void>( .post, path, data: nil, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval ) { _ in nil } } public static func post<T: Encodable & JSONValue>( _ data: T?, to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<T> { return Request<T>( .post, path, data: data, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval, bodyDataEncoder: JSONFragmentBodyEncoder ) } public static func post<T: Encodable>( _ data: T?, to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<T> { return Request<T>( .post, path, data: data, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval, bodyDataEncoder: JSONBodyEncoder ) } public static func put( to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<Void> { return Request<Void>( .put, path, data: nil, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval ) { _ in nil } } public static func put<T: Encodable>( _ data: T?, to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<T> { return Request<T>( .put, path, data: data, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval, bodyDataEncoder: JSONBodyEncoder ) } public static func put<T: Encodable & JSONValue>( _ data: T?, to path: String, parameters: [URLQueryItem]? = nil, headerFields: [String: String]? = nil, timeoutInterval: TimeInterval = 30) -> Request<T> { return Request<T>( .put, path, data: data, parameters: parameters, headerFields: headerFields, timeoutInterval: timeoutInterval, bodyDataEncoder: JSONFragmentBodyEncoder ) } } internal extension Request { func urlRequest(with baseURL: URL, gzip: Bool) throws -> URLRequest { var url = baseURL.appendingPathComponent(self.path) if let parameters = self.parameters, !parameters.isEmpty { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)! urlComponents.queryItems = parameters url = urlComponents.url! } var urlRequest = URLRequest(url: url) urlRequest.timeoutInterval = self.timeoutInterval self.headerFields?.forEach({ (key, value) in urlRequest.setValue(value, forHTTPHeaderField: key) }) switch self.method { case .post, .put: if let data = self.data, let body = try self.bodyDataEncoder(data) { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") if gzip { urlRequest.setValue("gzip", forHTTPHeaderField: "Content-Encoding") urlRequest.httpBody = try body.gzipped() } else { urlRequest.httpBody = body } } case .get, .delete: break } urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") urlRequest.httpMethod = self.method.rawValue return urlRequest } } fileprivate func JSONFragmentBodyEncoder<T: JSONValue>(_ object: T) throws -> Data? { let result: String switch object { case let value as Bool: result = value ? "true" : "false" case let value as Int: result = String(value) case let value as Int8: result = String(value) case let value as Int16: result = String(value) case let value as Int32: result = String(value) case let value as Int64: result = String(value) case let value as UInt: result = String(value) case let value as UInt8: result = String(value) case let value as UInt16: result = String(value) case let value as UInt32: result = String(value) case let value as UInt64: result = String(value) case let value as Double: result = String(value) case let value as Float: result = String(value) case let value as String: result = "\"\(value)\"" case let value as Date: result = "\"\(ISO8601DateTimeTransformer.formatter.string(from: value))\"" default: fatalError("Unexpected type \(String(describing: object))") } return result.data(using: .utf8) } fileprivate func JSONBodyEncoder<T: Encodable>(_ object: T) throws -> Data? { return try WSJSONEncoder().encode(object) }
// // VNCoreMLRequester.swift // ScrabbleSolver // // Created by Taylor Schmidt on 12/9/20. // Copyright © 2020 Taylor Schmidt. All rights reserved. // import Vision typealias VisionResultCallback = ([VNRecognizedObjectObservation]) -> Void protocol VNCoreMLRequestDelegate: class { func generateRequest(image: UIImage, callback: @escaping VisionResultCallback) throws -> [VNRequest] } class VNCoreMLRequester: VNCoreMLRequestDelegate { func generateRequest(image: UIImage, callback: @escaping VisionResultCallback) throws -> [VNRequest] { // Setup Vision parts guard let modelURL = Bundle.main.url(forResource: "IndoorOutdoor", withExtension: "mlmodelc") else { throw NSError(domain: "VisionObjectRecognitionViewController", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model file is missing"]) } let visionModel = try VNCoreMLModel(for: MLModel(contentsOf: modelURL)) let objDetectionReq = VNCoreMLRequest(model: visionModel) { (request, error) in guard let results = request.results else { print("Failed to get vision results") return } let objectObservations = results.compactMap { $0 as? VNRecognizedObjectObservation } callback(objectObservations) } return [objDetectionReq] } }
// // ContactEmailModel.swift // MMWallet // // Created by Dmitry Muravev on 13.08.2018. // Copyright © 2018 micromoney. All rights reserved. // import Foundation import RealmSwift import ObjectMapper class ContactEmailModel: Object, Mappable { @objc dynamic var id = 0 @objc dynamic var email = "" override class func primaryKey() -> String? { return "id" } required convenience init?(map: Map) { self.init() } func mapping(map: Map) { if map.mappingType == .toJSON { var id = self.id var email = self.email id <- map["id"] email <- map["email"] } else { id <- map["id"] email <- map["email"] } } }
// // Slider.swift // BasketGame // // Created by Jake Youssefzadeh on 5/17/18. // Copyright © 2018 Jake Youssefzadeh. All rights reserved. // import SpriteKit class Slider: UISlider { override func trackRect(forBounds bounds: CGRect) -> CGRect { var result = super.trackRect(forBounds: bounds) result.size.height *= 5 return result } }
// // ResultsTableViewController.swift // CSP Aggregate // // Created by nazda on 3/25/19. // Copyright © 2019 FRC 6317. All rights reserved. // import UIKit var results: [String] = [] var urlString: String = "http://ec2-3-214-19-72.compute-1.amazonaws.com:5000/submit/" extension Dictionary { func percentEscaped() -> String { return map { (key, value) in let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" return escapedKey + "=" + escapedValue } .joined(separator: "&") } } extension CharacterSet { static let urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed = CharacterSet.urlQueryAllowed allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") return allowed }() } class ResultsTableViewController: UITableViewController { override func viewDidLoad() { urlString = UserDefaults.standard.string(forKey: "REMOTE-URL") ?? "http://ec2-18-191-38-225.us-east-2.compute.amazonaws.com:5000/submit/matchscouting" } func randomString(length: Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" return String((0..<length).map{ _ in letters.randomElement()! }) } override func viewDidAppear(_ animated: Bool) { tableView.reloadData() } @IBAction func clear(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "Confirm", message: "Are you sure you want to clear this data?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (alertAction) in results.removeAll() self.tableView.reloadData() })) present(alert, animated: true, completion: nil) } @IBAction func upload(_ sender: UIBarButtonItem) { let numberOfPendingUploads = results.count if numberOfPendingUploads == 0 { return } let alert = UIAlertController(title: "Confirm", message: "\(numberOfPendingUploads) matches are about to be uploaded. Are you sure you want to do this?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alertAction) in let combinedMatches = results.joined(separator: "~~~~~") let file = "\(self.randomString(length: 10)).csv" if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(file) //writing do { try combinedMatches.write(to: fileURL, atomically: false, encoding: .utf8) } catch {print("ERROR 1")} } guard let url = URL(string: urlString) else { print("Error generating url") return } print("Asking for url \(urlString)") var request = URLRequest(url: url) request.httpMethod = "POST" let parameters: [String: String] = [ "csvdata": combinedMatches ] request.httpBody = parameters.percentEscaped().data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let response = response as? HTTPURLResponse, error == nil else { // check for fundamental networking error print("error", error ?? "Unknown error") return } guard (200 ... 299) ~= response.statusCode else { // check for http errors print("statusCode should be 2xx, but is \(response.statusCode)") print("response = \(response)") return } let responseString = String(data: data, encoding: .utf8) if responseString == String(results.count) { print("Worked!") results.removeAll() DispatchQueue.main.async { self.tableView.reloadData() } } } task.resume() })) present(alert, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Scanned Matches" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ScannedCell", for: indexPath) // Configure the cell... cell.textLabel?.text = results[indexPath.row] return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { results.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "GotoResultDetail" { let destination = segue.destination as! ResultDetailViewController guard let selectedIndex = tableView.indexPathForSelectedRow?.row else { return } destination.data = results[selectedIndex] } } }
// // GeoDataCell.swift // GraduatedApp // // Created by Miloš Čampar on 6/22/18. // Copyright © 2018 Miloš Čampar. All rights reserved. // import UIKit class GeoDataCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! }
// // AlertProtocols.swift // DTAlertControllerSample // // Created by Darshan D T on 28/05/19. // Copyright © 2019 Darshan D T. All rights reserved. // import Foundation import UIKit protocol AlertProtocol { var title: String? { get } var message: String? { get } var actionTitle: String? { get } var cancelTitle: String? { get } }
// // Movies_CatalogTests.swift // Movies CatalogTests // // Created by Jeraldo Abille on 5/2/18. // Copyright © 2018 Jerald Abille. All rights reserved. // import XCTest import Alamofire @testable import Movies_Catalog class Movies_CatalogTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testMostPopular() { let exp = XCTestExpectation(description: "MostPopular") Movie.getMovieList(.topRated, page: 1, success: { (movieList) in if let movies = movieList?.movies { print(movies) let movie = movies.first let viewModel = MovieViewModel(movie: movie!) print(viewModel) } exp.fulfill() XCTAssert(movieList?.movies != nil, "Movies must not be empty.") }) { (error) in print(error) exp.fulfill() XCTFail(error.localizedDescription) } wait(for: [ exp ], timeout: 10) } }
// // CreateViewController.swift // Carousel Demo // // Created by Amritha Prasad on 5/12/15. // Copyright (c) 2015 Amritha Prasad. All rights reserved. // import UIKit class CreateViewController: UIViewController { @IBOutlet weak var signUpView: UIView! @IBOutlet weak var buttonView: UIView! @IBOutlet weak var checkButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onBack(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } @IBAction func onPress(sender: AnyObject) { self.navigationController!.popViewControllerAnimated(true) } func keyboardWillShow(notification: NSNotification!) { //scrollView.contentOffset = CGPoint(x: 0, y: 80) signUpView.frame.origin.y = -130 buttonView.center.y = 315 } func keyboardWillHide(notification: NSNotification!) { //scrollView.contentOffset = CGPoint(x: 0, y: 80) signUpView.frame.origin.y = 3 buttonView.center.y = 471 } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } @IBAction func onCheck(sender: AnyObject) { if checkButton.selected == false { checkButton.selected = true } else{ checkButton.selected = false } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Carteiro.swift // Leilao // // Created by Gabriel Zambelli on 16/04/20. // Copyright © 2020 Alura. All rights reserved. // import Foundation class Carteiro{ func envia(_ leilao:Leilao){ } }
// // CAAnimationGroup+Extensions.swift // SensorVisualizerKit-iOS // // Created by Joe Blau on 4/9/19. // Copyright © 2019 SensorVisualizerKit. All rights reserved. // import UIKit extension CAAnimationGroup { static var createTouchAnimation: CAAnimationGroup { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = 0.7 let borderAnimation = CABasicAnimation(keyPath: "borderWidth") borderAnimation.toValue = 4 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.toValue = 0.4 return buildGroup(animations: [borderAnimation, scaleAnimation, opacityAnimation]) } static var removeTouchAnimation: CAAnimationGroup { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = 0.0 let borderAnimation = CABasicAnimation(keyPath: "borderWidth") borderAnimation.toValue = 0 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.toValue = 1.4 return buildGroup(animations: [borderAnimation, scaleAnimation, opacityAnimation]) } static var pressTouchAnimation: CAAnimationGroup { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = 0.7 let borderAnimation = CABasicAnimation(keyPath: "borderWidth") borderAnimation.toValue = 4 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.toValue = 0.4 return buildGroup(animations: [borderAnimation, scaleAnimation, opacityAnimation]) } static var peekTouchAnimation: CAAnimationGroup { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = 0.7 let borderAnimation = CABasicAnimation(keyPath: "borderWidth") borderAnimation.toValue = 4 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.toValue = 0.8 return buildGroup(animations: [borderAnimation, scaleAnimation, opacityAnimation]) } static var popTouchAnimation: CAAnimationGroup { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = 0.7 let borderAnimation = CABasicAnimation(keyPath: "borderWidth") borderAnimation.toValue = 4 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.toValue = 1.2 return buildGroup(animations: [borderAnimation, scaleAnimation, opacityAnimation]) } // MARK: - Private private static func buildGroup(animations: [CAAnimation]) -> CAAnimationGroup { let group = CAAnimationGroup() group.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) group.isRemovedOnCompletion = false group.fillMode = CAMediaTimingFillMode.forwards group.duration = 0.3 group.animations = animations return group } }
// // JuBiterEOS.swift // JubSDKProtobuf // // Created by Pan Min on 2019/12/31. // Copyright © 2019 JuBiter. All rights reserved. // import Foundation import JubSDKCore class JuBiterEOS { internal func inlinePbToEnumActionType(pb: JUB_Proto_EOS_ENUM_EOS_ACTION_TYPE) -> JUB_ENUM_EOS_ACTION_TYPE { var actionType: JUB_ENUM_EOS_ACTION_TYPE switch pb { case .xfer: actionType = XFER case .dele: actionType = DELE case .undele: actionType = UNDELE case .buyram: actionType = BUYRAM case .sellram: actionType = SELLRAM default: actionType = NS_ITEM_EOS_ACTION_TYPE } return actionType } internal func inlinePbToXferAction(pb: JUB_Proto_EOS_TransferAction) -> JUB_ACTION_TRANSFER { var action: JUB_ACTION_TRANSFER = JUB_ACTION_TRANSFER.init() action.from = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.from) action.to = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.to) action.asset = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.asset) action.memo = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.memo) return action } internal func inlinePbToDeleAction(pb: JUB_Proto_EOS_DelegateAction) -> JUB_ACTION_DELEGATE { var action: JUB_ACTION_DELEGATE = JUB_ACTION_DELEGATE.init() action.from = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.from) action.receiver = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.receiver) action.netQty = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.netQty) action.cpuQty = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.cpuQty) action.bStake = pb.stake return action } internal func inlinePbToBuyRamAction(pb: JUB_Proto_EOS_BuyRamAction) -> JUB_ACTION_BUYRAM { var action: JUB_ACTION_BUYRAM = JUB_ACTION_BUYRAM.init() action.payer = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.payer) action.quant = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.quant) action.receiver = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.receiver) return action } internal func inlinePbToSellRamAction(pb: JUB_Proto_EOS_SellRamAction) -> JUB_ACTION_SELLRAM { var action: JUB_ACTION_SELLRAM = JUB_ACTION_SELLRAM.init() action.account = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.account) action.bytes = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.byte) return action } internal func inlinePbToAction(pb: JUB_Proto_EOS_ActionEOS) -> JUB_ACTION_EOS { var action: JUB_ACTION_EOS = JUB_ACTION_EOS.init() action.type = inlinePbToEnumActionType(pb: pb.type) action.currency = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.currency) action.name = UnsafeMutablePointer<JUB_CHAR>(mutating: pb.name) switch pb.type { case .xfer: action.transfer = inlinePbToXferAction(pb: pb.xferAction) case .dele: action.delegate = inlinePbToDeleAction(pb: pb.deleAction) case .undele: action.delegate = inlinePbToDeleAction(pb: pb.deleAction) case .buyram: action.buyRam = inlinePbToBuyRamAction(pb: pb.buyRamAction) case .sellram: action.sellRam = inlinePbToSellRamAction(pb: pb.sellRamAction) default: break } return action } func createContext_Software(pbCfg: JUB_Proto_Common_ContextCfg, masterPriInXPRV: String) -> JUB_Proto_Common_ResultInt { do { let cfg = inlinePbToContextCfg(pb: pbCfg) var contextID = 0 as JUB_UINT16 let rv = JUB_CreateContextEOS_soft(cfg, masterPriInXPRV, &contextID) return inlineResultIntToPb(stateCode: UInt64(rv), value: UInt32(contextID)) } } func createContext(pbCfg: JUB_Proto_Common_ContextCfg, deviceID: UInt) -> JUB_Proto_Common_ResultInt { do { let cfg = inlinePbToContextCfg(pb: pbCfg) var contextID = 0 as JUB_UINT16 let rv = JUB_CreateContextEOS(cfg, JUB_UINT16(deviceID), &contextID) return inlineResultIntToPb(stateCode: UInt64(rv), value: UInt32(contextID)) } } func getAddress(contextID: UInt, pbPath: JUB_Proto_Common_Bip44Path, bShow: Bool) throws -> JUB_Proto_Common_ResultString { do { let path = inlinePbToBip44Path(pb: pbPath) var show:JUB_ENUM_BOOL = inlineBoolToEnumBool(bool: bShow) let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_GetAddressEOS(JUB_UINT16(contextID), path, show, buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let address = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: address) } } func signTransaction(contextID: UInt, pbPath: JUB_Proto_Common_Bip44Path, chainID: String, expiration: String, referenceBlockId: String, referenceBlockTime: String, actionsInJSON: String) throws -> JUB_Proto_Common_ResultString { do { let path = inlinePbToBip44Path(pb: pbPath) let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_SignTransactionEOS(JUB_UINT16(contextID), path, chainID, expiration, referenceBlockId, referenceBlockTime, actionsInJSON, buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let raw = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: raw) } } func buildAction(contextID: UInt, actions: [JUB_Proto_EOS_ActionEOS], actionCount: UInt16) throws -> JUB_Proto_Common_ResultString { do { var acts:[JUB_ACTION_EOS] = [] let actionsPtr = UnsafeMutablePointer<JUB_ACTION_EOS>.allocate(capacity: Int(actionCount)) actionsPtr.assign(from: acts, count: Int(actionCount)) defer { actionsPtr.deallocate() } for n in 0...Int(actionCount) { acts[n] = inlinePbToAction(pb: actions[n]) } let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_BuildActionEOS(JUB_UINT16(contextID), actionsPtr, actionCount, buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let actionsInJSON = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(JUBR_IMPL_NOT_SUPPORT), value: actionsInJSON) } } } // class JuBiterEOS end
// // TweetSearchAppApp.swift // TweetSearchApp // // Created by Mitsuaki Ihara on 2020/12/02. // import SwiftUI @main struct TweetSearchAppApp: App { var body: some Scene { WindowGroup { ContentView() } } }
// // HomeBenefitRecord.swift // ZGHFinance // // Created by zhangyr on 16/3/15. // Copyright © 2016年 cjxnfs. All rights reserved. // import UIKit class HomeBenefitRecordRequest: BaseRequest { required init(id : String , currentPage : Int , maxSize : Int) { super.init() self.isPostMethod = false self.addReqParam("bidId", value: id, isSign: false) self.addReqParam("currentPage", value: "\(currentPage)", isSign: false) self.addReqParam("maxSize", value: "\(maxSize)", isSign: false) } override func getRelativeURL() -> String { return "zgh/donateLog" } override func getServerType() -> ServerType { return .Base } override func getRequestVersion() -> String { return "1.0" } override func decodeJsonRequestData(responseDic: Dictionary<String, AnyObject>) -> BaseData { let recordData = FinanceRecordData() if let rows = responseDic["rows"] as? Array<Dictionary<String , AnyObject>> { recordData.cjxnfsCode = 10000 var recordList = Array<FinanceRecordDetailData>() for rDic in rows { let tmpDic = rDic as NSDictionary let record = FinanceRecordDetailData() record.name = (rDic["donor"] as? Dictionary<String , AnyObject>)?["username"] + "" record.amount = tmpDic.parseNumber("amount", numberType: ParseNumberType.int) as! Int record.enableAmount = tmpDic.parseNumber("validAmount", numberType: ParseNumberType.int) as! Int record.time = tmpDic.parseNumber("createTime", numberType: ParseNumberType.int) as! Int recordList.append(record) } recordData.recordList = recordList }else{ recordData.cjxnfsCode = 10001 recordData.responseMsg = "数据获取失败" } return recordData } }
// // BaseViewController.swift // quartzDemo // // Created by lkk on 15-3-20. // Copyright (c) 2015年 LKK. All rights reserved. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge.None } }
/** * CNAME file generator plugin for Publish * Copyright (c) Manny Guerrero 2020 * MIT license, see LICENSE file for details */ import XCTest import CNAMEPublishPluginTests var tests = [XCTestCaseEntry]() tests += CNAMEPublishPluginTests.allTests() XCTMain(tests)
// // VideoCollectionViewCell.swift // Amondo // // Created by James Bradley on 09/09/2016. // Copyright © 2016 Amondo. All rights reserved. // import AVKit import AVFoundation import Photos import UIKit class VideoCollectionViewCell: UICollectionViewCell { var avPlayer = AVPlayer() var asset: PHAsset? { didSet { self.avPlayer.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil) let layer = AVPlayerLayer(player: self.avPlayer) self.avPlayer.actionAtItemEnd = .None layer.frame = self.bounds layer.videoGravity = AVLayerVideoGravityResizeAspectFill self.layer.addSublayer(layer) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.avPlayer.currentItem) PHImageManager.defaultManager().requestAVAssetForVideo(self.asset!, options: PHVideoRequestOptions()) { (asset, audio, dictionary) in self.avPlayer.replaceCurrentItemWithPlayerItem(AVPlayerItem(asset: asset!)) } } } func playerItemDidReachEnd(notification: NSNotification) { self.avPlayer.seekToTime(kCMTimeZero) self.avPlayer.play() } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "status" && self.avPlayer.status == .ReadyToPlay { self.avPlayer.play() } } }
// // TrackManager.swift // Sourwrms // // Created by Mateus Maso on 2015-06-19. // Copyright (c) 2015 Purabucha. All rights reserved. // import Cocoa public protocol TrackManagerDelegate: NSObjectProtocol { func trackManager(manager: TrackManager!, didUpdateCurrentTrack track: TrackManagerService?) } public class TrackManagerService: NSObject { public var trackService: TrackService! public dynamic var position: Int = 0 public var positionStarted: Int = 0 public var playingAt: NSTimeInterval! public var playingSeconds: Int = 0 private var timer: NSTimer! public func startPlaying() { self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("incrementPosition"), userInfo: nil, repeats: true) self.playingAt = NSDate.timeIntervalSinceReferenceDate() } public func stopPlaying() { if self.timer != nil { self.timer.invalidate() } } public func incrementPosition() { self.position += 1000 self.playingSeconds += 1 } public func identifier() -> String { return "\(self.trackService.service)-\(self.trackService.sid)-\(self.trackService.url)" } } public class TrackManager: NSObject { public var delegate: TrackManagerDelegate? public var currentTrack: TrackManagerService? public var currentTracks: [String: TrackManagerService] = [String: TrackManagerService]() public var backgroundJob: BackgroundJob! private var timer: NSTimer! private var nativeScript: NSAppleScript! private var browserScript: NSAppleScript! let bundle = NSBundle(identifier: "com.purabucha.StereeoKit")! public override init() { super.init() self.browserScript = NSAppleScript(contentsOfURL: NSURL.fileURLWithPath(bundle.pathForResource("BrowserCurrentTracks", ofType: "scpt")!)!, error: nil)! self.nativeScript = NSAppleScript(contentsOfURL: NSURL.fileURLWithPath(bundle.pathForResource("NativeCurrentTracks", ofType: "scpt")!)!, error: nil)! } public func startListening() { self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("runScripts"), userInfo: nil, repeats: true) self.timer.tolerance = NSTimeInterval(0.3) } public func runScripts() { self.backgroundJob.queue("track-manager", task: { var results:Array = [JSON]() if let browserResult = self.browserScript.executeAndReturnError(nil) { for track in JSON.parse(browserResult.stringValue!).asArray! { results.append(track) } } if let nativeResult = self.nativeScript.executeAndReturnError(nil) { for track in JSON.parse(nativeResult.stringValue!).asArray! { results.append(track) } } dispatch_async(dispatch_get_main_queue(), { var currentTracks = [String: TrackManagerService]() for result in results { var trackService = TrackService() trackService.sid = result["id"].asString trackService.url = result["url"].asString trackService.name = result["name"].asString trackService.album = result["album"].asString trackService.artist = result["artist"].asString trackService.duration = result["duration"].asInt! trackService.service = result["service"].asString! var trackManagerService = TrackManagerService() trackManagerService.position = result["position"].asInt! trackManagerService.positionStarted = result["position"].asInt! trackManagerService.trackService = trackService var identifier = trackManagerService.identifier() var reusedTrackManagerService = self.currentTracks[identifier] if reusedTrackManagerService == nil { currentTracks[identifier] = trackManagerService trackManagerService.startPlaying() } else { if reusedTrackManagerService!.positionStarted != trackManagerService.positionStarted { reusedTrackManagerService!.position = trackManagerService.position reusedTrackManagerService!.positionStarted = trackManagerService.positionStarted } currentTracks[identifier] = reusedTrackManagerService } } for (identifier: String, trackManagerService: TrackManagerService) in self.currentTracks.difference(currentTracks) { trackManagerService.stopPlaying() } self.currentTracks = currentTracks self.checkCurrentTrack() }) }) } public func checkCurrentTrack() { var currentTrack = self.currentTracks.values.array.sorted { (track1: TrackManagerService, track2: TrackManagerService) -> Bool in return (track1.playingAt as Double) > (track2.playingAt as Double) }.first if currentTrack != self.currentTrack { self.currentTrack = currentTrack if self.delegate != nil { self.delegate?.trackManager(self, didUpdateCurrentTrack: self.currentTrack) } } } }
// // Language.swift // import Foundation import Api import RealmSwift public class Language: Object { public struct Modes: OptionSet { // MARK: - Public let public static let translation = Modes(rawValue: 1 << 0) public static let speechSynthesis = Modes(rawValue: 1 << 1) public static let imageRecognition = Modes(rawValue: 1 << 2) public static let imageObjectRecognition = Modes(rawValue: 1 << 3) // public static let parseWebPage = Modes(rawValue: 1 << 4) // public static let parseVoice = Modes(rawValue: 1 << 5) // public static let produceVoice = Modes(rawValue: 1 << 6) // public static let offlineTranslate = Modes(rawValue: 1 << 7) public static let phraseBook = Modes(rawValue: 1 << 8) // public static let wordNetDictionary = Modes(rawValue: 1 << 9) public static let translateWebSite = Modes(rawValue: 1 << 10) public static let translateDocument = Modes(rawValue: 1 << 11) public static let speechRecognition = Modes(rawValue: 1 << 12) public static let all: Modes = [ .translation, .speechSynthesis, .imageRecognition, .imageObjectRecognition, // .parseWebPage, // .parseVoice, // .produceVoice, // .offlineTranslate, .phraseBook, // .wordNetDictionary, .translateWebSite, .translateDocument, .speechRecognition ] // MARK: - OptionSet public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } // MARK: - Public var public var id: String { get { return _id.uuidString } } public var fullCode: String { get { return _fullCode } set { try! Realm().safeWrite { _fullCode = newValue } } } public var codeAlpha1: String { get { return _codeAlpha1 } set { try! Realm().safeWrite { _codeAlpha1 = newValue } } } public var englishName: String { get { return _englishName } set { try! Realm().safeWrite { _englishName = newValue } } } public var codeName: String { get { return _codeName } set { try! Realm().safeWrite { _codeName = newValue } } } public var flagPath: String { get { return _flagPath } set { try! Realm().safeWrite { _flagPath = newValue } } } public var testWordForSyntezis: String { get { return _testWordForSyntezis } set { try! Realm().safeWrite { _testWordForSyntezis = newValue } } } public var rtl: Bool { get { return _rtl } set { try! Realm().safeWrite { _rtl = newValue } } } public var modes: Modes { get { return Modes(rawValue: _modes) } set { try! Realm().safeWrite { _modes = newValue.rawValue } } } // MARK: - @Persisted var @Persisted(primaryKey: true) var _id: UUID @Persisted var _fullCode: String @Persisted var _codeAlpha1: String @Persisted var _englishName: String @Persisted var _codeName: String @Persisted var _flagPath: String @Persisted var _testWordForSyntezis: String @Persisted var _rtl: Bool @Persisted var _modes: Int // MARK: - Public init public override init() { super.init() } public init( fullCode: String, codeAlpha1: String, englishName: String, codeName: String, flagPath: String, testWordForSyntezis: String, rtl: Bool, modes: Modes ) { super.init() _fullCode = fullCode _codeAlpha1 = codeAlpha1 _englishName = englishName _codeName = codeName _flagPath = flagPath _testWordForSyntezis = testWordForSyntezis _rtl = rtl _modes = modes.rawValue } }
// SCNCylinderExtensions.swift - Copyright 2020 SwifterSwift #if canImport(SceneKit) import SceneKit // MARK: - Methods public extension SCNCylinder { /// SwifterSwift: Creates a cylinder geometry with the specified diameter and height. /// /// - Parameters: /// - diameter: The diameter of the cylinder’s circular cross section in the x- and z-axis dimensions of its local coordinate space. /// - height: The height of the cylinder along the y-axis of its local coordinate space. convenience init(diameter: CGFloat, height: CGFloat) { self.init(radius: diameter / 2, height: height) } /// SwifterSwift: Creates a cylinder geometry with the specified radius, height and material. /// /// - Parameters: /// - radius: The radius of the cylinder’s circular cross section in the x- and z-axis dimensions of its local coordinate space. /// - height: The height of the cylinder along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(radius: CGFloat, height: CGFloat, material: SCNMaterial) { self.init(radius: radius, height: height) materials = [material] } /// SwifterSwift: Creates a cylinder geometry with the specified diameter, height and material. /// /// - Parameters: /// - diameter: The diameter of the cylinder’s circular cross section in the x- and z-axis dimensions of its local coordinate space. /// - height: The height of the cylinder along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(diameter: CGFloat, height: CGFloat, material: SCNMaterial) { self.init(radius: diameter / 2, height: height) materials = [material] } /// SwifterSwift: Creates a cylinder geometry with the specified radius, height, and material color. /// /// - Parameters: /// - radius: The radius of the cylinder’s circular cross section in the x- and z-axis dimensions of its local coordinate space. /// - height: The height of the cylinder along the y-axis of its local coordinate space. /// - color: The color of the geometry's material. convenience init(radius: CGFloat, height: CGFloat, color: SFColor) { self.init(radius: radius, height: height) materials = [SCNMaterial(color: color)] } /// SwifterSwift: Creates a cylinder geometry with the specified diameter, height, and material color. /// /// - Parameters: /// - diameter: The diameter of the cylinder’s circular cross section in the x- and z-axis dimensions of its local coordinate space. /// - height: The height of the cylinder along the y-axis of its local coordinate space. /// - color: The color of the geometry's material. convenience init(diameter: CGFloat, height: CGFloat, color: SFColor) { self.init(radius: diameter / 2, height: height) materials = [SCNMaterial(color: color)] } } #endif
// // ThreadingUtil.swift // myEats // // Created by JABE on 11/11/15. // Copyright © 2015 JABELabs. All rights reserved. // class ThreadingUtil { static func inBackgroundAfter(block:() -> Void, afterDelay delay:NSTimeInterval){ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block) } // class func inBackground(executeBlock: () -> Void, callBack:() -> Void) { // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){ // executeBlock() // dispatch_async(dispatch_get_main_queue(), callBack) // } // } // class func inBackground(executeBlock: () -> Void) { // ThreadingUtil.inBackground(executeBlock, callBack: nil) // } static func inMainQueue(executeBlock:() -> Void){ dispatch_async(dispatch_get_main_queue(), executeBlock) } static func inBackground(executeBlock: () -> Void, callBack:(() -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){ executeBlock() if let callBack = callBack { dispatch_async(dispatch_get_main_queue(), callBack) } } } }
/*: ### iOSDevUK 2016 — Intermediate Swift This is the completed playground from part 2a on Safety. */ import UIKit import PlaygroundSupport class PlaygroundViewController: UIViewController { var button: UIButton! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.red button = UIButton(type: .roundedRect) // #selector! button.addTarget(self, action: #selector(PlaygroundViewController.buttonTapped(sender:)), for: .touchUpInside) button.setTitle("Hello iOSDevUK", for: .normal) button.setTitleColor(.white, for: .normal) button.center = CGPoint(x: 50, y: 50) button.sizeToFit() self.view.addSubview(button) } func buttonTapped(sender: UIButton) { print("button tapped!") self.view.backgroundColor = .brown // #keyPath! let kvcButton = self.value(forKeyPath: #keyPath(PlaygroundViewController.button)) print("kvcButton: \(kvcButton)") } } PlaygroundPage.current.liveView = PlaygroundViewController()
// // JsonRequest.swift // cookIn // // Created by Ivann Galic on 04/06/2020. // Copyright © 2020 Kevin. All rights reserved. // import Foundation import SwiftUI class JsonRequest: ObservableObject { @Published var json = [RecipeModel]() init() { load() // To remove only extra list separators below the list: UITableView.appearance().tableFooterView = UIView() // To remove all list separators including the actual ones: UITableView.appearance().separatorStyle = .none } func load() { let path = Bundle.main.path(forResource: "Recipes", ofType: "json") let url = URL(fileURLWithPath: path!) URLSession.shared.dataTask(with: url) { (data, response, error) in do { if let data = data { let json = try JSONDecoder().decode([RecipeModel].self, from: data) DispatchQueue.main.sync { self.json = json } } else { print("No data") } } catch { print(error) } }.resume() } }
// // PublicationCell.swift // iClanBattles // // Created by ALEXIS-PC on 10/23/18. // Copyright © 2018 ALEXIS-PC. All rights reserved. // import UIKit import AlamofireImage class PublicationCell : UICollectionViewCell { func updateValues(fromPublication publication: Publication) { if let url = URL(string: publication.urlToImage) { // logoImageview.af_setImage(withURL: url) } // nameLabel.text = game.name //descriptionLabel.text = game.description } }
// // CVCFood.swift // FoodApp // // Created by Michał Woś on 08.11.2017. // Copyright © 2017 Michał Woś. All rights reserved. // import UIKit class CVCFood: UICollectionViewCell { @IBOutlet weak var iv_FoodImage: UIImageView! @IBOutlet weak var iv_FoodName: UILabel! func setFood(food: Food){ iv_FoodImage.image = UIImage(named: food.image!) iv_FoodName.text = food.name! } }
// // SignupViewModel.swift // MapBoxTest // // Created by setsu on 2020/04/20. // Copyright © 2020 Prageeth. All rights reserved. // import Foundation import RxSwift import RxCocoa class SignupViewModel: ViewModelType { struct Input { let signupFinishTrigger: Driver<Void> let backTrigger: Driver<Void> let email: Driver<String> let password: Driver<String> let repeatedPassword: Driver<String> } struct Output { let validatedEmail: Driver<ValidationResult> let validatedPassword: Driver<ValidationResult> let validatedPasswordRepeated: Driver<ValidationResult> let signupFinish: Driver<UserModel> let back: Driver<Void> let signupEnabled: Driver<Bool> let error: Driver<Error> } struct State { let error = ErrorTracker() } private let navigator: SignupNavigator private let authModel: AuthModel init(with authModel: AuthModel, and navigator: SignupNavigator) { self.authModel = authModel self.navigator = navigator } func transform(input: SignupViewModel.Input) -> SignupViewModel.Output { let state = State() let validationService = MBDefaultValidationService() let validatedEmail = input.email.flatMapLatest { email in return validationService.validateEmail(email) .asDriver(onErrorJustReturn: .failed(message: "Error contacting server")) } let validatedPassword = input.password.map { password in return validationService.validatePassword(password) } let validateRepeatedPassword = Driver.combineLatest(input.password, input.repeatedPassword) { validationService.validateRepeatedPassword($0, repeatedPassword: $1) } let signupEnabled = Driver .combineLatest(validatedEmail, validatedPassword, validateRepeatedPassword) { (email, password, repeatedPassword) in email.isValid && password.isValid && repeatedPassword.isValid }.distinctUntilChanged() let requiredInputs = Driver.combineLatest(input.email, input.password) let signupFinish = input.signupFinishTrigger .withLatestFrom(requiredInputs) .flatMapLatest { [unowned self] (email: String, password: String) in return self.authModel.register(with: UserModel.init(mailAddress: email, passWord: password)) .do(onNext: { [unowned self] _ in self.navigator.dismiss() }) .trackError(state.error) .asDriverOnSkipError() } let back = input.backTrigger.do(onNext: { self.navigator.dismiss() }).asDriver() return SignupViewModel.Output(validatedEmail: validatedEmail, validatedPassword: validatedPassword, validatedPasswordRepeated: validateRepeatedPassword, signupFinish: signupFinish, back: back, signupEnabled: signupEnabled, error: state.error.asDriver()) } } extension ValidationResult { /// 検証済みかどうか var isValid: Bool { switch self { case .success: return true default: return false } } }
// File: MenuButton.swift // Package: CardGames // Created: 07/08/2020 // // MIT License // // Copyright © 2020 Christopher Boyle // // 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 SpriteKit import Foundation class MenuButton : SKShapeNode { private var text: SKLabelNode private let callback: ()->Void init(callback: @escaping ()->Void, width: CGFloat, height: CGFloat, text: String? = nil) { self.text = SKLabelNode() self.callback = callback super.init() self.path = CGPath(rect: CGRect(x: 0, y: 0, width: width, height: height), transform: nil) self.fillColor = .clear self.strokeColor = .clear self.addChild(self.text) self.text.position = CGPoint(x: 10, y: height/2.0) self.text.verticalAlignmentMode = .center self.text.horizontalAlignmentMode = .center self.text.text = text self.text.fontSize = height } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func mouse_over(point: CGPoint) { if self.frame.contains(point) { self.text.run(SKAction.scale(to: 1.2, duration: 0.1)) } else { self.text.run(SKAction.scale(to: 1.0, duration: 0.1)) } } func try_mouse_clicked(point: CGPoint) { if self.frame.contains(point) { self.text.run(SKAction.init(named: "ScaleDownUp")!) self.callback() } } }
import UIKit struct GifInfo: Codable { var id: Int var gifUrl: URL var text: String var shares: Int var title: String var tenorUrl: URL var tags: [String] init(dictionary: [String: Any]) { self.title = dictionary["title"] as? String ?? "" self.id = dictionary["id"] as? Int ?? 0 self.gifUrl = dictionary["gifUrl"] as? URL ?? URL(string: "http://www.google.com")! self.text = dictionary["text"] as? String ?? "" self.shares = dictionary["shares"] as? Int ?? 0 self.tenorUrl = dictionary["uid"] as? URL ?? URL(string: "http://www.google.com")! self.tags = dictionary["uid"] as? [String] ?? [] } }
// // AboutViewController.swift // Brizeo // // Created by Roman Bayik on 1/30/17. // Copyright © 2017 Kogi Mobile. All rights reserved. // import UIKit import ChameleonFramework import SVProgressHUD import Typist class AboutViewController: UIViewController { // MARK: - Types struct Constants { static let placeholderTextColor = HexColor("dbdbdb") static let defaultTextColor = UIColor.black static let headerViewHeight: CGFloat = 54.0 } enum Sections: Int { case passions = 0 case nationality case work case education case introduceYourself var title: String? { switch self { case .passions: return LocalizableString.SelectInterests.localizedString.uppercased() case .nationality: return LocalizableString.SelectNationality.localizedString.uppercased() case .introduceYourself: return LocalizableString.IntroduceYourself.localizedString.uppercased() case .work: return LocalizableString.Work.localizedString.uppercased() case .education: return LocalizableString.Education.localizedString.uppercased() } } var height: CGFloat { return Constants.headerViewHeight } var headerViewId: String { return "SettingsBigHeaderView" } func cellHeight(for row: Int, hasPassions: Bool = true) -> CGFloat { switch self { case .passions: if hasPassions { return 104.0 } else { return 55.0 } /* RB Comment: old functionality if row == 0 { return 53.0 } else { return 71.0 } */ case .introduceYourself: if row == 0 { return 189.0 } else { return 104.0 } case .work, .education, .nationality: return 55.0 } } func cellId(for row: Int, hasPassions: Bool = true) -> String { switch self { case .passions: return hasPassions ? AboutPassionsTableViewCell.identifier : SettingsInvitationCell.identifier /* RB Comment: Old functionality if row == 0 { return "AboutTitleTableViewCell" } else { return AboutTableViewCell.identifier } */ case .introduceYourself: if row == 0 { return AboutInputTableViewCell.identifier } else { return AboutSaveTableViewCell.identifier } case .work, .education, .nationality: return SettingsInvitationCell.identifier } } } // MARK: - Properties @IBOutlet weak var passionsTableView: UITableView! var user: User! var isSelected = false fileprivate var mutualFriends = [(name:String, pictureURL:String)]() fileprivate var selectedPassion = [String: Int]() fileprivate var passions: [Passion]? fileprivate var keyboardTypist: Typist! fileprivate var defaultTableViewContentHeight: CGFloat = -1.0 // MARK: - Controller lifecycle override func viewDidLoad() { super.viewDidLoad() registerHeaderViews() fetchPassions() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // reload passions passionsTableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) configureKeyboardBehaviour() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UserProvider.updateUser(user: UserProvider.shared.currentUser!, completion: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) } // MARK: - Observers @objc func keyboardWillShowForResizing(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let _ = self.view.window?.frame { self.passionsTableView.contentSize = CGSize(width: self.passionsTableView.contentSize.width, height: self.defaultTableViewContentHeight + keyboardSize.height) } else { debugPrint("We're showing the keyboard and either the keyboard size or window is nil: panic widely.") } } @objc func keyboardWillHideForResizing(notification: NSNotification) { if ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil { self.passionsTableView.contentSize = CGSize(width: self.passionsTableView.contentSize.width, height: self.defaultTableViewContentHeight) } else { debugPrint("We're about to hide the keyboard and the keyboard size is nil. Now is the rapture.") } } // MARK: - Public methods func reloadData() { passionsTableView.reloadData() } // MARK: - Private methods fileprivate func registerHeaderViews() { passionsTableView.register(UINib(nibName: SettingsBigHeaderView.nibName, bundle: nil), forHeaderFooterViewReuseIdentifier: SettingsBigHeaderView.nibName) } fileprivate func configureKeyboardBehaviour() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowForResizing(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideForResizing(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } fileprivate func normalizeUsersPassions() { // we need to check whether user has their selected passions that are not available on the database let availableIds = passions!.map({ return $0.objectId! }) let availablePassions = user.passionsIds.filter({ return availableIds.contains($0) }) user.passionsIds = availablePassions UserProvider.updateUser(user: user, completion: nil) } /* RB Comment: Old functionality fileprivate func setSelectedPassions() { guard (passions?.count)! >= 3 else { print("Error: can't operate selected passions with < 3 passions") return } // init selected passions let ids = user.passionsIds if ids.count == 0 { // set default passions // try to set travel, foodie and fitness if let travelPassion = passions!.filter({ $0.displayName == "Travel" }).first { selectedPassion[travelPassion.objectId] = 0 } if let travelPassion = passions!.filter({ $0.displayName == "Foodie" }).first { selectedPassion[travelPassion.objectId] = 1 } if let travelPassion = passions!.filter({ $0.displayName == "Fitness" }).first { selectedPassion[travelPassion.objectId] = 2 } } else { for i in 0 ..< ids.count { selectedPassion[ids[i]] = i } } if selectedPassion.count < 3 { for i in 0 ..< (3 - selectedPassion.count) { let restPassions = passions!.filter({ !Array(selectedPassion.keys).contains($0.objectId) }) selectedPassion[restPassions.first!.objectId] = selectedPassion.count + i } } user.assignPassionIds(dict: selectedPassion) // var idss = [String]() // for i in 0 ..< 4 { // idss.append(passions![i].objectId) // } // user.passionsIds = [String]() UserProvider.updateUser(user: user, completion: nil) } */ fileprivate func fetchPassions() { PassionsProvider.shared.retrieveAllPassions(true, type: .extended) { [weak self] (result) in if let welf = self { DispatchQueue.main.async { switch result { case .success(let passions): welf.passions = passions //welf.setSelectedPassions() welf.normalizeUsersPassions() welf.passionsTableView.reloadData() break case .failure(let error): welf.showAlert(LocalizableString.Error.localizedString, message: error.localizedDescription, dismissTitle: LocalizableString.Dismiss.localizedString) { welf.fetchPassions() } break default: break } } } } } } // MARK: - UITextViewDelegate extension AboutViewController: UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if defaultTableViewContentHeight == -1.0 { defaultTableViewContentHeight = passionsTableView.contentSize.height } return true } func textViewDidChange(_ textView: UITextView) { user.personalText = textView.text } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { user.personalText = textView.text return true } } // MARK: - UITableViewDataSource extension AboutViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 5 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let section = Sections(rawValue: section) else { return 0 } switch (section) { case .introduceYourself: return 2 case .passions: if passions != nil { return 1 } return 0 default: return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let section = Sections(rawValue: indexPath.section) else { return UITableViewCell() } let cellId = section.cellId(for: indexPath.row, hasPassions: user.passions.count == Configurations.General.requiredMinPassionsCount) let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) switch section { case .passions: if user.passions.count != Configurations.General.requiredMinPassionsCount { let passionCell = cell as! SettingsInvitationCell passionCell.titleLabel.text = LocalizableString.Select.localizedString return passionCell } let passionCell = cell as! AboutPassionsTableViewCell var passions = [Passion]() _ = user.passionsIds.map({ if let passion = PassionsProvider.shared.getPassion(by: $0, with: .extended) { passions.append(passion) } }) if passions.count == Configurations.General.requiredMinPassionsCount { passionCell.setPassions(passions) } return passionCell /* RB Comment: old functionality if indexPath.row == 0 { return cell } else { let typeCell = cell as! AboutTableViewCell let passion = passions![indexPath.row] typeCell.delegate = self typeCell.titleLabel.text = passion.displayName if let index = selectedPassion[passion.objectId] { typeCell.selectedIndex = index } else { typeCell.selectedIndex = -1 } return typeCell }*/ case .nationality: let typeCell = cell as! SettingsInvitationCell if let nationalityCode = user.nationality { let country = Country.initWith(nationalityCode) typeCell.titleLabel.text = country.name } else { typeCell.titleLabel.text = "Not set." } return typeCell case .introduceYourself: if indexPath.row == 0 { let typeCell = cell as! AboutInputTableViewCell typeCell.textView.delegate = self typeCell.textView.text = user.personalText return typeCell } else { let typeCell = cell as! AboutSaveTableViewCell typeCell.delegate = self return typeCell } case .work: let typeCell = cell as! SettingsInvitationCell typeCell.titleLabel.text = user.workInfo ?? "Not set." return typeCell case .education: let typeCell = cell as! SettingsInvitationCell typeCell.titleLabel.text = user.studyInfo ?? "Not set." return typeCell } } } // MARK: - UITableViewDelegate extension AboutViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let section = Sections(rawValue: indexPath.section) else { return 0.0 } return section.cellHeight(for: indexPath.row, hasPassions: user.passions.count == Configurations.General.requiredMinPassionsCount) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let section = Sections(rawValue: section) else { return 0.0 } return section.height } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let section = Sections(rawValue: section) else { return nil } let headerView: SettingsHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: section.headerViewId) headerView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: tableView.frame.width, height: section.height)) headerView.titleLabel.text = section.title headerView.titleLabel.textColor = HexColor("5f5f5f")! return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let section = Sections(rawValue: indexPath.section) else { return } if section == .introduceYourself { return } if section == .nationality { let controller: OptionsNationalityViewController = Helper.controllerFromStoryboard(controllerId: "OptionsNationalityViewController")! controller.user = user Helper.currentTabNavigationController()?.pushViewController(controller, animated: true) } else if section == .passions { let controller: CategoriesViewController = Helper.controllerFromStoryboard(controllerId: "CategoriesViewController")! controller.user = user Helper.currentTabNavigationController()?.pushViewController(controller, animated: true) } else { switch section { case .work: let controller: OptionsViewController = Helper.controllerFromStoryboard(controllerId: "OptionsViewController")! controller.type = .work controller.user = user Helper.currentTabNavigationController()?.pushViewController(controller, animated: true) break case .education: let controller: OptionsEducationViewController = Helper.controllerFromStoryboard(controllerId: "OptionsEducationViewController")! controller.user = user Helper.currentTabNavigationController()?.pushViewController(controller, animated: true) break default: break } } } } // MARK: - AboutTableViewCellDelegate extension AboutViewController: AboutTableViewCellDelegate { func aboutTableViewCell(_ cell: AboutTableViewCell, onSelectViewClicked index: Int) { guard let indexPath = passionsTableView.indexPath(for: cell) else { assertionFailure("No index path for cell") return } var pastPassionId: String? /* get the current interest with the selected index */ let newPassionId = passions![indexPath.row].objectId! for (passionId, _index) in selectedPassion { if _index == index { pastPassionId = passionId break } } if let alreadySelectedIndex = selectedPassion[newPassionId] { selectedPassion[newPassionId] = index if pastPassionId != nil { selectedPassion[pastPassionId!] = alreadySelectedIndex } } else { if pastPassionId != nil { selectedPassion[pastPassionId!] = nil } selectedPassion[newPassionId] = index } passionsTableView.reloadData() user.assignPassionIds(dict: selectedPassion) UserProvider.updateUser(user: user, completion: nil) // notify about changes Helper.sendNotification(with: searchLocationChangedNotification, object: nil, dict: nil) } } // MARK: - AboutSaveTableViewCellDelegate extension AboutViewController: AboutSaveTableViewCellDelegate { func aboutSaveCell(cell: AboutSaveTableViewCell, didClickedOnSave button: UIButton) { view.endEditing(true) showBlackLoader() UserProvider.updateUser(user: user) { (result) in switch(result) { case .success(_): SVProgressHUD.showSuccess(withStatus: LocalizableString.Success.localizedString) break case .failure(let error): SVProgressHUD.showError(withStatus: error.localizedDescription) break default: break } } } }
import UserNotifications import UIKit class NotificationManager { } extension NotificationManager: INotificationManager { var allowedBackgroundFetching: Bool { UIApplication.shared.backgroundRefreshStatus == .available } func requestPermission(onComplete: @escaping (Bool) -> ()) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (granted, error) in DispatchQueue.main.async { onComplete(granted) } } } func show(notification: AlertNotification) { let content = UNMutableNotificationContent() content.title = notification.title content.body = notification.body let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: "my_identifier_\(notification.title)", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } func removeNotifications() { UNUserNotificationCenter.current().removeAllDeliveredNotifications() UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } }
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford 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 UIKit public extension UIImage { class func resizableImage(withBorderWidth width: CGFloat, color: UIColor? = nil, backgroundColor: UIColor? = nil, cornerRadius: CGFloat, renderingMode: UIImageRenderingMode = .alwaysTemplate) -> UIImage { return resizableImage( border: (width: width, color: color), backgroundColor: backgroundColor, cornerRadius: cornerRadius, renderingMode: renderingMode ) } class func resizableImage(ofColor color: UIColor, cornerRadius: CGFloat, renderingMode: UIImageRenderingMode = .alwaysTemplate) -> UIImage { return resizableImage( backgroundColor: color, cornerRadius: cornerRadius, renderingMode: renderingMode ) } private class func resizableImage( border: (width: CGFloat, color: UIColor?)? = nil, backgroundColor: UIColor? = nil, cornerRadius: CGFloat, renderingMode: UIImageRenderingMode = .alwaysTemplate) -> UIImage { guard border != nil || backgroundColor != nil else { fatalError("You must pass a border configuration, or a background color (or both).") } let (lineWidth, lineColor) = border ?? (width: 0, color: nil) guard lineWidth >= 0 else { fatalError("The border width must be greater than or equal 0.") } guard cornerRadius >= 0 else { fatalError("The corner radius must be greater than or equal 0.") } if lineWidth > 0 && lineColor == nil && renderingMode != .alwaysTemplate { fatalError("If a border width is specified without a color, you must be using the \".alwaysTemplate\" rendering mode.") } let dimension = lineWidth + cornerRadius let size = (dimension * 2) + 1 let totalBounds = CGRect(x: 0, y: 0, width: size, height: size) let halfLineWidth = lineWidth / 2 let pathRect = CGRect(x: halfLineWidth, y: halfLineWidth, width: totalBounds.width - lineWidth, height: totalBounds.height - lineWidth) let renderer = UIGraphicsImageRenderer(bounds: totalBounds) let image = renderer.image { _ in let path = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRadius) if lineWidth > 0 { path.lineWidth = lineWidth (lineColor ?? .black).setStroke() path.stroke() } if let backgroundColor = backgroundColor { backgroundColor.setFill() path.fill() } } let capInsets = UIEdgeInsets( top: dimension, left: dimension, bottom: dimension, right: dimension ) return image .resizableImage(withCapInsets: capInsets) .withRenderingMode(renderingMode) } }
// // DescriptionTagger.swift // FeedKit Example iOS // // Created by Klaus Rodewig on 13.05.18. // import UIKit class DescriptionTagger { fileprivate let text: String init(inText : String){ self.text = inText; } public func namesPlacesAndOrganisations () -> NSAttributedString { let theTagger = NSLinguisticTagger(tagSchemes: [.nameType, .tokenType], options: 0) theTagger.string = self.text let theRange = NSRange(location:0, length: self.text.utf16.count) let theOptions: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace, .joinNames] let theTags: [NSLinguisticTag] = [.personalName, .placeName, .organizationName] let formattedDesciptionBasedOnTags = NSMutableAttributedString(string: self.text) let formattedDesciptionBasedOnTagsFontBold = UIFont(name:"Helvetica-Bold", size:16)! theTagger.enumerateTags(in: theRange, unit: .word, scheme: .nameType, options: theOptions) { tag, tokenRange, stop in if let tag = tag, theTags.contains(tag) { formattedDesciptionBasedOnTags.addAttribute(NSAttributedStringKey.font, value:formattedDesciptionBasedOnTagsFontBold, range:tokenRange) } } return formattedDesciptionBasedOnTags } }
// // WeatherDetailsViewController.swift // WeatherApp // // Created by Nikita Egoshin on 19.10.2020. // import RIBs import RxSwift import UIKit protocol WeatherDetailsPresentableListener: class { func selectCities() } final class WeatherDetailsViewController: UIViewController, WeatherDetailsPresentable, WeatherDetailsViewControllable { @IBOutlet weak var currentWeatherView: UIView! @IBOutlet weak var cityNameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var temperatureRangeLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var cloudsLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var windSpeedLabel: UILabel! @IBOutlet weak var pressureLabel: UILabel! @IBOutlet weak var weatherIconImageVIew: UIImageView! private let kDailyForecastCell = "DailyForecastCell" private let disposeBag = DisposeBag() weak var listener: WeatherDetailsPresentableListener? private var dailyForecast: [DailyForecast] = [] override func viewDidLoad() { super.viewDidLoad() weatherIconImageVIew.layer.shadowColor = UIColor.black.cgColor weatherIconImageVIew.layer.shadowRadius = 3.0 weatherIconImageVIew.layer.shadowOpacity = 0.75 weatherIconImageVIew.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) currentWeatherView.layer.shadowColor = UIColor.black.cgColor currentWeatherView.layer.shadowRadius = 3.0 currentWeatherView.layer.shadowOpacity = 0.75 currentWeatherView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) } // MARK: - Update func showForecast(_ forecast: BaseForecast, for city: City) { cityNameLabel.text = city.cityName dateLabel.text = dateFormatter.string(from: Date(timeIntervalSince1970: forecast.timestamp)) temperatureLabel.text = "\(forecast.temperature.current.fahrengeit) °F" temperatureRangeLabel.text = "\(forecast.temperature.minimum.fahrengeit) °F — \(forecast.temperature.maximum.fahrengeit) °F" cloudsLabel.text = "\(forecast.conditions.clouds) %" humidityLabel.text = "\(forecast.conditions.humidity) %" windSpeedLabel.text = "\(forecast.wind.speed) mps" pressureLabel.text = "\(Int(Double(forecast.conditions.pressure) * 0.0145038)) psi" loadIcon(withID: forecast.conditions.icon) .observeOn(MainScheduler.asyncInstance) .subscribe { [unowned self] (image) in weatherIconImageVIew.image = image } onError: { (error) in print(error.localizedDescription) } .disposed(by: disposeBag) } private func loadIcon(withID iconID: String) -> Single<UIImage?> { Single<UIImage?>.create { (s) -> Disposable in DispatchQueue.global(qos: .userInitiated).async { do { let url = URL(string: "http://openweathermap.org/img/wn/\(iconID)@2x.png")! let data = try Data(contentsOf: url) let icon = UIImage(data: data) s(.success(icon)) } catch { s(.error(error)) } } return Disposables.create() } } func showDailiyForecast(_ forecast: [DailyForecast]) { dailyForecast = forecast tableView.reloadData() } // MARK: - Actions @IBAction func onSelectCityButtonTouch(_ sender: UIButton) { listener?.selectCities() } // MARK: - Private private let dateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "" return df }() } extension WeatherDetailsViewController: UITableViewDataSource, UITableViewDelegate { private static let weekdayFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "EEEE HH:mm" return df }() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dailyForecast.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = dailyForecast[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: kDailyForecastCell) as! DailyForecastCell cell.humidityLabel.text = String(format: "%.2f%%", item.humidity) cell.maxTemperatureLabel.text = "\(Int(round(item.maxTemperature)).fahrengeit) °F" cell.minTemperatureLabel.text = "\(Int(round(item.minTemperature)).fahrengeit) ... " cell.weekdayLabel.text = WeatherDetailsViewController.weekdayFormatter.string(from: item.date) loadIcon(withID: item.icon) .observeOn(MainScheduler.asyncInstance) .subscribe(onSuccess: { [unowned tableView, unowned cell] image in guard let cellIndexPath = tableView.indexPath(for: cell), cellIndexPath == indexPath else { return } cell.weatherIconImageView.image = image }) .disposed(by: disposeBag) return cell } }
// // FirstViewController.swift // newsApp // // Created by Rohan Sharma on 8/27/18. // Copyright © 2018 Rohan Sharma. All rights reserved. // import UIKit import FirebaseFirestore class FirstViewController: UIViewController { var db: Firestore! var docIDs = [String](); //Dictionaries for all categories var studentLife = [String: String](); var sports = [String: String](); override func viewDidLoad() { super.viewDidLoad() let categories = ["studentLife": self.studentLife, "sports": self.sports]; let db = Firestore.firestore(); let settings = db.settings settings.areTimestampsInSnapshotsEnabled = true db.settings = settings for (name, var dict) in categories { db.collection(name).getDocuments { (snapshot, error) in if error != nil { //print(error) } else { for document in (snapshot?.documents)! { if let title = document.data()["title"] as? String, let body = document.data()["body"] as? String { dict[title] = body; } } } // print(dict); } } } @IBOutlet var story: UIView! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ExampleTests.swift // ExampleTests // // Created by André Campana on 09.10.17. // Copyright © 2017 Bell App Lab. All rights reserved. // import XCTest @testable import Example class NotificationObject: NSObject, UILoader { static let deinitNotification = NSNotification.Name(rawValue: "DidDeinit") static let loadingStatusNotification = NSNotification.Name(rawValue: "DidChangeStatus") static let loadingStatusUserInfoKey = "NewLoadingStatus" deinit { NotificationCenter.default.post(name: NotificationObject.deinitNotification, object: nil) } func didChangeLoadingStatus(_ loading: Bool) { NotificationCenter.default.post(name: NotificationObject.loadingStatusNotification, object: nil, userInfo: [NotificationObject.loadingStatusUserInfoKey: loading]) } } class ExampleTests: XCTestCase { func testDeinit() { var obj: NotificationObject? = NotificationObject() let expectDeinit = expectation(forNotification: NotificationObject.deinitNotification, object: nil) { (notification) -> Bool in return true } obj?.isLoading = true obj?.isLoading = false obj = nil wait(for: [expectDeinit], timeout: 10) } func testLoadingStatus() { let vc = ViewController() vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true") } func testFiveTimes() { let vc = ViewController() vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the first time") vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the second time") vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the third time") vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the fourth time") vc.isLoading = true XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the fifth time") vc.isLoading = false XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the first decrement") vc.isLoading = false XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the second decrement") vc.isLoading = false XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the third decrement") vc.isLoading = false XCTAssertTrue(vc.isLoading, "The ViewController's loading property should be true for the fourth decrement") vc.isLoading = false XCTAssertFalse(vc.isLoading, "The ViewController's loading property should be false for the fifth decrement") } func testLoadingStatusChange() { let obj = NotificationObject() let expectLoadingStatusChange = expectation(forNotification: NotificationObject.loadingStatusNotification, object: nil) { (notification) -> Bool in return notification.userInfo?[NotificationObject.loadingStatusUserInfoKey] as? Bool == obj.isLoading } obj.isLoading = true wait(for: [expectLoadingStatusChange], timeout: 10) } }
import XCTest import EasyImagy struct Foo { var xs: [RGBA] func map(f: RGBA -> RGBA) -> Foo { return Foo(xs: xs.map(f)) } } struct Bar<T> { var xs: [T] func map<U>(f: T -> U) -> Bar<U> { return Bar<U>(xs: xs.map(f)) } } class GenericsPerformanceTests: XCTestCase { func testNonGenericPerformance() { let xs = [RGBA](count: 1000000, repeatedValue: RGBA(red: 255, green: 0, blue: 0, alpha: 255)) measureBlock { let foo = Foo(xs: xs) let mapped = foo.map { RGBA(gray: $0.gray) } XCTAssertEqual(mapped.xs[0].red, 85) } } func testGenericPerformance() { let xs = [RGBA](count: 1000000, repeatedValue: RGBA(red: 255, green: 0, blue: 0, alpha: 255)) measureBlock { let bar = Bar<RGBA>(xs: xs) let mapped = bar.map { RGBA(gray: $0.gray) } XCTAssertEqual(mapped.xs[0].red, 85) } } }
// // AppDelegate.swift // TestECommerceApp // // Created by Ivan Stebletsov on 04/02/2019. // Copyright © 2019 Ivan Stebletsov. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Properties var window: UIWindow? private let coreDataManager = CoreDataStorage(modelName: "TestECommerceApp") private let dataSaver = DataSaver() // MARK: - Application lifecicle methods func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Preloading data from CSV when you first start the app importCSVDataIfNeeded() window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.backgroundColor = .white let storeViewController = StoreViewController() let backEndViewController = UINavigationController(rootViewController: BackEndViewController()) let appScreenControllers = [storeViewController, backEndViewController] // Pass an CoreDataStack instance to the initial ViewController (StoreViewController) dataSaver.coreDataManager = coreDataManager storeViewController.dataStorage = dataSaver let tabBarViewController = UITabBarController() tabBarViewController.tabBar.tintColor = UIColor(r: 70, g: 155, b: 252, alpha: 1) tabBarViewController.viewControllers = appScreenControllers storeViewController.tabBarItem = UITabBarItem(title: "Store-Front", image: UIImage(named: "Store-Front"), selectedImage: nil) backEndViewController.tabBarItem = UITabBarItem(title: "Back-End", image: UIImage(named: "Back-End"), selectedImage: nil) window?.rootViewController = tabBarViewController return true } func applicationWillResignActive(_ application: UIApplication) { coreDataManager.saveChanges() } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { coreDataManager.saveChanges() } // MARK: - Importing data // Check if there are no elements in CoreData, so we parse the CSV file and import the data into CoreData func importCSVDataIfNeeded() { let fetchRequest = NSFetchRequest<Item>(entityName: "Item") let count = try! coreDataManager.mainManagedObjectContext.count(for: fetchRequest) guard count == 0 else { return } do { let results = try coreDataManager.mainManagedObjectContext.fetch(fetchRequest) results.forEach { coreDataManager.mainManagedObjectContext.delete($0) } coreDataManager.saveChanges() importCSVData() } catch let error as NSError { print("Error fetching: \(error), \(error.userInfo)") } } // Parse CSV, create managedObjects and save into CoreData func importCSVData() { let csvURL = Bundle.main.url(forResource: "data", withExtension: "csv")! let csvLines = try! String(contentsOf: csvURL, encoding: .utf8).components(separatedBy: "\n") for line in csvLines { var lineComponents = line.components(separatedBy: ",") guard lineComponents.count >= 3 else { return } let itemName = lineComponents[0].trimmingCharacters(in: CharacterSet(charactersIn: "\"")) let itemPrice = Double(lineComponents[1].trimmingCharacters(in: CharacterSet(charactersIn: "01234567890.").inverted)) let itemStock = lineComponents[2].trimmingCharacters(in: CharacterSet(charactersIn: "01234567890").inverted) let item = Item(context: coreDataManager.mainManagedObjectContext) item.name = itemName item.price = String(itemPrice!) item.stock = itemStock } coreDataManager.saveChanges() } }
// // Woolly_MammothTests.swift // Woolly MammothTests // // Created by Boris Bügling on 26/10/14. // Copyright (c) 2014 Boris Bügling. All rights reserved. // import Cocoa import Woolly_Mammoth import XCTest class Woolly_MammothTests: XCTestCase { func testJaroWinkler() { let distance = JaroWinklerDistance("typoed", "tpoed") XCTAssertTrue(abs(distance - 0.95) <= FLT_EPSILON, "Distance is wrong") } }
// // BantuanViewController.swift // Lafzi // // Created by Alfat Saputra Harun on 13/12/18. // Copyright © 2018 Alfat Saputra Harun. All rights reserved. // import UIKit import WebKit class BantuanViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var webView: WKWebView! var html = "" override func viewDidLoad() { super.viewDidLoad() webView.loadHTMLString(html, baseURL: nil) webView.navigationDelegate = self } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { let url = navigationAction.request.url UIApplication.shared.canOpenURL(url!) UIApplication.shared.open(url!) decisionHandler(.cancel) } else { decisionHandler(.allow) } } }
import Foundation import PathKit enum BuildActions: String { case clean = "clean" case build = "build" case archive = "archive" } enum Configuration: String { case debug = "debug" case release = "release" } struct PackageTool { var project: String var scheme: String var midArguments: [String] // 暂时不开放 let archivePath: Path let exportPath: Path init(project: String?, scheme: String?) { self.midArguments = [] if let proj = project { self.midArguments += ["-project"] + ["\(proj)/\(Path(proj).lastComponent).xcodeproj"] self.project = proj } else { self.project = Path.current.description } if let sch = scheme { self.scheme = sch } else { self.scheme = Path(self.project).lastComponentWithoutExtension.description } self.archivePath = Path("\(self.project)/build/🐙/archive/\(self.scheme).xcarchive") self.exportPath = Path("\(self.project)/build/🐙/\(self.scheme).ipa") } public func package(bundleId: String?, configuration: String?) -> Void { clean(bundleId: bundleId, configuration: configuration) archive(bundleId: bundleId, configuration: configuration) export(bundleId: bundleId, configuration: configuration) } public func clean(bundleId: String?, configuration: String?) -> Void { try! FileManager.default.removeItem(atPath: "\(self.project)/build/🐙") let shell = xcodebuildShell(action: .clean, bundleId: bundleId, configuration: configuration) let status = try? self.run(shell: shell) print(status ?? "没有值啊") } public func archive(bundleId: String?, configuration: String?) -> Void { var shell = xcodebuildShell(action: .archive, bundleId: bundleId, configuration: configuration) shell += ["-scheme"] + [self.scheme] shell += ["-archivePath"] + [self.archivePath.description] let status = try? self.run(shell: shell) print(status ?? "没有值啊") } public func export(bundleId: String?, configuration: String?) -> Void { var shell = xcodebuildShell(bundleId: bundleId, configuration: configuration) shell += ["-exportArchive"] shell += ["-archivePath"] + [self.archivePath.description] shell += ["-exportPath"] + [self.exportPath.description] shell += ["-exportFormat"] + ["ipa"] let status = try? self.run(shell: shell) print(status ?? "没有值啊") } internal func xcodebuildShell(action: BuildActions = .build, bundleId: String?, configuration: String?) -> [String] { var arguments = [String]() if action != .build { arguments += [action.rawValue] } arguments += self.midArguments if let configuration = configuration { if configuration.lowercased() == Configuration.debug.rawValue { arguments += ["-configuration"] + ["Debug"] } else if configuration.lowercased() == Configuration.release.rawValue { arguments += ["-configuration"] + ["Release"] } } return arguments } @discardableResult private func run(shell args: [String], launchPath: String = "xcodebuild") throws -> Int32 { let task = Process() task.launchPath = "/usr/bin/" + launchPath task.arguments = args // print("LOG: \(task.arguments)") task.launch() task.waitUntilExit() return task.terminationStatus } }
// // TopicViewModel.swift // PrototypeApp // // Created by Surjeet on 30/03/21. // import UIKit class TopicViewModel: NSObject { var showLoader: ((_ show: Bool)->Void)? var networkRequestHandler: ((_ error: Error?)->Void)? var allTopics = [Topic]() var topics = [Topic]() func fetchTopics() { showLoader?(true) let url = URL(string:"https://tenpercent-interview-project.s3.amazonaws.com/topics.json")! NetworkManager.shared.performRequest(url: url, type: .GET) { [weak self] (result: Result<TopicModel, Error>) in self?.showLoader?(false) switch result { case .success(let topicModel): if let topicArray = topicModel.topics { self?.allTopics.append(contentsOf: topicArray) } self?.getParentTopics() case .failure(let error): self?.networkRequestHandler?(error) } } } private func getParentTopics() { let parentTopics = allTopics.filter { (topic) -> Bool in return topic.parentUuid == nil }.sorted { (topic1, topic2) -> Bool in return (topic1.position ?? 0) < (topic2.position ?? 0) } parentTopics.forEach { (topic) in let subtopics = allTopics.filter({$0.parentUuid == topic.uuid}) let meditataionIDs = Set(subtopics.map({$0.meditations ?? []}).joined()) var newTopic = topic newTopic.updateSubTopicMeditationsCount(meditataionIDs.count) topics.append(newTopic) } // topics.append(contentsOf: parentTopics) self.networkRequestHandler?(nil) } func fetchSubTopics(index: Int) -> [Topic] { let topic = getTopic(index: index) let subtopics = allTopics.filter({$0.parentUuid == topic.uuid}) return subtopics } } extension TopicViewModel { func getNumberOfTopics() -> Int { return topics.count } func getTopic(index: Int) -> Topic { return topics[index] } }
// // BeerListRemoteDataManager.swift // Bebida-Fractal // // Created by Fernanda de Lima on 13/12/2017. // Copyright © 2017 Empresinha. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper class BeerListRemoteDataManager:BeerListRemoteDataManagerInputProtocol { var remoteRequestHandler: BeerListRemoteDataManagerOutputProtocol? func retrieveBeerList() { Alamofire .request(Endpoints.Beers.list.url, method: .get) .validate() .responseArray(completionHandler: { (response: DataResponse<[Beer]>) in switch response.result { case .success(let beers): print("==========> SAIDA") print(beers) self.remoteRequestHandler?.onBeersRetrieved(beers) case .failure( _): self.remoteRequestHandler?.onError() } }) } }
// // Logging.swift // Squares // // Created by Matthias Hochgatterer on 03/12/14. // Copyright (c) 2014 Matthias Hochgatterer. All rights reserved. // import Foundation // Send all messages to the shared logger instance // The prefix is the current timestamp public func print(_ string: String, file: String = #file, function: String = #function, line: Int = #line) { let name = URL(fileURLWithPath: file).lastPathComponent Logger.sharedInstance.log(prefix() + ": \(name): \(function): \(line): " + string) } var _dateFormatter: DateFormatter? func dateFormatter() -> DateFormatter { if _dateFormatter == nil { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "y-MM-dd HH:mm:ss.SSS Z" _dateFormatter = dateFormatter } return _dateFormatter! } func prefix() -> String { return dateFormatter().string(from: Date()) }
// // STMineCustomViewController.swift // SpecialTraining // // Created by 徐军 on 2018/11/30. // Copyright © 2018年 youpeixun. All rights reserved. // import UIKit import RxDataSources class STMineCustomViewController: BaseViewController { @IBOutlet weak var topLayout: NSLayoutConstraint! @IBOutlet weak var collectionView: UICollectionView! var viewModel:MineCustomViewModel! override func setupUI() { title = "我的定制" if #available(iOS 11, *) { collectionView.contentInsetAdjustmentBehavior = .never }else { automaticallyAdjustsScrollViewInsets = false } topLayout.constant += 20 let layout = UICollectionViewFlowLayout() layout.sectionInset = .init(top: 10, left: 15, bottom: 10, right: 15) layout.minimumInteritemSpacing = 10 layout.minimumLineSpacing = 15 layout.itemSize = .init(width: (PPScreenW - 15*2 - 3*10)/4.0, height: 40) collectionView.collectionViewLayout = layout collectionView.register(UINib(nibName: "MineCustomCell", bundle: nil), forCellWithReuseIdentifier: "MineCustomCell") collectionView.register(UINib(nibName: "MineCustomCollectionReusableHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MineCustomCollectionReusableHeaderView") collectionView.register(UINib(nibName: "MineCustomCollectionReusableFooterView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "MineCustomCollectionReusableFooterView") } override func rxBind() { viewModel = MineCustomViewModel() let datasource = RxCollectionViewSectionedReloadDataSource<SectionModel<Int, String>>(configureCell: { (ds, col, indexpath, item) -> UICollectionViewCell in let cell = col.dequeueReusableCell(withReuseIdentifier: "MineCustomCell", for: indexpath) as! MineCustomCell cell.titleLbl.text = item return cell }, configureSupplementaryView: { (ds, col, kind, indexpath) -> UICollectionReusableView in // if indexpath.section == 3 { // let colFooter = col.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "MineCustomCollectionReusableFooterView", for: indexpath) as! MineCustomCollectionReusableFooterView // return colFooter // } let colHeader = col.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MineCustomCollectionReusableHeaderView", for: indexpath) as! MineCustomCollectionReusableHeaderView colHeader.titleString = self.viewModel.sectionTitle(indexpath) colHeader.delegate = nil colHeader.delegate = self return colHeader }, moveItem: { (_, _, _) in }) { (_, _) -> Bool in return false } viewModel.datasource.asDriver().drive(collectionView.rx.items(dataSource: datasource)).disposed(by: disposeBag) collectionView.rx.itemSelected.asDriver().drive(onNext: { (index) in PrintLog(index) }).disposed(by: disposeBag) collectionView.rx.setDelegate(self).disposed(by: disposeBag) } } extension STMineCustomViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let h: CGFloat = UIDevice.current.isX ? 44 : 20 return section == 0 ? CGSize.init(width: PPScreenW, height: h) : CGSize.init(width: collectionView.width, height: 45) } } extension STMineCustomViewController: MineSectionHeaderAction { func addBtnClick() { PrintLog("点击了添加按钮") } }
import AEXML import Foundation import PathKit extension XCScheme { public final class AdditionalOption: Equatable { // MARK: - Attributes public var key: String public var value: String public var isEnabled: Bool // MARK: - Init public init(key: String, value: String, isEnabled: Bool) { self.key = key self.value = value self.isEnabled = isEnabled } init(element: AEXMLElement) throws { key = element.attributes["key"]! value = element.attributes["value"]! isEnabled = element.attributes["isEnabled"] == "YES" } // MARK: - XML func xmlElement() -> AEXMLElement { AEXMLElement(name: "AdditionalOption", value: nil, attributes: [ "key": key, "value": value, "isEnabled": isEnabled.xmlString, ]) } // MARK: - Equatable public static func == (lhs: AdditionalOption, rhs: AdditionalOption) -> Bool { lhs.key == rhs.key && lhs.value == rhs.value && lhs.isEnabled == rhs.isEnabled } } }
//: Playground - noun: a place where people can play import UIKit let line = "a:b,c;d" // Create a NSCharacterSet of delimiters. let separators = NSCharacterSet(charactersInString: ":,;") // Split based on characters. let parts = line.componentsSeparatedByCharactersInSet(separators) // Print result array. print(Int.max^Int.max) Int(6.0) << Int(2.0) print(6<<4) Double("0.6 * 6")