repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
AaronMT/firefox-ios
refs/heads/main
Storage/SQL/ReadingListSchema.swift
mpl-2.0
14
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let AllTables: [String] = ["items"] private let log = Logger.syncLogger open class ReadingListSchema: Schema { static let DefaultVersion = 1 public var name: String { return "READINGLIST" } public var version: Int { return ReadingListSchema.DefaultVersion } public init() {} let itemsTableCreate = """ CREATE TABLE IF NOT EXISTS items ( client_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, client_last_modified INTEGER NOT NULL, id TEXT, last_modified INTEGER, url TEXT NOT NULL UNIQUE, title TEXT NOT NULL, added_by TEXT NOT NULL, archived INTEGER NOT NULL DEFAULT (0), favorite INTEGER NOT NULL DEFAULT (0), unread INTEGER NOT NULL DEFAULT (1) ) """ public func create(_ db: SQLiteDBConnection) -> Bool { return self.run(db, queries: [itemsTableCreate]) } public func update(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = self.version if from == to { log.debug("Skipping ReadingList schema update from \(from) to \(to).") return true } if from < 1 && to >= 1 { log.debug("Updating ReadingList database schema from \(from) to \(to).") return self.run(db, queries: [itemsTableCreate]) } log.debug("Dropping and re-creating ReadingList database schema from \(from) to \(to).") return drop(db) && create(db) } public func drop(_ db: SQLiteDBConnection) -> Bool { log.debug("Dropping ReadingList database.") let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" } let queries = Array([tables].joined()) return self.run(db, queries: queries) } func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { do { try db.executeChange(sql, withArgs: args) } catch let err as NSError { log.error("Error running SQL in ReadingListSchema: \(err.localizedDescription)") log.error("SQL was \(sql)") return false } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql, args: nil) { return false } } return true } }
bfa8d86c97a00f76ce965311b645475b
31.512195
96
0.588522
false
false
false
false
shmidt/ContactsPro
refs/heads/master
ContactsPro/ContactCell.swift
mit
1
// // ContactCell.swift // ContactsPro // // Created by Dmitry Shmidt on 16/02/15. // Copyright (c) 2015 Dmitry Shmidt. All rights reserved. // import UIKit import MGSwipeTableCell class ContactCell: MGSwipeTableCell { // let imageSize:CGFloat = 48.0 @IBOutlet weak var nameHeight: NSLayoutConstraint! @IBOutlet weak var imageWidth: NSLayoutConstraint! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var noteLabel: UILabel! @IBOutlet weak var todoLabel: UILabel! @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var todoView: UIView! var name:NSAttributedString?{ get { return nameLabel.attributedText } set { nameLabel.attributedText = newValue if let note = noteLabel.text{ nameHeight.constant = note.isEmpty ? 3 : -6 }else{ nameHeight.constant = 3 } } } var todo:Int{ get { return 1 } set { todoLabel.text = (newValue == 0) ? "" : "\(newValue)" todoView.hidden = (newValue == 0) } } var thumbImage:UIImage?{ get { return thumbImageView.image } set { thumbImageView.image = newValue imageWidth.constant = (newValue != nil) ? CGFloat(40) : CGFloat(8) } } // override func awakeFromNib() { super.awakeFromNib() // Initialization code imageView?.layer.masksToBounds = true imageView?.layer.cornerRadius = 20 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
eb67a9c6cf09f6371631302815aa8c3d
24.013889
78
0.578012
false
false
false
false
tensorflow/swift-models
refs/heads/main
Examples/GrowingNeuralCellularAutomata/SamplePool.swift
apache-2.0
1
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow struct SamplePool { var samples: [Tensor<Float>] let initialState: Tensor<Float> init(initialState: Tensor<Float>, size: Int) { samples = [Tensor<Float>](repeating: initialState, count: size) self.initialState = initialState } // This rearranges the pool to place the randomly sampled batch upfront, for easy replacement later. mutating func sample(batchSize: Int, damaged: Int = 0) -> Tensor<Float> { for index in 0..<batchSize { let choice = Int.random(in: index..<samples.count) if index != choice { samples.swapAt(index, choice) } } // TODO: Have this sorted by loss. samples[0] = initialState if damaged > 0 { for damagedIndex in (batchSize - damaged - 1)..<batchSize { samples[damagedIndex] = samples[damagedIndex].applyCircleDamage() } } return Tensor(stacking: Array(samples[0..<batchSize])) } mutating func replace(samples: Tensor<Float>) { let samplesToInsert = samples.unstacked() self.samples.replaceSubrange(0..<samplesToInsert.count, with: samplesToInsert) } } extension Tensor where Scalar == Float { func applyCircleDamage() -> Tensor { let width = self.shape[self.rank - 2] let height = self.shape[self.rank - 3] let radius = Float.random(in: 0.1..<0.4) let centerX = Float.random(in: -0.5..<0.5) let centerY = Float.random(in: -0.5..<0.5) var x = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: width, on: self.device) var y = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: height, on: self.device) x = ((x - centerX) / radius).broadcasted(to: [height, width]) y = ((y - centerY) / radius).expandingShape(at: 1).broadcasted(to: [height, width]) let distanceFromCenter = (x * x + y * y).expandingShape(at: 2) let circleMask = distanceFromCenter.mask { $0 .> 1.0 } return self * circleMask } // TODO: Extend this to arbitrary rectangular sections. func damageRightSide() -> Tensor { let width = self.shape[self.rank - 2] let height = self.shape[self.rank - 3] var x = Tensor<Float>(linearSpaceFrom: -1.0, to: 1.0, count: width, on: self.device) x = x.broadcasted(to: [height, width]).expandingShape(at: 2) let rectangleMask = x.mask { $0 .< 0.0 } return self * rectangleMask } }
626fe257cabaf63c439d698266e9a241
37.233766
102
0.674592
false
false
false
false
nineteen-apps/themify
refs/heads/master
Sources/NSObject+Extension.swift
mit
1
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-06-02 by Ronaldo Faria Lima // This file purpose: internal extension for NSObject import Foundation /// Adds a class function to NSObject in order to get a class type for a given string representing the class name. /// This is based on Maxim Bilan extension, updated to Swift 4. // swiftlint:disable:next line_length /// - seealso: https://medium.com/@maximbilan/ios-objective-c-project-nsclassfromstring-method-for-swift-classes-dbadb721723 // swiftlint:disable:previous line_length extension NSObject { class func swiftClassFromString(className: String) -> AnyClass? { #if DEBUG let bundle = Bundle(for: NSObject.self) #else let bundle = Bundle.main #endif var foundClass: AnyClass? = NSClassFromString(className) if foundClass == nil { if let bundleName = bundle.infoDictionary?["CFBundleName"] as? String { let appName = bundleName.replacingOccurrences(of: " ", with: "_") foundClass = NSClassFromString("\(appName).\(className)") } } return foundClass } }
5e1ee8f1760be35964e47736232f2fac
44.56
124
0.709833
false
false
false
false
FoodForTech/Handy-Man
refs/heads/1.0.0
HandyMan/HandyMan/HandyManCore/Spring/DesignableView.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // 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 @IBDesignable open class DesignableView: SpringView { @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable open var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable open var shadowColor: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColor.cgColor } } @IBInspectable open var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable open var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable open var shadowOffsetY: CGFloat = 0 { didSet { layer.shadowOffset.height = shadowOffsetY } } }
ea80293e6fe15dc67983a40912f2a8be
32.161765
81
0.666075
false
false
false
false
crspybits/SyncServerII
refs/heads/dev
Sources/Server/Controllers/FileController/FileController+DownloadAppMetaData.swift
mit
1
// // FileController+DownloadAppMetaData.swift // Server // // Created by Christopher G Prince on 3/23/18. // import Foundation import LoggerAPI import SyncServerShared extension FileController { func downloadAppMetaData(params:RequestProcessingParameters) { guard let downloadAppMetaDataRequest = params.request as? DownloadAppMetaDataRequest else { let message = "Did not receive DownloadAppMetaDataRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } Controllers.getMasterVersion(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, params: params) { (error, masterVersion) in if error != nil { params.completion(.failure(.message("\(error!)"))) return } if masterVersion != downloadAppMetaDataRequest.masterVersion { let response = DownloadAppMetaDataResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion params.completion(.success(response)) return } // Need to get the app meta data from the file index. // First, lookup the file in the FileIndex. This does an important security check too-- makes sure the fileUUID is in the sharing group. let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, fileUUID: downloadAppMetaDataRequest.fileUUID) let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init) var fileIndexObj:FileIndex! switch lookupResult { case .found(let modelObj): fileIndexObj = modelObj as? FileIndex if fileIndexObj == nil { let message = "Could not convert model object to FileIndex" Log.error(message) params.completion(.failure(.message(message))) return } case .noObjectFound: let message = "Could not find file in FileIndex" Log.error(message) params.completion(.failure(.message(message))) return case .error(let error): let message = "Error looking up file in FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } if fileIndexObj!.deleted! { let message = "The file you are trying to download app meta data for has been deleted!" Log.error(message) params.completion(.failure(.message(message))) return } guard let fileIndexAppMetaDataVersion = fileIndexObj.appMetaDataVersion else { let message = "Nil app meta data version in FileIndex." Log.error(message) params.completion(.failure(.message(message))) return } guard downloadAppMetaDataRequest.appMetaDataVersion == fileIndexAppMetaDataVersion else { let message = "Expected app meta data version \(String(describing: downloadAppMetaDataRequest.appMetaDataVersion)) was not the same as the actual version \(fileIndexAppMetaDataVersion)" Log.error(message) params.completion(.failure(.message(message))) return } let response = DownloadAppMetaDataResponse() response.appMetaData = fileIndexObj.appMetaData params.completion(.success(response)) } } }
03966aee5209e4a42a4d9155012f60b2
42.141414
201
0.589792
false
false
false
false
kevin-zqw/play-swift
refs/heads/master
swift-lang/08. Enumerations.playground/section-1.swift
apache-2.0
1
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Enumerations in Swift are different from their popular counterparts in C-like languages. // Rather that containing "one of a set of integer values" like most C-like languages, Swift's // enumerations can be thought of as holding one named type of a given set of named types. // // To clarify: Rather than holding an integer value that has been pre-defined integer value // (Error = -1, Success = 0) an enumeration in Swift only associates a name with a type (like // Int, String, Tuple, etc.) These elements of the enumeration can then be assigned "Associated // Values." For example, an enumeration can store an "Error" which is a Tuple with an Int value // for the error code and a String containing the message. Each time a function or piece of code // assignes or returns an Error(Int, String), it can set populate the Tuple with Int/String par // for the specific error condition. // // * Alternative to the enumeration storing named types, Swift enumerations can have a type. If // that type is Int, then they will behave more like their C-style counterparts. // ------------------------------------------------------------------------------------------------ // Here is the simple enumeration. // // Unlike their C counterparts, the members of the enumeration below are not integer values (0, // 1, 2, etc.) Instead, each member is a fully-fledged value in its own right. enum Planet { case Mercury case Venus case Earth case Mars case Jupiter case Saturn case Uranus case Neptune } enum Sex { case Male, Female } var mySex = Sex.Male // You can use shorter dot syntax mySex = .Female switch mySex { case .Male: print("a man") case .Female: print("a women") } // You can also combine members onto a single line if you prefer, or mix them up. This has no // effect on the enumeration itself. enum CompassPoint { case North, South case East, West } // Let's store an enumeration value into a variable. We'll let the compiler infer the type: var directionToHead = CompassPoint.West // Now that directionToHead has a CompassPoint type (which was inferred) we can set it to a // different CompassPoint value using a shorter syntax: directionToHead = .East // We can use a switch to match values from an enumeration. // // Remember that switches have to be exhaustive. But in this case, Swift knows that the CompassType // enumeration only has 4 values, so as long as we cover all 4, we don't need the default case. switch directionToHead { case .North: "North" case .South: "South" case .East: "East" case .West: "West" } // ------------------------------------------------------------------------------------------------ // Associated Values // // Associated values allows us to store information with each member of the switch using a Tuple. // // The following enumeration will store not only the type of a barcode (UPCA, QR Code) but also // the data of the barcode (this is likely a foreign concept for most.) enum Barcode { case UPCA(Int, Int, Int) // UPCA with associated value type (Int, Int, Int) case QRCode(String) // QRCode with associated value type of String } enum MyBarcode { case UPCA(Int, Int, Int) case QRCode(String) } let code = MyBarcode.QRCode("hello") let simpleCode = MyBarcode.UPCA(1, 1, 1) switch simpleCode { case .UPCA(let a, let b, let c): print("upca \(a) \(b) \(c)") case .QRCode(let code): print("QRCode: \(code)") } // case all constants, you can use one let switch simpleCode { case let .UPCA(a, b, c): print("upca \(a) \(b) \(c)") case let .QRCode(code): print("QRCode: \(code)") } // Let's specify a UPCA code (letting the compiler infer the enum type of Barcode): var productBarcode = Barcode.UPCA(0, 8590951226, 3) // Let's change that to a QR code (still of a Barcode type) productBarcode = .QRCode("ABCDEFGHIJKLMNOP") // We use a switch to check the value and extract the associated value: switch productBarcode { case .UPCA(let numberSystem, let identifier, let check): "UPCA: \(numberSystem), \(identifier), \(check)" case .QRCode(let productCode): "QR: \(productCode)" } // Using the switch statement simplification (see the Switch statement section) to reduce the // number of occurrances of the 'let' introducer: switch productBarcode { // All constants case let .UPCA(numberSystem, identifier, check): "UPCA: \(numberSystem), \(identifier), \(check)" // All variables case var .QRCode(productCode): "QR: \(productCode)" } // ------------------------------------------------------------------------------------------------ // Raw values // // We can assign a type to an enumeration. If we use Int as the type, then we are effectively // making an enumeration that functions like its C counterpart: enum StatusCode: Int { case Error = -1 case Success = 9 case OtherResult = 1 case YetAnotherResult // Unspecified values are auto-incremented from the previous value } enum ASCIICharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" } // String and Integer will get implicit raw value if you specified enum ImplicitRawValueInt: Int { case AA // raw value 0 case BB // raw value 1 case CC // raw value 2 case DD // raw value 3 } enum ImplicitRawValueString: String { case SS // raw value "SS" case BB // raw value "BB" case AA // raw value "AA" } // Raw values can be strings, characters, or any of the integer or floating-point number types // Each raw value must be unique within its enumeration declaration // We can get the raw value of an enumeration value with the rawValue member: StatusCode.OtherResult.rawValue // We can give enumerations many types. Here's one of type Character: enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" // Note that only Int type enumerations can auto-increment. Since this is a Character type, // the following line of code won't compile: // // case VerticalTab } print(StatusCode.Error.rawValue) // Alternatively, we could also use Strings enum FamilyPet: String { case Cat = "Cat" case Dog = "Dog" case Ferret = "Ferret" } // And we can get their raw value as well: FamilyPet.Ferret.rawValue // If you define an enumeration with a raw-value type, the enumeration automcatically receives an initializer that takes a value of the raw values's type(as a parameter called rawValue) and returns either an enumeration case or nil let myEnum = ASCIICharacter(rawValue: "A") // We can also generate the enumeration value from the raw value. Note that this is an optional // because not all raw values will have a matching enumeration: var pet = FamilyPet(rawValue: "Ferret") // Let's verify this: if pet != .None { "We have a pet!" } else { "No pet :(" } // An example of when a raw doesn't translate to an enum, leaving us with a nil optional: pet = FamilyPet(rawValue: "Snake") if pet != .None { "We have a pet" } else { "No pet :(" } // Use indirect to indicate that an enumeration case is recursive enum ArithmeticExpression { case Number(Int) indirect case Addition(ArithmeticExpression) indirect case Multiplication(ArithmeticExpression) } // Arecursive function is a straightforward way to work with data that has a recursive structure.
71a5c64bc1736140a5c0b9b71138ce8c
30.516949
231
0.680828
false
false
false
false
OpsLabJPL/MarsImagesIOS
refs/heads/main
MarsImagesIOS/TimeViewController.swift
apache-2.0
1
// // TimeViewController.swift // MarsImagesIOS // // Created by Powell, Mark W (397F) on 8/13/17. // Copyright © 2017 Mark Powell. All rights reserved. // import UIKit import MarsTimeConversion class TimeViewController: UIViewController { @IBOutlet weak var earthTimeLabel: UILabel! @IBOutlet weak var oppyTimeLabel: UILabel! @IBOutlet weak var mslTimeLabel: UILabel! var dateFormat = DateFormatter() let timeZone = TimeZone(abbreviation: "UTC") var timeFormat = DateFormatter() var timer = Timer() override func viewDidLoad() { super.viewDidLoad() dateFormat.timeZone = timeZone dateFormat.dateFormat = "yyyy-DDD" timeFormat.timeZone = timeZone timeFormat.dateFormat = "HH:mm:ss" //start clock update timer timer = Timer.scheduledTimer(timeInterval: 0.50, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true) updateTime() } @objc func updateTime() { let today = Date(timeIntervalSinceNow: 0) earthTimeLabel.text = "\(dateFormat.string(from: today))T\(timeFormat.string(from: today)) UTC" let oppy = Mission.missions[Mission.OPPORTUNITY]! var timeDiff = today.timeIntervalSince(oppy.epoch!) timeDiff /= MarsTimeConversion.EARTH_SECS_PER_MARS_SEC var sol = Int(timeDiff/86400) timeDiff -= Double(sol * 86400) var hour = Int(timeDiff / 3600) timeDiff -= Double(hour * 3600) var minute = Int(timeDiff / 60) var seconds = Int(timeDiff - Double(minute*60)) sol += 1 //MER convention of landing day sol 1 oppyTimeLabel.text = String(format:"Sol %03d %02d:%02d:%02d", sol, hour, minute, seconds) let curiosityTime = Date(timeIntervalSinceNow: 0) let marsTime = MarsTimeConversion.getMarsTime(curiosityTime, longitude: MarsTimeConversion.CURIOSITY_WEST_LONGITUDE) let msd = marsTime.msd let mtc = marsTime.mtc sol = Int(msd-(360.0-MarsTimeConversion.CURIOSITY_WEST_LONGITUDE)/360.0)-49268 let mtcInHours:Double = canonicalValue24(mtc - MarsTimeConversion.CURIOSITY_WEST_LONGITUDE*24.0/360.0) hour = Int(mtcInHours) minute = Int((mtcInHours-Double(hour))*60.0) seconds = Int((mtcInHours-Double(hour))*3600 - Double(minute*60)) // curiositySolLabel.text = [NSString stringWithFormat:@"Sol %03d", sol]; // curiosityTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", hour, minute]; // curiositySeconds.text = [NSString stringWithFormat:@":%02d", seconds]; // _curiosityTimeLabel.text = [NSString stringWithFormat:@"Sol %03d %02d:%02d:%02d", sol, hour, minute, seconds]; mslTimeLabel.text = String(format:"Sol %03d %02d:%02d:%02d", sol, hour, minute, seconds) self.view.setNeedsDisplay() } func canonicalValue24(_ hours:Double) -> Double { if hours < 0 { return 24 + hours } else if hours > 24 { return hours - 24 } return hours } }
2e44fb3fbd0b6910d49be7867430e75e
39.868421
133
0.644559
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
SignalServiceKit/src/Messages/UD/OWSUDManager.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit import SignalMetadataKit import SignalCoreKit public enum OWSUDError: Error { case assertionError(description: String) case invalidData(description: String) } @objc public enum OWSUDCertificateExpirationPolicy: Int { // We want to try to rotate the sender certificate // on a frequent basis, but we don't want to block // sending on this. case strict case permissive } @objc public enum UnidentifiedAccessMode: Int { case unknown case enabled case disabled case unrestricted } private func string(forUnidentifiedAccessMode mode: UnidentifiedAccessMode) -> String { switch mode { case .unknown: return "unknown" case .enabled: return "enabled" case .disabled: return "disabled" case .unrestricted: return "unrestricted" } } @objc public class OWSUDAccess: NSObject { @objc public let udAccessKey: SMKUDAccessKey @objc public let udAccessMode: UnidentifiedAccessMode @objc public let isRandomKey: Bool @objc public required init(udAccessKey: SMKUDAccessKey, udAccessMode: UnidentifiedAccessMode, isRandomKey: Bool) { self.udAccessKey = udAccessKey self.udAccessMode = udAccessMode self.isRandomKey = isRandomKey } } @objc public protocol OWSUDManager: class { @objc var keyValueStore: SDSKeyValueStore { get } @objc var phoneNumberAccessStore: SDSKeyValueStore { get } @objc var uuidAccessStore: SDSKeyValueStore { get } @objc func setup() @objc func trustRoot() -> ECPublicKey @objc func isUDVerboseLoggingEnabled() -> Bool // MARK: - Recipient State @objc func setUnidentifiedAccessMode(_ mode: UnidentifiedAccessMode, address: SignalServiceAddress) @objc func unidentifiedAccessMode(forAddress address: SignalServiceAddress) -> UnidentifiedAccessMode @objc func udAccessKey(forAddress address: SignalServiceAddress) -> SMKUDAccessKey? @objc func udAccess(forAddress address: SignalServiceAddress, requireSyncAccess: Bool) -> OWSUDAccess? // MARK: Sender Certificate // We use completion handlers instead of a promise so that message sending // logic can access the strongly typed certificate data. @objc func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) // MARK: Unrestricted Access @objc func shouldAllowUnrestrictedAccessLocal() -> Bool @objc func setShouldAllowUnrestrictedAccessLocal(_ value: Bool) } // MARK: - @objc public class OWSUDManagerImpl: NSObject, OWSUDManager { @objc public let keyValueStore = SDSKeyValueStore(collection: "kUDCollection") @objc public let phoneNumberAccessStore = SDSKeyValueStore(collection: "kUnidentifiedAccessCollection") @objc public let uuidAccessStore = SDSKeyValueStore(collection: "kUnidentifiedAccessUUIDCollection") // MARK: Local Configuration State private let kUDCurrentSenderCertificateKey_Production = "kUDCurrentSenderCertificateKey_Production" private let kUDCurrentSenderCertificateKey_Staging = "kUDCurrentSenderCertificateKey_Staging" private let kUDCurrentSenderCertificateDateKey_Production = "kUDCurrentSenderCertificateDateKey_Production" private let kUDCurrentSenderCertificateDateKey_Staging = "kUDCurrentSenderCertificateDateKey_Staging" private let kUDUnrestrictedAccessKey = "kUDUnrestrictedAccessKey" // MARK: Recipient State var certificateValidator: SMKCertificateValidator @objc public required override init() { self.certificateValidator = SMKCertificateDefaultValidator(trustRoot: OWSUDManagerImpl.trustRoot()) super.init() SwiftSingletons.register(self) } @objc public func setup() { AppReadiness.runNowOrWhenAppDidBecomeReady { guard self.tsAccountManager.isRegistered else { return } // Any error is silently ignored on startup. self.ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() } NotificationCenter.default.addObserver(self, selector: #selector(registrationStateDidChange), name: .RegistrationStateDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: NSNotification.Name.OWSApplicationDidBecomeActive, object: nil) } @objc func registrationStateDidChange() { AssertIsOnMainThread() guard tsAccountManager.isRegisteredAndReady else { return } // Any error is silently ignored ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() } @objc func didBecomeActive() { AssertIsOnMainThread() AppReadiness.runNowOrWhenAppDidBecomeReady { guard self.tsAccountManager.isRegistered else { return } // Any error is silently ignored on startup. self.ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() } } // MARK: - @objc public func isUDVerboseLoggingEnabled() -> Bool { return false } // MARK: - Dependencies private var profileManager: ProfileManagerProtocol { return SSKEnvironment.shared.profileManager } private var tsAccountManager: TSAccountManager { return TSAccountManager.sharedInstance() } private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: - Recipient state @objc public func randomUDAccessKey() -> SMKUDAccessKey { return SMKUDAccessKey(randomKeyData: ()) } private func unidentifiedAccessMode(forAddress address: SignalServiceAddress, transaction: SDSAnyWriteTransaction) -> UnidentifiedAccessMode { let defaultValue: UnidentifiedAccessMode = address.isLocalAddress ? .enabled : .unknown let existingUUIDValue: UnidentifiedAccessMode? if let uuidString = address.uuidString, let existingRawValue = uuidAccessStore.getInt(uuidString, transaction: transaction) { guard let value = UnidentifiedAccessMode(rawValue: existingRawValue) else { owsFailDebug("Couldn't parse mode value.") return defaultValue } existingUUIDValue = value } else { existingUUIDValue = nil } let existingPhoneNumberValue: UnidentifiedAccessMode? if let phoneNumber = address.phoneNumber, let existingRawValue = phoneNumberAccessStore.getInt(phoneNumber, transaction: transaction) { guard let value = UnidentifiedAccessMode(rawValue: existingRawValue) else { owsFailDebug("Couldn't parse mode value.") return defaultValue } existingPhoneNumberValue = value } else { existingPhoneNumberValue = nil } let existingValue: UnidentifiedAccessMode? if let existingUUIDValue = existingUUIDValue, let existingPhoneNumberValue = existingPhoneNumberValue { // If UUID and Phone Number setting don't align, defer to UUID and update phone number if existingPhoneNumberValue != existingUUIDValue { owsFailDebug("UUID and Phone Number unexpectedly have different UD values") Logger.info("Unexpected UD value mismatch, migrating phone number value: \(existingPhoneNumberValue) to uuid value: \(existingUUIDValue)") phoneNumberAccessStore.setInt(existingUUIDValue.rawValue, key: address.phoneNumber!, transaction: transaction) } existingValue = existingUUIDValue } else if let existingPhoneNumberValue = existingPhoneNumberValue { existingValue = existingPhoneNumberValue // We had phone number entry but not UUID, update UUID value if let uuidString = address.uuidString { uuidAccessStore.setInt(existingPhoneNumberValue.rawValue, key: uuidString, transaction: transaction) } } else if let existingUUIDValue = existingUUIDValue { existingValue = existingUUIDValue // We had UUID entry but not phone number, update phone number value if let phoneNumber = address.phoneNumber { phoneNumberAccessStore.setInt(existingUUIDValue.rawValue, key: phoneNumber, transaction: transaction) } } else { existingValue = nil } return existingValue ?? defaultValue } @objc public func unidentifiedAccessMode(forAddress address: SignalServiceAddress) -> UnidentifiedAccessMode { var mode: UnidentifiedAccessMode = .unknown databaseStorage.write { (transaction) in mode = self.unidentifiedAccessMode(forAddress: address, transaction: transaction) } return mode } @objc public func setUnidentifiedAccessMode(_ mode: UnidentifiedAccessMode, address: SignalServiceAddress) { if address.isLocalAddress { Logger.info("Setting local UD access mode: \(string(forUnidentifiedAccessMode: mode))") } databaseStorage.write { (transaction) in let oldMode = self.unidentifiedAccessMode(forAddress: address, transaction: transaction) if let uuidString = address.uuidString { self.uuidAccessStore.setInt(mode.rawValue, key: uuidString, transaction: transaction) } if let phoneNumber = address.phoneNumber { self.phoneNumberAccessStore.setInt(mode.rawValue, key: phoneNumber, transaction: transaction) } if mode != oldMode { Logger.info("Setting UD access mode for \(address): \(string(forUnidentifiedAccessMode: oldMode)) -> \(string(forUnidentifiedAccessMode: mode))") } } } // Returns the UD access key for a given recipient // if we have a valid profile key for them. @objc public func udAccessKey(forAddress address: SignalServiceAddress) -> SMKUDAccessKey? { let profileKeyData = databaseStorage.readReturningResult { transaction in return self.profileManager.profileKeyData(for: address, transaction: transaction) } guard let profileKey = profileKeyData else { // Mark as "not a UD recipient". return nil } do { let udAccessKey = try SMKUDAccessKey(profileKey: profileKey) return udAccessKey } catch { Logger.error("Could not determine udAccessKey: \(error)") return nil } } // Returns the UD access key for sending to a given recipient. @objc public func udAccess(forAddress address: SignalServiceAddress, requireSyncAccess: Bool) -> OWSUDAccess? { if requireSyncAccess { guard tsAccountManager.localAddress != nil else { if isUDVerboseLoggingEnabled() { Logger.info("UD disabled for \(address), no local number.") } owsFailDebug("Missing local number.") return nil } if address.isLocalAddress { let selfAccessMode = unidentifiedAccessMode(forAddress: address) guard selfAccessMode != .disabled else { if isUDVerboseLoggingEnabled() { Logger.info("UD disabled for \(address), UD disabled for sync messages.") } return nil } } } let accessMode = unidentifiedAccessMode(forAddress: address) switch accessMode { case .unrestricted: // Unrestricted users should use a random key. if isUDVerboseLoggingEnabled() { Logger.info("UD enabled for \(address) with random key.") } let udAccessKey = randomUDAccessKey() return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: true) case .unknown: // Unknown users should use a derived key if possible, // and otherwise use a random key. if let udAccessKey = udAccessKey(forAddress: address) { if isUDVerboseLoggingEnabled() { Logger.info("UD unknown for \(address); trying derived key.") } return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: false) } else { if isUDVerboseLoggingEnabled() { Logger.info("UD unknown for \(address); trying random key.") } let udAccessKey = randomUDAccessKey() return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: true) } case .enabled: guard let udAccessKey = udAccessKey(forAddress: address) else { if isUDVerboseLoggingEnabled() { Logger.info("UD disabled for \(address), no profile key for this recipient.") } if (!CurrentAppContext().isRunningTests) { owsFailDebug("Couldn't find profile key for UD-enabled user.") } return nil } if isUDVerboseLoggingEnabled() { Logger.info("UD enabled for \(address).") } return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: false) case .disabled: if isUDVerboseLoggingEnabled() { Logger.info("UD disabled for \(address), UD not enabled for this recipient.") } return nil } } // MARK: - Sender Certificate #if DEBUG @objc public func hasSenderCertificate() -> Bool { return senderCertificate(certificateExpirationPolicy: .permissive) != nil } #endif private func senderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy) -> SMKSenderCertificate? { var certificateDateValue: Date? var certificateDataValue: Data? databaseStorage.read { transaction in certificateDateValue = self.keyValueStore.getDate(self.senderCertificateDateKey(), transaction: transaction) certificateDataValue = self.keyValueStore.getData(self.senderCertificateKey(), transaction: transaction) } if certificateExpirationPolicy == .strict { guard let certificateDate = certificateDateValue else { return nil } guard certificateDate.timeIntervalSinceNow < kDayInterval else { // Discard certificates that we obtained more than 24 hours ago. return nil } } guard let certificateData = certificateDataValue else { return nil } do { let certificate = try SMKSenderCertificate(serializedData: certificateData) guard isValidCertificate(certificate) else { Logger.warn("Current sender certificate is not valid.") return nil } return certificate } catch { owsFailDebug("Certificate could not be parsed: \(error)") return nil } } func setSenderCertificate(_ certificateData: Data) { databaseStorage.write { transaction in self.keyValueStore.setDate(Date(), key: self.senderCertificateDateKey(), transaction: transaction) self.keyValueStore.setData(certificateData, key: self.senderCertificateKey(), transaction: transaction) } } private func senderCertificateKey() -> String { return IsUsingProductionService() ? kUDCurrentSenderCertificateKey_Production : kUDCurrentSenderCertificateKey_Staging } private func senderCertificateDateKey() -> String { return IsUsingProductionService() ? kUDCurrentSenderCertificateDateKey_Production : kUDCurrentSenderCertificateDateKey_Staging } @objc public func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) { return ensureSenderCertificate(certificateExpirationPolicy: .permissive, success: success, failure: failure) } private func ensureSenderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy, success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) { firstly { ensureSenderCertificate(certificateExpirationPolicy: certificateExpirationPolicy) }.map { certificate in success(certificate) }.catch { error in failure(error) }.retainUntilComplete() } public func ensureSenderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy) -> Promise<SMKSenderCertificate> { // If there is a valid cached sender certificate, use that. if let certificate = senderCertificate(certificateExpirationPolicy: certificateExpirationPolicy) { return Promise.value(certificate) } return firstly { requestSenderCertificate() }.map { (certificate: SMKSenderCertificate) in self.setSenderCertificate(certificate.serializedData) return certificate } } private func requestSenderCertificate() -> Promise<SMKSenderCertificate> { return firstly { SignalServiceRestClient().requestUDSenderCertificate() }.map { certificateData -> SMKSenderCertificate in let certificate = try SMKSenderCertificate(serializedData: certificateData) guard self.isValidCertificate(certificate) else { throw OWSUDError.invalidData(description: "Invalid sender certificate returned by server") } return certificate } } private func isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { // Ensure that the certificate will not expire in the next hour. // We want a threshold long enough to ensure that any outgoing message // sends will complete before the expiration. let nowMs = NSDate.ows_millisecondTimeStamp() let anHourFromNowMs = nowMs + kHourInMs do { try certificateValidator.throwswrapped_validate(senderCertificate: certificate, validationTime: anHourFromNowMs) return true } catch { OWSLogger.error("Invalid certificate") return false } } @objc public func trustRoot() -> ECPublicKey { return OWSUDManagerImpl.trustRoot() } @objc public class func trustRoot() -> ECPublicKey { guard let trustRootData = NSData(fromBase64String: kUDTrustRoot) else { // This exits. owsFail("Invalid trust root data.") } do { return try ECPublicKey(serializedKeyData: trustRootData as Data) } catch { // This exits. owsFail("Invalid trust root.") } } // MARK: - Unrestricted Access @objc public func shouldAllowUnrestrictedAccessLocal() -> Bool { return databaseStorage.readReturningResult { transaction in self.keyValueStore.getBool(self.kUDUnrestrictedAccessKey, defaultValue: false, transaction: transaction) } } @objc public func setShouldAllowUnrestrictedAccessLocal(_ value: Bool) { databaseStorage.write { transaction in self.keyValueStore.setBool(value, key: self.kUDUnrestrictedAccessKey, transaction: transaction) } // Try to update the account attributes to reflect this change. tsAccountManager.updateAccountAttributes().retainUntilComplete() } }
169ebbf9397855e49f3fb995f7d7e4ca
35.98227
162
0.638029
false
false
false
false
BENMESSAOUD/RSS
refs/heads/master
Example/Pods/SwiftyXMLParser/SwiftyXMLParser/Parser.swift
apache-2.0
4
/** * The MIT License (MIT) * * Copyright (C) 2016 Yahoo Japan Corporation. * * 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 Foundation extension XML { class Parser: NSObject, XMLParserDelegate { func parse(_ data: Data) -> Accessor { stack = [Element]() stack.append(documentRoot) let parser = XMLParser(data: data) parser.delegate = self parser.parse() return Accessor(documentRoot) } override init() { trimmingManner = nil } init(trimming manner: CharacterSet) { trimmingManner = manner } // MARK:- private fileprivate var documentRoot = Element(name: "XML.Parser.AbstructedDocumentRoot") fileprivate var stack = [Element]() fileprivate let trimmingManner: CharacterSet? func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { let node = Element(name: elementName) if !attributeDict.isEmpty { node.attributes = attributeDict } let parentNode = stack.last node.parentElement = parentNode parentNode?.childElements.append(node) stack.append(node) } func parser(_ parser: XMLParser, foundCharacters string: String) { if let text = stack.last?.text { stack.last?.text = text + string } else { stack.last?.text = "" + string } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if let trimmingManner = self.trimmingManner { stack.last?.text = stack.last?.text?.trimmingCharacters(in: trimmingManner) } stack.removeLast() } } }
40d895009fc63892b106938096a2a8f4
38.075949
177
0.629738
false
false
false
false
DaRkD0G/EasyHelper
refs/heads/master
EasyHelper/ArrayExtensions.swift
mit
1
// // Array_Extensions.swift // TastyImitationKeyboard // // Created by DaRk-_-D0G on 17/07/2015. // Copyright (c) 2015 Apple. All rights reserved. // import Foundation // MARK: - Classical public extension Array { /** Creates an array with the elements at indexes in the given list of integers. :param: first First index :param: second Second index :param: rest Rest of indexes :returns: Array with the items at the specified indexes */ public subscript (first: Int, second: Int, rest: Int...) -> Array { return ([first, second] + rest).map { self[$0] } } /** Gets the object at the specified index, if it exists. :param: index :returns: Object at index in self */ func get (index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil } /** Contains an objet in array :param: obj T Obj research :returns: Bool */ func contains<T where T : Equatable>(obj: T) -> Bool { return self.filter({$0 as? T == obj}).count > 0 } /** Contains an objet in array :param: obj T Obj research :returns: Array T Obj research */ func containsValues<T where T : Equatable>(obj: T) -> Array? { let values = self.filter({$0 as? T == obj}) return (values.count > 0) ? values : nil } /** Checks if test returns true for all the elements in self :param: test Function to call for each element :returns: True if test returns true for all the elements in self */ func forEachBySorts (test: (Element) -> Bool) -> Bool { for item in self { if test(item) { return false } } return true } /** Opposite of filter. :param: exclude Function invoked to test elements for the exclusion from the array :returns: Filtered array */ func forEachByReject (exclude: (Element -> Bool)) -> Array { return filter { return !exclude($0) } } /** Converts the array to a dictionary with the keys supplied via the keySelector. :param: keySelector :returns: A dictionary */ func toDictionary <U> (keySelector:(Element) -> U) -> [U: Element] { var result: [U: Element] = [:] for item in self { result[keySelector(item)] = item } return result } /** Converts the array to a dictionary with keys and values supplied via the transform function. :param: transform :returns: A dictionary */ func toDictionary <K, V> (transform: (Element) -> (key: K, value: V)?) -> [K: V] { var result: [K: V] = [:] for item in self { if let entry = transform(item) { result[entry.key] = entry.value } } return result } } // MARK: - File public extension Array { /** Loads a JSON file from the app bundle into a new dictionary - parameter filename: File name - throws: EHError : PathForResource / NSData / JSON - returns: [String : AnyObject] */ static func loadJSONFromBundle(filename: String, nameJson:String) throws -> [String : AnyObject] { guard let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") else { throw EHError.Nil(whereIs: "extension Array",funcIs: "loadJSONFromBundle",errorIs: "[->pathForResource] The file could not be located\nFile : '\(filename).json'") } guard let data = try? NSData(contentsOfFile: path, options:.DataReadingUncached) else { throw EHError.NSData(whereIs: "EasyHelper extension Array",funcIs: "loadJSONFromBundle",errorIs:"[->NSData] The absolute path of the file not find\nFile : '\(filename)'") } guard let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] else { throw EHError.JSON(whereIs: "extensions Dictionnay",funcIs: "loadJSONFromBundle",errorIs: "[->NSJSONSerialization]Error.InvalidJSON Level file '\(filename)' is not valid JSON") } return jsonDict } /** Load a Plist file from the app bundle into a new dictionary :param: File name :return: Dictionary<String, AnyObject>? */ /** Load a Plist file from the app bundle into a new dictionary - parameter filename: File name - throws: EHError : Nil - returns: [String : AnyObject] */ static func loadPlistFromBundle(filename: String) throws -> [String : AnyObject] { guard let path = NSBundle.mainBundle().pathForResource(filename, ofType: "plist") else { throw EHError.Nil(whereIs: "extension Array",funcIs: "loadPlistFromBundle",errorIs: "(pathForResource) The file could not be located\nFile : '\(filename).plist'") } guard let plistDict = NSDictionary(contentsOfFile: path) as? [String : AnyObject] else { throw EHError.Nil(whereIs: "extension Array",funcIs: "loadPlistFromBundle",errorIs: "(There is a file error or if the contents of the file are an invalid representation of a dictionary. File : '\(filename)'.plist") } return plistDict } }
999b261914e89d8a70b4a766162ccccc
31
226
0.598668
false
false
false
false
shaps80/Peek
refs/heads/master
Pod/Classes/Controllers & Views/Inspectors/PreviewCell.swift
mit
1
// // PreviewCell.swift // Peek // // Created by Shaps Benkau on 24/02/2018. // import UIKit internal final class PreviewCell: UITableViewCell { internal let previewImageView: UIImageView override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { previewImageView = UIImageView() previewImageView.contentMode = .scaleAspectFit previewImageView.clipsToBounds = true previewImageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) previewImageView.setContentHuggingPriority(.defaultLow, for: .horizontal) previewImageView.setContentHuggingPriority(.required, for: .vertical) previewImageView.setContentCompressionResistancePriority(.required, for: .vertical) super.init(style: .value1, reuseIdentifier: reuseIdentifier) addSubview(previewImageView, constraints: [ equal(\.layoutMarginsGuide.leadingAnchor, \.leadingAnchor), equal(\.layoutMarginsGuide.trailingAnchor, \.trailingAnchor), equal(\.topAnchor, constant: -16), equal(\.bottomAnchor, constant: 16) ]) clipsToBounds = true contentView.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
e8f72b9a307c9cd6e5d0c22a75674fd4
32.804878
95
0.676046
false
false
false
false
amnuaym/TiAppBuilder
refs/heads/master
Day6/MyShoppingListDB/MyShoppingListDB/AddItemViewController.swift
gpl-3.0
1
// // AddItemViewController.swift // MyShoppingListDB // // Created by DrKeng on 9/16/2560 BE. // Copyright © 2560 ANT. All rights reserved. // import UIKit import CoreData class AddItemViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var myShoppingItem : NSManagedObject? var myItemCategoriesList : [AnyObject]? = [] // let SwipLeft = UISwipeGestureRecognizer. // let SwipeLeft = UISwipeGestureRecognizerDirection // let SwipeLeft = UISwipeActionsConfiguration @IBOutlet weak var txtShoppingItem: UITextField! @IBOutlet weak var txtUnitPrice: UITextField! @IBOutlet weak var txtNumberOfItems: UITextField! @IBOutlet weak var pickerViewItemCategory: UIPickerView! @IBAction func saveShoppingItemMethod() { //สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext //Read Data from ItemCategory to PickerView let mySelectedItemCategory = pickerViewItemCategory.selectedRow(inComponent: 0) let myItemCategory = myItemCategoriesList![mySelectedItemCategory] //เช็คว่าเป็นการ Update ข้อมูลหรือสร้างใหม่ if myShoppingItem != nil{ myShoppingItem?.setValue(txtShoppingItem.text!, forKey: "itemName") myShoppingItem?.setValue(Float(txtUnitPrice.text!)!, forKey: "itemPrice") myShoppingItem?.setValue(Int(txtNumberOfItems.text!)!, forKey: "itemNumber") myShoppingItem?.setValue(1, forKey: "itemStatus") //Add ItemCategory Data myShoppingItem?.setValue(myItemCategory, forKey: "itemCategory") } else{ //สร้าง Object ข้อมูล ShoppingItem ของ Core Data let newShoppingItem = NSEntityDescription.insertNewObject(forEntityName: "ShoppingItem", into: myContext) newShoppingItem.setValue(txtShoppingItem.text!, forKey: "itemName") newShoppingItem.setValue(Float(txtUnitPrice.text!)!, forKey: "itemPrice") newShoppingItem.setValue(Int(txtNumberOfItems.text!)!, forKey: "itemNumber") newShoppingItem.setValue(1, forKey: "itemStatus") //Add ItemCategory Data newShoppingItem.setValue(myItemCategory, forKey: "itemCategory") } //บันทึกลงฐานข้อมูล do{ try myContext.save() print("บันทึกข้อมูลแล้ว!") }catch let error as NSError{ print(error.description + " : ไม่สามารถบันทึกข้อมูลได้") } //กลับไปหน้าหลัก navigationController?.popViewController(animated: true) } override func viewDidLoad() { super.viewDidLoad() pickerViewItemCategory.dataSource = self pickerViewItemCategory.delegate = self // Read Data of Item Category readItemCategoryFromDB() if myItemCategoriesList == nil { let myAlert = UIAlertController(title: "MyShoppingListDB", message: "Please create Item Category first", preferredStyle: .alert) let okButton = UIAlertAction(title: "OK", style: .cancel, handler: nil) myAlert.addAction(okButton) self.present(myAlert, animated: true, completion: nil) }else{ if myShoppingItem != nil { let myItemName = myShoppingItem?.value(forKey: "itemName") as! String let myItemNumber = myShoppingItem?.value(forKey: "itemNumber") as! Int let myUnitePrice = myShoppingItem?.value(forKey: "itemPrice") as! Float //Read ItemCategory from Shopping Item let myItemCategory = myShoppingItem?.value(forKey: "itemCategory") as! NSManagedObject txtShoppingItem.text = myItemName txtUnitPrice.text = String(myUnitePrice) txtNumberOfItems.text = String(myItemNumber) //Find index of ItemCategory to spin PickerView let myItemCategoryRow = myItemCategoriesList?.index{$0 === myItemCategory} pickerViewItemCategory.selectRow(myItemCategoryRow!, inComponent: 0, animated: true) } } } func readItemCategoryFromDB(){ let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCategory") do{ myItemCategoriesList = try myContext.fetch(myFetchRequest) }catch let error as NSError{ print(error.description) } } //MARK: Picker Datasource & Delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return myItemCategoriesList!.count } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 60.0 } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60)) let myImageView = UIImageView(frame: CGRect(x: 25, y: 0, width: 60, height: 60)) let myLabel = UILabel(frame: CGRect(x: 95, y: 0, width: pickerView.bounds.width - 90, height: 60)) let myItemCategory = myItemCategoriesList![row] let logo = myItemCategory.value(forKey: "categoryImage") as! Data myLabel.text = myItemCategory.value(forKey: "categoryName") as? String myImageView.image = UIImage(data: logo) myView.addSubview(myLabel) myView.addSubview(myImageView) return myView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
fb715098b45728cfbe80932726607394
37.775148
140
0.646727
false
false
false
false
CodaFi/swift
refs/heads/main
test/stdlib/OptionSetTest.swift
apache-2.0
11
//===--- OptionSetTest.swift - Test for library-only option sets ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest struct PackagingOptions : OptionSet { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } static let box = PackagingOptions(rawValue: 1) static let carton = PackagingOptions(rawValue: 2) static let bag = PackagingOptions(rawValue: 4) static let satchel = PackagingOptions(rawValue: 8) static let boxOrBag: PackagingOptions = [box, bag] static let boxOrCartonOrBag: PackagingOptions = [box, carton, bag] static let satchelOrBag = satchel.union(bag) } var tests = TestSuite("OptionSet") defer { runAllTests() } tests.test("basics") { typealias P = PackagingOptions expectNotEqual(P(), .box) expectEqual(P.box, .box) expectNotEqual(P.box, .carton) expectNotEqual(P.box, .boxOrBag) expectEqual(.box, P.box.intersection(.boxOrBag)) expectEqual(.bag, P.bag.intersection(.boxOrBag)) expectEqual(P(), P.bag.intersection(.box)) expectEqual(P(), P.box.intersection(.satchel)) expectEqual(.boxOrBag, P.bag.union(.box)) expectEqual(.boxOrBag, P.box.union(.bag)) expectEqual(.boxOrCartonOrBag, P.boxOrBag.union(.carton)) expectEqual([.satchel, .box], P.satchelOrBag.symmetricDifference(.boxOrBag)) var p = P.box p.formIntersection(.boxOrBag) expectEqual(.box, p) p = .bag p.formIntersection(.boxOrBag) expectEqual(.bag, p) p = .bag p.formIntersection(.box) expectEqual(P(), p) p = .box p.formIntersection(.satchel) expectEqual(P(), p) p = .bag p.formUnion(.box) expectEqual(.boxOrBag, p) p = .box p.formUnion(.bag) expectEqual(.boxOrBag, p) p = .boxOrBag p.formUnion(.carton) expectEqual(.boxOrCartonOrBag, p) p = .satchelOrBag p.formSymmetricDifference(.boxOrBag) expectEqual([.satchel, .box], p) } tests.test("set algebra") { typealias P = PackagingOptions // remove var p = P.boxOrBag expectNil(p.remove(P.carton)) p = P.boxOrBag p.remove(P.boxOrCartonOrBag) expectEqual(P(), p) p = P.boxOrBag let removed = p.remove(P.satchelOrBag) if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { // https://github.com/apple/swift/pull/28378 expectEqual(P.bag, removed) } expectEqual(P.box, p) // insert p = P.box var insertionResult = p.insert(.bag) expectTrue(insertionResult.inserted) expectEqual(P.bag, insertionResult.memberAfterInsert) expectEqual(P.boxOrBag, p) insertionResult = p.insert(.bag) expectFalse(insertionResult.inserted) expectEqual(P.bag, insertionResult.memberAfterInsert) // update p = P.box expectNil(p.update(with: .bag)) expectEqual(P.boxOrBag, p) p = P.box expectEqual(P.box, p.update(with: .boxOrBag)) expectEqual(P.boxOrBag, p) }
ce1c5da239e73615a30e40efd8c10e3e
25.622951
80
0.6875
false
true
false
false
jegumhon/URWeatherView
refs/heads/master
URWeatherView/SpriteAssets/URRainEmitterNode.swift
mit
1
// // URRainEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 15.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URRainEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URRainEmitterNode.self) let particleImage = UIImage(named: "rainDrop-1", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 100.0 // self.particleBirthRateMax? self.particleLifetime = 8.0 self.particleLifetimeRange = 0.0 self.particlePositionRange = CGVector(dx: 600.0, dy: 0.0) self.zPosition = 0.0 self.emissionAngle = CGFloat(240.0 * .pi / 180.0) self.emissionAngleRange = 0.0 self.particleSpeed = 200.0 self.particleSpeedRange = 150.0 self.xAcceleration = -100.0 self.yAcceleration = -150.0 self.particleAlpha = 0.7 self.particleAlphaRange = 1.0 self.particleAlphaSpeed = 0.0 self.particleScale = 0.1 self.particleScaleRange = 0.05 self.particleScaleSpeed = 0.0 self.particleRotation = CGFloat(-38.0 * .pi / 180.0) self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 0.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
0d794efc53d103329e123d4fcaf9ff77
36.755102
232
0.647027
false
false
false
false
joemcbride/outlander-osx
refs/heads/master
src/Outlander/VariablesViewController.swift
mit
1
// // VariablesViewController.swift // Outlander // // Created by Joseph McBride on 3/30/15. // Copyright (c) 2015 Joe McBride. All rights reserved. // import Cocoa public class GlobalVariable : NSObject { var name:String { willSet { self.willChangeValueForKey("name") } didSet { self.didChangeValueForKey("name") } } var val:String { willSet { self.willChangeValueForKey("val") } didSet { self.didChangeValueForKey("val") } } init(_ name:String, _ val:String){ self.name = name self.val = val } public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool { if key == "name" || key == "val" { return true } else { return super.automaticallyNotifiesObserversForKey(key) } } } public class VariablesViewController: NSViewController, SettingsView, NSTableViewDataSource { @IBOutlet weak var tableView: NSTableView! private var _context:GameContext? private var _appSettingsLoader:AppSettingsLoader? private var _globalVars:[GlobalVariable] = [] public var selectedItem:GlobalVariable? { willSet { self.willChangeValueForKey("selectedItem") } didSet { self.didChangeValueForKey("selectedItem") } } public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool { if key == "selectedItem" { return true } else { return super.automaticallyNotifiesObserversForKey(key) } } public override func awakeFromNib() { self.reloadVars() } public func save() { } public func setContext(context:GameContext) { _context = context _appSettingsLoader = AppSettingsLoader(context: _context) } private func reloadVars(){ _globalVars = [] for key in _context!.globalVars { let global = GlobalVariable(key.0, key.1.rawValue ?? "") _globalVars.append(global) } _globalVars = _globalVars.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == NSComparisonResult.OrderedAscending } self.tableView.reloadData() } @IBAction func addRemoveAction(sender: NSSegmentedControl) { if sender.selectedSegment == 0 { let global = GlobalVariable("", "") _globalVars.append(global) let count = _globalVars.count - 1; let idx = NSIndexSet(index: count) self.tableView.reloadData() self.tableView.selectRowIndexes(idx, byExtendingSelection: false) self.tableView.scrollRowToVisible(idx.firstIndex) } else { let count = _globalVars.count if self.tableView.selectedRow < 0 || self.tableView.selectedRow >= count { return } let item = self.selectedItem! self.selectedItem = nil; _context!.globalVars.removeValueForKey(item.name) self.reloadVars() } } // MARK: NSTableViewDataSource public func numberOfRowsInTableView(tableView: NSTableView) -> Int { return _globalVars.count; } public func tableViewSelectionDidChange(notification:NSNotification) { let selectedRow = self.tableView.selectedRow if(selectedRow > -1 && selectedRow < _globalVars.count) { self.selectedItem = _globalVars[selectedRow] } else { self.selectedItem = nil; } } public func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { if row >= _globalVars.count { return ""; } let item = _globalVars[row] if(tableColumn!.identifier == "name") { return item.name } return item.val } }
be02033d66a0126969b26592f9bdc066
25.607362
130
0.551533
false
false
false
false
Hout/JHDate
refs/heads/develop
Pod/Classes/JHDateComparisons.swift
mit
1
// // JHDateComparisons.swift // Pods // // Created by Jeroen Houtzager on 26/10/15. // // import Foundation // MARK: - Comparators public extension JHDate { /// Returns an NSComparisonResult value that indicates the ordering of two given dates based on their components down to a given unit granularity. /// /// - Parameters: /// - date: date to compare. /// - toUnitGranularity: The smallest unit that must, along with all larger units, be equal for the given dates to be considered the same. /// For possible values, see “[Calendar Units](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/c/tdef/NSCalendarUnit)” /// /// - Returns: NSOrderedSame if the dates are the same down to the given granularity, otherwise NSOrderedAscending or NSOrderedDescending. /// /// - seealso: [compareDate:toDate:toUnitGranularity:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/compareDate:toDate:toUnitGranularity:) /// public func compareDate(date: JHDate, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult { return calendar.compareDate(self.date, toDate: date.date, toUnitGranularity: unit) } /// Returns whether the given date is in today. /// /// - Returns: a boolean indicating whether the receiver is in today /// /// - note: This value is interpreted in the context of the calendar of the receiver /// /// - seealso: [isDateInToday:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInToday:) /// public func isInToday( ) -> Bool { return calendar.isDateInToday(date) } /// Returns whether the given date is in yesterday. /// /// - Returns: a boolean indicating whether the receiver is in yesterday /// /// - note: This value is interpreted in the context of the calendar of the receiver /// /// - seealso: [isDateInYesterday:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInYesterday:) /// public func isInYesterday() -> Bool { return calendar.isDateInYesterday(date) } /// Returns whether the given date is in tomorrow. /// /// - Returns: a boolean indicating whether the receiver is in tomorrow /// /// - note: This value is interpreted in the context of the calendar of the receiver /// /// - seealso: [isDateInTomorrow:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInTomorrow:) /// public func isInTomorrow() -> Bool { return calendar.isDateInTomorrow(date) } /// Returns whether the given date is in the weekend. /// /// - Returns: a boolean indicating whether the receiver is in the weekend /// /// - note: This value is interpreted in the context of the calendar of the receiver /// /// - seealso: [isDateInWeekend:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInWeekend:) /// public func isInWeekend() -> Bool { return calendar.isDateInWeekend(date) } } // MARK: - Comparable delegate /// Instances of conforming types can be compared using relational operators, which define a strict total order. /// /// A type conforming to Comparable need only supply the < and == operators; default implementations of <=, >, >=, and != are supplied by the standard library: /// extension JHDate : Comparable {} /// Returns whether the given date is later than the receiver. /// Just the dates are compared. Calendars, time zones are irrelevant. /// /// - Parameters: /// - date: a date to compare against /// /// - Returns: a boolean indicating whether the receiver is earlier than the given date /// public func <(ldate: JHDate, rdate: JHDate) -> Bool { return ldate.date.compare(rdate.date) == .OrderedAscending } /// Returns whether the given date is earlier than the receiver. /// Just the dates are compared. Calendars, time zones are irrelevant. /// /// - Parameters: /// - date: a date to compare against /// /// - Returns: a boolean indicating whether the receiver is later than the given date /// public func >(ldate: JHDate, rdate: JHDate) -> Bool { return ldate.date.compare(rdate.date) == .OrderedDescending }
b8909fdc7e7717c345b0512e8a294fc9
41.920354
263
0.703711
false
false
false
false
sarvex/SwiftRecepies
refs/heads/master
Maps/Pinpointing the Location of a Device/Pinpointing the Location of a Device/ViewController.swift
isc
1
// // ViewController.swift // Pinpointing the Location of a Device // // Created by Vandad Nahavandipoor on 7/7/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import CoreLocation import MapKit class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager: CLLocationManager? func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!){ println("Latitude = \(newLocation.coordinate.latitude)") println("Longitude = \(newLocation.coordinate.longitude)") } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){ println("Location manager failed with error = \(error)") } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus){ print("The authorization status of location services is changed to: ") switch CLLocationManager.authorizationStatus(){ case .AuthorizedAlways: println("Authorized") case .AuthorizedWhenInUse: println("Authorized when in use") case .Denied: println("Denied") case .NotDetermined: println("Not determined") case .Restricted: println("Restricted") default: println("Unhandled") } } func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(controller, animated: true, completion: nil) } func createLocationManager(#startImmediately: Bool){ locationManager = CLLocationManager() if let manager = locationManager{ println("Successfully created the location manager") manager.delegate = self if startImmediately{ manager.startUpdatingLocation() } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) /* Are location services available on this device? */ if CLLocationManager.locationServicesEnabled(){ /* Do we have authorization to access location services? */ switch CLLocationManager.authorizationStatus(){ case .AuthorizedAlways: /* Yes, always */ createLocationManager(startImmediately: true) case .AuthorizedWhenInUse: /* Yes, only when our app is in use */ createLocationManager(startImmediately: true) case .Denied: /* No */ displayAlertWithTitle("Not Determined", message: "Location services are not allowed for this app") case .NotDetermined: /* We don't know yet, we have to ask */ createLocationManager(startImmediately: false) if let manager = self.locationManager{ manager.requestWhenInUseAuthorization() } case .Restricted: /* Restrictions have been applied, we have no access to location services */ displayAlertWithTitle("Restricted", message: "Location services are not allowed for this app") } } else { /* Location services are not enabled. Take appropriate action: for instance, prompt the user to enable the location services */ println("Location services are not enabled") } } }
749e96dcd9722d1215299123c82b7f8f
31.330827
83
0.679767
false
false
false
false
cross-border-bridge/data-channel-ios
refs/heads/master
Example-swift/Example-swift/ViewController.swift
mit
1
// Copyright © 2017 DWANGO Co., Ltd. import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { var webView: WKWebView = WKWebView() var dataBus: CBBDataBus? var dataChannel: CBBDataChannel? var handlerIds: NSMutableArray? override func viewDidLoad() { super.viewDidLoad() handlerIds = NSMutableArray() let width = self.view.frame.size.width let height = self.view.frame.size.height let label = UILabel(frame: CGRect(x: 4, y: 30, width: width - 8, height: 30)) label.text = "CBBWKWebViewDataBus (native)" self.view.addSubview(label) // ボタンを準備 self.addButton(frame: CGRect(x: 4, y:70, width: 312, height: 30), title: "Send PUSH to JavaScript", action:#selector(self.sendPush(sender:))) self.addButton(frame: CGRect(x: 4, y:110, width: 312, height: 30), title: "Send REQUEST to JavaScript", action:#selector(self.sendRequest(sender:))) self.addButton(frame: CGRect(x: 4, y:150, width: 200, height: 30), title: "Destroy", action:#selector(self.destroy(sender:))) // WKWebViewを準備(※この時点ではまだコンテンツを読み込まない) self.webView.frame = CGRect(x: 4, y: height / 2 + 4, width: width - 8, height: height / 2 - 8) self.webView.layer.borderWidth = 2.0 self.webView.layer.borderColor = UIColor.blue.cgColor self.webView.layer.cornerRadius = 10.0 self.webView.navigationDelegate = self self.webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.webView.uiDelegate = self // WKWebView は App bundle のファイルを読めない為, bundleの内容を tmp // へコピーしてそこから読み込む self.copy(target: "index.html") self.copy(target: "script.js") self.copy(target: "data-channel.js") self.view.addSubview(self.webView) // CBBDataChannelを準備 self.dataBus = CBBWKWebViewDataBus(wkWebView: self.webView) self.dataChannel = CBBDataChannel(dataBus: self.dataBus!) // JavaScript側から電文を送信された時のハンドラを設定 self.dataChannel?.addHandler({ (packet: Any?, callback: CBBDataChannelResponseCallback?) in if (nil != callback) { // 応答が必要な電文(REQUEST)を受信時の処理 callback!("Thank you for your REQUEST by Native") } else { // 応答不要な電文(PUSH)を受信時の処理 let alert = UIAlertController(title: "Alert from Native", message: NSString.localizedStringWithFormat("Received PUSH\npacket = %@", packet as! CVarArg) as String, preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } }) // WKWebView にコンテンツを読み込む(CBBDataBusがインジェクトされる) let urlString = NSString.localizedStringWithFormat("file://%@/index.html", self.tmpFolder()) as String let url = URL(fileURLWithPath: urlString) self.webView.loadFileURL(url, allowingReadAccessTo: url) } func addButton(frame: CGRect, title: String, action: Selector) { let b = UIButton(type: UIButtonType.roundedRect) b.frame = frame b.layer.cornerRadius = 2.0 b.layer.borderColor = UIColor.blue.cgColor b.layer.borderWidth = 1.0 b.setTitle(title, for: UIControlState.normal) b.addTarget(self, action: action, for: UIControlEvents.touchUpInside) self.view.addSubview(b) } func sendPush(sender: Any) { self.dataChannel?.sendPush("Hello this is native (Swift)") } func sendRequest(sender: Any) { self.dataChannel?.sendRequest("GIVE ME RESPONSE!", callback: { (error, packet) in let alert = UIAlertController(title: "Alert from Native", message: NSString.localizedStringWithFormat("Received RESPONSE\npacket = %@", packet as! CVarArg) as String, preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) }) } func destroy(sender: Any) { self.dataBus?.destroy() } func tmpFolder() -> String { return NSTemporaryDirectory().appending("www") } // AppBundleの内容はWKWebViewから参照できないのでテンポラリディレクトリにコピーして用いる func copy(target: String) { let sourceFile = Bundle.main.path(forResource:target, ofType:nil) let destFile = self.tmpFolder().appending("/").appending(target) let fm = FileManager.default if !fm.fileExists(atPath: sourceFile!) { return } if fm.fileExists(atPath: destFile) { try! fm.removeItem(atPath: destFile) } try! fm.createDirectory(atPath: self.tmpFolder(), withIntermediateDirectories: true, attributes: nil) try! fm.copyItem(atPath: sourceFile!, toPath: destFile) } // JavaScript側でalertを発行した時の処理 func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: "Alert from JS", message: NSString.localizedStringWithFormat("Received message\n%@", message) as String, preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil) completionHandler() }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
40b0c82038a081c82c00816d0bda4834
45.29771
224
0.644023
false
false
false
false
BanyaKrylov/Learn-Swift
refs/heads/master
Pods/RealmSwift/RealmSwift/Results.swift
apache-2.0
4
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: MinMaxType /** Types of properties which can be used with the minimum and maximum value APIs. - see: `min(ofProperty:)`, `max(ofProperty:)` */ public protocol MinMaxType {} extension NSNumber: MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension Date: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /** Types of properties which can be used with the sum and average value APIs. - see: `sum(ofProperty:)`, `average(ofProperty:)` */ public protocol AddableType { /// :nodoc: init() } extension NSNumber: AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /** `Results` is an auto-updating container type in Realm returned from object queries. `Results` can be queried with the same predicates as `List<Element>`, and you can chain queries to further filter query results. `Results` always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. `Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any unnecessary work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results instances cannot be directly instantiated. */ public struct Results<Element: RealmCollectionValue>: Equatable { internal let rlmResults: RLMResults<AnyObject> /// A human-readable description of the objects represented by the results. public var description: String { return RLMDescriptionWithMaxDepth("Results", rlmResults, RLMDescriptionMaxDepth) } /// The type of the objects described by the results. public typealias ElementType = Element // MARK: Properties /// The Realm which manages this results. Note that this property will never return `nil`. public var realm: Realm? { return Realm(rlmResults.realm) } /** Indicates if the results are no longer valid. The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be accessed, but will always be empty. */ public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of objects in the results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal init(_ rlmResults: RLMResults<AnyObject>) { self.rlmResults = rlmResults } // MARK: Index Retrieval /** Returns the index of the given object in the results, or `nil` if the object is not present. */ public func index(of object: Element) -> Int? { return notFoundToNil(index: rlmResults.index(of: object as AnyObject)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> Element { throwForNegativeIndex(position) return dynamicBridgeCast(fromObjectiveC: rlmResults.object(at: UInt(position))) } /// Returns the first object in the results, or `nil` if the results are empty. public var first: Element? { return rlmResults.firstObject().map(dynamicBridgeCast) } /// Returns the last object in the results, or `nil` if the results are empty. public var last: Element? { return rlmResults.lastObject().map(dynamicBridgeCast) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results. - parameter key: The name of the property whose values are desired. */ public func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results. - parameter keyPath: The key path to the property whose values are desired. */ public func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return Results<Element>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return Results<Element>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects represented by the results, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return Results<Element>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } /** Returns a `Results` containing distinct objects based on the specified key paths - parameter keyPaths: The key paths used produce distinct results */ public func distinct<S: Sequence>(by keyPaths: S) -> Results<Element> where S.Iterator.Element == String { return Results<Element>(rlmResults.distinctResults(usingKeyPaths: Array(keyPaths))) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the results. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<T: AddableType>(ofProperty property: String) -> T { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the results, or `nil` if the results are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<T: AddableType>(ofProperty property: String) -> T? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let dogs = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.observe { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `invalidate()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func observe(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension Results: RealmCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the results. public func makeIterator() -> RLMIterator<Element> { return RLMIterator(collection: rlmResults) } /// :nodoc: // swiftlint:disable:next identifier_name public func _asNSFastEnumerator() -> Any { return rlmResults } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension Results: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results { return Results(objectiveCValue as! RLMResults) } var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: rlmResults, metadata: nil) } } // MARK: - Codable #if swift(>=4.1) extension Results: Encodable where Element: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for value in self { try container.encode(value) } } } #endif
e6996f5f477e61558ac49723334728e9
37.930394
122
0.685142
false
false
false
false
GEOSwift/GEOSwift
refs/heads/main
Sources/GEOSwift/GEOS/WKTConvertible.swift
mit
1
import Foundation import geos public protocol WKTConvertible { /// Serializes the `WKTConvertible` to a WKT string representation using the geos-default configuration /// options for `trim` and `roundingPrecision`. /// - Returns: A WKT string representation of the `WKTConvertible`. func wkt() throws -> String /// Serializes the `WKTConvertible` to a WKT string representation /// - Parameters: /// - trim: If `true`, digits after the decimal point that are unnecessary for lossless round-tripping /// are removed. /// - roundingPrecision: If `trim` is `true`, determines the maximum number of digits after the decimal /// point. If `trim` is false, determines the number of digits after the decimal point. Pass a /// negative value to default to the rounding precision determined by the underlying precision model. /// - Returns: A WKT string representation of the `WKTConvertible`. func wkt(trim: Bool, roundingPrecision: Int32) throws -> String } protocol WKTConvertibleInternal: WKTConvertible, GEOSObjectConvertible {} extension WKTConvertibleInternal { public func wkt() throws -> String { let context = try GEOSContext() let writer = try WKTWriter( context: context, trim: .geosDefault, roundingPrecision: .geosDefault) return try writer.write(self) } public func wkt(trim: Bool, roundingPrecision: Int32) throws -> String { let context = try GEOSContext() let writer = try WKTWriter( context: context, trim: .custom(trim), roundingPrecision: .custom(roundingPrecision)) return try writer.write(self) } } extension Point: WKTConvertible, WKTConvertibleInternal {} extension LineString: WKTConvertible, WKTConvertibleInternal {} extension Polygon.LinearRing: WKTConvertible, WKTConvertibleInternal {} extension Polygon: WKTConvertible, WKTConvertibleInternal {} extension MultiPoint: WKTConvertible, WKTConvertibleInternal {} extension MultiLineString: WKTConvertible, WKTConvertibleInternal {} extension MultiPolygon: WKTConvertible, WKTConvertibleInternal {} extension GeometryCollection: WKTConvertible, WKTConvertibleInternal {} extension Geometry: WKTConvertible, WKTConvertibleInternal {} private final class WKTWriter { private let context: GEOSContext private let writer: OpaquePointer init(context: GEOSContext, trim: Trim, roundingPrecision: RoundingPrecision) throws { guard let writer = GEOSWKTWriter_create_r(context.handle) else { throw GEOSError.libraryError(errorMessages: context.errors) } self.context = context self.writer = writer if case let .custom(value) = trim { GEOSWKTWriter_setTrim_r(context.handle, writer, value ? 1 : 0) } if case let .custom(value) = roundingPrecision { GEOSWKTWriter_setRoundingPrecision_r(context.handle, writer, value) } } deinit { GEOSWKTWriter_destroy_r(context.handle, writer) } func write(_ geometry: GEOSObjectConvertible) throws -> String { let geosObject = try geometry.geosObject(with: context) guard let chars = GEOSWKTWriter_write_r(context.handle, writer, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { chars.deallocate() } return String(cString: chars) } enum Trim { case geosDefault case custom(Bool) } enum RoundingPrecision { case geosDefault case custom(Int32) } }
90c4c560f7546a7ca12a77d135b5712f
36.773196
109
0.688319
false
false
false
false
pekoto/fightydot
refs/heads/master
FightyDot/FightyDot/GameVC.swift
mit
1
// // GameVC.swift // FightyDot // // Created by Graham McRobbie on 18/12/2016. // Copyright © 2016 Graham McRobbie. All rights reserved. // // The main view class for playing the game. // Implements EngineDelegate.swift. // import UIKit import Firebase class GameVC: UIViewController { @IBOutlet var nodeImgViews: Array<NodeImageView>! @IBOutlet var millViews: Array<MillView>! // Player one's view components @IBOutlet var p1NameLbl: UILabel! @IBOutlet var p1InitialLbl: UILabel! @IBOutlet var p1CounterImgs: Array<UIImageView>! @IBOutlet var p1ActiveImg: UIImageView! @IBOutlet var p1IconImg: UIImageView! @IBOutlet var p1StatusLbl: UILabel! // Player two's view components @IBOutlet var p2NameLbl: UILabel! @IBOutlet var p2InitialLbl: UILabel! @IBOutlet var p2CounterImgs: Array<UIImageView>! @IBOutlet var p2ActiveImg: UIImageView! @IBOutlet var p2IconImg: UIImageView! @IBOutlet var p2StatusLbl: UILabel! @IBOutlet var helpLbl: UILabel! @IBOutlet var tipLbl: UITextView! // Allows game type to be set via storyboard // (Swift does not currently allow Enums to be @IBInspectable) @IBInspectable var gameTypeStoryboardAdapter:Int { get { return _gameType.rawValue } set(gameTypeIndex) { _gameType = GameType(rawValue: gameTypeIndex) ?? .PlayerVsPlayer } } fileprivate var _gameType: GameType = .PlayerVsPlayer fileprivate var _engine: Engine! fileprivate var _p1View: PlayerView! fileprivate var _p2View: PlayerView! override func viewDidLoad() { super.viewDidLoad() addTapGestureRecognizerTo(nodeImgs: nodeImgViews) addDragGestureRecognizerTo(nodeImgs: nodeImgViews) _p1View = PlayerView(nameLbl: p1NameLbl, initialLbl: p1InitialLbl, iconImg: p1IconImg, counterImgs: p1CounterImgs, statusLbl: p1StatusLbl, activeImg: p1ActiveImg) _p2View = PlayerView(nameLbl: p2NameLbl, initialLbl: p2InitialLbl, iconImg: p2IconImg, counterImgs: p2CounterImgs, statusLbl: p2StatusLbl, activeImg: p2ActiveImg) _engine = Engine(gameType: _gameType, engineView: self) playSound(fileName: Constants.Sfx.startGame) } // MARK: - Actions // Used when placing or taking pieces @objc func nodeTapped(sender: UITapGestureRecognizer) { guard let nodeId = sender.view?.tag else { return } // Engine calls should only fail if the game/storyboard has been configured incorrectly, // but if they do fail we can't really recover from them since the state is invalid. do { try _engine.handleNodeTapFor(nodeWithId: nodeId) } catch { handleEngineError(logMsg: "Failed to handle tap for node \(nodeId). Error: \(error).") } } // Used when moving or flying pieces @objc func nodeDragged(sender: UIPanGestureRecognizer!) { guard let nodeImgView = sender.view as? NodeImageView else { return } guard let currentNodeId = sender.view?.tag else { return } // Started dragging if (sender.state == UIGestureRecognizerState.began) { removeAnimatedShadowFromDraggableViews() let validMoveSpots = try! getMovableViewsFor(nodeWithId: currentNodeId) nodeImgView.startDragging(to: validMoveSpots) helpLbl.text = Constants.Help.movePiece_Selected playSound(fileName: Constants.Sfx.dragStart) } // Drag in progress if (sender.state == UIGestureRecognizerState.changed) { nodeImgView.updatePosition(to: sender.location(in: self.view)) nodeImgView.updateIntersects() } // Finished dragging if ((sender.state == UIGestureRecognizerState.ended) || (sender.state == UIGestureRecognizerState.cancelled)) { var validMoveMade = false if(nodeImgView.intersectsWithMoveSpot()) { guard let newNodeId = nodeImgView.getLastIntersectingMoveSpot()?.tag else { return } do { try _engine.handleNodeDragged(from: currentNodeId, to: newNodeId) } catch { handleEngineError(logMsg: "Failed to handle drag from \(currentNodeId) to \(newNodeId). Error: \(error).") } validMoveMade = true } nodeImgView.endDrag() if(!validMoveMade) { playSound(fileName: Constants.Sfx.dragCancel) nodeImgView.resetOriginalImg() helpLbl.text = Constants.Help.movePiece_Select addAnimatedShadowToDraggableViews() } } } @IBAction func resetTapped(_ sender: Any) { removeAnimatedShadowFromNodes() _engine.reset() } // MARK: - Private functions private func addTapGestureRecognizerTo(nodeImgs: [NodeImageView]) { for nodeImg in nodeImgs { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(nodeTapped(sender:))) nodeImg.addGestureRecognizer(tapGestureRecognizer) } } private func addDragGestureRecognizerTo(nodeImgs: [NodeImageView]) { for nodeImg in nodeImgs { let dragGestureRecognizer = UIPanGestureRecognizer(target: self, action:#selector(nodeDragged(sender:))) nodeImg.addGestureRecognizer(dragGestureRecognizer) } } private func addAnimatedShadowToDraggableViews() { for nodeImg in nodeImgViews { guard let dragGestureRecognizer = nodeImg.gestureRecognizers?[Constants.View.dragGestureRecognizerIndex] else { continue } if (dragGestureRecognizer.isEnabled) { nodeImg.addAnimatedShadow() } } } private func removeAnimatedShadowFromDraggableViews() { for nodeImg in nodeImgViews { guard let dragGestureRecognizer = nodeImg.gestureRecognizers?[Constants.View.dragGestureRecognizerIndex] else { continue } if (dragGestureRecognizer.isEnabled) { nodeImg.removeAnimatedShadow() } } } private func removeAnimatedShadowFromNodes() { for nodeImg in nodeImgViews { nodeImg.removeAnimatedShadow() } } // Get the other nodes this node can be moved to when moving/flying private func getMovableViewsFor(nodeWithId id: Int) throws -> [NodeImageView] { let movableNodeIds = try _engine.getMovablePositionsFor(nodeWithId: id) var movableNodeImgs: [NodeImageView] = [NodeImageView]() for nodeId in movableNodeIds { guard let nodeImgView = getNodeImgViewFor(nodeWithId: nodeId) else { continue } movableNodeImgs.append(nodeImgView) } return movableNodeImgs } fileprivate func getNodeImgViewFor(nodeWithId id: Int) -> NodeImageView? { return nodeImgViews.filter { (nodeImg) in nodeImg.tag == id }.first } } // MARK: EngineDelegate extension GameVC: EngineDelegate { var p1View: PlayerView { get { return _p1View } } var p2View: PlayerView { get { return _p2View } } func animate(node: Node, to newColour: PieceColour) { let nodeImgView = getNodeImgViewFor(nodeWithId: node.id) let newImage = Constants.PieceDics.nodeImgs[newColour] if(nodeImgView?.image != newImage) { nodeImgView?.popTo(img: newImage!) } } func animate(mill: Mill, to newColour: PieceColour) { guard let newUIColour = Constants.PieceDics.pieceColours[mill.colour] else { return } let (firstConnector, secondConnector) = getMillsImgsFor(millWithId: mill.id) if(firstConnector?.backgroundColor != newUIColour || secondConnector?.backgroundColor != newUIColour) { firstConnector?.animate(to: newUIColour, completion: nil) secondConnector?.animate(to: newUIColour, completion: { self.popNodesIn(mill: mill) }) } } func enableTapDisableDragFor(node: Node) { let nodeImgView = getNodeImgViewFor(nodeWithId: node.id) nodeImgView?.enableTapDisableDrag() } func enableDragDisableTapFor(node: Node) { let nodeImgView = getNodeImgViewFor(nodeWithId: node.id) nodeImgView?.enableDragDisableTap() } func disableInteractionFor(node: Node) { let nodeImgView = getNodeImgViewFor(nodeWithId: node.id) nodeImgView?.disable() } func reset(mill: Mill) { let (firstConnector, secondConnector) = getMillsImgsFor(millWithId: mill.id) firstConnector?.reset() secondConnector?.reset() } func gameWon(by player: Player) { Analytics.logEvent(Constants.FirebaseEvents.gameComplete, parameters: ["gameType": NSNumber(value: _gameType.rawValue)]) playSound(fileName: Constants.Sfx.gameOver) showAlert(title: "\(player.name) \(Constants.AlertMessages.won)", message: Constants.AlertMessages.playAgain) { self._engine.reset() } } func playSound(fileName: String, type: String = ".wav") { let soundDisabled = UserDefaults.standard.bool(forKey: Constants.Settings.muteSounds) if(soundDisabled) { return } try! AudioPlayer.playFile(named: fileName, type: type) } func updateTips(state: GameState) { switch state { case .AITurn: helpLbl.text = Constants.Help.aiTurn case .PlacingPieces: helpLbl.text = Constants.Help.placePiece tipLbl.text = Constants.Tips.makeMove case .TakingPiece: helpLbl.text = Constants.Help.takePiece tipLbl.text = Constants.Tips.canTakePiece case .MovingPieces: helpLbl.text = Constants.Help.movePiece_Select tipLbl.text = Constants.Tips.makeMove case .MovingPieces_PieceSelected: helpLbl.text = Constants.Help.movePiece_Selected tipLbl.text = Constants.Tips.makeMove case .FlyingPieces: helpLbl.text = Constants.Help.movePiece_Select tipLbl.text = Constants.Tips.canFly case .FlyingPieces_PieceSelected: helpLbl.text = Constants.Help.movePiece_Selected_CanFly tipLbl.text = Constants.Tips.canFly case .GameOver: helpLbl.text = Constants.Help.gameWon tipLbl.text = Constants.Tips.restart } } public func handleEngineError(logMsg: String) { _engine.uploadStateToFirebase(msg: logMsg) showAlert(title: "\(Constants.AlertMessages.errorTitle)", message: Constants.AlertMessages.errorMsg) { self._engine.reset() } } // MARK: - Private functions // Mills have 2 connectors, represented by 2 views, that connect the 3 nodes. // This function returns the two connector views associated with a single mill. private func getMillsImgsFor(millWithId id: Int) -> (MillView?, MillView?) { let firstConnector = millViews.filter { (millConnectorImg) in millConnectorImg.tag == id * 2 }.first let secondConnector = millViews.filter { (millConnectorImg) in millConnectorImg.tag == (id * 2) + 1 }.first return (firstConnector, secondConnector) } // An extra "pop" animation function for emphasis private func popNodesIn(mill: Mill) -> () { for node in mill.nodes { let nodeImg = getNodeImgViewFor(nodeWithId: node.value.id) nodeImg?.pop() } } }
8e3874916a48f05a477df2497469606e
33.957265
170
0.619071
false
false
false
false
stephencelis/SQLite.swift
refs/heads/master
Tests/SQLiteTests/Schema/SchemaDefinitionsTests.swift
mit
1
import XCTest @testable import SQLite class ColumnDefinitionTests: XCTestCase { var definition: ColumnDefinition! var expected: String! static let definitions: [(String, ColumnDefinition)] = [ ("\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL", ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil)), ("\"other_id\" INTEGER NOT NULL REFERENCES \"other_table\" (\"some_id\")", ColumnDefinition(name: "other_id", primaryKey: nil, type: .INTEGER, nullable: false, defaultValue: .NULL, references: .init(table: "other_table", column: "", primaryKey: "some_id", onUpdate: nil, onDelete: nil))), ("\"text\" TEXT", ColumnDefinition(name: "text", primaryKey: nil, type: .TEXT, nullable: true, defaultValue: .NULL, references: nil)), ("\"text\" TEXT NOT NULL", ColumnDefinition(name: "text", primaryKey: nil, type: .TEXT, nullable: false, defaultValue: .NULL, references: nil)), ("\"text_column\" TEXT DEFAULT 'fo\"o'", ColumnDefinition(name: "text_column", primaryKey: nil, type: .TEXT, nullable: true, defaultValue: .stringLiteral("fo\"o"), references: nil)), ("\"integer_column\" INTEGER DEFAULT 123", ColumnDefinition(name: "integer_column", primaryKey: nil, type: .INTEGER, nullable: true, defaultValue: .numericLiteral("123"), references: nil)), ("\"real_column\" REAL DEFAULT 123.123", ColumnDefinition(name: "real_column", primaryKey: nil, type: .REAL, nullable: true, defaultValue: .numericLiteral("123.123"), references: nil)) ] #if !os(Linux) override class var defaultTestSuite: XCTestSuite { let suite = XCTestSuite(forTestCaseClass: ColumnDefinitionTests.self) for (expected, column) in ColumnDefinitionTests.definitions { let test = ColumnDefinitionTests(selector: #selector(verify)) test.definition = column test.expected = expected suite.addTest(test) } return suite } @objc func verify() { XCTAssertEqual(definition.toSQL(), expected) } #endif func testNullableByDefault() { let test = ColumnDefinition(name: "test", type: .REAL) XCTAssertEqual(test.name, "test") XCTAssertTrue(test.nullable) XCTAssertEqual(test.defaultValue, .NULL) XCTAssertEqual(test.type, .REAL) XCTAssertNil(test.references) XCTAssertNil(test.primaryKey) } } class AffinityTests: XCTestCase { func test_init() { XCTAssertEqual(ColumnDefinition.Affinity("TEXT"), .TEXT) XCTAssertEqual(ColumnDefinition.Affinity("text"), .TEXT) XCTAssertEqual(ColumnDefinition.Affinity("INTEGER"), .INTEGER) XCTAssertEqual(ColumnDefinition.Affinity("BLOB"), .BLOB) XCTAssertEqual(ColumnDefinition.Affinity("REAL"), .REAL) XCTAssertEqual(ColumnDefinition.Affinity("NUMERIC"), .NUMERIC) } func test_returns_TEXT_for_unknown_type() { XCTAssertEqual(ColumnDefinition.Affinity("baz"), .TEXT) } } class IndexDefinitionTests: XCTestCase { var definition: IndexDefinition! var expected: String! var ifNotExists: Bool! static let definitions: [(IndexDefinition, Bool, String)] = [ (IndexDefinition(table: "tests", name: "index_tests", unique: false, columns: ["test_column"], where: nil, orders: nil), false, "CREATE INDEX \"index_tests\" ON \"tests\" (\"test_column\")"), (IndexDefinition(table: "tests", name: "index_tests", unique: true, columns: ["test_column"], where: nil, orders: nil), false, "CREATE UNIQUE INDEX \"index_tests\" ON \"tests\" (\"test_column\")"), (IndexDefinition(table: "tests", name: "index_tests", unique: true, columns: ["test_column", "bar_column"], where: "test_column IS NOT NULL", orders: nil), false, "CREATE UNIQUE INDEX \"index_tests\" ON \"tests\" (\"test_column\", \"bar_column\") WHERE test_column IS NOT NULL"), (IndexDefinition(table: "tests", name: "index_tests", unique: true, columns: ["test_column", "bar_column"], where: nil, orders: ["test_column": .DESC]), false, "CREATE UNIQUE INDEX \"index_tests\" ON \"tests\" (\"test_column\" DESC, \"bar_column\")"), (IndexDefinition(table: "tests", name: "index_tests", unique: false, columns: ["test_column"], where: nil, orders: nil), true, "CREATE INDEX IF NOT EXISTS \"index_tests\" ON \"tests\" (\"test_column\")") ] #if !os(Linux) override class var defaultTestSuite: XCTestSuite { let suite = XCTestSuite(forTestCaseClass: IndexDefinitionTests.self) for (column, ifNotExists, expected) in IndexDefinitionTests.definitions { let test = IndexDefinitionTests(selector: #selector(verify)) test.definition = column test.expected = expected test.ifNotExists = ifNotExists suite.addTest(test) } return suite } @objc func verify() { XCTAssertEqual(definition.toSQL(ifNotExists: ifNotExists), expected) } #endif func test_validate() { let longIndex = IndexDefinition( table: "tests", name: String(repeating: "x", count: 65), unique: false, columns: ["test_column"], where: nil, orders: nil) XCTAssertThrowsError(try longIndex.validate()) { error in XCTAssertEqual(error.localizedDescription, "Index name 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' " + "on table 'tests' is too long; the limit is 64 characters") } } func test_rename() { let index = IndexDefinition(table: "tests", name: "index_tests_something", unique: true, columns: ["test_column"], where: "test_column IS NOT NULL", orders: nil) let renamedIndex = index.renameTable(to: "foo") XCTAssertEqual(renamedIndex, IndexDefinition( table: "foo", name: "index_tests_something", unique: true, columns: ["test_column"], where: "test_column IS NOT NULL", orders: nil ) ) } } class ForeignKeyDefinitionTests: XCTestCase { func test_toSQL() { XCTAssertEqual( ColumnDefinition.ForeignKey( table: "foo", column: "bar", primaryKey: "bar_id", onUpdate: nil, onDelete: "SET NULL" ).toSQL(), """ REFERENCES "foo" ("bar_id") ON DELETE SET NULL """ ) } } class TableDefinitionTests: XCTestCase { func test_quoted_columnList() { let definition = TableDefinition(name: "foo", columns: [ ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil), ColumnDefinition(name: "baz", primaryKey: nil, type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil) ], indexes: []) XCTAssertEqual(definition.quotedColumnList, """ "id", "baz" """) } func test_toSQL() { let definition = TableDefinition(name: "foo", columns: [ ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil) ], indexes: []) XCTAssertEqual(definition.toSQL(), """ CREATE TABLE foo ( \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ) """) } func test_toSQL_temp_table() { let definition = TableDefinition(name: "foo", columns: [ ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil) ], indexes: []) XCTAssertEqual(definition.toSQL(temporary: true), """ CREATE TEMPORARY TABLE foo ( \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ) """) } func test_copySQL() { let from = TableDefinition(name: "from_table", columns: [ ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil) ], indexes: []) let to = TableDefinition(name: "to_table", columns: [ ColumnDefinition(name: "id", primaryKey: .init(), type: .INTEGER, nullable: false, defaultValue: .NULL, references: nil) ], indexes: []) XCTAssertEqual(from.copySQL(to: to), """ INSERT INTO "to_table" ("id") SELECT "id" FROM "from_table" """) } } class PrimaryKeyTests: XCTestCase { func test_toSQL() { XCTAssertEqual( ColumnDefinition.PrimaryKey(autoIncrement: false).toSQL(), "PRIMARY KEY" ) } func test_toSQL_autoincrement() { XCTAssertEqual( ColumnDefinition.PrimaryKey(autoIncrement: true).toSQL(), "PRIMARY KEY AUTOINCREMENT" ) } func test_toSQL_on_conflict() { XCTAssertEqual( ColumnDefinition.PrimaryKey(autoIncrement: false, onConflict: .ROLLBACK).toSQL(), "PRIMARY KEY ON CONFLICT ROLLBACK" ) } func test_fromSQL() { XCTAssertEqual( ColumnDefinition.PrimaryKey(sql: "PRIMARY KEY"), ColumnDefinition.PrimaryKey(autoIncrement: false) ) } func test_fromSQL_invalid_sql_is_nil() { XCTAssertNil(ColumnDefinition.PrimaryKey(sql: "FOO")) } func test_fromSQL_autoincrement() { XCTAssertEqual( ColumnDefinition.PrimaryKey(sql: "PRIMARY KEY AUTOINCREMENT"), ColumnDefinition.PrimaryKey(autoIncrement: true) ) } func test_fromSQL_on_conflict() { XCTAssertEqual( ColumnDefinition.PrimaryKey(sql: "PRIMARY KEY ON CONFLICT ROLLBACK"), ColumnDefinition.PrimaryKey(autoIncrement: false, onConflict: .ROLLBACK) ) } } class LiteralValueTests: XCTestCase { func test_recognizes_TRUE() { XCTAssertEqual(LiteralValue("TRUE"), .TRUE) } func test_recognizes_FALSE() { XCTAssertEqual(LiteralValue("FALSE"), .FALSE) } func test_recognizes_NULL() { XCTAssertEqual(LiteralValue("NULL"), .NULL) } func test_recognizes_nil() { XCTAssertEqual(LiteralValue(nil), .NULL) } func test_recognizes_CURRENT_TIME() { XCTAssertEqual(LiteralValue("CURRENT_TIME"), .CURRENT_TIME) } func test_recognizes_CURRENT_TIMESTAMP() { XCTAssertEqual(LiteralValue("CURRENT_TIMESTAMP"), .CURRENT_TIMESTAMP) } func test_recognizes_CURRENT_DATE() { XCTAssertEqual(LiteralValue("CURRENT_DATE"), .CURRENT_DATE) } func test_recognizes_double_quote_string_literals() { XCTAssertEqual(LiteralValue("\"foo\""), .stringLiteral("foo")) } func test_recognizes_single_quote_string_literals() { XCTAssertEqual(LiteralValue("\'foo\'"), .stringLiteral("foo")) } func test_unquotes_double_quote_string_literals() { XCTAssertEqual(LiteralValue("\"fo\"\"o\""), .stringLiteral("fo\"o")) } func test_unquotes_single_quote_string_literals() { XCTAssertEqual(LiteralValue("'fo''o'"), .stringLiteral("fo'o")) } func test_recognizes_numeric_literals() { XCTAssertEqual(LiteralValue("1.2"), .numericLiteral("1.2")) XCTAssertEqual(LiteralValue("0xdeadbeef"), .numericLiteral("0xdeadbeef")) } func test_recognizes_blob_literals() { XCTAssertEqual(LiteralValue("X'deadbeef'"), .blobLiteral("deadbeef")) XCTAssertEqual(LiteralValue("x'deadbeef'"), .blobLiteral("deadbeef")) } func test_description_TRUE() { XCTAssertEqual(LiteralValue.TRUE.description, "TRUE") } func test_description_FALSE() { XCTAssertEqual(LiteralValue.FALSE.description, "FALSE") } func test_description_NULL() { XCTAssertEqual(LiteralValue.NULL.description, "NULL") } func test_description_CURRENT_TIME() { XCTAssertEqual(LiteralValue.CURRENT_TIME.description, "CURRENT_TIME") } func test_description_CURRENT_TIMESTAMP() { XCTAssertEqual(LiteralValue.CURRENT_TIMESTAMP.description, "CURRENT_TIMESTAMP") } func test_description_CURRENT_DATE() { XCTAssertEqual(LiteralValue.CURRENT_DATE.description, "CURRENT_DATE") } func test_description_string_literal() { XCTAssertEqual(LiteralValue.stringLiteral("foo").description, "'foo'") } func test_description_numeric_literal() { XCTAssertEqual(LiteralValue.numericLiteral("1.2").description, "1.2") XCTAssertEqual(LiteralValue.numericLiteral("0xdeadbeef").description, "0xdeadbeef") } func test_description_blob_literal() { XCTAssertEqual(LiteralValue.blobLiteral("deadbeef").description, "X'deadbeef'") } }
508e8d6ea4730034c3ce3693badc7f97
35.645078
138
0.575115
false
true
false
false
JacksunYX/DYLiving
refs/heads/master
DYLiving/DYLiving/Classes/Home/Controller/RecommendVC.swift
mit
1
// // RecommendVC.swift // DYLiving // // Created by 黑色o.o表白 on 2017/3/25. // Copyright © 2017年 黑色o.o表白. All rights reserved. // import UIKit let sCellMargin : CGFloat = 10 let sNormalCellW = (sScreenW - 3 * sCellMargin)/2 let sNormalCellH = (sNormalCellW) * 3 / 4 let sPrettyCellH = (sNormalCellW) * 4 / 3 let sCollectionViewHeadH : CGFloat = 50 let sCollcetionViewHeadViewID = "sCollcetionViewHeadViewID" let sNormaelCellID = "sNormaelCellID" let sPrettyCellID = "sPrettyCellID" class RecommendVC: UIViewController { //懒加载collectionView lazy var collectionView : UICollectionView = {[unowned self] in //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: sNormalCellW, height: sNormalCellH) layout.minimumLineSpacing = 5.0 //行间距为0(根据需要) layout.minimumInteritemSpacing = sCellMargin //cell间的最小间距 layout.headerReferenceSize = CGSize(width: sScreenW, height: sCollectionViewHeadH) layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10) //设置缩进 //2.创建collectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: HomeCenterViewH), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.white //需要将collectionView自动适应父视图的大小 collectionView.autoresizingMask = [.flexibleWidth,.flexibleWidth] //3.注册collectionCell //collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: sNormaelCellID) //普通cell collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: sNormaelCellID) //颜值cell collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: sPrettyCellID) //4.注册组头 //collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: sCollcetionViewHeadViewID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: sCollcetionViewHeadViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() //设置界面 setupUI() //求请数据 loadData() } } //设置UI界面xr extension RecommendVC { func setupUI(){ view.addSubview(collectionView) } } //请求数据 extension RecommendVC { func loadData (){ NetworkTool.requestData(type: .GET, URLString: "http://httpbin.org/get") { (respose) in print(respose) } } } //遵循collectionView协议 extension RecommendVC : UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell :UICollectionViewCell if indexPath.section == 1 { //颜值区 cell = collectionView.dequeueReusableCell(withReuseIdentifier: sPrettyCellID, for: indexPath) }else{ //普通cell cell = collectionView.dequeueReusableCell(withReuseIdentifier: sNormaelCellID, for: indexPath) } return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: sCollcetionViewHeadViewID, for: indexPath) return headView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { //颜值区 return CGSize(width: sNormalCellW, height: sPrettyCellH) } return CGSize(width: sNormalCellW, height: sNormalCellH) } }
e05304e809c17aaee9fe67a7fdb937c8
28.947368
198
0.679701
false
false
false
false
mas-cli/mas
refs/heads/main
Sources/MasKit/ExternalCommands/OpenSystemCommand.swift
mit
1
// // OpenSystemCommand.swift // MasKit // // Created by Ben Chatelain on 1/2/19. // Copyright © 2019 mas-cli. All rights reserved. // import Foundation /// Wrapper for the external open system command. /// https://ss64.com/osx/open.html struct OpenSystemCommand: ExternalCommand { var binaryPath: String let process = Process() let stdoutPipe = Pipe() let stderrPipe = Pipe() init(binaryPath: String = "/usr/bin/open") { self.binaryPath = binaryPath } }
5f9faa57d4af9ecc0527a19fabb3484d
19.666667
50
0.665323
false
false
false
false
NeilNie/Done-
refs/heads/master
Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift
apache-2.0
2
// // HorizontalBarChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class HorizontalBarChartRenderer: BarChartRenderer { private class Buffer { var rects = [CGRect]() } public override init(dataProvider: BarChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler) } // [CGRect] per dataset private var _buffers = [Buffer]() open override func initBuffers() { if let barData = dataProvider?.barData { // Matche buffers count to dataset count if _buffers.count != barData.dataSetCount { while _buffers.count < barData.dataSetCount { _buffers.append(Buffer()) } while _buffers.count > barData.dataSetCount { _buffers.removeLast() } } for i in stride(from: 0, to: barData.dataSetCount, by: 1) { let set = barData.dataSets[i] as! IBarChartDataSet let size = set.entryCount * (set.isStacked ? set.stackSize : 1) if _buffers[i].rects.count != size { _buffers[i].rects = [CGRect](repeating: CGRect(), count: size) } } } else { _buffers.removeAll() } } private func prepareBuffer(dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } let barWidthHalf = barData.barWidth / 2.0 let buffer = _buffers[index] var bufferIndex = 0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) let phaseY = animator.phaseY var barRect = CGRect() var x: Double var y: Double for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1) { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } let vals = e.yValues x = e.x y = e.y if !containsStacks || vals == nil { let bottom = CGFloat(x - barWidthHalf) let top = CGFloat(x + barWidthHalf) var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if right > 0 { right *= CGFloat(phaseY) } else { left *= CGFloat(phaseY) } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top buffer.rects[bufferIndex] = barRect bufferIndex += 1 } else { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // fill the stack for k in 0 ..< vals!.count { let value = vals![k] if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value yStart = y } else if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } let bottom = CGFloat(x - barWidthHalf) let top = CGFloat(x + barWidthHalf) var right = isInverted ? (y <= yStart ? CGFloat(y) : CGFloat(yStart)) : (y >= yStart ? CGFloat(y) : CGFloat(yStart)) var left = isInverted ? (y >= yStart ? CGFloat(y) : CGFloat(yStart)) : (y <= yStart ? CGFloat(y) : CGFloat(yStart)) // multiply the height of the rect with the phase right *= CGFloat(phaseY) left *= CGFloat(phaseY) barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top buffer.rects[bufferIndex] = barRect bufferIndex += 1 } } } } private var _barShadowRectBuffer: CGRect = CGRect() open override func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) prepareBuffer(dataSet: dataSet, index: index) trans.rectValuesToPixel(&_buffers[index].rects) let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 context.saveGState() // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { guard let barData = dataProvider.barData else { return } let barWidth = barData.barWidth let barWidthHalf = barWidth / 2.0 var x: Double = 0.0 for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1) { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } x = e.x _barShadowRectBuffer.origin.y = CGFloat(x - barWidthHalf) _barShadowRectBuffer.size.height = CGFloat(barWidth) trans.rectValueToPixel(&_barShadowRectBuffer) if !viewPortHandler.isInBoundsTop(_barShadowRectBuffer.origin.y + _barShadowRectBuffer.size.height) { break } if !viewPortHandler.isInBoundsBottom(_barShadowRectBuffer.origin.y) { continue } _barShadowRectBuffer.origin.x = viewPortHandler.contentLeft _barShadowRectBuffer.size.width = viewPortHandler.contentWidth context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(_barShadowRectBuffer) } } let buffer = _buffers[index] let isSingleColor = dataSet.colors.count == 1 if isSingleColor { context.setFillColor(dataSet.color(atIndex: 0).cgColor) } // In case the chart is stacked, we need to accomodate individual bars within accessibilityOrdereredElements let isStacked = dataSet.isStacked let stackSize = isStacked ? dataSet.stackSize : 1 for j in stride(from: 0, to: buffer.rects.count, by: 1) { let barRect = buffer.rects[j] if (!viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height)) { break } if (!viewPortHandler.isInBoundsBottom(barRect.origin.y)) { continue } if !isSingleColor { // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.color(atIndex: j).cgColor) } context.fill(barRect) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } // Create and append the corresponding accessibility element to accessibilityOrderedElements (see BarChartRenderer) if let chart = dataProvider as? BarChartView { let element = createAccessibleElement(withIndex: j, container: chart, dataSet: dataSet, dataSetIndex: index, stackSize: stackSize) { (element) in element.accessibilityFrame = barRect } accessibilityOrderedElements[j/stackSize].append(element) } } context.restoreGState() } open override func prepareBarHighlight( x: Double, y1: Double, y2: Double, barWidthHalf: Double, trans: Transformer, rect: inout CGRect) { let top = x - barWidthHalf let bottom = x + barWidthHalf let left = y1 let right = y2 rect.origin.x = CGFloat(left) rect.origin.y = CGFloat(top) rect.size.width = CGFloat(right - left) rect.size.height = CGFloat(bottom - top) trans.rectValueToPixelHorizontal(&rect, phaseY: animator.phaseY) } open override func drawValues(context: CGContext) { // if values are drawn if isDrawingValuesAllowed(dataProvider: dataProvider) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } var dataSets = barData.dataSets let textAlign = NSTextAlignment.left let valueOffsetPlus: CGFloat = 5.0 var posOffset: CGFloat var negOffset: CGFloat let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled for dataSetIndex in 0 ..< barData.dataSetCount { guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue } if !shouldDrawValues(forDataSet: dataSet) || !(dataSet.isDrawIconsEnabled && dataSet.isVisible) { continue } let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) let valueFont = dataSet.valueFont let yOffset = -valueFont.lineHeight / 2.0 guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY let iconsOffset = dataSet.iconsOffset let buffer = _buffers[dataSetIndex] // if only single values are drawn (sum) if !dataSet.isStacked { for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let rect = buffer.rects[j] let y = rect.origin.y + rect.size.height / 2.0 if !viewPortHandler.isInBoundsTop(rect.origin.y) { break } if !viewPortHandler.isInBoundsX(rect.origin.x) { continue } if !viewPortHandler.isInBoundsBottom(rect.origin.y) { continue } let val = e.y let valueText = formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(withAttributes: [NSAttributedString.Key.font: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if isInverted { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: valueText, xPos: (rect.origin.x + rect.size.width) + (val >= 0.0 ? posOffset : negOffset), yPos: y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(j)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = (rect.origin.x + rect.size.width) + (val >= 0.0 ? posOffset : negOffset) var py = y px += iconsOffset.x py += iconsOffset.y ChartUtils.drawImage( context: context, image: icon, x: px, y: py, size: icon.size) } } } else { // if each value of a potential stack should be drawn var bufferIndex = 0 for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue } let rect = buffer.rects[bufferIndex] let vals = e.yValues // we still draw stacked bars, but there is one non-stacked in between if vals == nil { if !viewPortHandler.isInBoundsTop(rect.origin.y) { break } if !viewPortHandler.isInBoundsX(rect.origin.x) { continue } if !viewPortHandler.isInBoundsBottom(rect.origin.y) { continue } let val = e.y let valueText = formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(withAttributes: [NSAttributedString.Key.font: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if isInverted { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: valueText, xPos: (rect.origin.x + rect.size.width) + (val >= 0.0 ? posOffset : negOffset), yPos: rect.origin.y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(index)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = (rect.origin.x + rect.size.width) + (val >= 0.0 ? posOffset : negOffset) var py = rect.origin.y px += iconsOffset.x py += iconsOffset.y ChartUtils.drawImage( context: context, image: icon, x: px, y: py, size: icon.size) } } else { let vals = vals! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for k in 0 ..< vals.count { let value = vals[k] var y: Double if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value } else if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: CGFloat(y * phaseY), y: 0.0)) } trans.pointValuesToPixel(&transformed) for k in 0 ..< transformed.count { let val = vals[k] let valueText = formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(withAttributes: [NSAttributedString.Key.font: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if isInverted { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } let drawBelow = (val == 0.0 && negY == 0.0 && posY > 0.0) || val < 0.0 let x = transformed[k].x + (drawBelow ? negOffset : posOffset) let y = rect.origin.y + rect.size.height / 2.0 if (!viewPortHandler.isInBoundsTop(y)) { break } if (!viewPortHandler.isInBoundsX(x)) { continue } if (!viewPortHandler.isInBoundsBottom(y)) { continue } if dataSet.isDrawValuesEnabled { drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(index)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage( context: context, image: icon, x: x + iconsOffset.x, y: y + iconsOffset.y, size: icon.size) } } } bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count) } } } } } open override func isDrawingValuesAllowed(dataProvider: ChartDataProvider?) -> Bool { guard let data = dataProvider?.data else { return false } return data.entryCount < Int(CGFloat(dataProvider?.maxVisibleCount ?? 0) * self.viewPortHandler.scaleY) } /// Sets the drawing position of the highlight object based on the riven bar-rect. internal override func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect) { high.setDraw(x: barRect.midY, y: barRect.origin.x + barRect.size.width) } }
e5f4a535ff3ada390d949741fea34754
39.659271
131
0.395853
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Test Doubles/Observers/CapturingLoginObserver.swift
mit
2
import EurofurenceModel class CapturingLoginObserver { private(set) var notifiedLoginSucceeded = false private(set) var notifiedLoginFailed = false private(set) var loggedInUser: User? func completionHandler(_ result: LoginResult) { switch result { case .success(let user): self.notifiedLoginSucceeded = true self.loggedInUser = user case .failure: self.notifiedLoginFailed = true } } }
1c923962ea47fa7c0b71db6b10594628
24.842105
51
0.633401
false
false
false
false
harryzjm/RotateWheel
refs/heads/master
Sample/Sample/ViewController.swift
mit
1
// // ViewController.swift // Sample // // Created by Magic on 9/5/2016. // Copyright © 2016 Magic. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .whiteColor() title = "Sample" let v = RotateWheel(6,wheelRadius: 120,cellType: Rotate.self) v.delegate = self view.addSubview(v) v.center = view.center } } extension ViewController: RotateWheelDelegate { func rotateWheel(rotateWheel: RotateWheel, initCell cell: RotateWheelCell, forPiece piece: Int) { guard let c = cell as? Rotate else { return } c.lb.text = "gogo" c.lb.bounds.size = CGSize(width: 100, height: 50) let sz = c.container.bounds.size c.lb.center = CGPoint(x: sz.width/2, y: sz.height/2) } func rotateWheel(rotateWheel: RotateWheel, configCell cell: RotateWheelCell, forPiece piece: Int) { guard let c = cell as? Rotate else { return } c.lb.text = "gogo" c.lb.sizeToFit() let sz = c.container.bounds.size c.lb.center = CGPoint(x: sz.width/2, y: sz.height/2) } } class Rotate: RotateWheelCell { required init(frame: CGRect) { super.init(frame: frame) lb.textAlignment = .Center container.addSubview(lb) container.backgroundColor = UIColor(hue: CGFloat(arc4random_uniform(255))/255, saturation: 1, brightness: 1, alpha: 1).colorWithAlphaComponent(0.3) } var lb = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
a429c3afa4896080d4d11687104c779e
27.540984
155
0.619759
false
false
false
false
izotx/iTenWired-Swift
refs/heads/master
Conference App/NearMeCollectionViewCell.swift
bsd-2-clause
1
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // NearMeCollectionViewCell.swift // Conference App // // Created by Felipe N. Brito on 7/8/16. // // import UIKit import Haneke class NearMeCollectionViewCell: UICollectionViewCell { var nearMeItem: iBeaconNearMeProtocol! @IBOutlet weak var headerView: UIView! // @IBOutlet weak var containerView: UIView! @IBOutlet weak var itemTypeLabel: UILabel! @IBOutlet weak var imageView: UIImageView! // @IBOutlet var icon: MIBadgeButton! @IBOutlet var title: UILabel! override var bounds: CGRect { didSet { contentView.frame = bounds } } func build(nearMeItem: iBeaconNearMeProtocol){ // icon.hnk_setImageFromURL(NSURL(string: nearMeItem.getNearMeIconURL())!) title.text = nearMeItem.getNearMeTitle() itemTypeLabel.text = "" if nearMeItem is Sponsor{ itemTypeLabel.text = "Sponsor" } if nearMeItem is Exhibitor{ itemTypeLabel.text = "Exhibitor" } if nearMeItem is Location{ itemTypeLabel.text = "Location" } self.UIConfig() } internal func UIConfig(){ self.backgroundColor = ItenWiredStyle.background.color.invertedColor headerView.backgroundColor = ItenWiredStyle.background.color.mainColor.colorWithAlphaComponent(0.7) title.textColor = ItenWiredStyle.text.color.mainColor self.contentView.layer.borderColor = ItenWiredStyle.background.color.mainColor.CGColor self.contentView.layer.borderWidth = 1 // self.containerView.layer.borderWidth = 1 // self.containerView.layer.borderColor = UIColor.greenColor().CGColor // self.imageView.layer.borderColor = UIColor.whiteColor().CGColor // self.imageView.layer.borderWidth = 2 } }
6081bf1855a4c4e48c704f39425ad518
34.806122
106
0.683956
false
false
false
false
wonderkiln/WKAwesomeMenu
refs/heads/master
Demo/MainTableViewController.swift
mit
1
// // MainTableViewController.swift // WKAwesomeMenu // // Created by Adrian Mateoaea on 09.02.2016. // Copyright © 2016 Wonderkiln. All rights reserved. // import UIKit import WKAwesomeMenu class MainTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red:0.96, green:0.96, blue:0.98, alpha:1) self.title = "HOME" self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: Image.menuImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(MainTableViewController.menu)) } func menu() { self.openSideMenu() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") cell.textLabel?.text = "Item number \((indexPath as NSIndexPath).row)" return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } }
d74e2b1b4a7f36a8e47435075f705644
32.044444
112
0.584398
false
false
false
false
avaidyam/Parrot
refs/heads/master
MochaUI/Interpolate.swift
mpl-2.0
1
import AppKit import Mocha import CoreGraphics /* TODO: Multiple animation blocks. */ /* TODO: Different interpolators between values (a la CAKeyframeAnimation). */ /* TODO: Use CAAnimation to enable presentation layer (a la UIViewPropertyAnimator). */ /* TODO: Turn on implicit animation in a CATransaction group. */ /* TODO: Better NSColor interpolation. */ private let Interpolate_displayLink = DisplayLink() // global!! private let Interpolate_backgroundQueue = DispatchQueue(label: "InterpolateCallbackQueue", qos: .userInteractive) public class AnyInterpolate { open var fractionComplete: CGFloat = 0.0 /// All interpolations in the group will not execute their handlers unless the policy is set to .always. //@available(*, deprecated: 1.0) public static func group(_ interpolations: AnyInterpolate...) -> Interpolate<Double> { return Interpolate(from: 0.0, to: 1.0, interpolator: LinearInterpolator()) { progress in interpolations.forEach { interp in interp.fractionComplete = CGFloat(progress) } } } } public class Interpolate<T: Interpolatable>: AnyInterpolate { public enum HandlerRunPolicy { case never case onlyWhenAnimating case always } fileprivate var fpsObserver: Any? = nil fileprivate var current: IPValue<T> fileprivate let values: [IPValue<T>] fileprivate var valuesCount: CGFloat { get { return CGFloat(values.count) } } fileprivate var vectorCount: Int { get { return current.components.count } } fileprivate var duration: CGFloat = 0.2 fileprivate var diffVectors = [[CGFloat]]() fileprivate let function: Interpolator fileprivate var internalProgress: CGFloat = 0.0 fileprivate var targetProgress: CGFloat = 0.0 fileprivate var apply: ((Interpolatable) -> ())? = nil fileprivate var animationCompletion: (()->())? fileprivate var handlers = [Double: [() -> ()]]() public var handlerRunPolicy = HandlerRunPolicy.onlyWhenAnimating /** Initialises an Interpolate object. - parameter values: Array of interpolatable objects, in order. - parameter apply: Apply closure. - parameter function: Interpolation function (Basic / Spring / Custom). - returns: an Interpolate object. */ public init(values: [T], interpolator: Interpolator = LinearInterpolator(), apply: @escaping ((T) -> ())) { assert(values.count >= 2, "You should provide at least two values") let vectorizedValues = values.map({IPValue(value: $0)}) self.values = vectorizedValues self.current = IPValue(from: self.values[0]) self.apply = { let _ = ($0 as? T).flatMap(apply) } self.function = interpolator super.init() self.diffVectors = self.calculateDiff(vectorizedValues) } /** Initialises an Interpolate object. - parameter from: Source interpolatable object. - parameter to: Target interpolatable object. - parameter apply: Apply closure. - parameter function: Interpolation function (Basic / Spring / Custom). - returns: an Interpolate object. */ public convenience init(from: T, to: T, interpolator: Interpolator = LinearInterpolator(), apply: @escaping ((T) -> ())) { self.init(values: [from, to], interpolator: interpolator, apply: apply) } public convenience init<A: AnyObject>(values: [T], interpolator: Interpolator = LinearInterpolator(), on object: A, keyPath: ReferenceWritableKeyPath<A, T>) { self.init(values: values, interpolator: interpolator) { value in object[keyPath: keyPath] = value } } public convenience init<A: AnyObject>(from: T, to: T, interpolator: Interpolator = LinearInterpolator(), on object: A, keyPath: ReferenceWritableKeyPath<A, T>) { self.init(values: [from, to], interpolator: interpolator, on: object, keyPath: keyPath) } /// Progress variable. Takes a value between 0.0 and 1.0. CGFloat. Setting it triggers the apply closure. open override var fractionComplete: CGFloat { didSet { // We make sure fractionComplete is between 0.0 and 1.0 guard (0.0...1.0).contains(fractionComplete) else { fractionComplete = fractionComplete.clamped(to: 0.0...1.0) return } internalProgress = function.apply(fractionComplete) let valueForProgress = internalProgress*(valuesCount - 1) let diffVectorIndex = max(Int(ceil(valueForProgress)) - 1, 0) let diffVector = diffVectors[diffVectorIndex] let originValue = values[diffVectorIndex] let adjustedProgress = valueForProgress - CGFloat(diffVectorIndex) for index in 0..<vectorCount { current.components[index] = originValue.components[index] + diffVector[index]*adjustedProgress } apply?(current.value) // Execute handlers if only when animating. if self.handlerRunPolicy == .always { self._executeHandlers(Double(oldValue), Double(fractionComplete)) } } } public func add(at fractionComplete: Double = 1.0, handler: @escaping () -> ()) { self.handlers[fractionComplete, default: []] += [handler] } /** Invalidates the apply function */ open func invalidate() { self.apply = nil } /// public private(set) var animating: Bool = false { didSet { guard self.animating != oldValue else { return } if self.animating { self.fpsObserver = Interpolate_displayLink.observe(self.next) } else { self.fpsObserver = nil } } } /** Animates to a targetProgress with a given duration. - parameter targetProgress: Target progress value. Optional. If left empty assumes 1.0. - parameter duration: Duration in seconds. CGFloat. - parameter completion: Completion handler. Optional. */ open func animate(_ fractionComplete: CGFloat = 1.0, duration: CGFloat) { self.targetProgress = fractionComplete self.duration = duration self.animating = true } /** Stops animation. */ open func stop() { self.animating = false } /** Calculates diff between two IPValues. - parameter from: Source IPValue. - parameter to: Target IPValue. - returns: Array of diffs. CGFloat */ fileprivate func calculateDiff(_ values: [IPValue<T>]) -> [[CGFloat]] { var valuesDiffArray = [[CGFloat]]() for i in 0..<(values.count - 1) { var diffArray = [CGFloat]() let from = values[i] let to = values[i+1] for index in 0..<from.components.count { let vectorDiff = to.components[index] - from.components[index] diffArray.append(vectorDiff) } valuesDiffArray.append(diffArray) } return valuesDiffArray } /** Next function used by animation(). Increments fractionComplete based on the duration. */ @objc dynamic fileprivate func next(_ fps: Double = 60.0) { let direction: CGFloat = (targetProgress > fractionComplete) ? 1.0 : -1.0 let oldProgress = fractionComplete var newProgress = fractionComplete + 1 / (self.duration * CGFloat(fps)) * direction // FIXME: Don't use fps... // Snap back if the current fractionComplete calls for the animation to stop. if (direction > 0 && newProgress >= targetProgress) || (direction < 0 && newProgress <= targetProgress) { newProgress = targetProgress } self.fractionComplete = newProgress if newProgress == targetProgress { stop() } // Execute handlers if only when animating. if self.handlerRunPolicy == .onlyWhenAnimating { self._executeHandlers(Double(oldProgress), Double(fractionComplete)) } } // Determine and run all handlers between the previous fractionComplete and the current one. private func _executeHandlers(_ old: Double, _ new: Double) { Interpolate_backgroundQueue.async { // This is required because we check `progress > old` and not `>=`... if (old == 0.0) { self.handlers[0.0]?.forEach { $0() } } Array(self.handlers.keys).lazy.sorted() .filter { (old < $0 && $0 <= new) || (new < $0 && $0 <= old) } .forEach { self.handlers[$0]?.forEach { $0() } } } } }
c6fcb8d1fe2b430c7c780e48bc14119e
38.210526
126
0.611633
false
false
false
false
emaloney/CleanroomConcurrency
refs/heads/master
Sources/ThreadLocalValue.swift
mit
1
// // ThreadLocalValue.swift // Cleanroom Project // // Created by Evan Maloney on 3/25/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import Foundation /** Provides a type-safe mechanism for accessing thread-local values (of type `T`) stored in the `threadDictionary` associated with the calling thread. As the class name implies, values set using `ThreadLocalValue` are only visible to the thread that set those values. */ public struct ThreadLocalValue<T: Any> { /** If the receiver was initialized with a `namespace`, this property will contain that value. */ public let namespace: String? /** The `key` that was originally passed to the receiver's initializer. If the receiver was initialized with a `namespace`, this value *will not* include the namespace; `fullKey` will include the namespace. */ public let key: String /** Contains the key that will be used to access the underlying `threadDictionary`. Unless the receiver was initialized with a `namespace`, this value will be the same as `key`. */ public let fullKey: String /** The signature of a function to be used for providing values when none exist in the `current` thread's `threadDictionary`. */ public typealias ValueProvider = (ThreadLocalValue) -> T? private let valueProvider: ValueProvider /** Initializes a new instance referencing the thread-local value associated with the specified key. - parameter key: The key used to access the value associated with the receiver in the `threadDictionary`. - parameter valueProvider: A `ValueProvider` function used to provide a value when the underlying `threadDictionary` does not contain a value. */ public init(key: String, valueProvider: @escaping ValueProvider = { _ in return nil }) { self.namespace = nil self.key = key self.fullKey = key self.valueProvider = valueProvider } /** Initializes a new instance referencing the thread-local value associated with the specified namespace and key. - parameter namespace: The name of the code module that will own the receiver. This is used in constructing the `fullKey`. - parameter key: The key within the namespace. Used to construct the `fullKey` associated with the receiver. - parameter valueProvider: A `ValueProvider` function used to provide a value when the underlying `threadDictionary` does not contain a value. */ public init(namespace: String, key: String, valueProvider: @escaping ValueProvider = { _ in return nil }) { self.namespace = namespace self.key = key self.fullKey = "\(namespace).\(key)" self.valueProvider = valueProvider } /** Retrieves the `current` thread's `threadDictionary` value associated with the receiver's `fullKey`. If the value is `nil` or if it is not of type `T`, the receiver's `valueProvider` will be consulted to provide a value, which will be stored in the `threadDictionary` using the key `fullKey`. `nil` will be returned if no value was provided. */ public var value: T? { if let value = cachedValue { return value } if let value = valueProvider(self) { set(value) return value } return nil } /** Retrieves the `threadDictionary` value currently associated with the receiver's `fullKey`. Will be `nil` if there is no value associated with `fullKey` or if the underlying value is not of type `T`. */ public var cachedValue: T? { return Thread.current.threadDictionary[fullKey] as? T } /** Sets a new value in the `current` thread's `threadDictionary` for the key specified by the receiver's `fullKey` property. - parameter newValue: The new thread-local value. */ public func set(_ newValue: T?) { Thread.current.threadDictionary[fullKey] = newValue } }
f747c0cafb885e4be854c4109c98a6b9
34.368421
109
0.677827
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
Pods/Eureka/Source/Core/Section.swift
lgpl-3.0
2
// Section.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // 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 Foundation import UIKit /// The delegate of the Eureka sections. public protocol SectionDelegate: class { func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet) func rowsHaveBeenRemoved(_ rows: [BaseRow], at: IndexSet) func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: IndexSet) } // MARK: Section extension Section : Equatable {} public func == (lhs: Section, rhs: Section) -> Bool { return lhs === rhs } extension Section : Hidable, SectionDelegate {} extension Section { public func reload(with rowAnimation: UITableView.RowAnimation = .none) { guard let tableView = (form?.delegate as? FormViewController)?.tableView, let index = index, index < tableView.numberOfSections else { return } tableView.reloadSections(IndexSet(integer: index), with: rowAnimation) } } extension Section { internal class KVOWrapper: NSObject { @objc dynamic private var _rows = NSMutableArray() var rows: NSMutableArray { return mutableArrayValue(forKey: "_rows") } var _allRows = [BaseRow]() private weak var section: Section? init(section: Section) { self.section = section super.init() addObserver(self, forKeyPath: "_rows", options: [.new, .old], context:nil) } deinit { removeObserver(self, forKeyPath: "_rows") _rows.removeAllObjects() _allRows.removeAll() } func removeAllRows() { _rows = [] _allRows.removeAll() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let newRows = change![NSKeyValueChangeKey.newKey] as? [BaseRow] ?? [] let oldRows = change![NSKeyValueChangeKey.oldKey] as? [BaseRow] ?? [] guard let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return } let delegateValue = section?.form?.delegate guard keyPathValue == "_rows" else { return } switch (changeType as! NSNumber).uintValue { case NSKeyValueChange.setting.rawValue: if newRows.count == 0 { let indexSet = IndexSet(integersIn: 0..<oldRows.count) section?.rowsHaveBeenRemoved(oldRows, at: indexSet) if let _index = section?.index { delegateValue?.rowsHaveBeenRemoved(oldRows, at: (0..<oldRows.count).map { IndexPath(row: $0, section: _index) }) } } else { let indexSet = IndexSet(integersIn: 0..<newRows.count) section?.rowsHaveBeenAdded(newRows, at: indexSet) if let _index = section?.index { delegateValue?.rowsHaveBeenAdded(newRows, at: indexSet.map { IndexPath(row: $0, section: _index) }) } } case NSKeyValueChange.insertion.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet section?.rowsHaveBeenAdded(newRows, at: indexSet) if let _index = section?.index { delegateValue?.rowsHaveBeenAdded(newRows, at: indexSet.map { IndexPath(row: $0, section: _index ) }) } case NSKeyValueChange.removal.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet section?.rowsHaveBeenRemoved(oldRows, at: indexSet) if let _index = section?.index { delegateValue?.rowsHaveBeenRemoved(oldRows, at: indexSet.map { IndexPath(row: $0, section: _index ) }) } case NSKeyValueChange.replacement.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet section?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, at: indexSet) if let _index = section?.index { delegateValue?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, at: indexSet.map { IndexPath(row: $0, section: _index)}) } default: assertionFailure() } } } /** * If this section contains a row (hidden or not) with the passed parameter as tag then that row will be returned. * If not, it returns nil. */ public func rowBy<Row: RowType>(tag: String) -> Row? { guard let index = kvoWrapper._allRows.firstIndex(where: { $0.tag == tag }) else { return nil } return kvoWrapper._allRows[index] as? Row } } /// The class representing the sections in a Eureka form. open class Section { /// The tag is used to uniquely identify a Section. Must be unique among sections and rows. public var tag: String? /// The form that contains this section public internal(set) weak var form: Form? /// The header of this section. public var header: HeaderFooterViewRepresentable? { willSet { headerView = nil } } /// The footer of this section public var footer: HeaderFooterViewRepresentable? { willSet { footerView = nil } } /// Index of this section in the form it belongs to. public var index: Int? { return form?.firstIndex(of: self) } /// Condition that determines if the section should be hidden or not. public var hidden: Condition? { willSet { removeFromRowObservers() } didSet { addToRowObservers() } } /// Returns if the section is currently hidden or not. public var isHidden: Bool { return hiddenCache } /// Returns all the rows in this section, including hidden rows. public var allRows: [BaseRow] { return kvoWrapper._allRows } public required init() {} #if swift(>=4.1) public required init<S>(_ elements: S) where S: Sequence, S.Element == BaseRow { self.append(contentsOf: elements) } #endif public init(_ initializer: @escaping (Section) -> Void) { initializer(self) } public init(_ header: String, _ initializer: @escaping (Section) -> Void = { _ in }) { self.header = HeaderFooterView(stringLiteral: header) initializer(self) } public init(header: String, footer: String, _ initializer: (Section) -> Void = { _ in }) { self.header = HeaderFooterView(stringLiteral: header) self.footer = HeaderFooterView(stringLiteral: footer) initializer(self) } public init(footer: String, _ initializer: (Section) -> Void = { _ in }) { self.footer = HeaderFooterView(stringLiteral: footer) initializer(self) } // MARK: SectionDelegate /** * Delegate method called by the framework when one or more rows have been added to the section. */ open func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet) {} /** * Delegate method called by the framework when one or more rows have been removed from the section. */ open func rowsHaveBeenRemoved(_ rows: [BaseRow], at: IndexSet) {} /** * Delegate method called by the framework when one or more rows have been replaced in the section. */ open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: IndexSet) {} // MARK: Private lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(section: self) }() var headerView: UIView? var footerView: UIView? var hiddenCache = false } extension Section: MutableCollection, BidirectionalCollection { // MARK: MutableCollectionType public var startIndex: Int { return 0 } public var endIndex: Int { return kvoWrapper.rows.count } public subscript (position: Int) -> BaseRow { get { if position >= kvoWrapper.rows.count { assertionFailure("Section: Index out of bounds") } return kvoWrapper.rows[position] as! BaseRow } set { if position > kvoWrapper.rows.count { assertionFailure("Section: Index out of bounds") } if position < kvoWrapper.rows.count { let oldRow = kvoWrapper.rows[position] let oldRowIndex = kvoWrapper._allRows.firstIndex(of: oldRow as! BaseRow)! // Remove the previous row from the form kvoWrapper._allRows[oldRowIndex].willBeRemovedFromSection() kvoWrapper._allRows[oldRowIndex] = newValue } else { kvoWrapper._allRows.append(newValue) } kvoWrapper.rows[position] = newValue newValue.wasAddedTo(section: self) } } public subscript (range: Range<Int>) -> ArraySlice<BaseRow> { get { return kvoWrapper.rows.map { $0 as! BaseRow }[range] } set { replaceSubrange(range, with: newValue) } } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } } extension Section: RangeReplaceableCollection { // MARK: RangeReplaceableCollectionType public func append(_ formRow: BaseRow) { kvoWrapper.rows.insert(formRow, at: kvoWrapper.rows.count) kvoWrapper._allRows.append(formRow) formRow.wasAddedTo(section: self) } public func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == BaseRow { kvoWrapper.rows.addObjects(from: newElements.map { $0 }) kvoWrapper._allRows.append(contentsOf: newElements) for row in newElements { row.wasAddedTo(section: self) } } public func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, C.Element == BaseRow { for i in subrange.lowerBound..<subrange.upperBound { if let row = kvoWrapper.rows.object(at: i) as? BaseRow { row.willBeRemovedFromSection() kvoWrapper._allRows.remove(at: kvoWrapper._allRows.firstIndex(of: row)!) } } kvoWrapper.rows.replaceObjects(in: NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound), withObjectsFrom: newElements.map { $0 }) kvoWrapper._allRows.insert(contentsOf: newElements, at: indexForInsertion(at: subrange.lowerBound)) for row in newElements { row.wasAddedTo(section: self) } } public func removeAll(keepingCapacity keepCapacity: Bool = false) { // not doing anything with capacity let rows = kvoWrapper._allRows kvoWrapper.removeAllRows() for row in rows { row.willBeRemovedFromSection() } } @discardableResult public func remove(at position: Int) -> BaseRow { let row = kvoWrapper.rows.object(at: position) as! BaseRow row.willBeRemovedFromSection() kvoWrapper.rows.removeObject(at: position) if let index = kvoWrapper._allRows.firstIndex(of: row) { kvoWrapper._allRows.remove(at: index) } return row } private func indexForInsertion(at index: Int) -> Int { guard index != 0 else { return 0 } let row = kvoWrapper.rows[index-1] if let i = kvoWrapper._allRows.firstIndex(of: row as! BaseRow) { return i + 1 } return kvoWrapper._allRows.count } } extension Section /* Condition */ { // MARK: Hidden/Disable Engine /** Function that evaluates if the section should be hidden and updates it accordingly. */ public final func evaluateHidden() { if let h = hidden, let f = form { switch h { case .function(_, let callback): hiddenCache = callback(f) case .predicate(let predicate): hiddenCache = predicate.evaluate(with: self, substitutionVariables: f.dictionaryValuesToEvaluatePredicate()) } if hiddenCache { form?.hideSection(self) } else { form?.showSection(self) } } } /** Internal function called when this section was added to a form. */ func wasAddedTo(form: Form) { self.form = form addToRowObservers() evaluateHidden() for row in kvoWrapper._allRows { row.wasAddedTo(section: self) } } /** Internal function called to add this section to the observers of certain rows. Called when the hidden variable is set and depends on other rows. */ func addToRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): form?.addRowObservers(to: self, rowTags: tags, type: .hidden) case .predicate(let predicate): form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden) } } /** Internal function called when this section was removed from a form. */ func willBeRemovedFromForm() { for row in kvoWrapper._allRows { row.willBeRemovedFromForm() } removeFromRowObservers() self.form = nil } /** Internal function called to remove this section from the observers of certain rows. Called when the hidden variable is changed. */ func removeFromRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): form?.removeRowObservers(from: self, rowTags: tags, type: .hidden) case .predicate(let predicate): form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden) } } func hide(row: BaseRow) { row.baseCell.cellResignFirstResponder() (row as? BaseInlineRowType)?.collapseInlineRow() kvoWrapper.rows.remove(row) } func show(row: BaseRow) { guard !kvoWrapper.rows.contains(row) else { return } guard var index = kvoWrapper._allRows.firstIndex(of: row) else { return } var formIndex = NSNotFound while formIndex == NSNotFound && index > 0 { index = index - 1 let previous = kvoWrapper._allRows[index] formIndex = kvoWrapper.rows.index(of: previous) } kvoWrapper.rows.insert(row, at: formIndex == NSNotFound ? 0 : formIndex + 1) } } extension Section /* Helpers */ { /** * This method inserts a row after another row. * It is useful if you want to insert a row after a row that is currently hidden. Otherwise use `insert(at: Int)`. * It throws an error if the old row is not in this section. */ public func insert(row newRow: BaseRow, after previousRow: BaseRow) throws { guard let rowIndex = (kvoWrapper._allRows as [BaseRow]).firstIndex(of: previousRow) else { throw EurekaError.rowNotInSection(row: previousRow) } kvoWrapper._allRows.insert(newRow, at: index(after: rowIndex)) show(row: newRow) newRow.wasAddedTo(section: self) } } /** * Navigation options for a form view controller. */ public struct MultivaluedOptions: OptionSet { private enum Options: Int { case none = 0, insert = 1, delete = 2, reorder = 4 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: Options) { self.rawValue = options.rawValue } /// No multivalued. public static let None = MultivaluedOptions(.none) /// Allows user to insert rows. public static let Insert = MultivaluedOptions(.insert) /// Allows user to delete rows. public static let Delete = MultivaluedOptions(.delete) /// Allows user to reorder rows public static let Reorder = MultivaluedOptions(.reorder) } /** * Multivalued sections allows us to easily create insertable, deletable and reorderable sections. By using a multivalued section we can add multiple values for a certain field, such as telephone numbers in a contact. */ open class MultivaluedSection: Section { public var multivaluedOptions: MultivaluedOptions public var showInsertIconInAddButton = true public var addButtonProvider: ((MultivaluedSection) -> ButtonRow) = { _ in return ButtonRow { $0.title = "Add" $0.cellStyle = .value1 }.cellUpdate { cell, _ in cell.textLabel?.textAlignment = .left } } public var multivaluedRowToInsertAt: ((Int) -> BaseRow)? public required init(multivaluedOptions: MultivaluedOptions = MultivaluedOptions.Insert.union(.Delete), header: String = "", footer: String = "", _ initializer: (MultivaluedSection) -> Void = { _ in }) { self.multivaluedOptions = multivaluedOptions super.init(header: header, footer: footer, {section in initializer(section as! MultivaluedSection) }) guard multivaluedOptions.contains(.Insert) else { return } initialize() } public required init() { self.multivaluedOptions = MultivaluedOptions.Insert.union(.Delete) super.init() initialize() } #if swift(>=4.1) public required init<S>(_ elements: S) where S : Sequence, S.Element == BaseRow { self.multivaluedOptions = MultivaluedOptions.Insert.union(.Delete) super.init(elements) initialize() } #endif func initialize() { let addRow = addButtonProvider(self) addRow.onCellSelection { cell, row in guard !row.isDisabled else { return } guard let tableView = cell.formViewController()?.tableView, let indexPath = row.indexPath else { return } cell.formViewController()?.tableView(tableView, commit: .insert, forRowAt: indexPath) } self <<< addRow } /** Method used to get all the values of the section. - returns: An Array mapping the row values. [value] */ public func values() -> [Any?] { return kvoWrapper._allRows.filter({ $0.baseValue != nil }).map({ $0.baseValue }) } }
dd2a483ada682d8dc131fa3718f7288a
35.531716
218
0.624585
false
false
false
false
Gatada/Bits
refs/heads/master
Sources/JBits/UIKit/Custom/DividerView.swift
gpl-3.0
1
// // DividerView.swift // JBits // // Created by Johan H. W. L. Basberg on 17/08/2017. // Copyright © 2017 Johan Basberg. All rights reserved. // import UIKit /// Creates a view with an optional hairline at the top, and optional hairline at the bottom. class DividerView: UIView { @IBInspectable var hairlineColor: UIColor? = nil @IBInspectable var showLineTop: Bool = false @IBInspectable var showLineBottom: Bool = true @IBInspectable var weightTop: CGFloat = 1 / UIScreen.main.scale @IBInspectable var weightBottom: CGFloat = 1 / UIScreen.main.scale var dividerTop, dividerBottom: UIView? override func didMoveToSuperview() { super.didMoveToSuperview() self.backgroundColor = UIColor(named: "Dark")?.withAlphaComponent(0.1) } override func layoutSubviews() { super.layoutSubviews() setup() } func setup() { var constraints = [NSLayoutConstraint]() let color = (hairlineColor ?? UIColor.systemGray).withAlphaComponent(0.5) if showLineTop && dividerTop == nil { let topHairline = UIView() topHairline.backgroundColor = color topHairline.translatesAutoresizingMaskIntoConstraints = false addSubview(topHairline) dividerTop = topHairline let views: [String: UIView] = ["divider": topHairline] constraints += NSLayoutConstraint.constraints(withVisualFormat: "|[divider]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[divider(height)]", options: [], metrics: ["height": weightTop], views: views) } if showLineBottom && dividerBottom == nil { dividerBottom = UIView() dividerBottom!.backgroundColor = color dividerBottom!.translatesAutoresizingMaskIntoConstraints = false addSubview(dividerBottom!) let views: [String: UIView] = ["divider": dividerBottom!] constraints += NSLayoutConstraint.constraints(withVisualFormat: "|[divider]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[divider(height)]|", options: [], metrics: ["height": weightBottom], views: views) } NSLayoutConstraint.activate(constraints) } }
24624bc2d191f391d7f5c50dcd91c40c
36.430769
161
0.643239
false
false
false
false
borglab/SwiftFusion
refs/heads/main
Sources/SwiftFusion/Core/Timer.swift
apache-2.0
1
import Foundation /// Utilities for timing and couting regions of code. /// /// NOT threadsafe, which we should probably fix soon. fileprivate var startedTimers: [String: UInt64] = [:] fileprivate var accumulatedTimers: [String: UInt64] = [:] /// Start the `name` timer. /// /// Precondition: The `name` timer is not running. public func startTimer(_ name: String) { guard startedTimers[name] == nil else { preconditionFailure("timer \(name) is already started") } startedTimers[name] = DispatchTime.now().uptimeNanoseconds } /// Stop the `name` timer. /// /// Precondition: The `name` timer is running. public func stopTimer(_ name: String) { guard let start = startedTimers[name] else { preconditionFailure("timer \(name) is not running") } startedTimers[name] = nil accumulatedTimers[name, default: 0] += DispatchTime.now().uptimeNanoseconds - start } /// Print the total times accumulated for each timer. public func printTimers() { guard startedTimers.count == 0 else { preconditionFailure("timers are still running: \(startedTimers)") } for (name, duration) in accumulatedTimers { print("\(name): \(Double(duration) / 1e9) seconds") } } fileprivate var counters: [String: Int] = [:] /// Increment the `name` counter. public func incrementCounter(_ name: String) { counters[name, default: 0] += 1 } /// Print the total counts for each counter. public func printCounters() { for (name, count) in counters { print("\(name): \(count)") } }
d7b1252db911bb95357340cfdb19925f
30.489362
107
0.7
false
false
false
false
weyert/Whisper
refs/heads/master
Source/WhistleFactory.swift
mit
1
import UIKit public enum WhistleAction { case Present case Show(NSTimeInterval) } let whistleFactory = WhistleFactory() public func whistle(murmur: Murmur, action: WhistleAction = .Show(1.5)) { guard !WhistleBlows() else { return } whistleFactory.whistler(murmur, action: action) } public func calm(after after: NSTimeInterval = 0) { whistleFactory.calm(after: after) } public func WhistleBlows() -> Bool { return whistleFactory.blows } public class WhistleFactory: UIViewController { public lazy var whistleWindow: UIWindow = UIWindow() public lazy var titleLabelHeight = CGFloat(20.0) public lazy var titleLabel: UILabel = { let label = UILabel() label.textAlignment = .Center return label }() public var duration: NSTimeInterval = 2 public var viewController: UIViewController? public var hideTimer = NSTimer() public var blows = false // MARK: - Initializers override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nil, bundle: nil) setupWindow() view.clipsToBounds = true view.addSubview(titleLabel) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WhistleFactory.orientationDidChange), name: UIDeviceOrientationDidChangeNotification, object: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil) } // MARK: - Configuration public func whistler(murmur: Murmur, action: WhistleAction) { titleLabel.text = murmur.title titleLabel.font = murmur.font titleLabel.textColor = murmur.titleColor view.backgroundColor = murmur.backgroundColor whistleWindow.backgroundColor = murmur.backgroundColor moveWindowToFront() setupFrames() switch action { case .Show(let duration): show(duration: duration) default: present() } } // MARK: - Setup public func setupWindow() { whistleWindow.addSubview(self.view) whistleWindow.clipsToBounds = true moveWindowToFront() } func moveWindowToFront() { let currentStatusBarStyle = UIApplication.sharedApplication().statusBarStyle whistleWindow.windowLevel = UIWindowLevelStatusBar UIApplication.sharedApplication().setStatusBarStyle(currentStatusBarStyle, animated: false) } public func setupFrames() { whistleWindow = UIWindow() setupWindow() let labelWidth = UIScreen.mainScreen().bounds.width let defaultHeight = titleLabelHeight if let text = titleLabel.text { let neededDimensions = NSString(string: text).boundingRectWithSize( CGSize(width: labelWidth, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil ) titleLabelHeight = CGFloat(neededDimensions.size.height) titleLabel.numberOfLines = 0 // Allows unwrapping if titleLabelHeight < defaultHeight { titleLabelHeight = defaultHeight } } else { titleLabel.sizeToFit() } whistleWindow.frame = CGRect(x: 0, y: 0, width: labelWidth, height: titleLabelHeight) view.frame = whistleWindow.bounds titleLabel.frame = view.bounds } // MARK: - Movement methods public func show(duration duration: NSTimeInterval) { present() calm(after: duration) } public func present() { hideTimer.invalidate() blows = true let initialOrigin = whistleWindow.frame.origin.y whistleWindow.frame.origin.y = initialOrigin - titleLabelHeight whistleWindow.makeKeyAndVisible() UIView.animateWithDuration(0.2, animations: { self.whistleWindow.frame.origin.y = initialOrigin }) } public func hide() { let finalOrigin = view.frame.origin.y - titleLabelHeight UIView.animateWithDuration(0.2, animations: { self.whistleWindow.frame.origin.y = finalOrigin }, completion: { _ in self.blows = false if let window = UIApplication.sharedApplication().windows.filter({ $0 != self.whistleWindow }).first { window.makeKeyAndVisible() self.whistleWindow.windowLevel = UIWindowLevelNormal - 1 window.rootViewController?.setNeedsStatusBarAppearanceUpdate() } }) } public func calm(after after: NSTimeInterval) { hideTimer.invalidate() hideTimer = NSTimer.scheduledTimerWithTimeInterval(after, target: self, selector: #selector(WhistleFactory.timerDidFire), userInfo: nil, repeats: false) } // MARK: - Timer methods public func timerDidFire() { hide() } func orientationDidChange() { if whistleWindow.keyWindow { setupFrames() hide() } } }
f66eb1e8c613e635531ba35a4062c415
26.75
177
0.706183
false
false
false
false
SVKorosteleva/heartRateMonitor
refs/heads/master
HeartMonitor/HeartMonitor/DataStorageManager.swift
mit
1
// // DataStorageManager.swift // HeartMonitor // // Created by Светлана Коростелёва on 8/10/17. // Copyright © 2017 home. All rights reserved. // import CoreData class DataStorageManager { private(set) static var shared = DataStorageManager() private(set) var settingsManager: SettingsStorageManager? private(set) var trainingsManager: TrainingsStorageManager? private lazy var model: NSManagedObjectModel? = self.dataModel() private lazy var storeCoordinator: NSPersistentStoreCoordinator? = self.persistentStoreCoordinator() private var context: NSManagedObjectContext? private var documentsPath: URL? { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last } private init() { self.context = managedObjectContext() if let context = self.context { self.settingsManager = SettingsStorageManager(context: context) self.trainingsManager = TrainingsStorageManager(context: context) } } private func dataModel() -> NSManagedObjectModel? { guard let url = Bundle.main.url(forResource: "HeartRateDataModel", withExtension: "momd") else { return nil } return NSManagedObjectModel(contentsOf: url) } private func persistentStoreCoordinator() -> NSPersistentStoreCoordinator? { guard let model = model else { return nil } let storeUrl = documentsPath?.appendingPathComponent("DataStorage.sqlite") let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) guard let _ = try? storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: nil) else { return nil } return storeCoordinator } private func managedObjectContext() -> NSManagedObjectContext? { guard let storeCoordinator = storeCoordinator else { return nil } let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) context.persistentStoreCoordinator = storeCoordinator return context } }
03af6210025eafbf0425a948a951ef2a
35.323077
92
0.640407
false
false
false
false
brokenhandsio/AWSwift
refs/heads/master
Sources/AWSwift/Signing/HeaderSignerGenerator.swift
mit
1
import Foundation import CryptoSwift struct HeaderSignerGenerator: Aws4Signer { fileprivate var awsAccessId: String fileprivate var awsAccessSecret: String init(awsAccessId: String, awsAccessSecret: String) { self.awsAccessId = awsAccessId self.awsAccessSecret = awsAccessSecret } // Move all the variables into a protocol `requestObject` func getAuthHeader(forRequest request: [String : Any], requestDate: Date, service: AwsService, region: AwsRegion, requestMethod: HttpMethod) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" let requestDateString = formatter.string(from: requestDate) let headers = [ "Content-Type": "application/x-amz-json-1.0", "Host": "\(service.getServiceHostname()).\(region.rawValue).amazonaws.com", "X-AMZ-Date": requestDateString ] let signedHeaders = Array(headers.keys) let jsonData = try? JSONSerialization.data(withJSONObject: request, options: .prettyPrinted) let jsonString = String(data: jsonData!, encoding: .utf8) let canonicalRequestHash = createCanonicalRequestHash(method: requestMethod, uri: nil, query: nil, headers: headers, signedHeaders: signedHeaders, body: jsonString) let credentialsHeader = createCredentialsHeader(awsAccessId: self.awsAccessId, requestDate: requestDate, region: region, service: service) let signingKey = createSigningKey(awsAccessSecret: self.awsAccessSecret, requestDate: requestDate, region: region, service: service) let signingString = createSigningString(requestDate: requestDate, region: region, service: service, canonicalRequestHash: canonicalRequestHash) let signature = createSignature(signingKey: signingKey, signingString: signingString) let authHeader = createAuthorizationHeader(credentialsHeader: credentialsHeader, signedHeaders: signedHeaders, signature: signature) return authHeader } internal func createCanonicalRequestHash(method: HttpMethod, uri: String?, query: String?, headers: [String : String], signedHeaders: [String], body: String?) -> String{ // HTTP Method var canonicalRequest = "\(method.rawValue)\n" // URI if let uri = uri { canonicalRequest += uri } else { canonicalRequest += "/" } canonicalRequest += "\n" // Query if let query = query { canonicalRequest += query } canonicalRequest += "\n" // Headers // Header keys must be in alphabetical order and lowercase and trimmed // TODO need to trim let sortedKeys = Array(headers.keys).sorted() for key in sortedKeys { canonicalRequest += "\(key.lowercased()):\(headers[key]!)\n" } canonicalRequest += "\n" // Signed Headers canonicalRequest += getSignedHeadersString(signedHeaders) canonicalRequest += "\n" // Payload Hash var bodyPayload = "" if let body = body { bodyPayload = body } canonicalRequest += bodyPayload.sha256() // Return SHA256 return canonicalRequest.sha256() } internal func createSigningString(requestDate: Date, region: AwsRegion, service: AwsService, canonicalRequestHash: String) -> String { let formatter = DateFormatter() let dateOnlyFormatter = DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" dateOnlyFormatter.dateFormat = "yyyyMMdd" // Algorithm var signingString = "AWS4-HMAC-SHA256\n" // Request Date // TODO convert to UTC signingString += "\(formatter.string(from: requestDate))\n" // Credentials Scope signingString += "\(dateOnlyFormatter.string(from: requestDate))/\(region.rawValue)/\(service.getServiceHostname())/aws4_request\n" // Hashed Canonical Request signingString += "\(canonicalRequestHash)" return signingString } internal func createSigningKey(awsAccessSecret: String, requestDate: Date, region: AwsRegion, service: AwsService) -> Array<UInt8> { // TODO sort out unwraps let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" let kDate = try? HMAC(key: "AWS4\(awsAccessSecret)", variant: .sha256).authenticate([UInt8](formatter.string(from: requestDate).utf8)) let kRegion = try? HMAC(key: kDate!, variant: .sha256).authenticate([UInt8](region.rawValue.utf8)) let kService = try? HMAC(key: kRegion!, variant: .sha256).authenticate([UInt8](service.getServiceHostname().utf8)) let kSigning = try? HMAC(key: kService!, variant: .sha256).authenticate([UInt8]("aws4_request".utf8)) return kSigning! } internal func createSignature(signingKey: Array<UInt8>, signingString: String) -> String { let signatureBytes = try? HMAC(key: signingKey, variant: .sha256).authenticate([UInt8](signingString.utf8)) let hexString = NSMutableString() for byte in signatureBytes! { hexString.appendFormat("%02x", UInt(byte)) } let signature = String(hexString) return signature } internal func createCredentialsHeader(awsAccessId: String, requestDate: Date, region: AwsRegion, service: AwsService) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" let credentialsHeader = "\(awsAccessId)/\(formatter.string(from: requestDate))/\(region.rawValue)/\(service.getServiceHostname())/aws4_request" return credentialsHeader } internal func createAuthorizationHeader(credentialsHeader: String, signedHeaders: [String], signature: String) -> String { let signedHeaderString = getSignedHeadersString(signedHeaders) let authHeader = "AWS4-HMAC-SHA256 Credential=\(credentialsHeader), SignedHeaders=\(signedHeaderString), Signature=\(signature)" return authHeader } internal func getSignedHeadersString(_ signedHeaders: [String]) -> String { let sortedSignedHeaderKeys = signedHeaders.sorted() let signedHeaderUppercase = sortedSignedHeaderKeys.joined(separator: ";") let signedHeadersString = signedHeaderUppercase.lowercased() return signedHeadersString } }
bdaa6b84b78bd3ea8f6c5175a73988b1
39.957576
173
0.64013
false
false
false
false
guardianproject/poe
refs/heads/master
Example/POE/RootViewController.swift
bsd-3-clause
1
// // RootViewController.swift // POE // // Created by Benjamin Erhart on 05.04.17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import POE class RootViewController: UIViewController, POEDelegate { let introVC = IntroViewController() var bridgeVC: UINavigationController? let conctVC = ConnectingViewController() let errorVC = ErrorViewController() var connectionSteps = [DispatchWorkItem]() public init() { super.init(nibName: "LaunchScreen", bundle: Bundle(for: RootViewController.classForCoder())) // You can register yourself here explicitly, or rely on the fact, // that you're the presenting view controller, which is also supported. // In that case you can simplify that code to a direct initialization // without the need to make bridgeVC optional. bridgeVC = BridgeSelectViewController.instantiate( currentId: UserDefaults.standard.integer(forKey: "use_bridges"), noBridgeId: 0, providedBridges: [1: "obfs4", 2: "meek-amazon", 3: "meek-azure"], customBridgeId: 99, customBridges: UserDefaults.standard.stringArray(forKey: "custom_bridges"), delegate: self) introVC.modalTransitionStyle = .crossDissolve conctVC.modalTransitionStyle = .crossDissolve errorVC.modalTransitionStyle = .crossDissolve } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if UserDefaults.standard.bool(forKey: "did_intro") { conctVC.autoClose = true present(conctVC, animated: animated, completion: nil) connect() } else { present(introVC, animated: animated, completion: nil) } } // MARK: - POEDelegate /** Callback, after the user finished the intro and selected, if she wants to use a bridge or not. - parameter useBridge: true, if user selected to use a bridge, false, if not. */ func introFinished(_ useBridge: Bool) { UserDefaults.standard.set(true, forKey: "did_intro") if useBridge { introVC.present(bridgeVC!, animated: true) return } UserDefaults.standard.set(0, forKey: "use_bridge") introVC.present(conctVC, animated: true) connect() } /** Receive this callback, after the user finished the bridges configuration. - parameter bridgesId: the selected ID of the list you gave in the constructor of BridgeSelectViewController. - parameter customBridges: the list of custom bridges the user configured. */ func bridgeConfigured(_ bridgesId: Int, customBridges: [String]) { UserDefaults.standard.set(bridgesId, forKey: "use_bridges") UserDefaults.standard.set(customBridges, forKey: "custom_bridges") if conctVC.presentingViewController != nil { // Already showing - do connection again from beginning. connect() } else { // Not showing - present the ConnectingViewController and start connecting afterwards. introVC.present(conctVC, animated: true, completion: { self.connect() }) } } /** Receive this callback, when the user pressed the gear icon in the ConnectingViewController. This probably means, the connection doesn't work and the user wants to configure bridges. Cancel the connection here and show the BridgeSelectViewController afterwards. */ func changeSettings() { cancel() conctVC.present(bridgeVC!, animated: true) } /** Callback, after the user pressed the "Start Browsing" button. */ func userFinishedConnecting() { conctVC.present(errorVC, animated: true) } // MARK: - Private private func connect() { conctVC.connectingStarted() connectionSteps = [ DispatchWorkItem { self.conctVC.updateProgress(0.25) }, DispatchWorkItem { self.conctVC.updateProgress(0.5) }, DispatchWorkItem { self.conctVC.updateProgress(0.75) }, DispatchWorkItem { self.conctVC.updateProgress(1) }, DispatchWorkItem { self.conctVC.connectingFinished() }, ] var count = 0.0 for step in connectionSteps { count += 1 DispatchQueue.main.asyncAfter(deadline: .now() + count, execute: step) } } private func cancel() { for step in connectionSteps { step.cancel() } connectionSteps = [] } }
f263ab44ca9a5ff01bc183260ac83fe4
30.927152
98
0.6285
false
false
false
false
huonw/swift
refs/heads/master
test/decl/ext/generic.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift protocol P1 { associatedtype AssocType } protocol P2 : P1 { } protocol P3 { } struct X<T : P1, U : P2, V> { struct Inner<A, B : P3> { } struct NonGenericInner { } } extension Int : P1 { typealias AssocType = Int } extension Double : P2 { typealias AssocType = Double } extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} typealias GGG = X<Int, Double, String> extension GGG { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { let x = 0 } extension LValueCheck { init(newY: Int) { x = 42 } } // Member type references into another extension. struct MemberTypeCheckA<T> { } protocol MemberTypeProto { associatedtype AssocType func foo(_ a: AssocType) init(_ assoc: MemberTypeCheckA<AssocType>) } struct MemberTypeCheckB<T> : MemberTypeProto { func foo(_ a: T) {} typealias Element = T var t1: T } extension MemberTypeCheckB { typealias Underlying = MemberTypeCheckA<T> } extension MemberTypeCheckB { init(_ x: Underlying) { } } extension MemberTypeCheckB { var t2: Element { return t1 } } // rdar://problem/19795284 extension Array { var pairs: [(Element, Element)] { get { return [] } } } // rdar://problem/21001937 struct GenericOverloads<T, U> { var t: T var u: U init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 0 } subscript (i: Int) -> Int { return i } } extension GenericOverloads where T : P1, U : P2 { init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 1 } subscript (i: Int) -> Int { return i } } extension Array where Element : Hashable { var worseHashEver: Int { var result = 0 for elt in self { result = (result << 1) ^ elt.hashValue } return result } } func notHashableArray<T>(_ x: [T]) { x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}} } func hashableArray<T : Hashable>(_ x: [T]) { // expected-warning @+1 {{unused}} x.worseHashEver // okay } func intArray(_ x: [Int]) { // expected-warning @+1 {{unused}} x.worseHashEver } class GenericClass<T> { } extension GenericClass where T : Equatable { func foo(_ x: T, y: T) -> Bool { return x == y } } func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) { _ = gc.foo(x, y: y) } func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) { gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}} } extension Array where Element == String { } extension GenericClass : P3 where T : P3 { } extension GenericClass where Self : P3 { } // expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}} // expected-error@-2{{type 'GenericClass<T>' in conformance requirement does not refer to a generic parameter or associated type}} protocol P4 { associatedtype T init(_: T) } protocol P5 { } struct S4<Q>: P4 { init(_: Q) { } } extension S4 where T : P5 {} struct S5<Q> { init(_: Q) { } } extension S5 : P4 {} // rdar://problem/21607421 public typealias Array2 = Array extension Array2 where QQQ : VVV {} // expected-error@-1 {{use of undeclared type 'QQQ'}} // expected-error@-2 {{use of undeclared type 'VVV'}}
f216aeaf7713db9ada7f8ac027629558
20.423529
181
0.65486
false
false
false
false
izotx/iTenWired-Swift
refs/heads/master
Conference App/FNBJSocialFeed/FacebookCell.swift
bsd-2-clause
1
// // FacebookCell.swift // FNBJSocialFeed // // Created by Felipe on 5/27/16. // Copyright © 2016 Academic Technology Center. All rights reserved. // import UIKit class FacebookCell: UITableViewCell { @IBOutlet weak var message: UILabel! @IBOutlet weak var name: UILabel! @IBOutlet weak var imageLabel: UIImageView! @IBOutlet weak var postImage: UIImageView! let defaults = NSUserDefaults.standardUserDefaults() func build(post: FNBJSocialFeedFacebookPost){ self.message.text = post.message self.name.text = post.fromName self.postImage.image = UIImage(named: "placeholder.png") self.imageLabel.image = UIImage(named: "placeholder.png") if let profileImageLink = defaults.stringForKey(post.userID) { let URL = NSURL(string: profileImageLink) self.imageLabel.hnk_setImageFromURL(URL!) }else{ let controller = FNBJSocialFeedFacebookController(pageID: "itenwired") controller.getUserProfile(post.userID, completion: { (user) in self.defaults.setObject(user.profilePicture, forKey: post.userID) let URL = NSURL(string: user.profilePicture) self.imageLabel.hnk_setImageFromURL(URL!) }) } if post.type != "link"{ if let link = defaults.stringForKey(post.object_id){ let URL = NSURL(string: link) self.postImage.hnk_setImageFromURL(URL!) } else{ fetchImage(post.object_id) } }else{ let URL = NSURL(string: post.picture) self.postImage.hnk_setImageFromURL(URL!) } } func fetchImage(object_id: String){ let controller = FNBJSocialFeedFacebookController(pageID: "itenwired") controller.getPostImage(withObjectId: object_id) { (imageUrl) in self.defaults.setObject(imageUrl, forKey: object_id) let URL = NSURL(string: imageUrl) self.postImage.hnk_setImageFromURL(URL!) } } }
b71bec0b8508768c1c69c6bd6a39607c
29.767123
82
0.579252
false
false
false
false
WSDOT/wsdot-ios-app
refs/heads/master
wsdot/BorderWaitItem.swift
gpl-3.0
2
// // BorderWaitItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import RealmSwift class BorderWaitItem: Object { @objc dynamic var id: Int = 0 @objc dynamic var route: Int = 0 @objc dynamic var waitTime: Int = 0 @objc dynamic var name: String = "" @objc dynamic var lane: String = "" @objc dynamic var direction: String = "" @objc dynamic var updated: String = "" @objc dynamic var selected: Bool = false @objc dynamic var delete: Bool = false override static func primaryKey() -> String? { return "id" } }
83b821776dead4ebe6bb601f98f6bcec
32.421053
72
0.693701
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Client/Frontend/Home/HomePanels.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared /** * Data for identifying and constructing a HomePanel. */ struct HomePanelDescriptor { let makeViewController: (_ profile: Profile) -> UIViewController let imageName: String let accessibilityLabel: String let accessibilityIdentifier: String } class HomePanels { let enabledPanels = [ HomePanelDescriptor( makeViewController: { profile in return ActivityStreamPanel(profile: profile) }, imageName: "TopSites", accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.TopSites"), HomePanelDescriptor( makeViewController: { profile in let bookmarks = BookmarksPanel() bookmarks.profile = profile let controller = UINavigationController(rootViewController: bookmarks) controller.setNavigationBarHidden(true, animated: false) // this re-enables the native swipe to pop gesture on UINavigationController for embedded, navigation bar-less UINavigationControllers // don't ask me why it works though, I've tried to find an answer but can't. // found here, along with many other places: // http://luugiathuy.com/2013/11/ios7-interactivepopgesturerecognizer-for-uinavigationcontroller-with-hidden-navigation-bar/ controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "Bookmarks", accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.Bookmarks"), HomePanelDescriptor( makeViewController: { profile in let history = HistoryPanel() history.profile = profile let controller = UINavigationController(rootViewController: history) controller.setNavigationBarHidden(true, animated: false) controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "History", accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.History"), HomePanelDescriptor( makeViewController: { profile in let controller = ReadingListPanel() controller.profile = profile return controller }, imageName: "ReadingList", accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.ReadingList"), ] }
f8d3f02cd865b0cc5ca230363ea7821e
44.161765
150
0.643113
false
false
false
false
iosprogrammingwithswift/iosprogrammingwithswift
refs/heads/master
04_Swift2015.playground/Pages/01_The Basics.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) | [Next](@next) print("Hallo Würzburg 🌟") // DAs ist ein Kommentar /* * Das auch! */ //MARK: Das ist meine Wichtige Section //: ## Simple Values //: //: Use `let` to make a constant and `var` to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places. //: var myVariable = 42 myVariable = 50 let myConstant = 42 //myConstant = 32 //: A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that `myVariable` is an integer because its initial value is an integer. //: //: If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon. //: let implicitInteger = 70 let implicitDouble = 70.0 let explicitInt:Int = 70 let explicitDouble: Double = 70 //: > **Experiment**: //: > Create a constant with an explicit type of `Float` and a value of `4`. //: //: Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type. //: let label = "The width is " let width = 94 let widthLabel = label + String(width) //: > **Experiment**: //: > Try removing the conversion to `String` from the last line. What error do you get? //: //: There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (`\`) before the parentheses. For example: //: //: > **Experiment**: //: > Use `\()` to include a floating-point calculation in a string and to include someone’s name in a greeting. //: let π = 3.14159 let 你好 = "你好世界" let 🐶🐮 = "dogcow🐶🐮" //: Printing Constants and Variables //: semicolon //MARK: syntax sugar //: Bounds UInt8.min UInt8.max //: Tuples // Constructing a simple tuple // Constructing a named tuple // Different types // Accessing tuple elements //: Ignoring Values During Decomposition //:Named Tuples //: das Json des kleinen Mannes //: Tuples in methods func origin() -> (Double, Double, Double) { //... return (1.0, 2.0, 1.5) } /*: largely Based of [Apple's Swift Language Guide: The Basics](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 ) */ //: [Previous](@previous) | [Next](@next)
2bb0b32ea288bc1c0b6b7dffad539928
25.971963
395
0.710672
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Views/Pickers/Pickers/Pickers/DependentComponentPickerViewController.swift
mit
1
// // DependentComponentPickerViewController.swift // Pickers // // Created by Domenico on 20.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class DependentComponentPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { fileprivate let stateComponent = 0 fileprivate let zipComponent = 1 fileprivate var stateZips:[String : [String]]! fileprivate var states:[String]! fileprivate var zips:[String]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let bundle = Bundle.main // It returns an URL let plistURL = bundle.url(forResource: "statedictionary", withExtension: "plist") stateZips = NSDictionary(contentsOf: plistURL!) as! [String : [String]] let allStates = stateZips.keys states = allStates.sorted() let selectedState = states[0] zips = stateZips[selectedState] } @IBOutlet weak var dependentPicker: UIPickerView! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ @IBAction func buttonPressed(_ sender: UIButton) { let stateRow = dependentPicker.selectedRow(inComponent: stateComponent) let zipRow = dependentPicker.selectedRow(inComponent: zipComponent) let state = states[stateRow] let zip = zips[zipRow] let title = "You selected zip code \(zip)" let message = "\(zip) is in \(state)" let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) let action = UIAlertAction( title: "OK", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } // MARK:- // MARK: Picker Data Source Methods func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == stateComponent{ return states.count }else{ return zips.count } } // MARK:- // MARK: Picker Delegate Methods func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let selectedState = states[row] zips = stateZips[selectedState] dependentPicker.reloadComponent(zipComponent) dependentPicker.selectRow(0, inComponent: zipComponent, animated: true) } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { if component == stateComponent{ return states[row] }else{ return zips[row] } } /// Check how wide should be each component in the picker func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { let pickerWidth = pickerView.bounds.size.width if component == zipComponent { return pickerWidth/3 } else { return 2 * pickerWidth/3 } } }
3791a39d7f52daf64ae7c4fbdca63a88
29.576
111
0.619309
false
false
false
false
snakajima/SwipeBrowser
refs/heads/master
ios/SwipeBrowser/SwipeBrowser/SwipePrefetcher.swift
mit
1
// // SwipePrefetcher.swift // sample // // Created by satoshi on 10/12/15. // Copyright © 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) import Cocoa #else import UIKit #endif private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { NSLog(text) } } class SwipePrefetcher { private var urls = [URL:String]() private var urlsFetching = [URL]() private var urlsFetched = [URL:URL]() private var urlsFailed = [URL]() private var errors = [NSError]() private var fComplete = false private var _progress = Float(0) var progress:Float { return _progress } init(urls:[URL:String]) { self.urls = urls } func start(_ callback:@escaping (Bool, [URL], [NSError]) -> Void) { if fComplete { MyLog("SWPrefe already completed", level:1) callback(true, self.urlsFailed, self.errors) return } let manager = SwipeAssetManager.sharedInstance() var count = 0 _progress = 0 let fileManager = FileManager.default for (url,prefix) in urls { if url.scheme == "file" { if fileManager.fileExists(atPath: url.path) { urlsFetched[url] = url } else { // On-demand resource support urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil) MyLog("SWPrefe onDemand resource at \(urlsFetched[url]) instead of \(url)", level:1) } } else { count += 1 urlsFetching.append(url) manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, type:String?, error:NSError?) -> Void in if let urlL = urlLocal { self.urlsFetched[url] = urlL } else { self.urlsFailed.append(url) if let error = error { self.errors.append(error) } } count -= 1 if (count == 0) { self.fComplete = true self._progress = 1 MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1) callback(true, self.urlsFailed, self.errors) } else { self._progress = Float(self.urls.count - count) / Float(self.urls.count) callback(false, self.urlsFailed, self.errors) } }) } } if count == 0 { self.fComplete = true self._progress = 1 callback(true, urlsFailed, errors) } } func append(_ urls:[URL:String], callback:@escaping (Bool, [URL], [NSError]) -> Void) { let manager = SwipeAssetManager.sharedInstance() var count = 0 _progress = 0 let fileManager = FileManager.default for (url,prefix) in urls { self.urls[url] = prefix if url.scheme == "file" { if fileManager.fileExists(atPath: url.path) { urlsFetched[url] = url } else { // On-demand resource support urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil) MyLog("SWPrefe onDemand resource at \(urlsFetched[url]) instead of \(url)", level:1) } } else { count += 1 urlsFetching.append(url) manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, type:String?, error:NSError?) -> Void in if let urlL = urlLocal { self.urlsFetched[url] = urlL } else if let error = error { self.urlsFailed.append(url) self.errors.append(error) } count -= 1 if (count == 0) { self.fComplete = true self._progress = 1 MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1) callback(true, self.urlsFailed, self.errors) } else { self._progress = Float(self.urls.count - count) / Float(self.urls.count) callback(false, self.urlsFailed, self.errors) } }) } } if count == 0 { self.fComplete = true self._progress = 1 callback(true, urlsFailed, errors) } } func map(_ url:URL) -> URL? { return urlsFetched[url] } static func extensionForType(_ memeType:String) -> String { let ext:String if memeType == "video/quicktime" { ext = ".mov" } else if memeType == "video/mp4" { ext = ".mp4" } else { ext = "" } return ext } static func isMovie(_ mimeType:String) -> Bool { return mimeType == "video/quicktime" || mimeType == "video/mp4" } }
0e079aa3747fa620994844e0afe7e177
34.012903
140
0.482587
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/BestPrice/DiscountInfoView.swift
mit
1
class DiscountInfoView: HLAutolayoutView { fileprivate struct Consts { static let backgroundHorizontalMargin: CGFloat = 15 static let right: CGFloat = 15 static let textHorizontalMargin: CGFloat = 15 static let backgroundTop: CGFloat = 13 static let textTop: CGFloat = 22 static let between: CGFloat = 3 static let textBottom: CGFloat = 10 static let backgroundbottom: CGFloat = 0 } let titleLabel = UILabel() let subtitleLabel = UILabel() let backgroundRoundView = UIView() override func initialize() { createSubviews() updateConstraintsIfNeeded() } private func createSubviews() { backgroundRoundView.backgroundColor = UIColor(hex: 0xEFF3F5) backgroundRoundView.layer.cornerRadius = 6 addSubview(backgroundRoundView) titleLabel.font = DiscountInfoView.titleFont() titleLabel.textColor = JRColorScheme.discountColor() addSubview(titleLabel) subtitleLabel.font = DiscountInfoView.subtitleFont() subtitleLabel.textColor = JRColorScheme.lightTextColor() subtitleLabel.numberOfLines = 0 addSubview(subtitleLabel) } fileprivate class func titleFont() -> UIFont { return UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium) } fileprivate class func subtitleFont() -> UIFont { return UIFont.systemFont(ofSize: 13) } override func setupConstraints() { super.setupConstraints() let insets = UIEdgeInsets(top: Consts.backgroundTop, left: Consts.backgroundHorizontalMargin, bottom: Consts.backgroundbottom, right: Consts.backgroundHorizontalMargin) backgroundRoundView.autoPinEdgesToSuperviewEdges(with: insets) titleLabel.autoPinEdge(.leading, to: .leading, of: backgroundRoundView, withOffset: Consts.textHorizontalMargin) titleLabel.autoPinEdge(toSuperviewEdge: .top, withInset: Consts.textTop) subtitleLabel.autoPinEdge(.leading, to: .leading, of: backgroundRoundView, withOffset: Consts.textHorizontalMargin) subtitleLabel.autoPinEdge(.trailing, to: .trailing, of: backgroundRoundView, withOffset: -Consts.textHorizontalMargin) subtitleLabel.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: Consts.between) subtitleLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: Consts.textBottom) } func configure(for room: HDKRoom, currency: HDKCurrency, duration: Int) { titleLabel.text = DiscountInfoView.titleText(room: room) subtitleLabel.text = DiscountInfoView.subtitleText(room: room, currency: currency, duration: duration) } class func titleText(room: HDKRoom) -> String { let format = NSLS("HL_HOTEL_DETAIL_DISCOUNT_PERCENT") let discount = "\(abs(room.discount))%" return String(format: format, discount) } class func subtitleText(room: HDKRoom, currency: HDKCurrency, duration: Int) -> String { var format, price: String format = NSLSP("HL_HOTEL_DETAIL_DISCOUNT_OLD_PRICE", Float(duration)) price = StringUtils.priceString(withPrice: room.oldPrice, currency: currency) return String(format: format, price, duration) } class func preferredHeight(containerWidth: CGFloat, room: HDKRoom, currency: HDKCurrency, duration: Int) -> CGFloat { let textWidth = containerWidth - Consts.backgroundHorizontalMargin * 2 - Consts.textHorizontalMargin * 2 let titleHeight = titleText(room: room).hl_height(attributes: [NSAttributedString.Key.font: titleFont()], width: textWidth) let attr = [NSAttributedString.Key.font: subtitleFont()] let subtitle = subtitleText(room: room, currency: currency, duration: duration) let subtitleHeight = subtitle.hl_height(attributes: attr, width: textWidth) return titleHeight + subtitleHeight + Consts.textTop + Consts.between + Consts.textBottom } }
1a8f07934309f052c7c59c9a4111777f
42.615385
176
0.707735
false
false
false
false
radubozga/Freedom
refs/heads/master
Sources/DynamicButtonStyles/DynamicButtonStyleCaretLeft.swift
apache-2.0
2
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * 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 /// Left caret style: ‹ struct DynamicButtonStyleCaretLeft: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let thirdSize = size / 3 let sixthSize = size / 6 let a = CGPoint(x: center.x - sixthSize, y: center.y) let b = CGPoint(x: center.x + sixthSize, y: center.y + thirdSize) let c = CGPoint(x: center.x + sixthSize, y: center.y - thirdSize) let offsetFromCenter = PathHelper.gravityPointOffset(fromCenter: center, a: a, b: b, c: c) let p12 = PathHelper.line(from: a, to: b, offset: offsetFromCenter) let p34 = PathHelper.line(from: a, to: c, offset: offsetFromCenter) pathVector = DynamicButtonPathVector(p1: p12, p2: p12, p3: p34, p4: p34) } /// "Caret Left" style. static var styleName: String { return "Caret Left" } }
7f6acb2600fea637a5d6ea2b1ddcb13c
38.075472
94
0.726702
false
false
false
false
viviancrs/fanboy
refs/heads/master
FanBoy/Source/Controller/SubDetail/SubDetailListViewController.swift
gpl-3.0
1
// // SubDetailListViewController.swift // FanBoy // // Created by Vivian Cristhine da Rosa Soares on 17/07/17. // Copyright © 2017 CI&T. All rights reserved. // import UIKit class SubDetailListViewController: UITableViewController { // MARK: - Constants private let manager = ItemManager() // MARK: - Private Properties private var detail: Detail? private var mainView: SubDetailListView { return self.view as! SubDetailListView } //MARK: - Initializers func initializerControllerData(_ detail: Detail) { self.detail = detail } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() if let detail = self.detail { title = detail.name manager.loadLinkedSubDetail(detail, completion: { [weak self] (result) in guard let _self = self else { return } do { guard let subdetails = try result() else { return } _self.detail?.subdetails = subdetails DispatchQueue.main.async(execute: { _self.tableView.reloadData() }) } catch { HandleError.handle(error: error) } }) } } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detail?.subdetails.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: SubDetailCell = tableView.dequeueReusableCell(withIdentifier: SubDetailCell.kCellReuseIdentifier, for: indexPath) as! SubDetailCell if let subdetails = detail?.subdetails { cell.fill(subdetails[(indexPath as NSIndexPath).row]) } return cell } }
bce82e5ba135c576354129c878408797
28.043478
149
0.573353
false
false
false
false
abdullasulaiman/RaeesIOSProject
refs/heads/master
SwiftOpenCV/AddCustomerControllerViewController.swift
mit
1
// // AddCustomerControllerViewController.swift // SwiftOpenCV // // Created by Mohamed Abdulla on 20/07/15. // Copyright (c) 2015 WhitneyLand. All rights reserved. // import UIKit import CoreData class AddCustomerControllerViewController: UIViewController { @IBOutlet weak var custName: UITextField! @IBOutlet weak var custAddress: UITextField! @IBOutlet weak var custMobileNumber: UITextField! @IBOutlet weak var custFax: UITextField! @IBOutlet weak var custTextScan: UITextView! let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func saveCustomer(sender: AnyObject) { let entityDescription = NSEntityDescription.entityForName("Customer", inManagedObjectContext: managedObjectContext!) let customer = Customer(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) customer.custName = custName.text customer.custAddress = custAddress.text customer.custMobile = custMobileNumber.text customer.custFax = custFax.text customer.custOriginalScanText = custTextScan.text var error: NSError? managedObjectContext?.save(&error) var message:String? if let err = error { message = err.localizedFailureReason } else { custName.text = "" custName.text = "" custMobileNumber.text = "" custFax.text = "" custTextScan.text = "" message = "Customer Data Saved" } let alertController = UIAlertController(title: "Customer Info", message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } /* // 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. } */ }
6ad1d696b76d1aea9f89dad4388e7090
31.098765
114
0.659231
false
false
false
false
rlaferla/InfiniteTableView
refs/heads/master
InfiniteTableView/Cache.swift
mit
1
// // Cache.swift // InfiniteTableView import Foundation class Cache { let table = Table() var sections:[Date] = [] var sectionToRows:[Date:[Record]] = [:] var offset:Int = 0 { didSet { if self.offset < 0 { self.offset = 0 } } } var limit:Int = 0 var buffer:Int = 10 func loadData() { print("loadData() offset=\(self.offset) limit=\(self.limit)") self.sectionToRows = [:] self.sections = [] let records = self.table.select(query:"", offset: self.offset, limit: self.limit) for record in records { let date = record.date.dateWithoutTime() if self.sectionToRows[date] == nil { self.sectionToRows[date] = [] self.sections.append(date) } self.sectionToRows[date]?.append(record) } } func numberOfSections() -> Int { return self.sections.count } func numberOfRows(for section:Int) -> Int { let date = self.sections[section] let records = self.sectionToRows[date]! return records.count } func section(for section:Int) -> Date { return self.sections[section] } func row(for anIndexPath:IndexPath) -> Record { let date = self.sections[anIndexPath.section] let records = self.sectionToRows[date]! let record = records[anIndexPath.row] return record } func indexPath(for rw:Int) -> IndexPath { var s = 0 var r = 0 outerLoop: for section in sections { for row in sectionToRows[section]! { if row.row == rw { break outerLoop } else { r += 1 } } s += 1 } return IndexPath(row: r, section: s) } }
53ed9973ffc0558ed337588bf02e9887
23.8
89
0.493952
false
false
false
false
GrouponChina/groupon-up
refs/heads/master
Groupon UP/Groupon UP/OrderViewController.swift
apache-2.0
1
// // OrderViewController.swift // Groupon UP // // Created by Robert Xue on 11/21/15. // Copyright © 2015 Chang Liu. All rights reserved. // import SnapKit import Alamofire import SwiftyJSON import Parse class OrderViewController: UIViewController { private var _tableView: UITableView! private var _refreshController: UIRefreshControl! var orders: [Order] = [] override func viewDidLoad() { super.viewDidLoad() addSubViews() addLayout() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) initData() } func addSubViews() { view.addSubview(tableView) tableView.addSubview(refreshController) } func addLayout() { navigationItem.title = "MY GROUPONS" view.backgroundColor = UPBackgroundGrayColor tableView.snp_makeConstraints { (make) -> Void in make.top.equalTo(view) make.left.equalTo(view) make.right.equalTo(view) make.bottom.equalTo(snp_bottomLayoutGuideTop).offset(-10) } } func initData() { makeGetOrdersRequest() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension OrderViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orders.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reuseId = "UpListTableViewCell" let cell: UpListTableViewCell if let reuseCell = tableView.dequeueReusableCellWithIdentifier(reuseId) as? UpListTableViewCell { cell = reuseCell } else { cell = UpListTableViewCell(style: .Subtitle, reuseIdentifier: reuseId) } let order = orders[indexPath.row] if order.associatedDeal == nil { DealClient.getDealByDealId(order.dealId) { (deal: Deal?, _) in if let deal = deal { dispatch_async(dispatch_get_main_queue()) { order.associatedDeal = deal cell.setDeal(order.associatedDeal!) } } } } else { cell.setDeal(order.associatedDeal!) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let dealDetailView = DealDetailsViewController() dealDetailView.selectedDeal = orders[indexPath.row].associatedDeal! navigationController?.pushViewController(dealDetailView, animated: true) } } extension OrderViewController { var tableView: UITableView { if _tableView == nil { _tableView = UITableView() _tableView.delegate = self _tableView.dataSource = self _tableView.separatorStyle = UITableViewCellSeparatorStyle.None _tableView.estimatedRowHeight = 300 _tableView.rowHeight = UITableViewAutomaticDimension _tableView.backgroundColor = UIColor.clearColor() } return _tableView } var refreshController: UIRefreshControl { if _refreshController == nil { _refreshController = UIRefreshControl() _refreshController.tintColor = UIColor.whiteColor() _refreshController.addTarget(self, action: "refreshView", forControlEvents: .ValueChanged) } return _refreshController } } extension OrderViewController { func makeGetOrdersRequest() { Order.findOrdersByUserId(PFUser.currentUser()!.objectId!) { (orders: [Order], error: NSError?) in self.orders = orders self.tableView.reloadData() self.refreshController.endRefreshing() } } func refreshView() { refreshController.beginRefreshing() initData() } }
9bb4e1b64992f40631b1c948ae093e83
29.818182
109
0.624785
false
false
false
false
barrymcandrews/aurora-ios
refs/heads/master
Aurora/ContextManager.swift
bsd-2-clause
1
// // ContextManager.swift // Aurora // // Created by Barry McAndrews on 5/21/17. // Copyright © 2017 Barry McAndrews. All rights reserved. // import UIKit public class ContextManager: NSObject { static var context: [String: Any] { get { let context = [ "hostname": Request.hostname!, "port": Request.port!, "requests": NSKeyedArchiver.archivedData(withRootObject: RequestContainer.shared.requests) ] as [String : Any] print(context) return context } set { if let hostname = newValue["hostname"] as? String { Request.hostname = hostname } if let port = newValue["port"] as? String { Request.port = port } if let requests = newValue["requests"] as? Data { RequestContainer.shared.requests = NSKeyedUnarchiver.unarchiveObject(with: requests) as! [Request] } } } }
799dd6040a1efe103bbbbec39c4b0f2a
26.384615
114
0.523408
false
false
false
false
marcelganczak/swift-js-transpiler
refs/heads/master
test/weheartswift/tuples-enums-1.swift
mit
1
print("TODO") /*enum Direction { case up case down case left case right } var location = (x: 0, y: 0) var steps: [Direction] = [.up, .up, .left, .down, .left] for step in steps { switch step { case .up: location.y += 1 case .down: location.y -= 1 case .right: location.x += 1 case .left: location.x -= 1 } } print(location)*/
7e7ba1752c31515ef0c4ccda9f5f3e8d
14.461538
56
0.521197
false
false
false
false
tlax/looper
refs/heads/master
looper/View/Camera/Shoot/VCameraShootProcess.swift
mit
1
import UIKit class VCameraShootProcess:UIView { private weak var controller:CCameraShoot! private weak var label:UILabel! private var endAngle:CGFloat private let innerFillColor:UIColor private let strokeColor:UIColor private let borderColor:UIColor private let kRadius:CGFloat = 40 private let kStartAngle:CGFloat = 0.0001 private let kEndAngle:CGFloat = 6.28319 private let kLineWidth:CGFloat = 12 private let kBorderWidth:CGFloat = 14 init(controller:CCameraShoot) { innerFillColor = UIColor.black strokeColor = UIColor.genericLight borderColor = UIColor.genericDark endAngle = kStartAngle super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false self.controller = controller let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.font = UIFont.bold(size:20) label.textColor = UIColor.genericLight label.textAlignment = NSTextAlignment.center self.label = label addSubview(label) NSLayoutConstraint.equals( view:label, toView:self) } required init?(coder:NSCoder) { return nil } override func draw(_ rect:CGRect) { guard let context:CGContext = UIGraphicsGetCurrentContext() else { return } let width:CGFloat = rect.width let height:CGFloat = rect.height let width_2:CGFloat = width / 2.0 let height_2:CGFloat = height / 2.0 let center:CGPoint = CGPoint( x:width_2, y:height_2) context.setLineCap(CGLineCap.round) context.setLineWidth(kBorderWidth) context.setStrokeColor(borderColor.cgColor) context.setFillColor(innerFillColor.cgColor) context.addArc( center:center, radius:kRadius, startAngle:kStartAngle, endAngle:kEndAngle, clockwise:false) context.drawPath(using:CGPathDrawingMode.fillStroke) context.setStrokeColor(strokeColor.cgColor) context.setLineWidth(kLineWidth) context.addArc( center:center, radius:kRadius, startAngle:kStartAngle, endAngle:endAngle, clockwise:false) context.drawPath(using:CGPathDrawingMode.stroke) } //MARK: public func update() { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in guard let countShots:Int = MSession.sharedInstance.camera?.raw?.items.count, let startAngle:CGFloat = self?.kStartAngle, let endAngle:CGFloat = self?.kEndAngle else { return } let shotsString:String = "\(countShots)" if countShots >= MCamera.kMaxShots { self?.endAngle = endAngle } else { var percent:CGFloat = CGFloat(countShots) / CGFloat(MCamera.kMaxShots) if percent <= 0 { percent = startAngle } self?.endAngle = percent * endAngle } DispatchQueue.main.async { [weak self] in self?.label.text = shotsString self?.setNeedsDisplay() } } } }
05b72c1585518c205947d0d7c29912e7
27.927007
86
0.554378
false
false
false
false
suragch/aePronunciation-iOS
refs/heads/master
aePronunciation/UIColor+custom.swift
unlicense
1
import UIKit extension UIColor { class var rightGreen: UIColor { return UIColor.rgb(fromHex: 0x249900) } class func rgb(fromHex: Int) -> UIColor { let red = CGFloat((fromHex & 0xFF0000) >> 16) / 0xFF let green = CGFloat((fromHex & 0x00FF00) >> 8) / 0xFF let blue = CGFloat(fromHex & 0x0000FF) / 0xFF let alpha = CGFloat(1.0) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } class var systemDefaultTextColor: UIColor { if #available(iOS 13.0, *) { return UIColor.init { (trait) -> UIColor in return trait.userInterfaceStyle == .dark ? UIColor.label : UIColor.black } } else { return UIColor.black } } }
0c7027579f5a9be17c450ddc49971111
27.166667
72
0.523077
false
false
false
false
AmberWhiteSky/Monkey
refs/heads/master
BugHub for Mac/BugHub/Carthage/Checkouts/Mantle/Carthage/Checkouts/Quick/Externals/Nimble/Nimble/Matchers/BeGreaterThan.swift
apache-2.0
77
import Foundation public func beGreaterThan<T: Comparable>(expectedValue: T?) -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" return actualExpression.evaluate() > expectedValue } } public func beGreaterThan(expectedValue: NMBComparable?) -> MatcherFunc<NMBComparable> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" let actualValue = actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending return matches } } public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThan(rhs)) } public func >(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) { lhs.to(beGreaterThan(rhs)) } extension NMBObjCMatcher { public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ actualBlock() as NMBComparable? }) let expr = Expression(expression: block, location: location) return beGreaterThan(expected).matches(expr, failureMessage: failureMessage) } } }
b8dcd295727fceea392ae1850a7bc9ed
38.8
123
0.711414
false
false
false
false
djensenius/HATexplorer-iOS
refs/heads/master
HATexplorer/DetailViewController.swift
mit
1
// // DetailViewController.swift // HATexplorer // // Created by David Jensenius on 2015-07-22. // Copyright (c) 2015 David Jensenius. All rights reserved. // import UIKit import MapKit import AVFoundation class DetailViewController: UIViewController, CLLocationManagerDelegate, AVAudioPlayerDelegate { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var loadingActivitySpinner: UIActivityIndicatorView! @IBOutlet weak var gameDescription: UITextView! let downloadURL = "https://mld.jensenius.org/download/" let locationManager = CLLocationManager() var currentLocation = CLLocation() var currentLon = Double() var currentLat = Double() var layers = NSArray() var currentGame = NSDictionary() var bytes: NSMutableData? var firstLoop = true var loaded = false var inGameArea = false var inPolygon = false var offsetLng:Double = 0 var offsetLat:Double = 0 var loader: NSURLSession? var downloadCount = 0 var currentEvent = NSString() dynamic var identityPlayers = NSMutableDictionary() dynamic var identityPlayerItems = NSMutableDictionary() dynamic var eventPlayers = NSMutableDictionary() dynamic var eventPlayerItems = NSMutableDictionary() var eventDebug = NSMutableDictionary() var identityDebug = NSMutableDictionary() var gameLoader = NSTimer() let userDefaults = NSUserDefaults.standardUserDefaults() var detailItem: AnyObject? { didSet { // Update the view. self.configureView() print("Detail item is set... \(detailItem)") } } func configureView() { // Update the user interface for the detail item. if let detail: AnyObject = self.detailItem { if let label = self.detailDescriptionLabel { label.text = "Loading Game" self.title = detail.objectForKey("title") as? String print("Set title to \(self.title)") loadGame() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() self.gameDescription.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { do { // Background sound try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch _ { } do { try AVAudioSession.sharedInstance().setActive(true) } catch _ { } UIApplication.sharedApplication().beginReceivingRemoteControlEvents() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() //loadGame() //Let's reload game data every 10 seconds gameLoader = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(DetailViewController.loadGame), userInfo: nil, repeats: true) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailViewController.stopEverything), name: "stopEverything", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailViewController.restartEverything), name: "restartEverything", object: nil) } override func viewWillDisappear(animated: Bool) { //Stop everything stopEverything() } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLat = manager.location!.coordinate.latitude - offsetLat currentLon = manager.location!.coordinate.longitude - offsetLng currentLocation = CLLocation(latitude: currentLat, longitude: currentLon) print("I have a location and I am loading more stuff") if (loaded == true) { checkStates() } } func checkStates() { var leastDistance = 1000000000000.1 if (firstLoop == true) { print("First loop, checking to see if we are in range") for layer in layers { //var layerTitle = layer["title"] as! NSString //println("Checking layer: \(layerTitle)") let zones = layer["zone"] as! NSArray for zone in zones { let zoneTitle = zone["title"] as! NSString if (inGameArea == false) { let polygon = zone["polygon"] as! NSArray print("Checking zone \(zoneTitle)") if (insidePolygon(polygon)) { inGameArea = true inPolygon = true } let distance = distanceFromPolygon(polygon) if (distance < leastDistance) { leastDistance = distance } } let identity = zone["identity"] as! NSDictionary checkFiles(identity["file"] as! NSArray) let event = zone["event"] as! NSDictionary checkFiles(event["file"] as! NSArray) //println("Identity is \(identity) ") } } //For now, if we are a kilometer away from the nearest sound, we will bail and set offsets if currentGame["longitude"] != nil { if (leastDistance > 1000) { offsetLng = currentLon - (currentGame["longitude"] as! Double) offsetLat = currentLat - (currentGame["latitude"] as! Double) print("We are offsetting by \(offsetLat), \(offsetLng)") } else { offsetLat = 0 offsetLng = 0 print("No offsetting needed") } } firstLoop = false } else if downloadCount == 0 { print("Regular loop") //Let's get sounds playing! self.detailDescriptionLabel.hidden = true self.loadingActivitySpinner.hidden = true self.gameDescription.hidden = false for layer in layers { //var layerTitle = layer["title"] as! NSString //println("Checking layer: \(layerTitle)") let zones = layer["zone"] as! NSArray for zone in zones { //var zoneTitle = zone["title"] as! NSString let id = zone["_id"] as! NSString let polygon = zone["polygon"] as! NSArray //println("Checking zone \(zoneTitle)") if (insidePolygon(polygon)) { inPolygon = true currentEvent = id; //println("In polygon") } else if (currentEvent == id) { currentEvent = "" //println("Removed from polygon") } else { //println("Not in polygon") } let distance = distanceFromPolygon(polygon) if (distance < leastDistance) { leastDistance = distance } let identity = zone["identity"] as! NSDictionary let event = zone["event"] as! NSDictionary let zt = zone["title"] as! NSString var sensitivity:Float = 0.0 if (identity["sensitivity"] != nil) { sensitivity = identity["sensitivity"] as! Float } setSound(id, identity: identity, event: event, polygon: currentEvent, distance: distance, sensitivity: sensitivity, zoneTitle: zt) } } } } func setSound(zoneId:NSString, identity:NSDictionary, event:NSDictionary, polygon:NSString, distance:Double, sensitivity:Float, zoneTitle:NSString) { //Check to see if sound is created, if not, create it //If the sound is in a polygon, start event and mute all others print("Setting sound?") if (identityPlayers.objectForKey(zoneId) == nil && eventPlayers.objectForKey(zoneId) == nil) { //Create item! print("Having to create?") //loop through both identity and event files, grab the last one and set it to play: FIX LATER let cachePath = cacheSoundDirectoryName() var hasIdentitySound = false let files:NSArray = identity["file"] as! NSArray var identityURL = NSURL() for file in files { let currentFile = file as! NSDictionary let fileid = currentFile["_id"] as! NSString let ext = (currentFile["title"] as! NSString).pathExtension let fileCheck = "\(fileid).\(ext)" identityURL = NSURL(fileURLWithPath: cachePath.stringByAppendingPathComponent(fileCheck)) hasIdentitySound = true } if hasIdentitySound == true { identityPlayers.setObject(try! AVAudioPlayer(contentsOfURL: identityURL), forKey: zoneId) (identityPlayers.objectForKey(zoneId) as! AVAudioPlayer).numberOfLoops = -1 (identityPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = 0.0 (identityPlayers.objectForKey(zoneId) as! AVAudioPlayer).play() } let eventFiles:NSArray = event["file"] as! NSArray //println("Event files \(eventFiles)") var eventURL = NSURL() var hasEventSound = false for file in eventFiles { let currentFile = file as! NSDictionary let fileid = currentFile["_id"] as! NSString let ext = (currentFile["title"] as! NSString).pathExtension let fileCheck = "\(fileid).\(ext)" eventURL = NSURL(fileURLWithPath: cachePath.stringByAppendingPathComponent(fileCheck)) hasEventSound = true } if hasEventSound == true { eventPlayers.setObject(try! AVAudioPlayer(contentsOfURL: eventURL), forKey: zoneId) (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).numberOfLoops = -1 (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = 0.0 (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).play() (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).pause() print("Setting event sound... and pausing") } } if polygon != "" { if eventPlayers.objectForKey(polygon) != nil { (eventPlayers.objectForKey(polygon) as! AVAudioPlayer).play() (eventPlayers.objectForKey(polygon) as! AVAudioPlayer).volume = 1.0 print("Event sound now plays") } if (zoneId != polygon) { if eventPlayers.objectForKey(zoneId) != nil { (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).pause() (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = 0.0 } } if identityPlayers.objectForKey(zoneId) != nil { (identityPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = 0.0 } } else { //Set volume! //Make sure all events are muted then set other volumes if (eventPlayers.objectForKey(zoneId) != nil) { (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).pause() (eventPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = 0.0 //println("Event not nil") } var distanceFrom = Float() userDefaults.synchronize() var formula = NSString() if let useLog: AnyObject = userDefaults.objectForKey("logIdentity") { print(useLog); if (useLog as! Bool == true) { //Logorithmic growth //println("Logorithmic growth!") distanceFrom = 1 + log(Float(distance / 1000)) formula = "1 + log(Float(\(distance) / 1000))" } else { //Normal growth //println("Normal growth!") distanceFrom = 1 + Float(distance / 1000) formula = "1 + Float(\(distance) / 1000)" } } else { //Normal growth //println("Normal growth!") distanceFrom = 1 + Float(distance / 1000) formula = "1 + Float(\(distance) / 1000)" } if (distanceFrom < 0) { distanceFrom = 0 } //println("Actual distance: \(distance)") //var volume:Float = 1.0 - (distanceFrom * sensitivity) var volume:Float = (1.0 - (distanceFrom * (sensitivity + 1.0))) formula = "1.0 - ((\(formula)) * (\(sensitivity) + 1.0))" if (volume < 0) { volume = 0 } //println("Setting volume to \(volume)") if (identityPlayers.objectForKey(zoneId) != nil) { (identityPlayers.objectForKey(zoneId) as! AVAudioPlayer).volume = volume } let debugText = "\(zoneTitle)\nDistance - \(distance)\nAdjusted Value - \(distanceFrom)\nVolume - \(volume)\n\(formula)" //println(debugText) identityDebug.setObject(debugText, forKey: zoneId) } } func playerItemDidReachEnd(notification: NSNotification) { print("Looping?? \(notification.object)") let p:AVPlayerItem = notification.object as! AVPlayerItem p .seekToTime(kCMTimeZero) } func insidePolygon(polygons:NSArray) -> Bool { //http://web.archive.org/web/20080812141848/http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ //http://stackoverflow.com/questions/25835985/determine-whether-a-cllocationcoordinate2d-is-within-a-defined-region-bounds //println("Checking polygon \(polygons)") var polyCoords:Array<CLLocationCoordinate2D> = [] for i in 0 ..< polygons.count { let polygon = polygons[i] as! NSDictionary //let curLat = polygon["latitude"] as! CLLocationDegrees polyCoords.append(CLLocationCoordinate2DMake(polygon["latitude"] as! CLLocationDegrees, polygon["longitude"] as! CLLocationDegrees)) } let mpr:CGMutablePathRef = CGPathCreateMutable() for i in 0 ..< polyCoords.count { let c:CLLocationCoordinate2D = polyCoords[i] if (i == 0) { CGPathMoveToPoint(mpr, nil, CGFloat(c.longitude), CGFloat(c.latitude)) } else { CGPathAddLineToPoint(mpr, nil, CGFloat(c.longitude), CGFloat(c.latitude)) } } let testCGPoint:CGPoint = CGPointMake(CGFloat(currentLon), CGFloat(currentLat)) let inPolygon:Bool = CGPathContainsPoint(mpr, nil, testCGPoint, false); //println("Are we in the polygon \(inPolygon)") return inPolygon } func distanceFromPolygon(polygon:NSArray) -> Double { var distance = 100000000000000000.1 for coords in polygon { //let location = coords as! NSDictionary let pointLocation = CLLocation(latitude: coords["latitude"] as! CLLocationDegrees, longitude: coords["longitude"] as! CLLocationDegrees) let distanceFrom = pointLocation.distanceFromLocation(currentLocation) if (distanceFrom < distance) { distance = distanceFrom } } //println("We are this far away: \(distance)") return distance } func checkFiles(files:NSArray) { // Check to see if file is in our local cache, if not, check to see if it is in the application, if not, download! let cachePath = cacheSoundDirectoryName() for file in files { let theFile = file as! NSDictionary let fileName = theFile.objectForKey("title")! as! NSString print("The file is \(fileName)") //let fileURL = NSURL(string: fileName) let ext = fileName.pathExtension let fileid = theFile["_id"] as! NSString //let filename = theFile["title"] as! NSString let fileCheck = "\(fileid).\(ext)" if NSFileManager.defaultManager().fileExistsAtPath(cachePath.stringByAppendingPathComponent(fileCheck)) { print("File exists in cache") } else { let resourceExists = NSBundle.mainBundle().pathForResource(fileid as String, ofType: ext) if ((resourceExists) != nil) { print("Resource in bundle") let fileManager = NSFileManager.defaultManager() let copyTo = "\(cachePath)/\(fileCheck)" print("Coping from \(resourceExists) to \(copyTo)") do { try fileManager.copyItemAtPath(resourceExists!, toPath: copyTo) print("Copied!") } catch _ { print("NOT COPIED!") } } else { //println("Resource not in bundle, must download \(theFile)!") downloadCount += 1 self.detailDescriptionLabel.text = "Downloading \(self.downloadCount) sounds." let soundPath = cacheSoundDirectoryName().stringByAppendingPathComponent(fileCheck) let soundURL = "\(downloadURL)\(fileid)" print("Downloading from \(soundURL)") let request = NSURLRequest(URL: NSURL(string: soundURL)!) let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(soundData, response, error) in if (soundData != nil) { NSFileManager.defaultManager().createFileAtPath(soundPath, contents: soundData, attributes: nil) print("Sound is now Cached! \(soundPath)") self.downloadCount = self.downloadCount - 1 self.detailDescriptionLabel.text = "Downloading \(self.downloadCount) sounds." } else { print("SOMETHNIG WRONG WITH soundData 😤") } }); task.resume() } } } } func cacheSoundDirectoryName() -> NSString { let directory = "Sounds" let cacheDirectoryName = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as NSString let finalDirectoryName = cacheDirectoryName.stringByAppendingPathComponent(directory) do { try NSFileManager.defaultManager().createDirectoryAtPath(finalDirectoryName, withIntermediateDirectories: true, attributes: nil) } catch { print(error) } return finalDirectoryName } func loadGame() { //http://www.bytearray.org/?p=5517 //Download JSON, check if file exists, download missing files. if loaded == false { print("Loaded in FALSE...") self.detailDescriptionLabel.hidden = false self.loadingActivitySpinner.hidden = false self.gameDescription.hidden = true } else { print("Loaded is TRUE") } if let detail: AnyObject = self.detailItem { print("Maybe I'm loading?") if let gameID = detail.objectForKey("_id") as? String { print("Loading gameID \(gameID)") let request = NSURLRequest(URL: NSURL(string: "https://mld.jensenius.org/api/dump/" + gameID)!) let detailSession = NSURLSession.sharedSession() detailSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in print("Finished lodaing?") var jsonResult : AnyObject! do { jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) } catch { print("Well, shit (delegate!) again, another error") } // we grab the colorsArray element //println(jsonResult.count) dispatch_async(dispatch_get_main_queue(), { if jsonResult.objectForKey("introduction") != nil { self.gameDescription.text = jsonResult.objectForKey("introduction") as? String //print("Set the game description \(self.gameDescription.text)") } else { self.gameDescription.text = "No introduction text has been entered in the settings." } self.gameDescription.textColor = UIColor.whiteColor() self.gameDescription.font = UIFont.systemFontOfSize(18.0) self.currentGame = jsonResult as! NSDictionary self.layers = jsonResult["layer"] as! NSArray self.loaded = true }) }).resume() print("SHOULD REALLY BE LOADING!") } } } func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) { self.bytes?.appendData(conData) } func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { self.bytes = NSMutableData() } func connectionDidFinishLoading(connection: NSURLConnection!) { // we serialize our bytes back to the original JSON structure if connection == loader { print("Finished lodaing?") let jsonResult: Dictionary = ((try! NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers)) as! Dictionary<String, AnyObject>) // we grab the colorsArray element //println(jsonResult.count) dispatch_async(dispatch_get_main_queue(), { if jsonResult["introduction"] != nil { self.gameDescription.text = jsonResult["introduction"] as? String print("Set the game description \(self.gameDescription.text)") } else { self.gameDescription.text = "No introduction text has been entered in the settings." } self.gameDescription.textColor = UIColor.whiteColor() self.gameDescription.font = UIFont.systemFontOfSize(18.0) self.currentGame = jsonResult self.layers = jsonResult["layer"] as! NSArray self.loaded = true }) } else { print("Must have finished downloading file") } } func stopEverything() { print("Going to stop everything!") gameLoader.invalidate() for layer in layers { //var layerTitle = layer["title"] as! NSString //println("Checking layer: \(layerTitle)") let zones = layer["zone"] as! NSArray for zone in zones { let id = zone["_id"] as! NSString if eventPlayers.objectForKey(id) != nil { (eventPlayers.objectForKey(id) as! AVAudioPlayer).stop() eventPlayers.removeObjectForKey(id) } if identityPlayers.objectForKey(id) != nil { (identityPlayers.objectForKey(id) as! AVAudioPlayer).stop() identityPlayers.removeObjectForKey(id) } } } locationManager.stopUpdatingLocation() } func restartEverything() { print("Going to restart everything!") for layer in layers { //var layerTitle = layer["title"] as! NSString //println("Checking layer: \(layerTitle)") let zones = layer["zone"] as! NSArray for zone in zones { let id = zone["_id"] as! NSString (eventPlayers.objectForKey(id) as! AVAudioPlayer).play() (identityPlayers.objectForKey(id) as! AVAudioPlayer).play() } } locationManager.startUpdatingLocation() } }
668814bff70138e1dde77ec108185fde
42.516722
184
0.545863
false
false
false
false
keshwans/IBM-Ready-App-for-Healthcare
refs/heads/master
iOS/ReadyAppPT-Tests/UtilsTest.swift
epl-1.0
2
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit import XCTest /** * Unit tests for various methods in the Utils class. */ class UtilsTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } /** Method to test every single digit number gets a 0 prefix on it. */ func testSingleDigitFormat() { var noPrefix = Utils.formatSingleDigits(5) XCTAssertEqual(noPrefix, "05", "zero was not added in front of the digit") var withPrefix = Utils.formatSingleDigits(05) XCTAssertEqual(withPrefix, "05", "\(withPrefix) does not match 05") } /** Method to test we can extract the correct data from an NSDate. */ func testDateExtraction() { var myDate = "Mon, 06 Sep 2009 16:45:00 -0900" var dateFormatter: NSDateFormatter = NSDateFormatter() var locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.locale = locale dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z" var sepDate = dateFormatter.dateFromString(myDate) var month = Utils.extractMonthNameFromDate(sepDate!) XCTAssertEqual(month, "September", "Month returned is not September") var day = Utils.extractDayFromDate(sepDate!) XCTAssertEqual(day, 6, "Day returned is not the 6th") } /** Method to test the appropriate suffix is attached to a day. */ func testDaySuffix() { for index in 1...31 { if index == 1 || index == 21 || index == 31 { XCTAssertEqual(Utils.daySuffixFromDay(index), "\(index)st", "number did not return with an 'st' suffix") } else if index == 2 || index == 22 { XCTAssertEqual(Utils.daySuffixFromDay(index), "\(index)nd", "number did not return with an 'nd' suffix") } else if index == 3 || index == 23 { XCTAssertEqual(Utils.daySuffixFromDay(index), "\(index)rd", "number did not return with an 'rd' suffix") } else { XCTAssertEqual(Utils.daySuffixFromDay(index), "\(index)th", "number did not return with an 'th' suffix") } } } func testIntervalDateForUnit() { var dateOne = Utils.intervalDataForUnit("day") XCTAssertEqual(dateOne.hour, 1, "Hour interval should be equal to 1") var dateTwo = Utils.intervalDataForUnit("week") XCTAssertEqual(dateTwo.day, 1, "Day interval should be equal to 1") var dateThree = Utils.intervalDataForUnit("month") XCTAssertEqual(dateThree.day, 7, "Day interval should be equal to 7") var dateFour = Utils.intervalDataForUnit("year") XCTAssertEqual(dateFour.month, 1, "Month interval should be equal to 1") } func testPerformanceExample() { self.measureBlock() { // Put the code you want to measure the time of here. } } }
a75f58a52c49e3c1da54f83ceb1953e7
33.326316
120
0.605642
false
true
false
false
bigyelow/rexxar-ios
refs/heads/master
RexxarDemo/Library/FRDToast/LoadingView.swift
mit
1
// // LoadingView.swift // Frodo // // Created by 李俊 on 15/12/7. // Copyright © 2015年 Douban Inc. All rights reserved. // import UIKit private let animationDuration: TimeInterval = 2.4 @objc class LoadingView: UIView { var lineWidth: CGFloat = 5 { didSet { setNeedsLayout() } } var strokeColor = UIColor(hex: 0x42BD56) { didSet { ringLayer.strokeColor = strokeColor.cgColor rightPointLayer.strokeColor = strokeColor.cgColor leftPointLayer.strokeColor = strokeColor.cgColor } } fileprivate let ringLayer = CAShapeLayer() fileprivate let pointSuperLayer = CALayer() fileprivate let rightPointLayer = CAShapeLayer() fileprivate let leftPointLayer = CAShapeLayer() fileprivate var isAnimating = false init(frame: CGRect, color: UIColor?) { super.init(frame: frame) strokeColor = color ?? strokeColor ringLayer.contentsScale = UIScreen.main.scale ringLayer.strokeColor = strokeColor.cgColor ringLayer.fillColor = UIColor.clear.cgColor ringLayer.lineCap = kCALineCapRound ringLayer.lineJoin = kCALineJoinBevel layer.addSublayer(ringLayer) layer.addSublayer(pointSuperLayer) rightPointLayer.strokeColor = strokeColor.cgColor rightPointLayer.lineCap = kCALineCapRound pointSuperLayer.addSublayer(rightPointLayer) leftPointLayer.strokeColor = strokeColor.cgColor leftPointLayer.lineCap = kCALineCapRound pointSuperLayer.addSublayer(leftPointLayer) NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let centerPoint = CGPoint(x: bounds.width/2, y: bounds.height/2) let radius = bounds.width/2 - lineWidth let path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle:CGFloat(-Double.pi), endAngle: CGFloat(Double.pi * 0.6), clockwise: true) ringLayer.lineWidth = lineWidth ringLayer.path = path.cgPath ringLayer.frame = bounds let x = bounds.width/2 - CGFloat(sin(Double.pi * 50.0/180.0)) * radius let y = bounds.height/2 - CGFloat(sin(Double.pi * 40.0/180.0)) * radius let rightPoint = CGPoint(x: bounds.width - x, y: y) let leftPoint = CGPoint(x: x, y: y) let rightPointPath = UIBezierPath() rightPointPath.move(to: rightPoint) rightPointPath.addLine(to: rightPoint) rightPointLayer.path = rightPointPath.cgPath rightPointLayer.lineWidth = lineWidth let leftPointPath = UIBezierPath() leftPointPath.move(to: leftPoint) leftPointPath.addLine(to: leftPoint) leftPointLayer.path = leftPointPath.cgPath leftPointLayer.lineWidth = lineWidth pointSuperLayer.frame = bounds } func startAnimation() { if isAnimating { return } pointSuperLayer.isHidden = false let keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.216 as Double), NSNumber(value: 0.396 as Double), NSNumber(value: 0.8 as Double), NSNumber(value: 1 as Int32)] // pointSuperLayer animation let pointKeyAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") pointKeyAnimation.duration = animationDuration pointKeyAnimation.repeatCount = Float.infinity pointKeyAnimation.values = [0, (2 * Double.pi * 0.375 + 2 * Double.pi), (4 * Double.pi), (4 * Double.pi), (4 * Double.pi + 0.3 * Double.pi)] pointKeyAnimation.keyTimes = keyTimes pointSuperLayer.add(pointKeyAnimation, forKey: nil) // ringLayer animation let ringAnimationGroup = CAAnimationGroup() let ringKeyRotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") ringKeyRotationAnimation.values = [0, (2 * Double.pi), (Double.pi/2 + 2 * Double.pi), (Double.pi/2 + 2 * Double.pi), (4 * Double.pi)] ringKeyRotationAnimation.keyTimes = keyTimes ringAnimationGroup.animations = [ringKeyRotationAnimation] let ringKeyStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart") ringKeyStartAnimation.values = [0, 0.25, 0.35, 0.35, 0] ringKeyStartAnimation.keyTimes = keyTimes ringAnimationGroup.animations?.append(ringKeyStartAnimation) let ringKeyEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd") ringKeyEndAnimation.values = [1, 1, 0.9, 0.9, 1] ringKeyEndAnimation.keyTimes = keyTimes ringAnimationGroup.animations?.append(ringKeyEndAnimation) ringAnimationGroup.duration = animationDuration ringAnimationGroup.repeatCount = Float.infinity ringLayer.add(ringAnimationGroup, forKey: nil) // pointAnimation let rightPointKeyAnimation = CAKeyframeAnimation(keyPath: "lineWidth") rightPointKeyAnimation.values = [lineWidth, lineWidth, lineWidth * 1.4, lineWidth * 1.4, lineWidth] rightPointKeyAnimation.keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.21 as Double), NSNumber(value: 0.29 as Double), NSNumber(value: 0.88 as Double), NSNumber(value: 0.96 as Double)] rightPointKeyAnimation.duration = animationDuration rightPointKeyAnimation.repeatCount = Float.infinity rightPointLayer.add(rightPointKeyAnimation, forKey: nil) let leftPointKeyAnimation = CAKeyframeAnimation(keyPath: "lineWidth") leftPointKeyAnimation.values = [lineWidth, lineWidth, lineWidth * 1.4, lineWidth * 1.4, lineWidth] leftPointKeyAnimation.keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.31 as Double), NSNumber(value: 0.39 as Double), NSNumber(value: 0.8 as Double), NSNumber(value: 0.88 as Double)] leftPointKeyAnimation.duration = animationDuration leftPointKeyAnimation.repeatCount = Float.infinity leftPointLayer.add(leftPointKeyAnimation, forKey: nil) isAnimating = true } func stopAnimation() { pointSuperLayer.removeAllAnimations() ringLayer.removeAllAnimations() rightPointLayer.removeAllAnimations() leftPointLayer.removeAllAnimations() isAnimating = false } func setPercentage(_ percent: CGFloat) { pointSuperLayer.isHidden = true ringLayer.strokeEnd = percent } @objc fileprivate func appWillEnterForeground() { if isAnimating { isAnimating = false startAnimation() } } override func willMove(toWindow newWindow: UIWindow?) { if newWindow != nil && isAnimating { isAnimating = false startAnimation() } } deinit { NotificationCenter.default.removeObserver(self) } }
f7ba011b31f219e72fedd8299a78e9f7
34.672131
200
0.73223
false
false
false
false
Skogetroll/JSONSerializer
refs/heads/master
Argo/Types/DecodeError.swift
mit
7
/// Possible decoding failure reasons. public enum DecodeError: ErrorType { /// The type existing at the key didn't match the type being requested. case TypeMismatch(expected: String, actual: String) /// The key did not exist in the JSON. case MissingKey(String) /// A custom error case for adding explicit failure info. case Custom(String) } extension DecodeError: CustomStringConvertible { public var description: String { switch self { case let .TypeMismatch(expected, actual): return "TypeMismatch(Expected \(expected), got \(actual))" case let .MissingKey(s): return "MissingKey(\(s))" case let .Custom(s): return "Custom(\(s))" } } } extension DecodeError: Hashable { public var hashValue: Int { switch self { case let .TypeMismatch(expected: expected, actual: actual): return expected.hashValue ^ actual.hashValue case let .MissingKey(string): return string.hashValue case let .Custom(string): return string.hashValue } } } public func == (lhs: DecodeError, rhs: DecodeError) -> Bool { switch (lhs, rhs) { case let (.TypeMismatch(expected: expected1, actual: actual1), .TypeMismatch(expected: expected2, actual: actual2)): return expected1 == expected2 && actual1 == actual2 case let (.MissingKey(string1), .MissingKey(string2)): return string1 == string2 case let (.Custom(string1), .Custom(string2)): return string1 == string2 default: return false } }
a87109721b9bec89763f15f57f088517
28.52
118
0.692412
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Solution/Items/MLinearEquationsSolutionEquationItemPolynomialDecimal.swift
mit
1
import UIKit class MLinearEquationsSolutionEquationItemPolynomialDecimal:MLinearEquationsSolutionEquationItemPolynomial { let string:NSAttributedString let stringSign:String let signWidth:CGFloat let imageSign:UIImage? private let kMaxSignWidth:CGFloat = 20 private let kFontSize:CGFloat = 20 private let kMaxStringWidth:CGFloat = 5000 private let kMaxStringHeight:CGFloat = 30 private let kShowAsDivision:Bool = false private let kAdd:String = "+" private let kSubstract:String = "-" private let kEmpty:String = "" init( indeterminate:MLinearEquationsSolutionIndeterminatesItem, coefficientDividend:Double, coefficientDivisor:Double, showSign:Bool) { let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.numeric(size:kFontSize)] let drawingOptions:NSStringDrawingOptions = NSStringDrawingOptions([ NSStringDrawingOptions.usesFontLeading, NSStringDrawingOptions.usesLineFragmentOrigin]) let maxSize:CGSize = CGSize( width:kMaxStringWidth, height:kMaxStringHeight) let coefficient:Double = coefficientDividend / coefficientDivisor let absoluteCoefficient:Double = abs(coefficient) let attributedIndeterminate:NSAttributedString = NSAttributedString( string:indeterminate.symbol, attributes:attributes) let mutableString:NSMutableAttributedString = NSMutableAttributedString() if absoluteCoefficient != 1 { let rawString:String = MSession.sharedInstance.stringFrom( number:absoluteCoefficient) let attributedCoefficient:NSAttributedString = NSAttributedString( string:rawString, attributes:attributes) mutableString.append(attributedCoefficient) } mutableString.append(attributedIndeterminate) string = mutableString let stringRect:CGRect = string.boundingRect( with:maxSize, options:drawingOptions, context:nil) let textWidth:CGFloat = ceil(stringRect.size.width) let reusableIdentifier:String = VLinearEquationsSolutionCellPolynomialDecimal.reusableIdentifier if showSign { signWidth = kMaxSignWidth if coefficientDividend >= 0 { imageSign = #imageLiteral(resourceName: "assetGenericColAddSmall") stringSign = kAdd } else { imageSign = #imageLiteral(resourceName: "assetGenericColSubstractSmall") stringSign = kSubstract } } else { signWidth = 0 imageSign = nil stringSign = kEmpty } let cellWidth:CGFloat = textWidth + signWidth super.init( indeterminate:indeterminate, coefficientDividend:coefficientDividend, coefficientDivisor:coefficientDivisor, showSign:showSign, showAsDivision:kShowAsDivision, reusableIdentifier:reusableIdentifier, cellWidth:cellWidth) } override func shareText() -> String? { let mutableString:NSMutableString = NSMutableString() mutableString.append(stringSign) mutableString.append(self.string.string) let string:String = mutableString as String return string } override func drawInRect(rect:CGRect) { let rectX:CGFloat = rect.origin.x let rectY:CGFloat = rect.origin.y let rectWidth:CGFloat = rect.size.width let rectHeight:CGFloat = rect.size.height if let imageSign:UIImage = self.imageSign { let imageWidth:CGFloat = imageSign.size.width let imageHeight:CGFloat = imageSign.size.height let imageRemainX:CGFloat = signWidth - imageWidth let imageRemainY:CGFloat = rectHeight - imageHeight let imageMarginX:CGFloat = imageRemainX / 2.0 let imageMarginY:CGFloat = imageRemainY / 2.0 let imageRect:CGRect = CGRect( x:rectX + imageMarginX, y:rectY + imageMarginY, width:imageWidth, height:imageHeight) imageSign.draw(in:imageRect) } let stringRect:CGRect = CGRect( x:rectX + signWidth, y:rectY, width:rectWidth - signWidth, height:rectHeight) string.draw(in:stringRect) } }
c6126fd3b48d9213d3d13d6ebd8953f0
33.715328
106
0.616064
false
false
false
false
calebd/swift
refs/heads/master
benchmark/single-source/Substring.swift
apache-2.0
9
//===--- Substring.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // A string that doesn't fit in small string storage and doesn't fit in Latin-1 let longWide = "fὢasὢodὢijὢadὢolὢsjὢalὢsdὢjlὢasὢdfὢijὢliὢsdὢjøὢslὢdiὢalὢiὢ" @inline(never) public func run_SubstringFromLongString(_ N: Int) { var s = longWide s += "!" // ensure the string has a real buffer for _ in 1...N*500 { blackHole(Substring(s)) } } func create<T : RangeReplaceableCollection, U : Collection>( _: T.Type, from source: U ) where T.Iterator.Element == U.Iterator.Element { blackHole(T(source)) } @inline(never) public func run_SubstringFromLongStringGeneric(_ N: Int) { var s = longWide s += "!" // ensure the string has a real buffer for _ in 1...N*500 { create(Substring.self, from: s) } } @inline(never) public func run_StringFromLongWholeSubstring(_ N: Int) { var s0 = longWide s0 += "!" // ensure the string has a real buffer let s = Substring(s0) for _ in 1...N*500 { blackHole(String(s)) } } @inline(never) public func run_StringFromLongWholeSubstringGeneric(_ N: Int) { var s0 = longWide s0 += "!" // ensure the string has a real buffer let s = Substring(s0) for _ in 1...N*500 { create(String.self, from: s) } } private func equivalentWithDistinctBuffers() -> (String, Substring) { var s0 = longWide withUnsafeMutablePointer(to: &s0) { blackHole($0) } s0 += "!" // These two should be equal but with distinct buffers, both refcounted. let a = Substring(s0).dropFirst() let b = String(a) return (b, a) } @inline(never) public func run_EqualStringSubstring(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a == b) } } @inline(never) public func run_EqualSubstringString(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(b == a) } } @inline(never) public func run_EqualSubstringSubstring(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a == b) } } @inline(never) public func run_EqualSubstringSubstringGenericEquatable(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() func check<T>(_ x: T, _ y: T) where T : Equatable { blackHole(x == y) } for _ in 1...N*500 { check(a, b) } } /* func checkEqual<T, U>(_ x: T, _ y: U) where T : StringProtocol, U : StringProtocol { blackHole(x == y) } @inline(never) public func run _EqualStringSubstringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(a, b) } } @inline(never) public func run _EqualSubstringStringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(b, a) } } @inline(never) public func run _EqualSubstringSubstringGenericStringProtocol(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkEqual(a, b) } } */ //===----------------------------------------------------------------------===// /* @inline(never) public func run _LessStringSubstring(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a < b) } } @inline(never) public func run _LessSubstringString(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(b < a) } } */ @inline(never) public func run_LessSubstringSubstring(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { blackHole(a < b) } } @inline(never) public func run_LessSubstringSubstringGenericComparable(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() func check<T>(_ x: T, _ y: T) where T : Comparable { blackHole(x < y) } for _ in 1...N*500 { check(a, b) } } @inline(never) public func run_SubstringEquatable(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") var count = 0 for _ in 1...N*500 { for s in substrings { if substrings.contains(s) { count = count &+ 1 } } } CheckResults(count == 8*N*500) } @inline(never) public func run_SubstringEqualString(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") let pineapple = "pineapple" let apple = "🍏" var count = 0 for _ in 1...N*500 { for s in substrings { if s == pineapple || s == apple { count = count &+ 1 } } } CheckResults(count == 2*N*500) } @inline(never) public func run_SubstringComparable(_ N: Int) { var string = "pen,pineapple,apple,pen" string += ",✒️,🍍,🍏,✒️" let substrings = string.split(separator: ",") let comparison = substrings + ["PPAP"] var count = 0 for _ in 1...N*500 { if substrings.lexicographicallyPrecedes(comparison) { count = count &+ 1 } } CheckResults(count == N*500) } /* func checkLess<T, U>(_ x: T, _ y: U) where T : StringProtocol, U : StringProtocol { blackHole(x < y) } @inline(never) public func run _LessStringSubstringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(a, b) } } @inline(never) public func run _LessSubstringStringGenericStringProtocol(_ N: Int) { let (a, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(b, a) } } @inline(never) public func run _LessSubstringSubstringGenericStringProtocol(_ N: Int) { let (_, a) = equivalentWithDistinctBuffers() let (_, b) = equivalentWithDistinctBuffers() for _ in 1...N*500 { checkLess(a, b) } } */
455b2103f53be9b6652c7c548852227a
23.44186
80
0.631938
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
refs/heads/master
App 09 - RainyShinyCloudy/RainyShinyCloudy/Constants.swift
mit
1
// // Constants.swift // RainyShinyCloudy // // Created by Per Kristensen on 13/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import Foundation let WEATHER_BASE_URL = "http://api.openweathermap.org/data/2.5/weather?" let FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?" let LATITUDE = "lat=" let LONGITUDE = "&lon=" let CNT = "&cnt=10" let APP_ID = "&appid=" let API_KEY = "b304ad647ea8d08d7f87e0940b17c6e9" let CURRENT_WEATHER_URL = "\(WEATHER_BASE_URL)\(LATITUDE)\(Location.sharedInstance.latitude!)\(LONGITUDE)\(Location.sharedInstance.longitude!)\(APP_ID)\(API_KEY)" let FORECAST_URL = "\(FORECAST_BASE_URL)\(LATITUDE)\(Location.sharedInstance.latitude!)\(LONGITUDE)\(Location.sharedInstance.longitude!)\(CNT)\(APP_ID)\(API_KEY)" typealias DownloadComplete = () -> ()
0b4f905bfd61979ed91c02fc7e587c1f
36.772727
162
0.719615
false
false
false
false
mbuchetics/RealmDataSource
refs/heads/master
RealmDataSource/RealmSection.swift
mit
1
// // RealmSection.swift // RealmDataSource // // Created by Matthias Buchetics on 27/11/15. // Copyright © 2015 all about apps GmbH. All rights reserved. // import Foundation import RealmSwift import DataSource /** Representation of a table section where the rows are the results of a Realm query. Note that all rows have the same row identifier. */ public struct RealmSection<T: Object>: SectionType { /// Optional title of the section public let title: String? /// Row identifier for all rows of this section public let rowIdentifier: String /// Realm query results representing the rows of this section public var results: Results<T>? public init() { self.title = nil self.rowIdentifier = "" } public init(title: String? = nil, rowIdentifier: String, results: Results<T>) { self.results = results self.title = title self.rowIdentifier = rowIdentifier } public subscript(index: Int) -> Row<T> { return Row(identifier: rowIdentifier, data: results![index]) } public subscript(index: Int) -> RowType { return Row(identifier: rowIdentifier, data: results![index]) } public var numberOfRows: Int { return results!.count } public var hasTitle: Bool { if let title = title where !title.isEmpty { return true } else { return false } } }
18f8ab83060390df43a9fdffb0f6e687
24.517241
86
0.623394
false
false
false
false
Skyvive/JsonSerializer
refs/heads/master
JsonSerializer/JsonSerializer+Serialization.swift
mit
2
// // JsonSerializer+Serialization.swift // JsonSerializer // // Created by Bradley Hilton on 4/18/15. // Copyright (c) 2015 Skyvive. All rights reserved. // import Foundation // MARK: JsonObject+Serialization extension JsonSerializer { class func jsonDictionaryFromObject(object: NSObject) -> NSDictionary { var dictionary = NSMutableDictionary() for (name, mirrorType) in properties(object) { if let mapper = mapperForType(mirrorType.valueType), let value: AnyObject = valueForProperty(name, mirrorType: mirrorType, object: object) { if let jsonValue = mapper.jsonValueFromPropertyValue(value), let key = dictionaryKeyForPropertyKey(name, object: object) { dictionary.setObject(jsonValue.value(), forKey: key) } } } return dictionary } private class func valueForProperty(name: String, mirrorType: MirrorType, object: NSObject) -> AnyObject? { if let value: AnyObject = mirrorType.value as? AnyObject { return value } else if object.respondsToSelector(NSSelectorFromString(name)) { if let value: AnyObject = object.valueForKey(name) { return value } } return nil } }
39a494ed0107394a9120aad22a24f28d
32.775
111
0.614815
false
false
false
false
AlexRamey/mbird-iOS
refs/heads/master
Pods/Nuke/Sources/DataDecoder.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). #if os(macOS) import Cocoa #else import UIKit #endif #if os(watchOS) import WatchKit #endif /// Decodes image data. public protocol DataDecoding { /// Decodes image data. func decode(data: Data, response: URLResponse) -> Image? } /// Decodes image data. public struct DataDecoder: DataDecoding { /// Initializes the receiver. public init() {} /// Creates an image with the given data. public func decode(data: Data, response: URLResponse) -> Image? { return _decode(data) } } // Image initializers are documented as fully-thread safe: // // > The immutable nature of image objects also means that they are safe // to create and use from any thread. // // However, there are some versions of iOS which violated this. The // `UIImage` is supposably fully thread safe again starting with iOS 10. // // The `queue.sync` call below prevents the majority of the potential // crashes that could happen on the previous versions of iOS. // // See also https://github.com/AFNetworking/AFNetworking/issues/2572 private let _queue = DispatchQueue(label: "com.github.kean.Nuke.DataDecoder") private func _decode(_ data: Data) -> Image? { return _queue.sync { #if os(macOS) return NSImage(data: data) #else #if os(iOS) || os(tvOS) let scale = UIScreen.main.scale #else let scale = WKInterfaceDevice.current().screenScale #endif return UIImage(data: data, scale: scale) #endif } } /// Composes multiple data decoders. public struct DataDecoderComposition: DataDecoding { public let decoders: [DataDecoding] /// Composes multiple data decoders. public init(decoders: [DataDecoding]) { self.decoders = decoders } /// Decoders are applied in order in which they are present in the decoders /// array. The decoding stops when one of the decoders produces an image. public func decode(data: Data, response: URLResponse) -> Image? { for decoder in decoders { if let image = decoder.decode(data: data, response: response) { return image } } return nil } }
9519ff30f8b027c1973ab5897db15d5a
27.604938
79
0.649115
false
false
false
false
akkakks/firefox-ios
refs/heads/master
Providers/AccountManager.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation let KeyUsername = "username" let KeyLoggedIn = "loggedIn" class AccountProfileManager: NSObject { let loginCallback: (account: Profile) -> () let logoutCallback: LogoutCallback private let userDefaults = NSUserDefaults(suiteName: ExtensionUtils.sharedContainerIdentifier())! init(loginCallback: (account: Profile) -> (), logoutCallback: LogoutCallback) { self.loginCallback = loginCallback self.logoutCallback = logoutCallback } func getAccount() -> Profile? { if !isLoggedIn() { return nil } if let user = getUsername() { let credential = getKeychainUser(user) return getRESTAccount(credential) } return nil } private func isLoggedIn() -> Bool { if let loggedIn = userDefaults.objectForKey(KeyLoggedIn) as? Bool { return loggedIn } return false } func getUsername() -> String? { return userDefaults.objectForKey(KeyUsername) as? String } // TODO: Logging in once saves the credentials for the entire session, making it impossible // to really log out. Using "None" as persistence should fix this -- why doesn't it? func login(username: String, password: String, error: ((error: RequestError) -> ())) { let credential = NSURLCredential(user: username, password: password, persistence: .None) RestAPI.sendRequest( credential, // TODO: this should use a different request request: "bookmarks/recent", success: { _ in println("Logged in as user \(username)") self.setKeychainUser(username, password: password) let account = self.getRESTAccount(credential) self.loginCallback(account: account) }, error: error ) } private func getRESTAccount(credential: NSURLCredential) -> RESTAccountProfile { return RESTAccountProfile(localName: "default", credential: credential, logoutCallback: { account in // Remove this user from the keychain, regardless of whether the account is actually logged in. self.removeKeychain(credential.user!) // If the username is the active account, log out. if credential.user! == self.getUsername() { self.userDefaults.removeObjectForKey(KeyUsername) self.userDefaults.setObject(false, forKey: KeyLoggedIn) self.logoutCallback(profile: account) } }) } func getKeychainUser(username: NSString) -> NSURLCredential { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, "Firefox105", username, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue]) var dataTypeRef :Unmanaged<AnyObject>? // Search for the keychain items let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef) let opaque = dataTypeRef?.toOpaque() var contentsOfKeychain: NSString? if let op = opaque? { let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue() // Convert the data retrieved from the keychain into a string contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) } else { println("Nothing was retrieved from the keychain. Status code \(status)") } let credential = NSURLCredential(user: username, password: contentsOfKeychain!, persistence: .None) return credential } private func removeKeychain(username: NSString) { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) let query = NSDictionary(objects: [kSecClassGenericPassword, "Client", username], forKeys: [kSecClass,kSecAttrService, kSecAttrAccount]) SecItemDelete(query as CFDictionaryRef) } private func setKeychainUser(username: String, password: String) -> Bool { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) let secret: NSData = password.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let query = NSDictionary(objects: [kSecClassGenericPassword, "Firefox105", username, secret], forKeys: [kSecClass,kSecAttrService, kSecAttrAccount, kSecValueData]) SecItemDelete(query as CFDictionaryRef) SecItemAdd(query as CFDictionaryRef, nil) userDefaults.setObject(username, forKey: KeyUsername) userDefaults.setObject(true, forKey: KeyLoggedIn) return true } }
ec62ed5f57d3c1aae8edda7912de7555
42.226667
287
0.690315
false
false
false
false
coderMONSTER/iosstar
refs/heads/master
iOSStar/Other/UIBarExtension.swift
gpl-3.0
1
// // UIBarExtension.swift // iOSStar // // Created by sum on 2017/4/26. // Copyright © 2017年 YunDian. All rights reserved. // import Foundation import UIKit extension UINavigationBar { func hideBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(view: self) navigationBarImageView!.isHidden = true } func showBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(view: self) navigationBarImageView!.isHidden = false } private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? { if view.isKind(of: UIImageView.classForCoder()) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) { return imageView } } return nil } } extension UIToolbar { func hideHairline() { let navigationBarImageView = hairlineImageViewInToolbar(view: self) navigationBarImageView!.isHidden = true } func showHairline() { let navigationBarImageView = hairlineImageViewInToolbar(view: self) navigationBarImageView!.isHidden = false } private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? { if view.isKind(of: UIImageView() as! AnyClass) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) { return imageView } } return nil } }
38afc5a4e69bca362d25ba48215f5c3f
32.4
93
0.645073
false
false
false
false
JGiola/swift
refs/heads/main
validation-test/stdlib/StringUTF8.swift
apache-2.0
14
// RUN: %empty-directory(%t) // RUN: %target-clang -fobjc-arc %S/Inputs/NSSlowString/NSSlowString.m -c -o %t/NSSlowString.o // RUN: %target-build-swift -I %S/Inputs/NSSlowString/ %t/NSSlowString.o %s -o %t/String // RUN: %target-codesign %t/String // RUN: %target-run %t/String // REQUIRES: executable_test // XFAIL: interpret // UNSUPPORTED: freestanding import StdlibUnittest import StdlibCollectionUnittest import StdlibUnicodeUnittest #if _runtime(_ObjC) import NSSlowString import Foundation // For NSRange #endif extension String { func withFastUTF8IfAvailable<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R? { return try utf8.withContiguousStorageIfAvailable(f) } var isFastUTF8: Bool { return withFastUTF8IfAvailable({ _ in return 0 }) != nil } // Prevent that the optimizer removes 'self += ""' in makeNative() @inline(never) static func emptyString() -> String { return "" } mutating func makeNative() { self += String.emptyString() } var isASCII: Bool { return utf8.allSatisfy { $0 < 0x7f } } } var UTF8Tests = TestSuite("StringUTF8Tests") var strings: Array<String> = [ "abcd", "abcdefghijklmnop", "abcde\u{301}fghijk", "a\u{301}", "👻", "Spooky long string. 👻", "в чащах юга жил-был цитрус? да, но фальшивый экземпляр", "日", ] let kCFStringEncodingASCII: UInt32 = 0x0600 #if _runtime(_ObjC) var utf16ByteSequences = utf16Tests.flatMap { $0.value }.map { $0.encoded } private func testForeignContiguous(slowString: NSSlowString, string: String) { // Lazily bridged strings are not contiguous UTF-8 var slowString = NSSlowString(string: string) as String expectFalse(slowString.isFastUTF8) expectEqualSequence(string.utf8, slowString.utf8) // They become fast when mutated slowString.makeNative() expectTrue(slowString.isFastUTF8) expectEqualSequence( string.utf8, slowString.withFastUTF8IfAvailable(Array.init)!) // Contiguous ASCII CFStrings provide access, even if lazily bridged if string.isASCII { let cfString = string.withCString { CFStringCreateWithCString(nil, $0, kCFStringEncodingASCII)! } as String expectTrue(cfString.isFastUTF8) expectEqualSequence( string.utf8, cfString.withFastUTF8IfAvailable(Array.init)!) } } #endif UTF8Tests.test("Contiguous Access") { for string in strings { print(string) // Native strings are contiguous UTF-8 expectTrue(string.isFastUTF8) expectEqualSequence( Array(string.utf8), string.withFastUTF8IfAvailable(Array.init)!) // FIXME: Bridge small non-ASCII as StringStorage // expectTrue(((string as NSString) as String).isFastUTF8) var copy = string expectTrue(copy.isFastUTF8) copy.makeNative() expectTrue(copy.isFastUTF8) // FIXME: Bridge small non-ASCII as StringStorage // expectTrue(((copy as NSString) as String).isFastUTF8) #if _runtime(_ObjC) testForeignContiguous(slowString: NSSlowString(string: string), string: string) #endif } #if _runtime(_ObjC) for bytes in utf16ByteSequences { bytes.withContiguousStorageIfAvailable { let slowString = NSSlowString(characters: $0.baseAddress!, length: UInt($0.count)) let string = String(decoding: $0, as: UTF16.self) testForeignContiguous(slowString: slowString, string: string) } } #endif } runAllTests()
5c297481e3d83a783572715a801b536b
27.231405
94
0.702283
false
true
false
false
KrishMunot/swift
refs/heads/master
test/ClangModules/AppKit_test.swift
apache-2.0
3
// RUN: %target-parse-verify-swift %clang-importer-sdk // REQUIRES: OS=macosx import AppKit class MyDocument : NSDocument { override func read(from URL: NSURL, ofType type: String) throws { try super.read(from: URL, ofType: type) } override func write(to URL: NSURL, ofType type: String) throws { try super.write(to: URL, ofType: type) } } func test(_ URL: NSURL, controller: NSDocumentController) { try! NSDocument(contentsOf: URL, ofType: "") // expected-warning{{unused}} try! MyDocument(contentsOf: URL, ofType: "") try! controller.makeDocument(withContentsOf: URL, ofType: "") } extension NSBox { func foo() { print("abc") // expected-warning {{use of 'print' treated as a reference to instance method in class 'NSView'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} } } class MyView : NSView { func foo() { print("abc") // expected-warning {{use of 'print' treated as a reference to instance method in class 'NSView'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} } }
106dbacd18ecf609744edf7a1df0fa03
31.435897
115
0.664032
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
test/decl/protocol/req/recursion.swift
apache-2.0
1
// RUN: %target-parse-verify-swift protocol SomeProtocol { typealias T } extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}} // rdar://problem/20000145 public protocol P { typealias T } public struct S<A: P where A.T == S<A>> {} // rdar://problem/19840527 class X<T where T == X> { // expected-error{{same-type requirement makes generic parameter 'T' non-generic}} var type: T { return self.dynamicType } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}} } protocol Y { typealias Z = Z // expected-error{{type alias 'Z' circularly references itself}} }
2e1a12903e5a06d8e243f4f8700fa6a5
30.545455
136
0.693084
false
false
false
false
sztoth/PodcastChapters
refs/heads/develop
PodcastChapters/UI/Views/ChapterCell/ChapterViewItem.swift
mit
1
// // ChapterViewItem.swift // PodcastChapters // // Created by Szabolcs Toth on 2016. 10. 25.. // Copyright © 2016. Szabolcs Toth. All rights reserved. // import Cocoa class ChapterViewItem: NSCollectionViewItem { var text: String { get { return chapterView.text } set { chapterView.text = newValue } } var highlighted: Bool { get { return chapterView.highlighted } set { chapterView.highlighted = newValue } } fileprivate var chapterView: ChapterViewItemView { return view as! ChapterViewItemView } override func loadView() { let customView: ChapterViewItemView = ChapterViewItemView.pch_loadFromNib()! view = customView } override func prepareForReuse() { super.prepareForReuse() highlighted = false } override func viewDidLoad() { super.viewDidLoad() chapterView.setup() highlighted = false } }
fe2ab30cafb37486b082d549b68584a6
21.738095
84
0.640838
false
false
false
false
nathankot/RxSwift
refs/heads/master
RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchViewModel.swift
mit
2
// // SearchViewModel.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import RxCocoa class SearchViewModel: Disposable { // outputs let rows: Observable<[SearchResultViewModel]> let subscriptions = CompositeDisposable() // public methods init(searchText: Observable<String>, selectedResult: Observable<SearchResultViewModel>) { let $: Dependencies = Dependencies.sharedDependencies let wireframe = Dependencies.sharedDependencies.wireframe let API = DefaultWikipediaAPI.sharedAPI self.rows = searchText >- throttle(0.3, $.mainScheduler) >- distinctUntilChanged >- map { query in API.getSearchResults(query) >- startWith([]) // clears results on new search term >- catch([]) } >- switchLatest >- map { results in results.map { SearchResultViewModel( searchResult: $0 ) } } selectedResult >- subscribeNext { searchResult in wireframe.openURL(searchResult.searchResult.URL) } >- subscriptions.addDisposable } func dispose() { subscriptions.dispose() } }
76efaafefde7735f587fc3d567162d2d
25.482143
73
0.551957
false
false
false
false
andriitishchenko/vkLibManage
refs/heads/master
vkLibManage/PlaylistController.swift
mit
1
// // PlaylistController.swift // vkLibManage // // Created by Andrii Tiischenko on 10/7/16. // Copyright © 2016 Andrii Tiischenko. All rights reserved. // import UIKit class PlaylistController:BaseTableController { let cellId = "PlaylistCell" var selectedPlaylist:PlaylistItem? = nil override func viewDidLoad() { super.viewDidLoad() let play = UIBarButtonItem(title: "Sync", style: .plain, target: self, action: #selector(startSync)) self.navigationItem.rightBarButtonItems = [play] self.reload() self.pullRefreshInection() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath) let item:PlaylistItem? = (self.dataSource?[indexPath.row] as? PlaylistItem) cell.textLabel?.text = item?.title return cell } @IBAction func startSync(sender: UIButton?) { SyncManager.sharedInstance.sync { self.reload() } } override func reload() { DBManager.sharedInstance.getLocalPlaylists { list in self.dataSource = list self.tableView.reloadData() } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let cell = tableView.cellForRow(at: indexPath) // if cell != nil {} let item:PlaylistItem? = (self.dataSource?[indexPath.row] as? PlaylistItem) selectedPlaylist = item self.performSegue(withIdentifier: "SongsListControllerSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc:SongsListController = segue.destination as! SongsListController vc.album = self.selectedPlaylist } @IBAction func toolBarClick(sender: UIBarButtonItem?) { } }
2a70caa9d47f2e757748e1b0b6ceafec
25.428571
109
0.625225
false
false
false
false
mattdonnelly/Swifter
refs/heads/master
SwifterDemoMac/ViewController.swift
mit
1
// // ViewController.swift // SwifterDemoMac // // Copyright (c) 2014 Matt Donnelly. // // 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 Cocoa import Accounts import SwifterMac import AuthenticationServices enum AuthorizationMode { @available(macOS, deprecated: 10.13) case account case browser } let authorizationMode: AuthorizationMode = .browser class ViewController: NSViewController { private var swifter = Swifter( consumerKey: "nLl1mNYc25avPPF4oIzMyQzft", consumerSecret: "Qm3e5JTXDhbbLl44cq6WdK00tSUwa17tWlO8Bf70douE4dcJe2" ) @objc dynamic var tweets: [Tweet] = [] override func viewDidLoad() { super.viewDidLoad() switch authorizationMode { case .account: authorizeWithACAccountStore() case .browser: authorizeWithWebLogin() } } @available(macOS, deprecated: 10.13) private func authorizeWithACAccountStore() { if #available(macOS 10.13, *) { self.alert(title: "Deprecated", message: "ACAccountStore was deprecated on macOS 10.13, please use the OAuth flow instead") return } let store = ACAccountStore() let type = store.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) store.requestAccessToAccounts(with: type, options: nil) { granted, error in guard let twitterAccounts = store.accounts(with: type), granted else { self.alert(error: error) return } if twitterAccounts.isEmpty { self.alert(title: "Error", message: "There are no Twitter accounts configured. You can add or create a Twitter account in Settings.") return } else { let twitterAccount = twitterAccounts[0] as! ACAccount self.swifter = Swifter(account: twitterAccount) self.fetchTwitterHomeStream() } } } private func authorizeWithWebLogin() { let callbackUrl = URL(string: "swifter://success")! if #available(macOS 10.15, *) { swifter.authorize(withProvider: self, callbackURL: callbackUrl) { _, _ in self.fetchTwitterHomeStream() } failure: { self.alert(error: $0) } } else { swifter.authorize(withCallback: callbackUrl) { _, _ in self.fetchTwitterHomeStream() } failure: { self.alert(error: $0) } } } private func fetchTwitterHomeStream() { swifter.getHomeTimeline(count: 100) { json in guard let tweets = json.array else { return } self.tweets = tweets.map { return Tweet(name: $0["user"]["name"].string!, text: $0["text"].string!) } } failure: { self.alert(error: $0) } } private func alert(title: String, message: String) { let alert = NSAlert() alert.alertStyle = .warning alert.messageText = title alert.informativeText = message alert.runModal() } private func alert(error: Error) { NSAlert(error: error).runModal() } } // This is need for ASWebAuthenticationSession @available(macOS 10.15, *) extension ViewController: ASWebAuthenticationPresentationContextProviding { func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return self.view.window! } }
76adc68f415563362c6bcb9bbc68ab58
35.524194
149
0.650916
false
false
false
false
segura2010/exodobb-for-iOS
refs/heads/swift3/ios10
exodoapp/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // exodoapp // // Created by Alberto on 18/9/15. // Copyright © 2015 Alberto. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool { // Override point for customization after application launch. let addStatusBar = UIView() addStatusBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 20); addStatusBar.backgroundColor = UIColor.orange self.window?.rootViewController?.view .addSubview(addStatusBar) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.xxxx.ProjectName" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "DataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("ProjectName.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do{ try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) }catch{ coordinator = nil // Report any error we got. var dict = [String: AnyObject]() //dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" //dict[NSLocalizedFailureReasonErrorKey] = failureReason //dict[NSUnderlyingErrorKey] = error //error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { let error: NSError? = nil if moc.hasChanges { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
b0c42f778bb774b1f4c20d4f268e40d2
51.108333
290
0.699024
false
false
false
false
ivygulch/IVGFoundation
refs/heads/master
IVGFoundation/source/extensions/Dictionary+IVGFoundation.swift
mit
1
// // Dictionary+IVGFoundation.swift // IVGFoundation // // Created by Douglas Sjoquist on 4/30/17. // Copyright © 2017 Ivy Gulch. All rights reserved. // import Foundation public extension Dictionary { // snarfed from: https://ericasadun.com/2015/07/08/swift-merging-dictionaries/ public mutating func merge<S: Sequence>(_ sequence: S?) where S.Iterator.Element == (key: Key, value: Value) { guard let s = sequence else { return } for (key, value) in s { self[key] = value } } public func hasKey(_ key: Key) -> Bool { return keys.contains(key) } public mutating func set(ifNotEmpty optionalValue: Value?, forKey key: Key) { if let stringValue = optionalValue as? String { if !stringValue.isEmpty { self[key] = optionalValue } } else if let _ = optionalValue { self[key] = optionalValue } } }
b77e91656f9d3e7b2a9cb1ee5761243f
26.171429
114
0.599369
false
false
false
false
gabmarfer/CucumberPicker
refs/heads/master
CucumberPicker/Classes/ViewControllers/HomeViewController.swift
mit
1
// // ViewController.swift // CucumberPicker // // Created by gabmarfer on 24/01/2017. // Copyright © 2017 Kenoca Software. All rights reserved. // import UIKit class HomeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { static let HomeCellIdentifier = "HomeCell" var images = [UIImage]() var cucumberManager: CucumberManager! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. cucumberManager = CucumberManager(self) cucumberManager.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: CollectionView override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeViewController.HomeCellIdentifier, for: indexPath) as! HomeCell cell.imgView.image = images[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let width = collectionView.bounds.width - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) return CGSize(width: width, height: width*2/3) } // MARK: Actions @IBAction func handleTapCameraButton(_ sender: UIBarButtonItem) { cucumberManager.showImagePicker(fromButton: sender) } } extension HomeViewController: CucumberDelegate { func cumberManager(_ manager: CucumberManager, didFinishPickingImages images: [UIImage]) { self.images = images collectionView?.reloadData() } }
a5af8e2163b4347250378ef6e5cb3ae4
34.15625
160
0.706222
false
false
false
false
calebd/swift
refs/heads/master
stdlib/public/core/StaticString.swift
apache-2.0
8
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: Because StaticString is used in the // implementation of _precondition(), _fatalErrorMessage(), etc., we // keep it extremely close to the bare metal. In particular, because // we store only Builtin types, we are guaranteed that no assertions // are involved in its construction. This feature is crucial for // preventing infinite recursion even in non-asserting cases. /// A string type designed to represent text that is known at compile time. /// /// Instances of the `StaticString` type are immutable. `StaticString` provides /// limited, pointer-based access to its contents, unlike Swift's more /// commonly used `String` type. A static string can store its value as a /// pointer to an ASCII code unit sequence, as a pointer to a UTF-8 code unit /// sequence, or as a single Unicode scalar value. @_fixed_layout public struct StaticString : _ExpressibleByBuiltinUnicodeScalarLiteral, _ExpressibleByBuiltinExtendedGraphemeClusterLiteral, _ExpressibleByBuiltinStringLiteral, ExpressibleByUnicodeScalarLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringLiteral, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// Either a pointer to the start of UTF-8 data, represented as an integer, /// or an integer representation of a single Unicode scalar. @_versioned internal var _startPtrOrData: Builtin.Word /// If `_startPtrOrData` is a pointer, contains the length of the UTF-8 data /// in bytes. @_versioned internal var _utf8CodeUnitCount: Builtin.Word /// Extra flags: /// /// - bit 0: set to 0 if `_startPtrOrData` is a pointer, or to 1 if it is a /// Unicode scalar. /// /// - bit 1: set to 1 if `_startPtrOrData` is a pointer and string data is /// ASCII. @_versioned internal var _flags: Builtin.Int8 /// A pointer to the beginning of the string's UTF-8 encoded representation. /// /// The static string must store a pointer to either ASCII or UTF-8 code /// units. Accessing this property when `hasPointerRepresentation` is /// `false` triggers a runtime error. @_transparent public var utf8Start: UnsafePointer<UInt8> { _precondition( hasPointerRepresentation, "StaticString should have pointer representation") return UnsafePointer(bitPattern: UInt(_startPtrOrData))! } /// The stored Unicode scalar value. /// /// The static string must store a single Unicode scalar value. Accessing /// this property when `hasPointerRepresentation` is `true` triggers a /// runtime error. @_transparent public var unicodeScalar: Unicode.Scalar { _precondition( !hasPointerRepresentation, "StaticString should have Unicode scalar representation") return Unicode.Scalar(UInt32(UInt(_startPtrOrData)))! } /// The length in bytes of the static string's ASCII or UTF-8 representation. /// /// - Warning: If the static string stores a single Unicode scalar value, the /// value of `utf8CodeUnitCount` is unspecified. @_transparent public var utf8CodeUnitCount: Int { _precondition( hasPointerRepresentation, "StaticString should have pointer representation") return Int(_utf8CodeUnitCount) } /// A Boolean value indicating whether the static string stores a pointer to /// ASCII or UTF-8 code units. @_transparent public var hasPointerRepresentation: Bool { return (UInt8(_flags) & 0x1) == 0 } /// A Boolean value that is `true` if the static string stores a pointer to /// ASCII code units. /// /// Use this property in conjunction with `hasPointerRepresentation` to /// determine whether a static string with pointer representation stores an /// ASCII or UTF-8 code unit sequence. /// /// - Warning: If the static string stores a single Unicode scalar value, the /// value of `isASCII` is unspecified. @_transparent public var isASCII: Bool { return (UInt8(_flags) & 0x2) != 0 } /// Invokes the given closure with a buffer containing the static string's /// UTF-8 code unit sequence. /// /// This method works regardless of whether the static string stores a /// pointer or a single Unicode scalar value. /// /// The pointer argument to `body` is valid only during the execution of /// `withUTF8Buffer(_:)`. Do not store or return the pointer for later use. /// /// - Parameter body: A closure that takes a buffer pointer to the static /// string's UTF-8 code unit sequence as its sole argument. If the closure /// has a return value, that value is also used as the return value of the /// `withUTF8Buffer(invoke:)` method. The pointer argument is valid only /// for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure. public func withUTF8Buffer<R>( _ body: (UnsafeBufferPointer<UInt8>) -> R) -> R { if hasPointerRepresentation { return body(UnsafeBufferPointer( start: utf8Start, count: utf8CodeUnitCount)) } else { var buffer: UInt64 = 0 var i = 0 let sink: (UInt8) -> Void = { #if _endian(little) buffer = buffer | (UInt64($0) << (UInt64(i) * 8)) #else buffer = buffer | (UInt64($0) << (UInt64(7-i) * 8)) #endif i += 1 } UTF8.encode(unicodeScalar, into: sink) return body(UnsafeBufferPointer( start: UnsafePointer(Builtin.addressof(&buffer)), count: i)) } } /// Creates an empty static string. @_transparent public init() { self = "" } @_versioned @_transparent internal init( _start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { // We don't go through UnsafePointer here to make things simpler for alias // analysis. A higher-level algorithm may be trying to make sure an // unrelated buffer is not accessed or freed. self._startPtrOrData = Builtin.ptrtoint_Word(_start) self._utf8CodeUnitCount = utf8CodeUnitCount self._flags = Bool(isASCII) ? (0x2 as UInt8)._value : (0x0 as UInt8)._value } @_versioned @_transparent internal init( unicodeScalar: Builtin.Int32 ) { self._startPtrOrData = UInt(UInt32(unicodeScalar))._builtinWordValue self._utf8CodeUnitCount = 0._builtinWordValue self._flags = Unicode.Scalar(_builtinUnicodeScalarLiteral: unicodeScalar).isASCII ? (0x3 as UInt8)._value : (0x1 as UInt8)._value } @effects(readonly) @_transparent public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = StaticString(unicodeScalar: value) } /// Creates an instance initialized to a single Unicode scalar. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string with a Unicode scalar. @effects(readonly) @_transparent public init(unicodeScalarLiteral value: StaticString) { self = value } @effects(readonly) @_transparent public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self = StaticString( _builtinStringLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII ) } /// Creates an instance initialized to a single character that is made up of /// one or more Unicode code points. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string using an extended grapheme cluster. @effects(readonly) @_transparent public init(extendedGraphemeClusterLiteral value: StaticString) { self = value } @effects(readonly) @_transparent public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self = StaticString( _start: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII) } /// Creates an instance initialized to the value of a string literal. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string using a string literal. @effects(readonly) @_transparent public init(stringLiteral value: StaticString) { self = value } /// A string representation of the static string. public var description: String { return withUTF8Buffer { (buffer) in return String._fromWellFormedCodeUnitSequence(UTF8.self, input: buffer) } } /// A textual representation of the static string, suitable for debugging. public var debugDescription: String { return self.description.debugDescription } } extension StaticString { public var customMirror: Mirror { return Mirror(reflecting: description) } } extension StaticString { @available(*, unavailable, renamed: "utf8CodeUnitCount") public var byteSize: Int { Builtin.unreachable() } @available(*, unavailable, message: "use the 'String(_:)' initializer") public var stringValue: String { Builtin.unreachable() } }
8c729d06dc18576a62c455b1c9d4514b
32.622378
85
0.689476
false
false
false
false
git-hushuai/MOMO
refs/heads/master
MMHSMeterialProject/UINavigationController/BusinessFile/订单Item/TKOptimizeViewController.swift
mit
1
// // TKOptimizeViewController.swift // MMHSMeterialProject // // Created by hushuaike on 16/4/10. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class TKOptimizeViewController: UIViewController { let OptimizeTableView = UITableView.init(frame: CGRectZero, style: .Plain); override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0); self.SetUpUI(); } func SetUpUI(){ let viewNameArray = ["全部","已完成","处理中"]; let optionmizeTopScrollView = TKMineOrderTopScrollView.shareInstance(); let optionmizeDetailScrooLView = TKMineOrderDetailScrollView.shareInstance(); optionmizeTopScrollView.nameArray = viewNameArray; optionmizeDetailScrooLView.viewNameArray = viewNameArray; self.view.addSubview(optionmizeTopScrollView) self.view.addSubview(optionmizeDetailScrooLView); optionmizeTopScrollView.initWithNameButtons(); optionmizeDetailScrooLView.initWithViews(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: rgb color func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } }
9f0c2d6af7b1ba7b590c9519e7dfc200
25.923077
85
0.657857
false
false
false
false
cohena100/Shimi
refs/heads/master
Carthage/Checkouts/RxSwiftExt/Tests/RxCocoa/distinct+RxCocoa.swift
mit
2
// // distinct+RxCocoa.swift // RxSwiftExt // // Created by Rafael Ferreira on 3/8/17. // Copyright © 2017 RxSwiftCommunity. All rights reserved. // import XCTest import RxCocoa import RxSwift import RxTest import RxSwiftExt class DistinctCocoaTests: XCTestCase { func testDistinctHashableOne() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyHashable(id: 1, name: "SomeName")] let errored = DummyHashable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyHashable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored).distinct().drive(observer) scheduler.start() let correct = [ next(0, DummyHashable(id: 1, name: "SomeName")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctHashableTwo() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyHashable(id: 1, name: "SomeName"), DummyHashable(id: 2, name: "SomeName2"), DummyHashable(id: 1, name: "SomeName")] let errored = DummyHashable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyHashable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored).distinct().drive(observer) scheduler.start() let correct = [ next(0, DummyHashable(id: 1, name: "SomeName")), next(0, DummyHashable(id: 2, name: "SomeName2")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctHashableEmpty() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let errored = DummyHashable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyHashable.self) _ = Observable<DummyHashable>.empty().asDriver(onErrorJustReturn: errored) .distinct().drive(observer) scheduler.start() let correct: [Recorded<Event<DummyHashable>>] = [ completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctEquatableOne() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName")] let value = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: value) .distinct().drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctEquatableTwo() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName"), DummyEquatable(id: 2, name: "SomeName2"), DummyEquatable(id: 1, name: "SomeName")] let errored = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored).distinct().drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName")), next(0, DummyEquatable(id: 2, name: "SomeName2")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctEquatableEmpty() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let errored = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable<DummyEquatable>.empty().asDriver(onErrorJustReturn: errored).distinct().drive(observer) scheduler.start() let correct: [Recorded<Event<DummyEquatable>>] = [ completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctPredicateOne() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName1"), DummyEquatable(id: 2, name: "SomeName2"), DummyEquatable(id: 3, name: "SomeName1")] let errored = DummyEquatable(id: 0, name: "SomeName0") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored) .distinct { $0.name.contains("1") }.drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName1")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctPredicateAll() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName1"), DummyEquatable(id: 2, name: "SomeName2"), DummyEquatable(id: 3, name: "SomeName3")] let errored = DummyEquatable(id: 0, name: "SomeName0") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored) .distinct { $0.name.contains("T") }.drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName1")), next(0, DummyEquatable(id: 2, name: "SomeName2")), next(0, DummyEquatable(id: 3, name: "SomeName3")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctPredicateEmpty() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let errored = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable<DummyEquatable>.empty().asDriver(onErrorJustReturn: errored) .distinct { $0.id < 0 } .drive(observer) scheduler.start() let correct: [Recorded<Event<DummyEquatable>>] = [ completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctPredicateFirst() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName1"), DummyEquatable(id: 2, name: "SomeName2"), DummyEquatable(id: 3, name: "SomeName3")] let errored = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored) .distinct { $0.id > 0 }.drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName1")), completed(0) ] XCTAssertEqual(observer.events, correct) } } func testDistinctPredicateTwo() { let scheduler = TestScheduler(initialClock: 0, simulateProcessingDelay: false) driveOnScheduler(scheduler) { let values = [DummyEquatable(id: 1, name: "SomeName1"), DummyEquatable(id: 2, name: "SomeName2"), DummyEquatable(id: 3, name: "SomeName3")] let errored = DummyEquatable(id: 0, name: "NoneName") let observer = scheduler.createObserver(DummyEquatable.self) _ = Observable.from(values).asDriver(onErrorJustReturn: errored) .distinct { $0.id > 1 }.drive(observer) scheduler.start() let correct = [ next(0, DummyEquatable(id: 1, name: "SomeName1")), next(0, DummyEquatable(id: 2, name: "SomeName2")), completed(0) ] XCTAssertEqual(observer.events, correct) } } }
6dfd82cc9c5fad18e480eb8e7afad7f4
32.875887
114
0.557835
false
true
false
false
ruanjunhao/RJWeiBo
refs/heads/master
RJWeiBo/RJWeiBo/Classes/OAuth/Model/UserAccount.swift
apache-2.0
1
// // UserAccount.swift // RJWeiBo // // Created by ruanjh on 2017/3/8. // Copyright © 2017年 app. All rights reserved. // import UIKit class UserAccount: NSObject,NSCoding { // MARK:- 属性 /// 授权AccessToken var access_token : String? /// 过期时间-->秒 var expires_in : TimeInterval = 0.0 { didSet { expires_date = Date(timeIntervalSinceNow: expires_in) } } /// 用户ID var uid : String? /// 过期日期 var expires_date : Date? /// 昵称 var screen_name : String? /// 用户的头像地址 var avatar_large : String? init(dict : [String : AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } // MARK:- 属性重写description属性 override var description: String { return dictionaryWithValues(forKeys: ["access_token", "expires_date", "uid", "screen_name", "avatar_large"]).description } // MARK:- 归档&解档 /// 解档的方法 required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObject(forKey: "access_token") as? String uid = aDecoder.decodeObject(forKey: "uid") as? String expires_date = aDecoder.decodeObject(forKey: "expires_date") as? Date avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String } func encode (with aCoder: NSCoder) { aCoder.encode(access_token, forKey: "access_token") aCoder.encode(uid, forKey: "uid") aCoder.encode(expires_date, forKey: "expires_date") aCoder.encode(avatar_large, forKey: "avatar_large") aCoder.encode(screen_name, forKey: "screen_name") } //ruantime 归档 // // 归档 // func encode(with aCoder: NSCoder) { // var count: UInt32 = 0 // guard let ivars = class_copyIvarList(self.classForCoder, &count) else { // return // } // for i in 0 ..< count { // let ivar = ivars[Int(i)] // let name = ivar_getName(ivar) // // let key = NSString.init(utf8String: name!) as! String // // if let value = self.value(forKey: key) { // aCoder.encode(value, forKey: key) // } // } // // 释放ivars // free(ivars) // } // // // 反归档 // required init?(coder aDecoder: NSCoder) { // super.init() // var count: UInt32 = 0 // guard let ivars = class_copyIvarList(self.classForCoder, &count) else { // return // } // for i in 0 ..< count { // let ivar = ivars[Int(i)] // let name = ivar_getName(ivar) // let key = NSString.init(utf8String: name!) as! String // if let value = aDecoder.decodeObject(forKey: key) { // self.setValue(value, forKey: key) // } // } // // 释放ivars // free(ivars) // } }
46da6f83f3740c6a3deac92b77c02cbc
24.682927
128
0.523583
false
false
false
false
Zane6w/MoreColorButton
refs/heads/master
ColorfulButton/ColorfulButton/Home Page/HomeViewController.swift
apache-2.0
1
// // HomeViewController.swift // ColorfulButton // // Created by zhi zhou on 2017/2/11. // Copyright © 2017年 zhi zhou. All rights reserved. // import UIKit import AudioToolbox private let contentIdentifier = "contentCell" class HomeViewController: UIViewController { // MARK:- 属性 var tableView: UITableView? let weekTitleView = WeekView() var effectView: UIVisualEffectView? /// 标题数组 var titles = [String]() // MARK:- 系统函数 override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupTableView() setupWeekTitleView() loadTitleData() _ = opinionEditStatus() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK:- tableView 相关 extension HomeViewController: UITableViewDataSource, UITableViewDelegate { fileprivate func setupTableView() { tableView = UITableView(frame: self.view.bounds, style: .plain) tableView?.dataSource = self tableView?.delegate = self tableView?.separatorInset = .zero tableView?.separatorColor = #colorLiteral(red: 0.8862745098, green: 0.8862745098, blue: 0.8941176471, alpha: 1) tableView?.tableFooterView = UIView() self.view.addSubview(tableView!) tableView?.register(ContentCell.self, forCellReuseIdentifier: contentIdentifier) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: contentIdentifier, for: indexPath) as! ContentCell cell.titleStr = titles[indexPath.row] cell.controller = self cell.selectionStyle = .none tableView.rowHeight = cell.cellHeight return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailController = CalendarViewController() detailController.title = titles[indexPath.row] navigationController?.pushViewController(detailController, animated: true) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { if tableView.isEditing { return .delete } else { return .none } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let thisYear = Calendar.current.component(.year, from: Date()) _ = SQLite.shared.delete(id: "\(titles[indexPath.row])#\(thisYear)", inTable: regularDataBase) _ = SQLite.shared.delete(title: titles[indexPath.row], inTable: regularDataBase) titles.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) let isEnabled = opinionEditStatus() editButtonChange(isEnabled: isEnabled) if titles.count == 0 { tableView.setEditing(false, animated: true) } } } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { if isChineseLanguage { return "删除" } else { return "Delete" } } } // MARK:- 导航栏设置 extension HomeViewController: CAAnimationDelegate { fileprivate func setupNavigationBar() { let naviBar = navigationController?.navigationBar let naviBarBottomLine = naviBar?.subviews.first?.subviews.first if (naviBarBottomLine?.isKind(of: UIImageView.self))! { // 隐藏导航栏底部的黑色细线 naviBarBottomLine?.isHidden = true } setupNavigationItem() } fileprivate func setupNavigationItem() { if isChineseLanguage { self.title = "规律" } else { self.title = "Regular" } // ----------------- let editButton = UIButton(type: .system) if isChineseLanguage { editButton.setTitle("编辑", for: .normal) } else { editButton.setTitle("Edit", for: .normal) } editButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) editButton.frame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width / 7, height: (navigationController?.navigationBar.bounds.height)!)) editButton.tintColor = appColor editButton.contentVerticalAlignment = .center editButton.contentHorizontalAlignment = .left editButton.addTarget(self, action: #selector(editRegular), for: .touchUpInside) let editRegularItem = UIBarButtonItem(customView: editButton) navigationItem.leftBarButtonItem = editRegularItem // ----------------- let addNewRegularItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewRegular)) addNewRegularItem.style = .plain navigationItem.rightBarButtonItem = addNewRegularItem _ = opinionEditStatus() } @objc fileprivate func editRegular() { tableView?.setEditing(!(tableView?.isEditing)!, animated: true) editButtonChange(isEnabled: true) } @objc fileprivate func addNewRegular() { let remarksVC = RemarksController() remarksVC.style = .add setupBlur() UIView.animate(withDuration: 0.3, animations: { remarksVC.modalPresentationStyle = .custom self.present(remarksVC, animated: true, completion: nil) self.navigationController?.navigationBar.isHidden = true self.effectView?.alpha = 1.0 }) // 取消备注后隐藏蒙版 remarksVC.cancelTapHandler = { (_) in UIView.animate(withDuration: 0.3, animations: { self.effectView?.alpha = 0 }, completion: { (_) in self.navigationController?.navigationBar.isHidden = false }) } remarksVC.pinTapHandler = { (controller, text) in if text! == "" { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) self.shake(view: controller.remarksView) } else { // 添加数据 self.loadTitleData(title: text!) self.dismiss(animated: true, completion: nil) UIView.animate(withDuration: 0.3, animations: { self.effectView?.alpha = 0 }, completion: { (_) in self.navigationController?.navigationBar.isHidden = false _ = self.opinionEditStatus() }) } } } /// 判断左上角编辑按钮是否可用 fileprivate func opinionEditStatus() -> Bool { if titles.count == 0 { navigationItem.leftBarButtonItem?.isEnabled = false return false } else { navigationItem.leftBarButtonItem?.isEnabled = true return true } } /// 左上角编辑按钮状态改变判断 fileprivate func editButtonChange(isEnabled: Bool) { let editButton = navigationItem.leftBarButtonItem?.customView as! UIButton if (tableView?.isEditing)! { editButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17) if isChineseLanguage { editButton.setTitle("完成", for: .normal) } else { editButton.setTitle("Done", for: .normal) } } else { editButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) if isChineseLanguage { editButton.setTitle("编辑", for: .normal) } else { editButton.setTitle("Edit", for: .normal) } } if isEnabled { } else { editButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) if isChineseLanguage { editButton.setTitle("编辑", for: .normal) } else { editButton.setTitle("Edit", for: .normal) } } } fileprivate func setupBlur() { let effect = UIBlurEffect(style: .dark) effectView = UIVisualEffectView(effect: effect) effectView?.frame = UIScreen.main.bounds effectView?.alpha = 0 view.addSubview(effectView!) } /// 左右晃动动画 fileprivate func shake(view: UIView) { let shakeAnimation = CAKeyframeAnimation() shakeAnimation.keyPath = "transform.translation.x" // 偏移量 let offset = 5 // 过程 shakeAnimation.values = [-offset, 0, offset, 0, -offset, 0, offset, 0, -offset, 0, offset, 0, -offset, 0, offset, 0, -offset, 0, offset, 0, -offset, 0, offset, 0] // 动画时间 shakeAnimation.duration = 0.3 // 执行次数 shakeAnimation.repeatCount = 1 // 切出此界面再回来动画不会停止 shakeAnimation.isRemovedOnCompletion = true shakeAnimation.delegate = self view.layer.add(shakeAnimation, forKey: "shake") } fileprivate func setupWeekTitleView() { weekTitleView.frame = CGRect(x: 0, y: (navigationController?.navigationBar.frame.maxY)!, width: UIScreen.main.bounds.width, height: 30) weekTitleView.sorted = .Right weekTitleView.firstWorkday = 0 self.view.addSubview(weekTitleView) tableView?.contentInset = UIEdgeInsets(top: weekTitleView.bounds.height, left: 0, bottom: 0, right: 0) } } // MARK:- 数据相关 extension HomeViewController { /// 加载标题数据 fileprivate func loadTitleData(title: String? = nil) { if title == nil { let titleArray = SQLite.shared.queryAllTitle(inTable: regularDataBase) if titleArray != nil, titleArray?.count != 0 { var titles = titleArray! titles.reverse() self.titles = titles as! [String] } } else { _ = SQLite.shared.insert(title: title!, inTable: regularDataBase) self.titles.insert(title!, at: 0) } tableView?.reloadData() } }
c42692603aa490a3510eeb7d56765a6d
31.504505
170
0.585828
false
false
false
false
PGSSoft/3DSnakeAR
refs/heads/master
3DSnake/common classes/GameController.swift
mit
1
// // GameController.swift // 3DSnake // // Created by Michal Kowalski on 19.07.2017. // Copyright © 2017 PGS Software. All rights reserved. // import SceneKit protocol GameControllerDelegate: class { func gameOver(sender: GameController) } final class GameController { private let sceneSize = 15 private var timer: Timer! // MARK: - Properties Nodes public var worldSceneNode: SCNNode? private var pointsNode: SCNNode? private var pointsText: SCNText? // MARK: - Properties model var snake: Snake = Snake() private var points: Int = 0 private var mushroomNode: Mushroom private var mushroomPos: int2 = int2(0, 0) private var gameOver: Bool = false weak var delegate: GameControllerDelegate? init() { if let worldScene = SCNScene(named: "worldScene.scn") { worldSceneNode = worldScene.rootNode.childNode(withName: "worldScene", recursively: true) worldSceneNode?.removeFromParentNode() worldSceneNode?.addChildNode(snake) pointsNode = worldSceneNode?.childNode(withName: "pointsText", recursively: true) pointsNode?.pivot = SCNMatrix4MakeTranslation(5, 0, 0) pointsText = pointsNode?.geometry as? SCNText } mushroomNode = Mushroom() } // MARK: - Game Lifecycle func reset() { gameOver = false points = 0 snake.reset() worldSceneNode?.addChildNode(mushroomNode) placeMushroom() } func startGame() { timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateSnake), userInfo: nil, repeats: true) let rotateAction = SCNAction.rotate(by: CGFloat.pi * 2, around: SCNVector3(0, 1, 0), duration: 10.0) pointsNode?.runAction(SCNAction.repeatForever(rotateAction)) } // MARK: - Actions @objc func updateSnake(timer: Timer) { if snake.canMove(sceneSize: sceneSize) { snake.move() if snake.ateItself || !snake.canMove(sceneSize: sceneSize) { gameOver = true snake.runCrashAnimation() delegate?.gameOver(sender: self) timer.invalidate() } if snake.headPos == mushroomPos { snake.grow() placeMushroom() } } else { snake.runCrashAnimation() delegate?.gameOver(sender: self) } updatePoints(points: "\(snake.body.count - 4)") } func turnRight() { snake.turnRight() } func turnLeft() { snake.turnLeft() } func addToNode(rootNode: SCNNode) { guard let worldScene = worldSceneNode else { return } worldScene.removeFromParentNode() rootNode.addChildNode(worldScene) worldScene.scale = SCNVector3(0.1, 0.1, 0.1) } // MARK: - Helpers private func updatePoints(points: String) { guard let pointsNode = pointsNode else { return } pointsText?.string = points let width = pointsNode.boundingBox.max.x - pointsNode.boundingBox.min.x pointsNode.pivot = SCNMatrix4MakeTranslation(width / 2, 0, 0) pointsNode.position.x = -width / 2 } private func placeMushroom() { repeat { let x = Int32(arc4random() % UInt32((sceneSize - 1))) - 7 let y = Int32(arc4random() % UInt32((sceneSize - 1))) - 7 mushroomPos = int2(x, y) } while snake.body.contains(mushroomPos) mushroomNode.position = SCNVector3(Float(mushroomPos.x), 0, Float(mushroomPos.y)) mushroomNode.runAppearAnimation() } }
68a9d0336c0f71ba3983d8ef5f2ee545
29.859504
133
0.607659
false
false
false
false
calebkleveter/BluetoothKit
refs/heads/master
Source/BKRemotePeer.swift
mit
2
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // 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 Foundation public protocol BKRemotePeerDelegate: class { /** Called when the remote peer sent data. - parameter remotePeripheral: The remote peripheral that sent the data. - parameter data: The data it sent. */ func remotePeer(_ remotePeer: BKRemotePeer, didSendArbitraryData data: Data) } public func == (lhs: BKRemotePeer, rhs: BKRemotePeer) -> Bool { return (lhs.identifier == rhs.identifier) } public class BKRemotePeer: Equatable { /// A unique identifier for the peer, derived from the underlying CBCentral or CBPeripheral object, or set manually. public let identifier: UUID public weak var delegate: BKRemotePeerDelegate? internal var configuration: BKConfiguration? private var data: Data? init(identifier: UUID) { self.identifier = identifier } internal var maximumUpdateValueLength: Int { return 20 } internal func handleReceivedData(_ receivedData: Data) { if receivedData == configuration!.endOfDataMark { if let finalData = data { delegate?.remotePeer(self, didSendArbitraryData: finalData) } data = nil return } if self.data != nil { self.data?.append(receivedData) return } self.data = receivedData } }
ad5d5f7c750ec4b194fffba3413c944e
33.972603
120
0.695652
false
false
false
false
asurinsaka/swift_examples_2.1
refs/heads/master
QRCode/QRCode/BarcodeImageViewController.swift
mit
1
// // BarcodeImageViewController.swift // QRCode // // Created by larryhou on 22/12/2015. // Copyright © 2015 larryhou. All rights reserved. // import Foundation import UIKit class BarcodeImageViewController:UIViewController, UITextFieldDelegate { @IBOutlet weak var inputTextView: UITextField! @IBOutlet weak var quietSpaceSlider: UISlider! @IBOutlet weak var quietSpaceIndicator: UILabel! @IBOutlet weak var barcodeImageView: BarcodeImageView! override func viewDidLoad() { super.viewDidLoad() // barcodeImageView.layer.borderWidth = 1.0 // barcodeImageView.layer.borderColor = UIColor(white: 0.9, alpha: 1.0).CGColor } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) quietSpaceDidChange(quietSpaceSlider) } @IBAction func quietSpaceDidChange(sender: UISlider) { quietSpaceIndicator.text = String(format: "%5.2f", sender.value) barcodeImageView.inputQuietSpace = Double(sender.value) } @IBAction func inputTextDidChange(sender: UITextField) { barcodeImageView.inputMessage = sender.text! } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
4df7d24b725ab7b6ed51a9c7bc48bd25
25.7
86
0.680899
false
false
false
false
juanm95/Soundwich
refs/heads/master
Quaggify/LibraryViewController.swift
mit
1
// // LibraryViewController.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit import AVFoundation import MediaPlayer import Flurry_iOS_SDK class LibraryViewController: ViewController, SPTAudioStreamingDelegate, SPTAudioStreamingPlaybackDelegate { private func react(reactionEmoji: String, trackResponse: Track, frommember: String, time: String, elaboration: String) { API.reactToSong(reaction: "\(reactionEmoji) \(elaboration)", time: time, username: UserDefaults.standard.value(forKey: "username") as! String, to: frommember) thePlayer.needToReact = false thePlayer.injected = false let commandCenter = MPRemoteCommandCenter.shared() commandCenter.nextTrackCommand.isEnabled = true commandCenter.previousTrackCommand.isEnabled = true commandCenter.pauseCommand.isEnabled = true commandCenter.playCommand.isEnabled = true if #available(iOS 9.1, *) { commandCenter.changePlaybackPositionCommand.isEnabled = true } else { // Fallback on earlier versions } let playlistId = UserDefaults.standard.value(forKey: "playlistId") let ownerid = User.current.id let owner = User(JSON: ["id": ownerid]) var soundwichPlaylist = Playlist(JSON: ["id": UserDefaults.standard.value(forKey: "playlistId")]) soundwichPlaylist?.owner = owner API.addTrackToPlaylist(track: trackResponse, playlist: soundwichPlaylist) {(string: String?, error: Error?) in print (string) } var plainTextReaction = "" switch reactionEmoji { case "😂": plainTextReaction = "laughing" break case "😎": plainTextReaction = "dope" break case "💩": plainTextReaction = "poop" break case "😡": plainTextReaction = "angry" break default: break } let reactionParameters = ["reaction": plainTextReaction, "message": elaboration] as [String: Any] Flurry.logEvent("Plaintext reactions", withParameters: reactionParameters) } func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didStopPlayingTrack trackUri: String!) { var trackName = "spotify:track:" if (thePlayer.needToReact) { thePlayer.nowPlaying?.playSong() return } API.checkQueue() { [weak self] (response) in guard let strongSelf = self else { return } print(response) let randomNumber = arc4random_uniform(100) let response = response as [String:Any] let chanceOfQueue = 40 as UInt32 if response["queued"] as! Bool && randomNumber < chanceOfQueue { thePlayer.needToReact = true thePlayer.injected = true let commandCenter = MPRemoteCommandCenter.shared() commandCenter.nextTrackCommand.isEnabled = false commandCenter.previousTrackCommand.isEnabled = false commandCenter.pauseCommand.isEnabled = false commandCenter.playCommand.isEnabled = false if #available(iOS 9.1, *) { commandCenter.changePlaybackPositionCommand.isEnabled = false } else { // Fallback on earlier versions } let data = response["data"] as! [String:Any] let songid = data["songid"] as! String let time = data["time"] as! String let tomember = data["tomember"] as! String let frommember = data["frommember"] as! String trackName += songid thePlayer.nowPlaying?.track?.id = songid API.fetchTrack(track: thePlayer.nowPlaying?.track) { [weak self] (trackResponse, error) in guard let strongSelf = self else { return } if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let trackResponse = trackResponse { let alertController = UIAlertController(title: "Soundwich", message: "React to this song \(frommember) sent.", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "💩", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in let elaboration = alertController.textFields![0].text! self?.react(reactionEmoji: "💩", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration) })) alertController.addAction(UIAlertAction(title: "😂", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in let elaboration = alertController.textFields![0].text! self?.react(reactionEmoji: "😂", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration) })) alertController.addAction(UIAlertAction(title: "😡", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in let elaboration = alertController.textFields![0].text! self?.react(reactionEmoji: "😡", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration) })) alertController.addAction(UIAlertAction(title: "😎", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in let elaboration = alertController.textFields![0].text! self?.react(reactionEmoji: "😎", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration) })) alertController.addTextField { textfield in textfield.placeholder = "Attach message to reaction" } thePlayer.nowPlaying?.track = trackResponse DispatchQueue.main.async { UIApplication.topViewController()?.present(alertController, animated: true) } } } } else { thePlayer.indeX += 1 if thePlayer.indeX >= (thePlayer.trackList?.total)! { thePlayer.indeX = 0 } if(thePlayer.indeX < 0 ) { thePlayer.indeX = 0} thePlayer.nowPlaying?.track = thePlayer.trackList?.items?[thePlayer.indeX].track } } } func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChangePosition position: TimeInterval){ thePlayer.nowPlaying?.playbackSlider.setValue(Float(position), animated: false) } var auth = SPTAuth.defaultInstance()! var session:SPTSession! var ACCESS_TOKEN: String? { return UserDefaults.standard.string(forKey: "ACCESS_TOKEN_KEY") } func initializePlayer() { UIApplication.shared.beginReceivingRemoteControlEvents() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: []) self.becomeFirstResponder() do { try AVAudioSession.sharedInstance().setActive(true) print("AVAudioSession is Active") } catch let error as NSError { print(error.localizedDescription) } } catch let error as NSError { print(error.localizedDescription) } let CLIENT_ID = "9f0cac5d230c4877a2a769febe804681" if thePlayer.spotifyPlayer == nil { thePlayer.spotifyPlayer = SPTAudioStreamingController.sharedInstance() thePlayer.spotifyPlayer!.playbackDelegate = self thePlayer.spotifyPlayer!.delegate = self try! thePlayer.spotifyPlayer!.start(withClientId: CLIENT_ID) thePlayer.spotifyPlayer!.login(withAccessToken: ACCESS_TOKEN) } } var spotifyObject: SpotifyObject<Playlist>? var playlists: [Playlist] = [] { didSet { collectionView.reloadData() } } lazy var logoutButton: UIBarButtonItem = { let button = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logout)) button.tintColor = ColorPalette.white return button }() lazy var searchButton: UIBarButtonItem = { let button = UIBarButtonItem(image: UIImage(named: "tab_icon_search"), style: .plain, target: self, action: #selector(search)) button.tintColor = ColorPalette.white return button }() var limit = 20 var offset = 0 var isFetching = false let lineSpacing: CGFloat = 16 let interItemSpacing: CGFloat = 8 let contentInset: CGFloat = 8 lazy var refreshControl: UIRefreshControl = { let rc = UIRefreshControl() rc.addTarget(self, action: #selector(refreshPlaylists), for: .valueChanged) return rc }() lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .vertical flowLayout.minimumLineSpacing = self.lineSpacing flowLayout.minimumInteritemSpacing = self.interItemSpacing let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) cv.addSubview(self.refreshControl) cv.keyboardDismissMode = .onDrag cv.alwaysBounceVertical = true cv.showsVerticalScrollIndicator = false cv.contentInset = UIEdgeInsets(top: self.contentInset, left: self.contentInset, bottom: self.contentInset, right: self.contentInset) cv.backgroundColor = .clear cv.delegate = self cv.dataSource = self cv.register(PlaylistCell.self, forCellWithReuseIdentifier: PlaylistCell.identifier) cv.register(LoadingFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier) return cv }() // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() setupViews() addListeners() fetchPlaylists() //addCreateNewPlaylistCell() } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { collectionView.collectionViewLayout.invalidateLayout() } // MARK: Layout override func setupViews() { super.setupViews() initializePlayer() navigationItem.title = "Your Playlists".uppercased() navigationItem.rightBarButtonItem = logoutButton navigationItem.leftBarButtonItem = searchButton view.addSubview(collectionView) collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) } } // MARK: Actions extension LibraryViewController { func addCreateNewPlaylistCell () { /*if let createNewPlaylistItem = Playlist(JSON: ["name": "Create new playlist"]) { playlists.append(createNewPlaylistItem) }*/ } func logout () { SpotifyService.shared.logout() thePlayer.nowPlaying?.pauseSong() } func search() { let searchViewController = SearchViewController() searchViewController.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) navigationController?.pushViewController(searchViewController, animated: true) } func addListeners () { NotificationCenter.default.addObserver(self, selector: #selector(onUserPlaylistUpdate), name: .onUserPlaylistUpdate, object: nil) } func onUserPlaylistUpdate (notification: Notification) { guard let playlist = notification.object as? Playlist else { return } if playlists[safe: 1] != nil { playlists.insert(playlist, at: 1) collectionView.reloadData() } } func fetchPlaylists () { isFetching = true API.fetchSoundwichPlaylist() { (soundwichPlaylist: Playlist?, error: Error?) in self.playlists.append(soundwichPlaylist!) API.fetchCurrentUsersPlaylists(limit: self.limit, offset: self.offset) { [weak self] (spotifyObject, error) in guard let strongSelf = self else { return } strongSelf.isFetching = false strongSelf.refreshControl.endRefreshing() strongSelf.offset += strongSelf.limit if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let items = spotifyObject?.items { strongSelf.playlists.append(contentsOf: items) strongSelf.spotifyObject = spotifyObject } } } } func refreshPlaylists () { if isFetching { return } isFetching = true print("Refreshing ") API.fetchSoundwichPlaylist() { (soundwichPlaylist: Playlist?, error: Error?) in //self.playlists.append(soundwichPlaylist!) API.fetchCurrentUsersPlaylists(limit: self.limit, offset: self.offset) { [weak self] (spotifyObject, error) in guard let strongSelf = self else { return } strongSelf.isFetching = false strongSelf.refreshControl.endRefreshing() strongSelf.offset += strongSelf.limit if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let items = spotifyObject?.items { strongSelf.playlists.append(contentsOf: items) strongSelf.spotifyObject = spotifyObject } } } /* API.fetchCurrentUsersPlaylists(limit: limit, offset: 0) { [weak self] (spotifyObject, error) in guard let strongSelf = self else { return } strongSelf.isFetching = false strongSelf.refreshControl.endRefreshing() strongSelf.offset = strongSelf.limit if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let items = spotifyObject?.items { strongSelf.playlists.removeAll() strongSelf.addCreateNewPlaylistCell() strongSelf.playlists.append(contentsOf: items) strongSelf.spotifyObject = spotifyObject } }*/ } func showNewPlaylistModal () { /*let alertController = UIAlertController(title: "Create new Playlist".uppercased(), message: nil, preferredStyle: .alert) alertController.addTextField { textfield in textfield.placeholder = "Playlist name" textfield.addTarget(self, action: #selector(self.textDidChange(textField:)), for: .editingChanged) } let cancelAction = UIAlertAction(title: "Cancel".uppercased(), style: .destructive, handler: nil) let createAction = UIAlertAction(title: "Create".uppercased(), style: .default) { _ in if let textfield = alertController.textFields?.first, let playlistName = textfield.text { API.createNewPlaylist(name: playlistName) { [weak self] (playlist, error) in if let error = error { print(error) // Showing error message Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let playlist = playlist { if self?.playlists[safe: 1] != nil { self?.collectionView.performBatchUpdates({ self?.playlists.insert(playlist, at: 1) self?.collectionView.insertItems(at: [IndexPath(item: 1, section: 0)]) }, completion: nil) } } } } } createAction.isEnabled = false alertController.addAction(cancelAction) alertController.addAction(createAction) present(alertController, animated: true, completion: nil) } func textDidChange (textField: UITextField) { if let topVc = UIApplication.topViewController() as? UIAlertController, let createAction = topVc.actions[safe: 1] { if let text = textField.text, text != "" { createAction.isEnabled = true } else { createAction.isEnabled = false } } */ } } // MARK: UICollectionViewDelegate extension LibraryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let playlistVC = PlaylistViewController() playlistVC.playlist = playlists[safe: indexPath.item] if playlistVC.playlist?.name == "Recommended by Soundwich" { let playlistParameters = ["playlist": "Soundwich Recommended"] as [String: Any] Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters) } else if playlistVC.playlist?.name == "Received on Soundwich" { let playlistParameters = ["playlist": "Soundwich Received"] as [String: Any] Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters) } else { let playlistParameters = ["playlist": "Theirs"] as [String: Any] Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters) } navigationController?.pushViewController(playlistVC, animated: true) } } // MARK: UICollectionViewDataSource extension LibraryViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return playlists.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PlaylistCell.identifier, for: indexPath) as? PlaylistCell { let playlist = playlists[safe: indexPath.item] cell.playlist = playlist if indexPath.item == 0 { cell.subTitleLabel.text = "Soundwich" } // Create ne playlist /*if indexPath.item == 0 { cell.imageView.image = #imageLiteral(resourceName: "icon_add_playlist").withRenderingMode(.alwaysTemplate) cell.subTitleLabel.isHidden = true cell.imageView.tintColor = ColorPalette.white }*/ if let totalItems = spotifyObject?.items?.count, indexPath.item == totalItems - 1, spotifyObject?.next != nil { if !isFetching { fetchPlaylists() } } return cell } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionFooter: if let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier, for: indexPath) as? LoadingFooterView { return footerView } default: break } return UICollectionReusableView() } } // MARK: UICollectionViewDelegateFlowLayout extension LibraryViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width - (contentInset * 2), height: 72) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { if spotifyObject?.next != nil { return CGSize(width: view.frame.width, height: 36) } return .zero } } extension LibraryViewController: ScrollDelegate { func scrollToTop() { if spotifyObject?.items?.count ?? 0 > 0 { collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true) } } }
c6e61f163780c69e625a437559c64cbc
43.020161
227
0.61221
false
false
false
false
WildDogTeam/lib-ios-streambase
refs/heads/master
StreamBaseExample/StreamBaseKit/ResourceBase.swift
mit
1
// // ResourceBase.swift // StreamBaseKit // // Created by IMacLi on 15/10/12. // Copyright © 2015年 liwuyang. All rights reserved. // import Foundation import Wilddog /** A dictionary for associating object instances with keys. These keys are used for interpolating paths. */ public typealias ResourceDict = [String: BaseItemProtocol] /** An error handler invoked when a persistance operation fails. */ public typealias ResourceErrorHandler = (error: NSError) -> Void /** A done handler. Operation was successful if error is nil. */ public typealias ResourceDoneHandler = (error: NSError?) -> Void /** A predicate that is evaluated when updating counters. */ public typealias CounterPredicate = BaseItemProtocol -> Bool /** An interface for registering resources, binding classes with the location of where they are stored in Wilddog. */ public protocol ResourceRegistry { /// This handler is invoked when persistance operations fail. var errorHandler: ResourceErrorHandler? { get set } /** Register a specific type with a path. Each class can only be registered one time. The path is interpolated dynamically based on context. For example, registry.resource(Message.self, "group/$group/messages/@") will have $group interpolated by context, and that the message id (represented by "@") will be filled in using childByAutoId() for ```create()``` or the value of the object's key for ```update()``` and ```destroy()```. If you want to store the same object in two different paths, you can do so by subclassing it. :param: type The object type being registered. :param: path The path being registered with this object type. */ func resource(type: BaseItemProtocol.Type, path: String) /** Register a counter so that a field is updated on one object whenever another object is created or destroyed. For example, registry.counter(Message.self, "like_count", MessageLike.self) says that the message's ```like_count``` should be incremented when messages are liked, and decremented when those likes are removed. It's ok to register multiple counters for the same object. Note that these counters are computed client-side. You may also need a server-side job to correct the inconsistencies that will inevitably occur. :param: type The object type that has a counter. :param: name The name of the counter property. :param: countingType The object type that is being counted. */ func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type) /** Register a counter with a predicate. The predicate can be used to filter which objects affect the count. If the object is updated, the predicate is evaulated before and after the change and the counter is updated accordingly. :param: type The object type that has a counter. :param: name The name of the counter property. :param: countingType The object type that is being counted. :param: predicate A predicate that determines whether the counter applies. */ func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type, predicate: CounterPredicate?) } /** Core functionality for persisting BaseItems. It coordinates the mapping from objects to wilddog storage through create/update/delete operations. Extensible to provide custom functionality through subclassing. NOTE: Client code should not interact with this class directly. Use the ResourceRegistry protocol to register paths, and the far more convient ResourceContext to invoke create/update/destroy. The public methods in this class generally are so for subclasses. */ public class ResourceBase : CustomDebugStringConvertible { struct ResourceSpec : CustomDebugStringConvertible { let type: BaseItemProtocol.Type let path: String init(type: BaseItemProtocol.Type, path: String) { self.type = type self.path = path } var debugDescription: String { return "\(path) \(type)" } } struct CounterSpec : CustomDebugStringConvertible, Equatable { let type: BaseItemProtocol.Type let countingType: BaseItemProtocol.Type let path: String let predicate: CounterPredicate? init(type: BaseItemProtocol.Type, countingType: BaseItemProtocol.Type, path: String, predicate: CounterPredicate?) { self.type = type self.countingType = countingType self.path = path self.predicate = predicate } var debugDescription: String { return "\(path) \(type) counting: \(countingType)" } } struct ResolvedCounter : Hashable { let spec: CounterSpec let counterInstance: BaseItemProtocol init(spec: CounterSpec, counterInstance: BaseItemProtocol) { self.spec = spec self.counterInstance = counterInstance } var hashValue: Int { return spec.path.hashValue } } /// The underlying wilddog instance for this base. public let wilddog: WDGSyncReference var resources = [ResourceSpec]() var counters = [CounterSpec]() /// An error handler. Set this to be notified of errors communicating with Wilddog. public var errorHandler: ResourceErrorHandler? /** Construct a new instance. :param: wilddog The underlying Wilddog store. */ public init(wilddog: WDGSyncReference) { self.wilddog = wilddog } /// Provide a description including basic stats. public var debugDescription: String { return "ResourceBase with \(resources.count) resources and \(counters.count) counters" } // MARK: Create hooks /** Called before creating an instance. Subclass can invoke done handler when ready (eg, after performing some network operation, including one with wilddog). If ```done()``` is not invoked, then nothing happens. If it's invoked with an error, then the error handler is invoked and no futher processing happens. :param: instance The instance to create. Typically the key is nil. :param: key The key for the instance. Typically this is a new auto id. :param: context The resouce context for this request. :param: done The handler to call (or not) for storage process to continue. */ public func willCreateInstance(instance: BaseItemProtocol, key: String, context: ResourceContext, done: ResourceDoneHandler) { done(error: nil) } /** Called immediately after a newly created instance has added to local storage. The underlying Wilddog will asynchronously push that instance to cloud storage. :param: instance The instance that was just created with key filled in. :param: context The resource context. */ public func didCreateInstance(instance: BaseItemProtocol, context: ResourceContext) { } /** Called after a newly created instance has been successfully persisted. Note that if the client is offline, this may never be called even if the operation succeeeds. For example, the app might be restarted before it goes back online. :param: instance The instance just persisted. :param: context The resource context. :param: error The error. If non-nil, the instance is NOT expected to be stored in cloud. */ public func didCreateAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) { } // MARK: Update hooks /** Called before updating an instance. Subclasses can reject this operation by not calling ```done()```. :param: instance The instance being updated. :param: context The resource context. :param: done Invoke this when ready to proceed with update. */ public func willUpdateInstance(instance: BaseItemProtocol, context: ResourceContext, done: ResourceDoneHandler) { done(error: nil) } /** Called immediately after an instance has been updated. :param: instance The instance updated. :param: context The resource context. */ public func didUpdateInstance(instance: BaseItemProtocol, context: ResourceContext) { } /** Called after an instance update has been successfully persisted. Note that if the client is offline, this may never be called even if the operation succeeeds. For example, the app might be restarted before it goes back online. :param: instance The instance just persisted. :param: context The resource context. :param: error The error. If non-nil, the update is NOT expected to be stored in cloud. */ public func didUpdateAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) { } // MARK: Destroy hooks /** Called before deleting an instance. Subclasses can reject this operation by not calling ```done()```. :param: instance The instance being updated. :param: context The resource context. :param: done Invoke this when ready to proceed with update. */ public func willDestroyInstance(instance: BaseItemProtocol, context: ResourceContext, done: ResourceDoneHandler) { done(error: nil) } /** Called immediately after an instance has been deleted. :param: instance The instance updated. :param: context The resource context. */ public func didDestroyInstance(instance: BaseItemProtocol, context: ResourceContext) { } /** Called after an instance delete has been successfully persisted. Note that if the client is offline, this may never be called even if the operation succeeeds. For example, the app might be restarted before it goes back online. :param: instance The instance just deleted from persistent store. :param: context The resource context. :param: error The error. If non-nil, the delete is NOT expected to be stored in cloud. */ public func didDestroyAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) { } /** Return the path part of the Wilddog ref. Eg, if the ref is ```"https://my.wilddogio.com/a/b/c"```, this method would return ```"/a/b/c"```. :param: ref The Wilddog ref. :returns: The path part of the ref URL. */ public class func refToPath(ref: WDGSyncReference) -> String { return NSURL(string: ref.description())!.path! } /** Override to maintain an log of actions for server-side processing of side-effects, notifications, etc. For more information, see: https://medium.com/@spf2/action-logs-for-wilddog-30a699200660 :param: path The path of the resource that just changed. :param: old The previous state of the data. If present, this is an update or delete. :param: new The new state of the data. If present, this is a create or update. :param: extraContext The context values that were not used in resolving the path. */ public func logAction(path: String, old: WDGDataSnapshot?, new: BaseItemProtocol?, extraContext: ResourceDict) { } /** Helper for splitting a path into components like "/a/b/c" -> ["a", "b", "c"]. Leading "/" ignored. :param: path The path to split. :returns: An array of path components. */ public class func splitPath(path: String) -> [String] { var p = path p.trimPrefix("/") return p.componentsSeparatedByString("/") } func buildRef(path: String, key: String?, context: ResourceContext) -> WDGSyncReference { var ref = wilddog for part in ResourceBase.splitPath(path) { if part == "@" { if let k = key { ref = ref.child(k) } else { ref = ref.childByAutoId() } } else if part.hasPrefix("$") { let name = part.prefixTrimmed("$") if let obj = context.get(name) { ref = ref.child(obj.key!) } else { fatalError("Cannot find \"\(name)\" for \(path) with context: \(context)") } } else { ref = ref.child(part) } } return ref } private func log(ref: WDGSyncReference, old: WDGDataSnapshot?, new: BaseItemProtocol?, context: ResourceContext, path: String) { let path = ResourceBase.refToPath(ref) var extra = ResourceDict() let skip = Set(ResourceBase.splitPath(path).filter{ $0.hasPrefix("$") }.map{ $0.prefixTrimmed("$") }) for (k, v) in context { if !skip.contains(k) { extra[k] = v } } logAction(path, old: old, new: new, extraContext: extra) } func incrementCounter(ref: WDGSyncReference, by: Int) { ref.runTransactionBlock({ current in var result = max(0, by) if let v = current.value as? Int { result = v + by } current.value = result return WDGTransactionResult.successWithValue(current) }) } public func findResourcePath(type: BaseItemProtocol.Type, context: ResourceContext?) -> String? { return resources.filter({ $0.type.self === type }).first?.path } func findCounters(countingInstance: BaseItemProtocol, context: ResourceContext) -> [ResolvedCounter] { return counters.filter { spec in if spec.countingType.self !== countingInstance.dynamicType.self { return false } if let pred = spec.predicate { return pred(countingInstance) } return true }.map { spec in (spec, self.findCounterInstance(spec.type, context: context)) }.filter { (spec, instance) in instance != nil }.map { (spec, instance) in ResolvedCounter(spec: spec, counterInstance: instance!) } } func findCounterInstance(type: BaseItemProtocol.Type, context: ResourceContext) -> BaseItemProtocol? { for (_, v) in context { if v.dynamicType.self === type.self { return v } } return nil } /** Get the Wilddog ref for a given instance in this context. :param: instance The instance. :param: context The resource context. :returns: A wilddog ref for this instance in this context. */ public func ref(instance: BaseItemProtocol, context: ResourceContext) -> WDGSyncReference { let path = findResourcePath(instance.dynamicType, context: context) assert(path != nil, "Cannot find ref for type \(instance.dynamicType)") return buildRef(path!, key: instance.key, context: context) } /** Get a Wilddog ref for where instances of this type are stored. :param: type The type. :param: context The resource context. :returns: A wilddog ref where to find instances of the given type. */ public func collectionRef(type: BaseItemProtocol.Type, context: ResourceContext) -> WDGSyncReference { let path = findResourcePath(type, context: context) assert(path != nil, "Cannot find stream for type \(type)") return buildRef(path!, key: "~", context: context).parent! } /** Store a a new item. If the key is not provided and the path its type is registered with contains "@", then an auto-id will be generated. :param: instance The instance to create. :param: context The resource context. */ public func create(instance: BaseItemProtocol, context: ResourceContext) { let path = findResourcePath(instance.dynamicType, context: context)! let ref = buildRef(path, key: instance.key, context: context) let inflight = Inflight() willCreateInstance(instance, key: ref.key, context: context) { (error) in if let err = error { self.errorHandler?(error: err) } else { instance.key = ref.key ref.setValue(instance.dict) { (error, ref) in inflight.hold() if let err = error { self.errorHandler?(error: err) } self.didCreateAndPersistInstance(instance, context: context, error: error) } for counter in self.findCounters(instance, context: context) { let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context) self.incrementCounter(counterRef, by: 1) } self.log(ref, old: nil, new: instance, context: context, path: path) self.didCreateInstance(instance, context: context) } } } /** Store updates made to an item. :param: instance The instance to update. :param: context The resource context. */ public func update(instance: BaseItemProtocol, context: ResourceContext) { let path = findResourcePath(instance.dynamicType, context: context)! let ref = buildRef(path, key: instance.key, context: context) let inflight = Inflight() willUpdateInstance(instance, context: context) { (error) in if let err = error { self.errorHandler?(error: err) } else { ref.observeSingleEventOfType(.Value, withBlock: { snapshot in ref.updateChildValues(instance.dict) { (error, ref) in inflight.hold() if let err = error { self.errorHandler?(error: err) } self.didUpdateAndPersistInstance(instance, context: context, error: error) } // If this change affects any counters, do corresponding increments and decrements. if let dict = snapshot.value as? [String: AnyObject] { let prev = instance.clone() prev.update(dict) let prevCounters = Set(self.findCounters(prev, context: context)) let curCounters = Set(self.findCounters(instance, context: context)) for counter in curCounters.subtract(prevCounters) { let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context) self.incrementCounter(counterRef, by: 1) } for counter in prevCounters.subtract(curCounters) { let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context) self.incrementCounter(counterRef, by: -1) } } self.log(ref, old: snapshot, new: instance, context: context, path: path) }, withCancelBlock: { error in self.errorHandler?(error: error) }) self.didUpdateInstance(instance, context: context) } } } /** Remove an item from cloud store. :param: instance The instance to update. :param: context The resource context. */ public func destroy(instance: BaseItemProtocol, context: ResourceContext) { let path = findResourcePath(instance.dynamicType, context: context)! let ref = buildRef(path, key: instance.key, context: context) let inflight = Inflight() willDestroyInstance(instance, context: context) { (error) in if let err = error { self.errorHandler?(error: err) } else { ref.observeSingleEventOfType(.Value, withBlock: { snapshot in ref.removeValueWithCompletionBlock { (error, ref) in inflight.hold() if let err = error { self.errorHandler?(error: err) } self.didDestroyAndPersistInstance(instance, context: context, error: error) } for counter in self.findCounters(instance, context: context) { let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context) self.incrementCounter(counterRef, by: -1) } self.log(ref, old: snapshot, new: nil, context: context, path: path) }, withCancelBlock: { error in self.errorHandler?(error: error) }) self.didDestroyInstance(instance, context: context) } } } } extension ResourceBase : ResourceRegistry { public func resource(type: BaseItemProtocol.Type, path: String) { precondition(findResourcePath(type, context: nil) == nil, "Attempted to add resource twice for same type: \(type) at \(path)") let spec = ResourceSpec(type: type, path: path) resources.append(spec) } public func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type) { counter(type, name: name, countingType: countingType, predicate: nil) } public func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type, predicate: CounterPredicate?) { let path = [findResourcePath(type, context: nil)!, name].joinWithSeparator("/") counters.append(CounterSpec(type: type, countingType: countingType, path: path, predicate: predicate)) } } func ==(lhs: ResourceBase.CounterSpec, rhs: ResourceBase.CounterSpec) -> Bool { return lhs.path == rhs.path && lhs.countingType === rhs.countingType } func ==(lhs: ResourceBase.ResolvedCounter, rhs: ResourceBase.ResolvedCounter) -> Bool { return lhs.spec == rhs.spec && lhs.counterInstance === rhs.counterInstance }
8e360420b1374825beb71798e1797fd0
39.929078
135
0.613585
false
false
false
false
GTennis/SuccessFramework
refs/heads/master
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Managers/LocalizationManager.swift
mit
2
// // LocalizationManager.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 22/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit // MARK: Convenience functions func localizedString(key: String)->String { let managerFactory: ManagerFactoryProtocol = ManagerFactory.shared() return managerFactory.localizationManager.localizedString(key: key) } class LocalizationManager: /*NSObject,*/ LocalizationManagerProtocol { init() { // ... } // MARK: LocalizationManagerProtocol // MARK: Strings // Gets the current localized string func localizedString(key: String) -> String { return _bundle.localizedString(forKey: key, value: nil, table: nil) } // Sets the desired language of the ones you have. // // If this function is not called it will use the default OS language. // If the language does not exists y returns the default OS language. func setLanguage(lang: String) { DDLogDebug(log: "LocalizationManager: setLanguage to " + lang) let path: String? = _bundle.path(forResource: lang, ofType: "lproj") if let path = path { _bundle = Bundle(path: path)! } else { //in case the language does not exists self.resetLocalization() } let userDefaults = UserDefaults.standard userDefaults.set([lang], forKey: "AppleLanguages") userDefaults.synchronize() // Post notification self.notifyObserversWithLangChange() } // Just gets the current setted up language func getLanguage() -> String { var result: String = ConstLangKeys.langEnglish if let languages = UserDefaults.standard.value(forKey: "AppleLanguages") as? Array<String> { if let preferredLang = languages.first { // Only 2-letter language codes are used accross the app. This method will always return first to letters on country code (e.g. for en-GB it will return en) result = String(preferredLang.characters.prefix(2)) } } return result } func getCurrentACLanguage() -> LanguageEntity { let shortName: String = self.getLanguage() let longName: String = self.getFullLanguageName(key: shortName) let lang: LanguageEntity = LanguageEntity.init(shortName: shortName, longName: longName) return lang } func resetLocalization() { _bundle = Bundle.main } func getFullLanguageName(key: String) -> String { // returns full language name in that language e.g.: // en = English // de = Deutsch let locale: NSLocale = NSLocale.init(localeIdentifier: key) var result: String = "UnknownLanguage" if let langName = locale.displayName(forKey: NSLocale.Key.identifier, value: key) { result = langName } return result } // MARK: State observers func addServiceObserver(observer: LocalizationManagerObserver, notificationType: LocalizationManagerNotificationType, callback: @escaping Callback, context: Any?) { _observers.add(observer: observer as AnyObject, notificationName: notificationType.rawValue, callback: callback, context: context) } func removeServiceObserver(observer: LocalizationManagerObserver, notificationType: LocalizationManagerNotificationType) { _observers.remove(observer: observer as AnyObject, notificationName: notificationType.rawValue) } func removeServiceObserver(observer: LocalizationManagerObserver) { _observers.remove(observer: observer as AnyObject) } // MARK: // MARK: Internal // MARK: // http://mikebuss.com/2014/06/22/lazy-initialization-swift/ internal lazy var _observers: ObserverListProtocol = SFObserverList.init(observedSubject: self) internal lazy var _bundle: Bundle = Bundle.main internal func notifyObserversWithLangChange() { _observers.notifyObservers(notificationName: LocalizationManagerNotificationType.didChangeLang.rawValue) } }
fc3ad620facf84fe8bfd082edd3027a0
33.121951
172
0.65386
false
false
false
false
danthorpe/Examples
refs/heads/development
Operations/Permissions/Permissions/PermissionViewController.swift
mit
1
// // PermissionViewController.swift // Permissions // // Created by Daniel Thorpe on 28/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import UIKit import PureLayout import Operations class PermissionViewController: UIViewController { class InfoBox: UIView { let informationLabel = UILabel.newAutoLayoutView() override init(frame: CGRect) { super.init(frame: frame) addSubview(informationLabel) informationLabel.autoPinEdgesToSuperviewMargins() configure() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { informationLabel.textAlignment = .Center informationLabel.numberOfLines = 4 informationLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) } } class InfoInstructionButtonBox: InfoBox { let instructionLabel = UILabel.newAutoLayoutView() let button = UIButton(type: .Custom) var verticalSpaceBetweenLabels: NSLayoutConstraint! var verticalSpaceBetweenButton: NSLayoutConstraint! override init(frame: CGRect) { super.init(frame: frame) addSubview(instructionLabel) addSubview(button) removeConstraints(constraints) informationLabel.autoPinEdgesToSuperviewMarginsExcludingEdge(.Bottom) verticalSpaceBetweenLabels = instructionLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: informationLabel, withOffset: 10) instructionLabel.autoPinEdgeToSuperviewMargin(.Leading) instructionLabel.autoPinEdgeToSuperviewMargin(.Trailing) verticalSpaceBetweenButton = button.autoPinEdge(.Top, toEdge: .Bottom, ofView: instructionLabel, withOffset: 10) button.autoPinEdgeToSuperviewMargin(.Bottom) button.autoAlignAxisToSuperviewMarginAxis(.Vertical) configure() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func configure() { super.configure() instructionLabel.textAlignment = .Center instructionLabel.numberOfLines = 0 instructionLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) button.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) } } enum Action { case RequestPermission case PerformOperation var selector: Selector { switch self { case .RequestPermission: return #selector(PermissionViewController.requestPermissionAction(_:)) case .PerformOperation: return #selector(PermissionViewController.performOperationAction(_:)) } } } enum State: Int { case Unknown, Authorized, Denied, Completed static var all: [State] = [ .Unknown, .Authorized, .Denied, .Completed ] } // UIViews let permissionNotDetermined = InfoInstructionButtonBox.newAutoLayoutView() let permissionDenied = InfoInstructionButtonBox.newAutoLayoutView() let permissionGranted = InfoInstructionButtonBox.newAutoLayoutView() let permissionReset = InfoInstructionButtonBox.newAutoLayoutView() let operationResults = InfoBox.newAutoLayoutView() let queue = OperationQueue() private var _state: State = .Unknown var state: State { get { return _state } set { switch (_state, newValue) { case (.Completed, _): break case (.Unknown, _): _state = newValue queue.addOperation(displayOperationForState(newValue, silent: true)) default: _state = newValue queue.addOperation(displayOperationForState(newValue, silent: false)) } } } override func loadView() { let _view = UIView(frame: CGRectZero) _view.backgroundColor = UIColor.whiteColor() func configureHierarchy() { _view.addSubview(permissionNotDetermined) _view.addSubview(permissionDenied) _view.addSubview(permissionGranted) _view.addSubview(operationResults) _view.addSubview(permissionReset) } func configureLayout() { for view in [permissionNotDetermined, permissionDenied, permissionGranted] { view.autoSetDimension(.Width, toSize: 300) view.autoCenterInSuperview() } operationResults.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero) permissionReset.button.hidden = true permissionReset.verticalSpaceBetweenButton.constant = 0 permissionReset.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top) } configureHierarchy() configureLayout() view = _view } override func viewDidLoad() { super.viewDidLoad() permissionNotDetermined.informationLabel.text = "We haven't yet asked permission to access your Address Book." permissionNotDetermined.instructionLabel.text = "Tap the button below to ask for permissions." permissionNotDetermined.button.setTitle("Start", forState: .Normal) permissionNotDetermined.button.addTarget(self, action: Action.RequestPermission.selector, forControlEvents: .TouchUpInside) permissionGranted.informationLabel.text = "Permissions was granted. Yay!" permissionGranted.instructionLabel.text = "We can now perform an operation as we've been granted the required permissions." permissionGranted.button.setTitle("Run", forState: .Normal) permissionGranted.button.addTarget(self, action: Action.PerformOperation.selector, forControlEvents: .TouchUpInside) permissionDenied.informationLabel.text = "Permission was denied or restricted. Oh Nos!" permissionDenied.instructionLabel.hidden = true permissionDenied.button.enabled = false permissionDenied.button.hidden = true permissionReset.informationLabel.text = "iOS remembers permissions for apps between launches and installes. But you can get around this." permissionReset.informationLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) permissionReset.informationLabel.textColor = UIColor.redColor() permissionReset.instructionLabel.text = "Either, run the app with a different bundle identififier. or reset your global permissions in General > Reset > Location & Address Book for example." permissionReset.instructionLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) permissionReset.instructionLabel.textColor = UIColor.redColor() permissionReset.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.3) for view in [permissionNotDetermined, permissionGranted, permissionDenied, permissionReset, operationResults] { view.hidden = true } for button in [permissionNotDetermined.button, permissionGranted.button] { button.setTitleColor(UIColor.globalTintColor ?? UIColor.blueColor(), forState: .Normal) } } // For Overriding func requestPermission() { assertionFailure("Must be overridden") } func performOperation() { assertionFailure("Must be overridden") } // MARK: Update UI func configureConditionsForState<C: Condition>(state: State, silent: Bool = true) -> (C) -> [Condition] { return { condition in switch (silent, state) { case (true, .Unknown): return [ SilentCondition(NegatedCondition(condition)) ] case (false, .Unknown): return [ NegatedCondition(condition) ] case (true, .Authorized): return [ SilentCondition(condition) ] case (false, .Authorized): return [ condition ] default: return [] } } } func conditionsForState(state: State, silent: Bool = true) -> [Condition] { // Subclasses should override and call this... // return configureConditionsForState(state, silent: silent)(BlockCondition { true }) fatalError("Requires subclassing otherwise view controller will be left hanging.") } func viewsForState(state: State) -> [UIView] { switch state { case .Unknown: return [permissionNotDetermined] case .Authorized: return [permissionGranted, permissionReset] case .Denied: return [permissionDenied, permissionReset] case .Completed: return [operationResults] } } func displayOperationForState(state: State, silent: Bool = true) -> Operation { let others: [State] = { var all = Set(State.all) let _ = all.remove(state) return Array(all) }() let viewsToHide = others.flatMap { self.viewsForState($0) } let viewsToShow = viewsForState(state) let update = BlockOperation { (continueWithError: BlockOperation.ContinuationBlockType) in dispatch_async(Queue.Main.queue) { viewsToHide.forEach { $0.hidden = true } viewsToShow.forEach { $0.hidden = false } continueWithError(error: nil) } } update.name = "Update UI for state \(state)" let conditions = conditionsForState(state, silent: silent) conditions.forEach { update.addCondition($0) } return update } // Actions @IBAction func requestPermissionAction(sender: UIButton) { requestPermission() } @IBAction func performOperationAction(sender: UIButton) { performOperation() } }
837ebae129d3a779a0d41fa00f2cf4b0
36.428571
198
0.642885
false
false
false
false
ingresse/ios-sdk
refs/heads/dev
IngresseSDK/Model/Response/AuthResponse.swift
mit
1
// // Copyright © 2019 Ingresse. All rights reserved. // extension Response { public struct Auth { public struct TwoFactor: Decodable { public var status: Bool? = false public var data: TwoFactorData? public struct TwoFactorData: Decodable { public var token: String? = "" public var userId: Int? = -1 public var authToken: String? = "" public var device: TwoFactorDevice? } public struct TwoFactorDevice: Decodable { public var id: String? = "" public var name: String? = "" public var creationdate: String? = "" } } } }
0864820a029d7907817786116bf66f60
28.36
54
0.513624
false
false
false
false
sahandnayebaziz/Dana-Hills
refs/heads/master
Dana Hills/CalendarViewController.swift
mit
1
// // CalendarViewController.swift // Dana Hills // // Created by Nayebaziz, Sahand on 9/21/16. // Copyright © 2016 Nayebaziz, Sahand. All rights reserved. // import UIKit import AFDateHelper class CalendarViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var days: [CalendarDay] = [] let tableView = UITableView() var dayForToday: CalendarDay? { return self.days.first(where: { day in day.date.compare(.isToday) }) } var dayNearestToTodayInFuture: CalendarDay? { return self.days.min { day, otherDay in return abs(day.date.timeIntervalSince(Date())) < abs(otherDay.date.timeIntervalSince(Date())) && day.date.compare(.isInTheFuture) } } override func viewDidLoad() { super.viewDidLoad() title = "Calendar" automaticallyAdjustsScrollViewInsets = false view.addSubview(tableView) tableView.snp.makeConstraints { make in make.top.equalTo(topLayoutGuide.snp.bottom) make.bottom.equalTo(bottomLayoutGuide.snp.top).offset(-58) make.width.equalTo(view) make.centerX.equalTo(view) } tableView.delegate = self tableView.dataSource = self tableView.register(CalendarTableViewCell.self, forCellReuseIdentifier: "cell") let bellSchedulesButton = UIButton() bellSchedulesButton.backgroundColor = Colors.blue bellSchedulesButton.setTitle("Bell Schedules", for: .normal) view.addSubview(bellSchedulesButton) bellSchedulesButton.snp.makeConstraints { make in make.height.equalTo(58) make.width.equalTo(view) make.centerX.equalTo(view) make.bottom.equalTo(bottomLayoutGuide.snp.top) } bellSchedulesButton.addTarget(self, action: #selector(tappedBellSchedules), for: .touchUpInside) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) _ = DanaHillsBack.getSchedule() .then { days -> Void in self.days = days self.tableView.reloadData() var scrollToIndex: IndexPath? = nil if let dayForToday = self.dayForToday, let i = self.days.index(of: dayForToday) { scrollToIndex = IndexPath(row: i, section: 0) } else if let dayNearestToTodayInFuture = self.dayNearestToTodayInFuture, let i = self.days.index(of: dayNearestToTodayInFuture) { scrollToIndex = IndexPath(row: i, section: 0) } if let scrollToIndex = scrollToIndex { self.tableView.scrollToRow(at: scrollToIndex, at: .top, animated: true) } }.recover { error -> Void in self.displayAlert(forError: error as! DanaHillsBackError) } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return days.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CalendarTableViewCell cell.set(forCalendarDay: days[indexPath.row]) return cell } @objc func tappedBellSchedules() { let vc = BellSchedulesViewController() let nav = LightNavigationController(rootViewController: vc) present(nav, animated: true, completion: nil) } }
57424d1ce546dbc32532c87b5dd3d5ea
34.981818
142
0.637191
false
false
false
false
SwiftGen/SwiftGen
refs/heads/stable
Sources/SwiftGenCLI/TemplateRef.swift
mit
1
// // SwiftGen // Copyright © 2022 SwiftGen // MIT Licence // import PathKit public enum TemplateRef: Equatable { case name(String) case path(Path) enum Error: Swift.Error { case namedTemplateNotFound(name: String) case templatePathNotFound(path: Path) case noTemplateProvided case multipleTemplateOptions(path: String, name: String) } public init(templateShortName: String, templateFullPath: String) throws { switch (!templateFullPath.isEmpty, !templateShortName.isEmpty) { case (false, false): throw Self.Error.noTemplateProvided case (false, true): self = .name(templateShortName) case (true, false): self = .path(Path(templateFullPath)) case (true, true): throw Self.Error.multipleTemplateOptions(path: templateFullPath, name: templateShortName) } } /// Returns the path of a template /// /// * If it's a `.path`, check that the path exists and return it (throws if it isn't an existing file) /// * If it's a `.name`, search the named template in the folder `parserName` /// in the Application Support directory first, then in the bundled templates, /// and returns the path if found (throws if none is found) /// /// - Parameter parserName: The folder to search for the template. /// Typically the name of one of the SwiftGen parsers like `strings`, `colors`, etc /// - Returns: The Path matching the template found /// - Throws: TemplateRef.Error /// public func resolvePath(forParser parser: ParserCLI, logger: (LogLevel, String) -> Void = logMessage) throws -> Path { switch self { case .name(let templateShortName): var path = Path.deprecatedAppSupportTemplates + parser.templateFolder + "\(templateShortName).stencil" if path.isFile { logger( .warning, """ Referring to templates in Application Support by name is deprecated and will be removed in SwiftGen 7.0. For custom templates, please use `templatePath` instead of `templateName` to point to them. We also recommend you move your custom templates from \(Path.deprecatedAppSupportTemplates) to your project's folder so that your project is able to run independently on all machines. """ ) } else { path = Path.bundledTemplates + parser.templateFolder + "\(templateShortName).stencil" } guard path.isFile else { throw Self.Error.namedTemplateNotFound(name: templateShortName) } return path case .path(let fullPath): guard fullPath.isFile else { throw Self.Error.templatePathNotFound(path: fullPath) } return fullPath } } /// Check if the template is a bundled template for the given parser /// - Parameter parserName: The folder to search for the template. /// Typically the name of one of the SwiftGen parsers like `strings`, `colors`, etc /// - Returns: The Path matching the template found public func isBundled(forParser parser: ParserCLI) -> Bool { switch self { case .name(let templateShortName): let path = Path.bundledTemplates + parser.templateFolder + "\(templateShortName).stencil" return path.isFile case .path: return false } } } extension TemplateRef.Error: CustomStringConvertible { var description: String { switch self { case .namedTemplateNotFound(let name): return """ Template named \(name) not found. Use `swiftgen template list` to list available named templates \ or use `templatePath` to specify a template by its full path. """ case .templatePathNotFound(let path): return "Template not found at path \(path.description)." case .noTemplateProvided: return """ You must specify a template by name (templateName) or path (templatePath). To list all the available named templates, use 'swiftgen template list'. """ case .multipleTemplateOptions(let path, let name): return "You need to choose EITHER a named template OR a template path. Found name '\(name)' and path '\(path)'" } } }
35b032099fd67f3d08e651093efd4738
37.220183
120
0.671387
false
false
false
false
SlimGinz/HomeworkHelper
refs/heads/master
Homework Helper/PathMenu/PathMenu.swift
gpl-2.0
1
// // PathMenu.swift // PathMenu // // Created by pixyzehn on 12/27/14. // Copyright (c) 2014 pixyzehn. All rights reserved. // import Foundation import UIKit @objc protocol PathMenuDelegate:NSObjectProtocol { optional func pathMenu(menu: PathMenu, didSelectIndex idx: Int) optional func pathMenuDidFinishAnimationClose(menu: PathMenu) optional func pathMenuDidFinishAnimationOpen(menu: PathMenu) optional func pathMenuWillAnimateOpen(menu: PathMenu) optional func pathMenuWillAnimateClose(menu: PathMenu) } let kPathMenuDefaultNearRadius: CGFloat = 110.0 let kPathMenuDefaultEndRadius: CGFloat = 120.0 let kPathMenuDefaultFarRadius: CGFloat = 140.0 let kPathMenuDefaultStartPointX: CGFloat = UIScreen.mainScreen().bounds.width/2 let kPathMenuDefaultStartPointY: CGFloat = UIScreen.mainScreen().bounds.height/2 let kPathMenuDefaultTimeOffset: CGFloat = 0.036 let kPathMenuDefaultRotateAngle: CGFloat = 0.0 let kPathMenuDefaultMenuWholeAngle: CGFloat = CGFloat(M_PI) * 2 let kPathMenuDefaultExpandRotation: CGFloat = -CGFloat(M_PI) * 2 let kPathMenuDefaultCloseRotation: CGFloat = CGFloat(M_PI) * 2 let kPathMenuDefaultAnimationDuration: CGFloat = 0.5 let kPathMenuDefaultExpandRotateAnimationDuration: CGFloat = 2.0 let kPathMenuDefaultCloseRotateAnimationDuration: CGFloat = 1.0 let kPathMenuStartMenuDefaultAnimationDuration: CGFloat = 0.2 private func RotateCGPointAroundCenter(point: CGPoint, center:CGPoint, angle: CGFloat) -> CGPoint { let translation: CGAffineTransform = CGAffineTransformMakeTranslation(center.x, center.y) let rotation: CGAffineTransform = CGAffineTransformMakeRotation(angle) let transformGroup: CGAffineTransform = CGAffineTransformConcat(CGAffineTransformConcat(CGAffineTransformInvert(translation), rotation), translation) return CGPointApplyAffineTransform(point, transformGroup) } class PathMenu: UIView, PathMenuItemDelegate { var hamburgerButtonCloseBig:LBHamburgerButton! enum State { case Close // Intial state case Expand } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect!, startItem: PathMenuItem?, optionMenus aMenusArray:[PathMenuItem]?) { self.init(frame: frame) backgroundColor = UIColor.clearColor() timeOffset = kPathMenuDefaultTimeOffset rotateAngle = kPathMenuDefaultRotateAngle menuWholeAngle = kPathMenuDefaultMenuWholeAngle startPoint = CGPointMake(kPathMenuDefaultStartPointX, kPathMenuDefaultStartPointY) expandRotation = kPathMenuDefaultExpandRotation closeRotation = kPathMenuDefaultCloseRotation animationDuration = kPathMenuDefaultAnimationDuration expandRotateAnimationDuration = kPathMenuDefaultExpandRotateAnimationDuration closeRotateAnimationDuration = kPathMenuDefaultCloseRotateAnimationDuration startMenuAnimationDuration = kPathMenuStartMenuDefaultAnimationDuration rotateAddButton = true nearRadius = kPathMenuDefaultNearRadius endRadius = kPathMenuDefaultEndRadius farRadius = kPathMenuDefaultFarRadius menusArray = aMenusArray! motionState = State.Close startButton = startItem! startButton.delegate = self startButton.center = startPoint addSubview(startButton) hamburgerButtonCloseBig = LBHamburgerButton(frame: CGRect(x: 0, y: 0, width: 45, height: 45), type: LBHamburgerButtonType.CloseButton, lineWidth: 30, lineHeight: 30/6, lineSpacing: 7, lineCenter: CGPoint(x: 50, y: 50), color: UIColor.whiteColor()) hamburgerButtonCloseBig.center = CGPoint(x: self.frame.size.width - 83.0, y: self.frame.size.height - 147.5) self.addSubview(hamburgerButtonCloseBig) bringSubviewToFront(hamburgerButtonCloseBig) } var _menusArray: [PathMenuItem] = [] var menusArray: [PathMenuItem] { get { return _menusArray } set(newArray) { _menusArray = newArray for v in subviews { if v.tag >= 1000 { v.removeFromSuperview() } } } } var _startButton: PathMenuItem = PathMenuItem(frame: CGRectZero) var startButton: PathMenuItem { get { return _startButton } set { _startButton = newValue } } weak var delegate: PathMenuDelegate! var flag: Int? var timer: NSTimer? var timeOffset: CGFloat! var rotateAngle: CGFloat! var menuWholeAngle: CGFloat! var expandRotation: CGFloat! var closeRotation: CGFloat! var animationDuration: CGFloat! var expandRotateAnimationDuration: CGFloat! var closeRotateAnimationDuration: CGFloat! var startMenuAnimationDuration: CGFloat! var rotateAddButton: Bool! var nearRadius: CGFloat! var endRadius: CGFloat! var farRadius: CGFloat! var motionState: State? var _startPoint: CGPoint = CGPointZero var startPoint: CGPoint { get { return _startPoint } set { _startPoint = newValue startButton.center = newValue } } // Image var _image = UIImage() var image: UIImage? { get { return startButton.image } set(newImage) { startButton.image = newImage } } var highlightedImage: UIImage? { get { return startButton.highlightedImage } set(newImage) { startButton.highlightedImage = newImage } } var contentImage: UIImage? { get { return startButton.contentImageView?.image } set { startButton.contentImageView?.image = newValue } } var highlightedContentImage: UIImage? { get { return startButton.contentImageView?.highlightedImage } set { startButton.contentImageView?.highlightedImage = newValue } } // UIView's methods override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if motionState == State.Expand { return true } else { // Close return CGRectContainsPoint(startButton.frame, point) } } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { if let animId: AnyObject = anim.valueForKey("id") { if (animId.isEqual("lastAnimation")) { delegate?.pathMenuDidFinishAnimationClose?(self) } if (animId.isEqual("firstAnimation")) { delegate?.pathMenuDidFinishAnimationOpen?(self) } } } // UIGestureRecognizer override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { handleTap() } // PathMenuItemDelegate func PathMenuItemTouchesBegan(item: PathMenuItem) { if (item == startButton) { handleTap() } } func PathMenuItemTouchesEnd(item:PathMenuItem) { if (item == startButton) { return } let blowup: CAAnimationGroup = blowupAnimationAtPoint(item.center) item.layer.addAnimation(blowup, forKey: "blowup") item.center = item.startPoint! for (var i = 0; i < menusArray.count; i++) { let otherItem: PathMenuItem = menusArray[i] as PathMenuItem let shrink: CAAnimationGroup = shrinkAnimationAtPoint(otherItem.center) if (otherItem.tag == item.tag) { continue } otherItem.layer.addAnimation(shrink, forKey: "shrink") otherItem.center = otherItem.startPoint! } motionState = State.Close delegate?.pathMenuWillAnimateClose?(self) let angle: CGFloat = motionState == State.Expand ? CGFloat(M_PI_4) + CGFloat(M_PI) : 0.0 UIView.animateWithDuration(Double(startMenuAnimationDuration!), animations: {() -> Void in self.startButton.transform = CGAffineTransformMakeRotation(angle) }) delegate?.pathMenu?(self, didSelectIndex: item.tag - 1000) } // Animation, Position func handleTap() { var state = motionState! var selector: Selector? var angle: CGFloat? switch state { case .Close: setMenu() delegate?.pathMenuWillAnimateOpen?(self) selector = "expand" flag = 0 motionState = State.Expand angle = CGFloat(M_PI_4) + CGFloat(M_PI) case .Expand: delegate?.pathMenuWillAnimateClose?(self) selector = "close" flag = menusArray.count - 1 motionState = State.Close angle = 0.0 } if let rotateAddButton = rotateAddButton { buttonPressed(hamburgerButtonCloseBig) } if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(Double(timeOffset!), target: self, selector: selector!, userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } } func buttonPressed(sender: UIButton) { var btn = sender as! LBHamburgerButton btn.switchState() } func expand() { if flag == menusArray.count { timer?.invalidate() timer = nil return } let tag: Int = 1000 + flag! var item: PathMenuItem = viewWithTag(tag) as! PathMenuItem //let rotateAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") //rotateAnimation.values = [NSNumber(float: 0.0), NSNumber(float: Float(expandRotation!)), NSNumber(float: 0.0)] //rotateAnimation.duration = CFTimeInterval(expandRotateAnimationDuration!) //rotateAnimation.keyTimes = [NSNumber(float: 0.0), NSNumber(float: 0.4), NSNumber(float: 0.5)] let positionAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = CFTimeInterval(animationDuration!) let path: CGMutablePathRef = CGPathCreateMutable() CGPathMoveToPoint(path, nil, CGFloat(item.startPoint!.x), CGFloat(item.startPoint!.y)) CGPathAddLineToPoint(path, nil, item.farPoint!.x, item.farPoint!.y) CGPathAddLineToPoint(path, nil, item.nearPoint!.x, item.nearPoint!.y) CGPathAddLineToPoint(path, nil, item.endPoint!.x, item.endPoint!.y) positionAnimation.path = path let animationgroup: CAAnimationGroup = CAAnimationGroup() animationgroup.animations = [positionAnimation, /*rotateAnimation*/] animationgroup.duration = CFTimeInterval(animationDuration!) animationgroup.fillMode = kCAFillModeForwards animationgroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) animationgroup.delegate = self if flag == (menusArray.count - 1) { animationgroup.setValue("firstAnimation", forKey: "id") } item.layer.addAnimation(animationgroup, forKey: "Expand") item.center = item.endPoint! flag!++ } func close() { if (flag! == -1) { timer?.invalidate() timer = nil return } let tag :Int = 1000 + flag! var item: PathMenuItem = viewWithTag(tag) as! PathMenuItem //let rotateAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") //rotateAnimation.values = [NSNumber(float: 0.0), NSNumber(float: Float(closeRotation!)), NSNumber(float: 0.0)] //rotateAnimation.duration = CFTimeInterval(closeRotateAnimationDuration!) //rotateAnimation.keyTimes = [NSNumber(float: 0.0), NSNumber(float: 0.4), NSNumber(float: 0.5)] let positionAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = CFTimeInterval(animationDuration!) let path: CGMutablePathRef = CGPathCreateMutable() CGPathMoveToPoint(path, nil, item.endPoint!.x, item.endPoint!.y) CGPathAddLineToPoint(path, nil, item.farPoint!.x, item.farPoint!.y) CGPathAddLineToPoint(path, nil, CGFloat(item.startPoint!.x), CGFloat(item.startPoint!.y)) positionAnimation.path = path let animationgroup: CAAnimationGroup = CAAnimationGroup() animationgroup.animations = [positionAnimation, /*rotateAnimation*/] animationgroup.duration = CFTimeInterval(animationDuration!) animationgroup.fillMode = kCAFillModeForwards animationgroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) animationgroup.delegate = self if flag == 0 { animationgroup.setValue("lastAnimation", forKey: "id") } item.layer.addAnimation(animationgroup, forKey: "Close") item.center = item.startPoint! flag!-- } func setMenu() { let count: Int = menusArray.count var denominator: Int? for (var i = 0; i < menusArray.count; i++) { var item: PathMenuItem = menusArray[i] item.tag = 1000 + i item.startPoint = startPoint // avoid overlap if (menuWholeAngle >= CGFloat(M_PI) * 2) { menuWholeAngle = menuWholeAngle! - menuWholeAngle! / CGFloat(count) } if count == 1 { denominator = 1 } else { denominator = count - 1 } let i1 = Float(endRadius) * sinf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let i2 = Float(endRadius) * cosf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let endPoint: CGPoint = CGPointMake(startPoint.x + CGFloat(i1), startPoint.y - CGFloat(i2)) item.endPoint = RotateCGPointAroundCenter(endPoint, startPoint, rotateAngle!) let j1 = Float(nearRadius) * sinf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let j2 = Float(nearRadius) * cosf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let nearPoint: CGPoint = CGPointMake(startPoint.x + CGFloat(j1), startPoint.y - CGFloat(j2)) item.nearPoint = RotateCGPointAroundCenter(nearPoint, startPoint, rotateAngle!) let k1 = Float(farRadius) * sinf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let k2 = Float(farRadius) * cosf(Float(i) * Float(menuWholeAngle!) / Float(denominator!)) let farPoint: CGPoint = CGPointMake(startPoint.x + CGFloat(k1), startPoint.y - CGFloat(k2)) item.farPoint = RotateCGPointAroundCenter(farPoint, startPoint, rotateAngle!) item.center = item.startPoint! item.delegate = self insertSubview(item, belowSubview: startButton) } } func blowupAnimationAtPoint(p: CGPoint) -> CAAnimationGroup { let positionAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.values = [NSValue(CGPoint: p)] positionAnimation.keyTimes = [3] let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform") scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(3, 3, 1)) let opacityAnimation: CABasicAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = NSNumber(float: 0.0) let animationgroup: CAAnimationGroup = CAAnimationGroup() animationgroup.animations = [positionAnimation, scaleAnimation, opacityAnimation] animationgroup.duration = CFTimeInterval(animationDuration!) animationgroup.fillMode = kCAFillModeForwards return animationgroup } func shrinkAnimationAtPoint(p: CGPoint) -> CAAnimationGroup { let positionAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.values = [NSValue(CGPoint: p)] positionAnimation.keyTimes = [3] let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform") scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(0.01, 0.01, 1)) let opacityAnimation: CABasicAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.toValue = NSNumber(float: 0.0) let animationgroup: CAAnimationGroup = CAAnimationGroup() animationgroup.animations = [positionAnimation, scaleAnimation, opacityAnimation] animationgroup.duration = CFTimeInterval(animationDuration!) animationgroup.fillMode = kCAFillModeForwards return animationgroup } }
6760a3d2a61d3efc70a2a85c74263b9a
36.688312
255
0.640535
false
false
false
false
abeintopalo/AppIconSetGen
refs/heads/master
Sources/AppIconSetGenCore/NSImage+Extensions.swift
mit
1
// // NSImage+Extensions.swift // AppIconSetGenCore // // Created by Attila Bencze on 11/05/2017. // // import Cocoa import Foundation extension NSImage { func imagePNGRepresentation(widthInPixels: CGFloat, heightInPixels: CGFloat) -> NSData? { let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(widthInPixels), pixelsHigh: Int(heightInPixels), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) imageRep?.size = NSMakeSize(widthInPixels, heightInPixels) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: imageRep!) draw(in: NSMakeRect(0, 0, widthInPixels, heightInPixels), from: NSZeroRect, operation: .copy, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() let imageProps: [NSBitmapImageRep.PropertyKey: Any] = [:] let imageData = imageRep?.representation(using: NSBitmapImageRep.FileType.png, properties: imageProps) as NSData? return imageData } }
02ac952b674a75fa3a7f6bb9e92506e4
41.2
121
0.558565
false
false
false
false
amraboelela/swift
refs/heads/master
test/RemoteAST/structural_types.swift
apache-2.0
3
// RUN: %target-swift-remoteast-test %s | %FileCheck %s // REQUIRES: swift-remoteast-test @_silgen_name("printMetadataType") func printType(_: Any.Type) typealias Fn1 = () -> () printType(Fn1.self) // CHECK: found type: () -> () typealias Fn2 = (Int, Float) -> () printType(Fn2.self) // CHECK: found type: (Int, Float) -> () typealias Fn3 = (inout Int, Float) -> () printType(Fn3.self) // CHECK: found type: (inout Int, Float) -> () typealias Fn4 = (inout Int, inout Float) -> () printType(Fn4.self) // CHECK: found type: (inout Int, inout Float) -> () typealias Fn5 = (Int, inout Float) -> () printType(Fn5.self) // CHECK: found type: (Int, inout Float) -> () typealias Fn6 = (Int, inout String, Float) -> () printType(Fn6.self) // CHECK: found type: (Int, inout String, Float) -> () typealias Fn7 = (inout Int, String, inout Float, Double) -> () printType(Fn7.self) // CHECK: found type: (inout Int, String, inout Float, Double) -> () typealias Fn8 = (String, Int, Double, Float) -> () printType(Fn8.self) // CHECK: found type: (String, Int, Double, Float) -> () typealias Fn9 = ((Int, Float)) -> () printType(Fn9.self) // CHECK: found type: ((Int, Float)) -> () typealias Fn10 = (Int...) -> () printType(Fn10.self) // CHECK: found type: (Int...) -> () typealias Tuple1 = (Int, Float, Int) printType(Tuple1.self) // CHECK: found type: (Int, Float, Int) printType(Int.Type.self) // CHECK: found type: Int.Type printType(Tuple1.Type.self) // CHECK: found type: (Int, Float, Int).Type typealias Tuple2 = (Int.Type, x: Float, Int) printType(Tuple2.self) // CHECK: found type: (Int.Type, x: Float, Int) typealias Tuple3 = (x: Int, Float, y: Int.Type) printType(Tuple3.self) // CHECK: found type: (x: Int, Float, y: Int.Type) func foo<T>(_: T) { var f = T.self printType(f) } foo() { (x: Int) -> Int in return x } // CHECK: found type: (Int) -> Int
0656dc25707c71042fd05164e7b0c939
24.944444
68
0.63651
false
false
false
false
zisko/swift
refs/heads/master
test/Sema/enum_equatable_hashable.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift -verify-ignore-unknown enum Foo { case A, B } if Foo.A == .B { } var aHash: Int = Foo.A.hashValue Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} enum Generic<T> { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } if Generic<Foo>.A == .B { } var gaHash: Int = Generic<Foo>.A.hashValue func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B var hashValue: Int { return 0 } } func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note 4 {{non-matching type}} return true } if CustomHashable.A == .B { } var custHash: Int = CustomHashable.A.hashValue // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-note{{previously declared here}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note 4 {{non-matching type}} return "" } if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue var i: Int = InvalidCustomHashable.A.hashValue // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue func getFromOtherFile() -> AlsoFromOtherFile { return .A } if .A == getFromOtherFile() {} func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } if .A == overloadFromOtherFile() {} // Complex enums are not implicitly Equatable or Hashable. enum Complex { case A(Int) case B } if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } if GenericHashable<String>.A("a") == .B { } var genericHashableHash: Int = GenericHashable<String>.A("a").hashValue // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error {{does not conform}} case A(T) case B } if GenericNotHashable<String>.A("a") == .B { } var genericNotHashableHash: Int = GenericNotHashable<String>.A("a").hashValue // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hashValue'}} // An enum with no cases should not derive conformance. enum NoCases: Hashable {} // expected-error 2 {{does not conform}} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note 3 {{non-matching type}} return true } // No explicit conformance; it could be derived, but we don't support extensions // yet. extension Complex : Hashable {} // expected-error 2 {{cannot be automatically synthesized in an extension}} // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { // expected-note 3 {{non-matching type}} return true } var hashValue: Int { return 0 } } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
66594b1c9bb62e7186b953b56495b60b
30.481781
168
0.722994
false
false
false
false
FlexMonkey/Filterpedia
refs/heads/master
Filterpedia/customFilters/SimplePlasma.swift
gpl-3.0
1
// // SimplePlasma.swift // Filterpedia // // Created by Simon Gladman on 16/05/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // Based on https://www.shadertoy.com/view/XsVSzW import CoreImage class SimplePlasma: CIFilter { var inputSize = CIVector(x: 640, y: 640) var inputTime: CGFloat = 0 var inputSharpness: CGFloat = 0.5 var inputIterations: CGFloat = 7 var inputScale: CGFloat = 100 override var attributes: [String : AnyObject] { return [ kCIAttributeFilterDisplayName: "Simple Plasma", "inputSize": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Size", kCIAttributeDefault: CIVector(x: 640, y: 640), kCIAttributeType: kCIAttributeTypeOffset], "inputTime": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Time", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1024, kCIAttributeType: kCIAttributeTypeScalar], "inputSharpness": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.5, kCIAttributeDisplayName: "Sharpness", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputIterations": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 7, kCIAttributeDisplayName: "Iterations", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 7, kCIAttributeType: kCIAttributeTypeScalar], "inputScale": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 100, kCIAttributeDisplayName: "Scale", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 1000, kCIAttributeType: kCIAttributeTypeScalar], ] } let kernel = CIColorKernel(string: "kernel vec4 colorkernel(float time, float iterations, float sharpness, float scale)" + "{" + " vec2 uv = destCoord() / scale; " + " vec2 uv0=uv; " + " vec4 i = vec4(1.0, 1.0, 1.0, 0.0);" + " for(int s = 0;s < int(iterations); s++) " + " { " + " vec2 r=vec2(cos(uv.y * i.x - i.w + time / i.y),sin(uv.x * i.x - i.w + time / i.y)) / i.z; " + " r+=vec2(-r.y,r.x) * 0.3; " + " uv.xy+=r; " + " i *= vec4(1.93, 1.15, (2.25 - sharpness), time * i.y); " + " } " + " float r=sin(uv.x-time)*0.5+0.5; " + " float b=sin(uv.y+time)*0.5+0.5; " + " float g=sin((uv.x+uv.y+sin(time))*0.5)*0.5+0.5; " + " return vec4(r,g,b,1.0);" + "}") override var outputImage: CIImage? { guard let kernel = kernel else { return nil } let extent = CGRect(origin: CGPointZero, size: CGSize(width: inputSize.X, height: inputSize.Y)) return kernel.applyWithExtent( extent, arguments: [inputTime / 10, inputIterations, inputSharpness, inputScale]) } }
bbea2555658a6446c5b6bf44073dff1f
34.761905
113
0.515579
false
false
false
false
Ezimetzhan/Moya
refs/heads/master
Demo/Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Sink.swift
apache-2.0
11
// // Sink.swift // Rx // // Created by Krunoslav Zaher on 2/19/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Sink<O : ObserverType> : Disposable { private typealias Element = O.Element typealias State = ( observer: O?, cancel: Disposable, disposed: Bool ) private var lock = SpinLock() private var _state: State var observer: O? { get { return lock.calculateLocked { _state.observer } } } var cancel: Disposable { get { return lock.calculateLocked { _state.cancel } } } var state: State { get { return lock.calculateLocked { _state } } } init(observer: O, cancel: Disposable) { #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif _state = ( observer: observer, cancel: cancel, disposed: false ) } func dispose() { var cancel: Disposable? = lock.calculateLocked { if _state.disposed { return nil } var cancel = _state.cancel _state.disposed = true _state.observer = nil _state.cancel = NopDisposable.instance return cancel } if let cancel = cancel { cancel.dispose() } } deinit { #if TRACE_RESOURCES OSAtomicDecrement32(&resourceCount) #endif } }
29d7f8269589f557ca5b2c4660d6cd47
19.597403
60
0.505994
false
false
false
false