repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Petrachkov/SPSwiftExtensions
SPSwiftExtensions/Classes/UIColor+.swift
1
806
// // UIColor+.swift // SwiftExtensions // // Created by guys from actonica on 15/01/16. // Copyright © 2016 Actonica studio. All rights reserved. // import UIKit public extension UIColor { convenience init(rgbaColorCode:Int) { let r = ((CGFloat)((rgbaColorCode & 0xff0000) >> 24)) / 255.0; let g = ((CGFloat)((rgbaColorCode & 0xff0000) >> 16)) / 255.0; let b = ((CGFloat)((rgbaColorCode & 0xff00) >> 8)) / 255.0; let a = ((CGFloat)(rgbaColorCode & 0xff)) / 255.0; self.init(red: r, green: g, blue: b, alpha: a); } convenience init(rgbColorCode:Int) { let r = ((CGFloat)((rgbColorCode & 0xff0000) >> 16)) / 255.0; let g = ((CGFloat)((rgbColorCode & 0xff00) >> 8)) / 255.0; let b = ((CGFloat)(rgbColorCode & 0xff)) / 255.0; self.init(red: r, green: g, blue: b, alpha: 1); } }
mit
91e4553256686301faaf2220463928b4
29.961538
64
0.62236
2.710438
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Objects/Entities/KnowledgeGroupImpl.swift
1
1722
import Foundation struct KnowledgeGroupImpl: KnowledgeGroup { var identifier: KnowledgeGroupIdentifier var title: String var groupDescription: String var fontAwesomeCharacterAddress: Character var order: Int var entries: [KnowledgeEntry] } extension KnowledgeGroupImpl { static func fromServerModels( groups: [KnowledgeGroupCharacteristics], entries: [KnowledgeEntryCharacteristics], shareableURLFactory: ShareableURLFactory ) -> [KnowledgeGroup] { return groups.map({ (group) -> KnowledgeGroup in let entries = entries .filter({ $0.groupIdentifier == group.identifier }) .map({ KnowledgeEntryImpl.fromServerModel($0, shareableURLFactory: shareableURLFactory) }) .sorted(by: { (first, second) in return first.order < second.order }) let defaultFontAwesomeBackupCharacter: Character = " " let fontAwesomeCharacter: Character = Int(group.fontAwesomeCharacterAddress, radix: 16) .flatMap(UnicodeScalar.init) .map(Character.init) .defaultingTo(defaultFontAwesomeBackupCharacter) return KnowledgeGroupImpl( identifier: KnowledgeGroupIdentifier(group.identifier), title: group.groupName, groupDescription: group.groupDescription, fontAwesomeCharacterAddress: fontAwesomeCharacter, order: group.order, entries: entries ) }).sorted(by: { (first, second) in return first.order < second.order }) } }
mit
e2da2c618144b72724db7893d135de36
34.875
106
0.609756
5.645902
false
false
false
false
soleiltw/ios-swift-basic
Swift-Basic-Function/Object.playground/Contents.swift
1
1204
//: Playground - noun: a place where people can play import Foundation // Object & Class class Shape { var numberOfSides = 0 var name : String init() { self.name = "Empty Name" } init(name: String, numberOfSides: Int) { self.name = name self.numberOfSides = numberOfSides } func simpleDescription() -> String { return "The shape is \(name), with \(numberOfSides) sides." } } var emptyShape = Shape() emptyShape.name = "Triangle" emptyShape.numberOfSides = 3 print(emptyShape.simpleDescription()) var myShape = Shape(name: "Square", numberOfSides: 4) print(myShape.simpleDescription()) // Extend Class class Square : Shape { var sideLength: Double init(sideLength:Double, name: String) { self.sideLength = sideLength super.init(name: name, numberOfSides: 4) } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength), thus it's area is \(self.area())" } } var mySqure = Square(sideLength: 10.0, name: "My Land") print(mySqure.simpleDescription())
mit
27d1d331ad5290bfb1d0396054da84e5
22.173077
94
0.636213
4.195122
false
false
false
false
ccwuzhou/WWZSwift
Source/Views/WWZTipView.swift
1
5054
// // WWZTipView.swift // wwz_swift // // Created by wwz on 17/3/1. // Copyright © 2017年 tijio. All rights reserved. // import UIKit fileprivate let TIP_LINE_COLOR = UIColor.colorFromRGBA(204, 204, 204, 1) fileprivate let TIP_BUTTON_TAG = 99 fileprivate let TIP_BUTTON_HEIGHT : CGFloat = 45.0 open class WWZTipView: WWZShowView { // MARK: -私有属性 fileprivate var block : ((Int)->())? fileprivate lazy var titleLabel : UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() // MARK: -设置方法 public var buttonTitleColor : UIColor = UIColor.black { didSet { for subView in self.subviews { if let subView = subView as? UIButton { subView.setTitleColor(buttonTitleColor, for: .normal) } } } } public var buttonTitleFont : UIFont = UIFont.systemFont(ofSize: 16) { didSet { for subView in self.subviews { if let button = subView as? UIButton { button.titleLabel?.font = buttonTitleFont } } } } public init(attributedText: NSAttributedString, buttonTitles: [String], clickButtonAtIndex block: @escaping (_ index: Int)->()) { let screenSize = UIScreen.main.bounds.size var tipViewX : CGFloat = 0; if screenSize.width == 320 { tipViewX = 30 }else if screenSize.width == 375 { tipViewX = 45 }else{ tipViewX = 60 } super.init(frame: CGRect(x: tipViewX, y: 0, width: screenSize.width - 2*tipViewX, height: 0)) if buttonTitles.count == 0 || buttonTitles.count > 2 { return } self.block = block self.layer.masksToBounds = true self.layer.cornerRadius = 15.0 // title label self.p_addTitleLabel(attributedText: attributedText) self.height = 2 * self.titleLabel.y + self.titleLabel.height + TIP_BUTTON_HEIGHT self.y = (screenSize.height-self.height)*0.5 // buttons self.p_addBottomButtons(buttonTitles: buttonTitles) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension WWZTipView { // MARK: -添加label fileprivate func p_addTitleLabel(attributedText: NSAttributedString) { self.titleLabel.attributedText = attributedText let titleLabelXY : CGFloat = 20.0 self.titleLabel.x = titleLabelXY; self.titleLabel.width = self.width-titleLabelXY*2 self.titleLabel.height = self.titleLabel.textRect(forBounds: CGRect(x: 0.0, y: 0.0, width: self.titleLabel.width, height: 500), limitedToNumberOfLines: 0).size.height self.titleLabel.y = self.titleLabel.height < 30 ? titleLabelXY + 2.5 : titleLabelXY; self.addSubview(self.titleLabel) } // MARK: -添加按钮 fileprivate func p_addBottomButtons(buttonTitles: [String]) { for buttonTitle in buttonTitles { let index = buttonTitles.index(of: buttonTitle)! let rect = CGRect(x: 0+CGFloat(index)*self.width/CGFloat(buttonTitles.count), y: self.height-TIP_BUTTON_HEIGHT, width: self.width/CGFloat(buttonTitles.count), height: TIP_BUTTON_HEIGHT) self.addSubview(self.p_bottomButton(frame: rect, title: buttonTitle, tag: index)) if index == 1 { let lineView = UIView(frame: CGRect(x: self.width*0.5-0.25, y: self.height-TIP_BUTTON_HEIGHT, width: 0.5, height: TIP_BUTTON_HEIGHT), backgroundColor: TIP_LINE_COLOR) self.addSubview(lineView) } } } fileprivate func p_bottomButton(frame: CGRect, title: String, tag: Int) -> UIButton { let btn = UIButton(frame: frame) btn.setTitle(title, for: .normal) btn.setTitleColor(self.buttonTitleColor, for: .normal) btn.setBackgroundImage(UIImage.wwz_image(color: TIP_LINE_COLOR, size: frame.size), for: .highlighted) btn.titleLabel?.font = self.buttonTitleFont btn.tag = TIP_BUTTON_TAG + tag btn.addTarget(self, action: #selector(self.clickButtonAtIndex), for: .touchUpInside) let lineView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 0.5)) lineView.backgroundColor = TIP_LINE_COLOR btn.addSubview(lineView) return btn } @objc private func clickButtonAtIndex(sender: UIButton) { self.block?(sender.tag - TIP_BUTTON_TAG) self.wwz_dismiss(completion: nil) } }
mit
2c90fe0e02eb2a700587eea58fd64d48
30.39375
197
0.570177
4.464889
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/Observables/Implementations/Filter.swift
1
1743
// // Filter.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Where_<O : ObserverType>: Sink<O>, ObserverType { typealias Element = O.Element typealias Parent = Where<Element> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let value): _ = self.parent.predicate(value).recoverWith { e in trySendError(observer, e) self.dispose() return failure(e) }.flatMap { satisfies -> RxResult<Void> in if satisfies { trySend(observer, event) } return SuccessResult } case .Completed: fallthrough case .Error: trySend(observer, event) self.dispose() } } } class Where<Element> : Producer<Element> { typealias Predicate = (Element) -> RxResult<Bool> let source: Observable<Element> let predicate: Predicate init(source: Observable<Element>, predicate: Predicate) { self.source = source self.predicate = predicate } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Where_(parent: self, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } }
mit
fbdfefab1a9b48f6828149c1ed72fbb7
28.066667
145
0.55938
4.710811
false
false
false
false
EstefaniaGilVaquero/ciceIOS
App_RetoMVCWS/App_RetoMVCWS/ICOParserUsers.swift
1
2365
// // ICOParserUsers.swift // App_RetoMVCWS // // Created by User on 27/7/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit import SwiftyJSON class ICOParserUsers: NSObject { func getUsersModel(dataFromNetworking : NSData) -> [ICOUsersModel]{ var arrayUsersModel = [ICOUsersModel]() let readableJSON = JSON(data: dataFromNetworking, options: NSJSONReadingOptions.MutableContainers, error: nil) for item in 0..<readableJSON.count{ let geoModel = ICOGeoModel(pLat: readableJSON[item]["address"]["geo"]["lat"].string!, pLng: readableJSON[item]["address"]["geo"]["lng"].string!) let companyModel = ICOCompanyModel(pName: readableJSON[item]["company"]["name"].string!, pCatchPhrase: readableJSON[item]["company"]["catchPhrase"].string!, pBs: readableJSON[item]["company"]["bs"].string!) let addressModel = ICOAddressModel(pStreet: readableJSON[item]["address"]["street"].string!, pSuite: readableJSON[item]["address"]["suite"].string!, pCity: readableJSON[item]["address"]["city"].string!, pZipcode: readableJSON[item]["address"]["zipcode"].string!, pGeo: geoModel) let usersModel = ICOUsersModel(pId: readableJSON[item]["id"].int!, pName: readableJSON[item]["name"].string!, pUsername: readableJSON[item]["username"].string!, pEmail: readableJSON[item]["email"].string!, pAddress: addressModel, pPhone: readableJSON[item]["phone"].string!, pWebsite: readableJSON[item]["website"].string!, pCompany: companyModel) arrayUsersModel.append(usersModel) } return arrayUsersModel } }
apache-2.0
785badcedb4ecab33d4e41c4e13d068f
43.603774
118
0.475042
5.523364
false
false
false
false
apple/swift
test/Constraints/dictionary_literal.swift
4
11393
// RUN: %target-typecheck-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class MyDictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: MyDictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary value type 'DictStringInt.Value' (aka 'Int')}} useDictStringInt([4.5 : 2]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt([nil : 2]) // expected-error@-1 {{'nil' is not compatible with expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt([7 : 1, "World" : 2]) // expected-error@-1 {{cannot convert value of type 'Int' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt(["Hello" : nil]) // expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'DictStringInt.Value' (aka 'Int')}} typealias FuncBoolToInt = (Bool) -> Int let dict1: MyDictionary<String, FuncBoolToInt> = ["Hello": nil] // expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'MyDictionary<String, FuncBoolToInt>.Value' (aka '(Bool) -> Int')}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Swift.Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: MyDictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'MyDictionary<String, (Int) -> Int>' cannot be initialized with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: MyDictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} var _: MyDictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} {{53-54=:}} var _: MyDictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{none}} var _: MyDictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'MyDictionary<String, Int>.Value' (aka 'Int')}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} var _ = useDictStringInt([]) // expected-error {{use [:] to get an empty dictionary literal}} {{27-27=:}} var _: [[Int: Int]] = [[]] // expected-error {{use [:] to get an empty dictionary literal}} {{25-25=:}} var _: [[Int: Int]?] = [[]] // expected-error {{use [:] to get an empty dictionary literal}} {{26-26=:}} var assignDict = [1: 2] assignDict = [] // expected-error {{use [:] to get an empty dictionary literal}} {{15-15=:}} var _: [Int: Int] = [1] // expected-error {{dictionary of type '[Int : Int]' cannot be initialized with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{23-23=: <#value#>}} var _: [Float: Int] = [1] // expected-error {{dictionary of type '[Float : Int]' cannot be initialized with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{25-25=: <#value#>}} var _: [Int: Int] = ["foo"] // expected-error {{dictionary of type '[Int : Int]' cannot be initialized with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{27-27=: <#value#>}} var _ = useDictStringInt(["Key"]) // expected-error {{dictionary of type 'DictStringInt' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{32-32=: <#value#>}} var _ = useDictStringInt([4]) // expected-error {{dictionary of type 'DictStringInt' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{28-28=: <#value#>}} var _: [[Int: Int]] = [[5]] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{26-26=: <#value#>}} var _: [[Int: Int]] = [["bar"]] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{30-30=: <#value#>}} assignDict = [1] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{16-16=: <#value#>}} assignDict = [""] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{17-17=: <#value#>}} func arrayLiteralDictionaryMismatch<T>(a: inout T) where T: ExpressibleByDictionaryLiteral, T.Key == Int, T.Value == Int { a = [] // expected-error {{use [:] to get an empty dictionary literal}} {{8-8=:}} a = [1] // expected-error {{dictionary of type 'T' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{9-9=: <#value#>}} a = [""] // expected-error {{dictionary of type 'T' cannot be used with array literal}} // expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{10-10=: <#value#>}} } class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any]}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let _ = ["a" : 1, "b" : nil, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any?]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any?]}} let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type '[AnyHashable : Any]'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}} // expected-warning@-3{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type '[String : A]'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : String]'}} } /// rdar://problem/32330004 /// https://github.com/apple/swift/issues/47529 /// Assertion failure during `swift::ASTVisitor<::FailureDiagnosis,...>::visit` func rdar32330004_1() -> [String: Any] { return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}} // expected-error@-1 {{expected ',' separator}} // expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}} } func rdar32330004_2() -> [String: Any] { return ["a", 0, "one", 1, "two", 2, "three", 3] // expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}} // expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}} } // https://github.com/apple/swift/issues/59215 class S59215 { var m: [String: [String: String]] = [:] init() { m["a"] = ["", 1] //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{17-18=:}} m["a"] = [1 , ""] //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{17-18=:}} m["a"] = ["", ""] //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{17-18=:}} m["a"] = [1 , 1] //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{17-18=:}} m["a"] = Optional(["", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{26-27=:}} } } func f59215(_ a: [String: String]) {} f59215(["", 1]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} f59215([1 , ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} f59215([1 , 1]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} f59215(["", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} f59215(["", "", "", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} {{19-20=:}} f59215(["", "", "", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}} // expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} {{19-20=:}}
apache-2.0
80534df840ab8dbf73e6acaa0e174ca8
56.251256
190
0.652594
3.608806
false
false
false
false
rsmoz/swift-corelibs-foundation
Foundation/NSTask.swift
1
13775
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public enum NSTaskTerminationReason : Int { case Exit case UncaughtSignal } private func WEXITSTATUS(status: CInt) -> CInt { return (status >> 8) & 0xff } private var managerThreadSetupOnceToken = pthread_once_t() private var threadID = pthread_t() private var managerThreadRunLoop : NSRunLoop? = nil private var managerThreadRunLoopIsRunning = false private var managerThreadRunLoopIsRunningCondition = NSCondition() #if os(OSX) || os(iOS) internal let kCFSocketDataCallBack = CFSocketCallBackType.DataCallBack.rawValue #endif private func emptyRunLoopCallback(context : UnsafeMutablePointer<Void>) -> Void {} // Retain method for run loop source private func runLoopSourceRetain(pointer : UnsafePointer<Void>) -> UnsafePointer<Void> { let _ = Unmanaged<AnyObject>.fromOpaque(COpaquePointer(pointer)).retain() return pointer } // Release method for run loop source private func runLoopSourceRelease(pointer : UnsafePointer<Void>) -> Void { Unmanaged<AnyObject>.fromOpaque(COpaquePointer(pointer)).release() } // Equal method for run loop source private func runloopIsEqual(a : UnsafePointer<Void>, b : UnsafePointer<Void>) -> _DarwinCompatibleBoolean { let unmanagedrunLoopA = Unmanaged<AnyObject>.fromOpaque(COpaquePointer(a)) guard let runLoopA = unmanagedrunLoopA.takeUnretainedValue() as? NSRunLoop else { return false } let unmanagedRunLoopB = Unmanaged<AnyObject>.fromOpaque(COpaquePointer(a)) guard let runLoopB = unmanagedRunLoopB.takeUnretainedValue() as? NSRunLoop else { return false } guard runLoopA == runLoopB else { return false } return true } @noreturn private func managerThread(x: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> { managerThreadRunLoop = NSRunLoop.currentRunLoop() var emptySourceContext = CFRunLoopSourceContext (version: 0, info: UnsafeMutablePointer<Void>(Unmanaged.passUnretained(managerThreadRunLoop!).toOpaque()), retain: runLoopSourceRetain, release: runLoopSourceRelease, copyDescription: nil, equal: runloopIsEqual, hash: nil, schedule: nil, cancel: nil, perform: emptyRunLoopCallback) CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &emptySourceContext), kCFRunLoopDefaultMode) managerThreadRunLoopIsRunningCondition.lock() CFRunLoopPerformBlock(managerThreadRunLoop?._cfRunLoop, kCFRunLoopDefaultMode) { managerThreadRunLoopIsRunning = true managerThreadRunLoopIsRunningCondition.broadcast() managerThreadRunLoopIsRunningCondition.unlock() } managerThreadRunLoop?.run() fatalError("NSTask manager run loop exited unexpectedly; it should run forever once initialized") } private func managerThreadSetup() -> Void { pthread_create(&threadID, nil, managerThread, nil) managerThreadRunLoopIsRunningCondition.lock() while managerThreadRunLoopIsRunning == false { managerThreadRunLoopIsRunningCondition.wait() } managerThreadRunLoopIsRunningCondition.unlock() } // Equal method for task in run loop source private func nstaskIsEqual(a : UnsafePointer<Void>, b : UnsafePointer<Void>) -> _DarwinCompatibleBoolean { let unmanagedTaskA = Unmanaged<AnyObject>.fromOpaque(COpaquePointer(a)) guard let taskA = unmanagedTaskA.takeUnretainedValue() as? NSTask else { return false } let unmanagedTaskB = Unmanaged<AnyObject>.fromOpaque(COpaquePointer(a)) guard let taskB = unmanagedTaskB.takeUnretainedValue() as? NSTask else { return false } guard taskA == taskB else { return false } return true } public class NSTask : NSObject { // Create an NSTask which can be run at a later time // An NSTask can only be run once. Subsequent attempts to // run an NSTask will raise. // Upon task death a notification will be sent // { Name = NSTaskDidTerminateNotification; object = task; } // public override init() { } // these methods can only be set before a launch public var launchPath: String? public var arguments: [String]? public var environment: [String : String]? // if not set, use current public var currentDirectoryPath: String = NSFileManager.defaultInstance.currentDirectoryPath // standard I/O channels; could be either an NSFileHandle or an NSPipe public var standardInput: AnyObject? public var standardOutput: AnyObject? public var standardError: AnyObject? private var runLoopSourceContext : CFRunLoopSourceContext? private var runLoopSource : CFRunLoopSource? private weak var runLoop : NSRunLoop? = nil private var processLaunchedCondition = NSCondition() // actions public func launch() { self.processLaunchedCondition.lock() // Dispatch the manager thread if it isn't already running pthread_once(&managerThreadSetupOnceToken, managerThreadSetup) // Ensure that the launch path is set guard let launchPath = self.launchPath else { fatalError() } // Convert the arguments array into a posix_spawn-friendly format var args = [launchPath.lastPathComponent] if let arguments = self.arguments { args.appendContentsOf(arguments) } let argv : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = args.withUnsafeBufferPointer { let array : UnsafeBufferPointer<String> = $0 let buffer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(array.count + 1) buffer.initializeFrom(array.map { $0.withCString(strdup) }) buffer[array.count] = nil return buffer } defer { for arg in argv ..< argv + args.count { free(UnsafeMutablePointer<Void>(arg.memory)) } argv.dealloc(args.count + 1) } let envp: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> if let env = environment { let nenv = env.count envp = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(1 + nenv) envp.initializeFrom(env.map { strdup("\($0)=\($1)") }) envp[env.count] = nil defer { for pair in envp ..< envp + env.count { free(UnsafeMutablePointer<Void>(pair.memory)) } envp.dealloc(env.count + 1) } } else { envp = _CFEnviron() } var taskSocketPair : [Int32] = [0, 0] socketpair(AF_UNIX, _CF_SOCK_STREAM(), 0, &taskSocketPair) var context = CFSocketContext(version: 0, info: UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque()), retain: runLoopSourceRetain, release: runLoopSourceRelease, copyDescription: nil) let socket = CFSocketCreateWithNative( nil, taskSocketPair[0], CFOptionFlags(kCFSocketDataCallBack), { (socket, type, address, data, info ) in let task = Unmanaged<NSTask>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() task.processLaunchedCondition.lock() while task.running == false { task.processLaunchedCondition.wait() } task.processLaunchedCondition.unlock() var exitCode : Int32 = 0 var waitResult : Int32 = 0 repeat { waitResult = waitpid( task.processIdentifier, &exitCode, 0) } while ( (waitResult == -1) && (errno == EINTR) ) task.terminationStatus = WEXITSTATUS( exitCode ) // If a termination handler has been set, invoke it on a background thread if task.terminationHandler != nil { var threadID = pthread_t() pthread_create(&threadID, nil, { (context) -> UnsafeMutablePointer<Void> in let unmanagedTask : Unmanaged<NSTask> = Unmanaged.fromOpaque(context) let task = unmanagedTask.takeRetainedValue() task.terminationHandler!( task ) return context }, UnsafeMutablePointer<Void>(Unmanaged.passRetained(task).toOpaque())) } // Set the running flag to false task.running = false // Invalidate the source and wake up the run loop, if it's available CFRunLoopSourceInvalidate(task.runLoopSource) if let runLoop = task.runLoop { CFRunLoopWakeUp(runLoop._cfRunLoop) } CFSocketInvalidate( socket ) }, &context ) CFSocketSetSocketFlags( socket, CFOptionFlags(kCFSocketCloseOnInvalidate)) let source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0) CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, source, kCFRunLoopDefaultMode) // Launch var pid = pid_t() let status = posix_spawn(&pid, launchPath, nil, nil, argv, envp) guard status == 0 else { fatalError() } close(taskSocketPair[1]) self.runLoop = NSRunLoop.currentRunLoop() self.runLoopSourceContext = CFRunLoopSourceContext (version: 0, info: UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque()), retain: runLoopSourceRetain, release: runLoopSourceRelease, copyDescription: nil, equal: nstaskIsEqual, hash: nil, schedule: nil, cancel: nil, perform: emptyRunLoopCallback) self.runLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &runLoopSourceContext!) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode) running = true self.processIdentifier = pid self.processLaunchedCondition.unlock() self.processLaunchedCondition.broadcast() } public func interrupt() { NSUnimplemented() } // Not always possible. Sends SIGINT. public func terminate() { NSUnimplemented() }// Not always possible. Sends SIGTERM. public func suspend() -> Bool { NSUnimplemented() } public func resume() -> Bool { NSUnimplemented() } // status public private(set) var processIdentifier: Int32 = -1 public private(set) var running: Bool = false public private(set) var terminationStatus: Int32 = 0 public var terminationReason: NSTaskTerminationReason { NSUnimplemented() } /* A block to be invoked when the process underlying the NSTask terminates. Setting the block to nil is valid, and stops the previous block from being invoked, as long as it hasn't started in any way. The NSTask is passed as the argument to the block so the block does not have to capture, and thus retain, it. The block is copied when set. Only one termination handler block can be set at any time. The execution context in which the block is invoked is undefined. If the NSTask has already finished, the block is executed immediately/soon (not necessarily on the current thread). If a terminationHandler is set on an NSTask, the NSTaskDidTerminateNotification notification is not posted for that task. Also note that -waitUntilExit won't wait until the terminationHandler has been fully executed. You cannot use this property in a concrete subclass of NSTask which hasn't been updated to include an implementation of the storage and use of it. */ public var terminationHandler: ((NSTask) -> Void)? public var qualityOfService: NSQualityOfService = .Default // read-only after the task is launched } extension NSTask { // convenience; create and launch public class func launchedTaskWithLaunchPath(path: String, arguments: [String]) -> NSTask { let task = NSTask() task.launchPath = path task.arguments = arguments task.launch() return task } // poll the runLoop in defaultMode until task completes public func waitUntilExit() { repeat { } while( self.running == true && NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: 0.05)) ) self.runLoop = nil } } public let NSTaskDidTerminateNotification: String = "NSTaskDidTerminateNotification"
apache-2.0
f5eea99a3f3bf8714ada3d2a5cc78cea
38.133523
957
0.632595
5.357837
false
false
false
false
apple/swift
test/SILGen/properties.swift
2
34546
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s var zero: Int = 0 func use(_: Int) {} func use(_: Double) {} func getInt() -> Int { return zero } // CHECK-LABEL: sil hidden [ossa] @{{.*}}physical_tuple_lvalue // CHECK: bb0(%0 : $Int): func physical_tuple_lvalue(_ c: Int) { var x : (Int, Int) // CHECK: [[BOX:%[0-9]+]] = alloc_box ${ var (Int, Int) } // CHECK: [[MARKED_BOX:%[0-9]+]] = mark_uninitialized [var] [[BOX]] // CHECK: [[XADDR:%.*]] = project_box [[MARKED_BOX]] x.1 = c // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[XADDR]] // CHECK: [[X_1:%[0-9]+]] = tuple_element_addr [[WRITE]] : {{.*}}, 1 // CHECK: assign %0 to [[X_1]] } func tuple_rvalue() -> (Int, Int) {} // CHECK-LABEL: sil hidden [ossa] @{{.*}}physical_tuple_rvalue func physical_tuple_rvalue() -> Int { return tuple_rvalue().1 // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s10properties12tuple_rvalue{{[_0-9a-zA-Z]*}}F // CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]() // CHECK: ({{%.*}}, [[RET:%[0-9]+]]) = destructure_tuple [[TUPLE]] // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties16tuple_assignment{{[_0-9a-zA-Z]*}}F func tuple_assignment(_ a: inout Int, b: inout Int) { // CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[B_ADDR]] // CHECK: [[B:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[A_ADDR]] // CHECK: [[A:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[A_ADDR]] // CHECK: assign [[B]] to [[WRITE]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[B_ADDR]] // CHECK: assign [[A]] to [[WRITE]] (a, b) = (b, a) } // CHECK-LABEL: sil hidden [ossa] @$s10properties18tuple_assignment_2{{[_0-9a-zA-Z]*}}F func tuple_assignment_2(_ a: inout Int, b: inout Int, xy: (Int, Int)) { // CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int, [[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int): (a, b) = xy // CHECK: [[XY2:%[0-9]+]] = tuple ([[X]] : $Int, [[Y]] : $Int) // CHECK: ([[X:%[0-9]+]], [[Y:%[0-9]+]]) = destructure_tuple [[XY2]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[A_ADDR]] // CHECK: assign [[X]] to [[WRITE]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[B_ADDR]] // CHECK: assign [[Y]] to [[WRITE]] } class Ref { var x, y : Int var ref : Ref var z: Int { get {} set {} } var val_prop: Val { get {} set {} } subscript(i: Int) -> Float { get {} set {} } init(i: Int) { x = i y = i ref = self } } class RefSubclass : Ref { var w : Int override init (i: Int) { w = i super.init(i: i) } } struct Val { var x, y : Int var ref : Ref var z: Int { get {} set {} } var z_tuple: (Int, Int) { get {} set {} } subscript(i: Int) -> Float { get {} set {} } } // CHECK-LABEL: sil hidden [ossa] @$s10properties22physical_struct_lvalue{{[_0-9a-zA-Z]*}}F func physical_struct_lvalue(_ c: Int) { var v : Val // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } v.y = c // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] // CHECK: [[YADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK: assign %0 to [[YADDR]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties21physical_class_lvalue{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Ref, Int) -> () // CHECK: bb0([[ARG0:%.*]] : @guaranteed $Ref, func physical_class_lvalue(_ r: Ref, a: Int) { r.y = a // CHECK: [[FN:%[0-9]+]] = class_method [[ARG0]] : $Ref, #Ref.y!setter // CHECK: apply [[FN]](%1, [[ARG0]]) : $@convention(method) (Int, @guaranteed Ref) -> () } // CHECK-LABEL: sil hidden [ossa] @$s10properties24physical_subclass_lvalue{{[_0-9a-zA-Z]*}}F func physical_subclass_lvalue(_ r: RefSubclass, a: Int) { // CHECK: bb0([[ARG1:%.*]] : @guaranteed $RefSubclass, [[ARG2:%.*]] : $Int): r.y = a // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] : $RefSubclass // CHECK: [[R_SUP:%[0-9]+]] = upcast [[ARG1_COPY]] : $RefSubclass to $Ref // CHECK: [[FN:%[0-9]+]] = class_method [[R_SUP]] : $Ref, #Ref.y!setter : (Ref) -> (Int) -> (), $@convention(method) (Int, @guaranteed Ref) -> () // CHECK: apply [[FN]]([[ARG2]], [[R_SUP]]) : // CHECK: destroy_value [[R_SUP]] r.w = a // CHECK: [[FN:%[0-9]+]] = class_method [[ARG1]] : $RefSubclass, #RefSubclass.w!setter // CHECK: apply [[FN]](%1, [[ARG1]]) : $@convention(method) (Int, @guaranteed RefSubclass) -> () // CHECK-NOT: destroy_value [[ARG1]] // CHECK: } // end sil function '$s10properties24physical_subclass_lvalue{{[_0-9a-zA-Z]*}}F' } func struct_rvalue() -> Val {} // CHECK-LABEL: sil hidden [ossa] @$s10properties22physical_struct_rvalue{{[_0-9a-zA-Z]*}}F func physical_struct_rvalue() -> Int { return struct_rvalue().y // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s10properties13struct_rvalueAA3ValVyF // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]() // CHECK: [[BORROWED_STRUCT:%.*]] = begin_borrow [[STRUCT]] // CHECK: [[RET:%[0-9]+]] = struct_extract [[BORROWED_STRUCT]] : $Val, #Val.y // CHECK: end_borrow [[BORROWED_STRUCT]] // CHECK: destroy_value [[STRUCT]] // CHECK: return [[RET]] } func class_rvalue() -> Ref {} // CHECK-LABEL: sil hidden [ossa] @$s10properties21physical_class_rvalue{{[_0-9a-zA-Z]*}}F func physical_class_rvalue() -> Int { return class_rvalue().y // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s10properties12class_rvalueAA3RefCyF // CHECK: [[CLASS:%[0-9]+]] = apply [[FUNC]]() // CHECK: [[BORROW:%.*]] = begin_borrow [[CLASS]] // CHECK: [[FN:%[0-9]+]] = class_method [[BORROW]] : $Ref, #Ref.y!getter // CHECK: [[RET:%[0-9]+]] = apply [[FN]]([[BORROW]]) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties18logical_struct_get{{[_0-9a-zA-Z]*}}F func logical_struct_get() -> Int { return struct_rvalue().z // CHECK: [[GET_RVAL:%[0-9]+]] = function_ref @$s10properties13struct_rvalue{{[_0-9a-zA-Z]*}}F // CHECK: [[STRUCT:%[0-9]+]] = apply [[GET_RVAL]]() // CHECK: [[BORROW:%[0-9]+]] = begin_borrow [[STRUCT]] // CHECK: [[GET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV1z{{[_0-9a-zA-Z]*}}vg // CHECK: [[VALUE:%[0-9]+]] = apply [[GET_METHOD]]([[BORROW]]) // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties18logical_struct_set{{[_0-9a-zA-Z]*}}F func logical_struct_set(_ value: inout Val, z: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z:%[0-9]+]] : $Int): value.z = z // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[VAL]] // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV1z{{[_0-9a-zA-Z]*}}vs // CHECK: apply [[Z_SET_METHOD]]([[Z]], [[WRITE]]) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s10properties27logical_struct_in_tuple_set{{[_0-9a-zA-Z]*}}F func logical_struct_in_tuple_set(_ value: inout (Int, Val), z: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*(Int, Val), [[Z:%[0-9]+]] : $Int): value.1.z = z // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[VAL]] // CHECK: [[VAL_1:%[0-9]+]] = tuple_element_addr [[WRITE]] : {{.*}}, 1 // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV1z{{[_0-9a-zA-Z]*}}vs // CHECK: apply [[Z_SET_METHOD]]([[Z]], [[VAL_1]]) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s10properties29logical_struct_in_reftype_set{{[_0-9a-zA-Z]*}}F func logical_struct_in_reftype_set(_ value: inout Val, z1: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int): value.ref.val_prop.z_tuple.1 = z1 // -- val.ref // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[VAL]] // CHECK: [[VAL_REF_ADDR:%[0-9]+]] = struct_element_addr [[READ]] : $*Val, #Val.ref // CHECK: [[VAL_REF:%[0-9]+]] = load [copy] [[VAL_REF_ADDR]] // -- getters and setters // -- val.ref.val_prop // CHECK: [[BORROW:%.*]] = begin_borrow [[VAL_REF]] // CHECK: [[MAT_VAL_PROP_METHOD:%[0-9]+]] = class_method {{.*}} : $Ref, #Ref.val_prop!modify : (Ref) -> () // CHECK: ([[VAL_REF_VAL_PROP_MAT:%[0-9]+]], [[TOKEN:%.*]]) = begin_apply [[MAT_VAL_PROP_METHOD]]([[BORROW]]) // -- val.ref.val_prop.z_tuple // CHECK: [[V_R_VP_Z_TUPLE_MAT:%[0-9]+]] = alloc_stack $(Int, Int) // CHECK: [[LD:%[0-9]+]] = load_borrow [[VAL_REF_VAL_PROP_MAT]] // CHECK: [[A0:%.*]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 0 // CHECK: [[A1:%.*]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 1 // CHECK: [[GET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV7z_tupleSi_Sitvg // CHECK: [[V_R_VP_Z_TUPLE:%[0-9]+]] = apply [[GET_Z_TUPLE_METHOD]]([[LD]]) // CHECK: ([[T0:%.*]], [[T1:%.*]]) = destructure_tuple [[V_R_VP_Z_TUPLE]] // CHECK: store [[T0]] to [trivial] [[A0]] // CHECK: store [[T1]] to [trivial] [[A1]] // CHECK: end_borrow [[LD]] // -- write to val.ref.val_prop.z_tuple.1 // CHECK: [[V_R_VP_Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 1 // CHECK: assign [[Z1]] to [[V_R_VP_Z_TUPLE_1]] // -- writeback to val.ref.val_prop.z_tuple // CHECK: [[WB_V_R_VP_Z_TUPLE:%[0-9]+]] = load [trivial] [[V_R_VP_Z_TUPLE_MAT]] // CHECK: [[SET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV7z_tupleSi_Sitvs // CHECK: apply [[SET_Z_TUPLE_METHOD]]({{%[0-9]+, %[0-9]+}}, [[VAL_REF_VAL_PROP_MAT]]) // -- writeback to val.ref.val_prop // CHECK: end_apply [[TOKEN]] // -- cleanup // CHECK: dealloc_stack [[V_R_VP_Z_TUPLE_MAT]] // -- don't need to write back to val.ref because it's a ref type } func reftype_rvalue() -> Ref {} // CHECK-LABEL: sil hidden [ossa] @$s10properties18reftype_rvalue_set{{[_0-9a-zA-Z]*}}F func reftype_rvalue_set(_ value: Val) { reftype_rvalue().val_prop = value } // CHECK-LABEL: sil hidden [ossa] @$s10properties27tuple_in_logical_struct_set{{[_0-9a-zA-Z]*}}F func tuple_in_logical_struct_set(_ value: inout Val, z1: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int): value.z_tuple.1 = z1 // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[VAL]] // CHECK: [[Z_TUPLE_MATERIALIZED:%[0-9]+]] = alloc_stack $(Int, Int) // CHECK: [[VAL1:%[0-9]+]] = load_borrow [[WRITE]] // CHECK: [[A0:%.*]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 0 // CHECK: [[A1:%.*]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 1 // CHECK: [[Z_GET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV7z_tupleSi_Sitvg // CHECK: [[Z_TUPLE:%[0-9]+]] = apply [[Z_GET_METHOD]]([[VAL1]]) // CHECK: ([[T0:%.*]], [[T1:%.*]]) = destructure_tuple [[Z_TUPLE]] // CHECK: store [[T0]] to [trivial] [[A0]] // CHECK: store [[T1]] to [trivial] [[A1]] // CHECK: end_borrow [[VAL1]] // CHECK: [[Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 1 // CHECK: assign [[Z1]] to [[Z_TUPLE_1]] // CHECK: [[Z_TUPLE_MODIFIED:%[0-9]+]] = load [trivial] [[Z_TUPLE_MATERIALIZED]] // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV7z_tupleSi_Sitvs // CHECK: apply [[Z_SET_METHOD]]({{%[0-9]+, %[0-9]+}}, [[WRITE]]) // CHECK: dealloc_stack [[Z_TUPLE_MATERIALIZED]] // CHECK: return } var global_prop : Int { // CHECK-LABEL: sil hidden [ossa] @$s10properties11global_prop{{[_0-9a-zA-Z]*}}vg get { return zero } // CHECK-LABEL: sil hidden [ossa] @$s10properties11global_prop{{[_0-9a-zA-Z]*}}vs set { use(newValue) } } // CHECK-LABEL: sil hidden [ossa] @$s10properties18logical_global_get{{[_0-9a-zA-Z]*}}F func logical_global_get() -> Int { return global_prop // CHECK: [[GET:%[0-9]+]] = function_ref @$s10properties11global_prop{{[_0-9a-zA-Z]*}}vg // CHECK: [[VALUE:%[0-9]+]] = apply [[GET]]() // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties18logical_global_set{{[_0-9a-zA-Z]*}}F func logical_global_set(_ x: Int) { global_prop = x // CHECK: [[SET:%[0-9]+]] = function_ref @$s10properties11global_prop{{[_0-9a-zA-Z]*}}vs // CHECK: apply [[SET]](%0) } // CHECK-LABEL: sil hidden [ossa] @$s10properties17logical_local_get{{[_0-9a-zA-Z]*}}F func logical_local_get(_ x: Int) -> Int { var prop : Int { get { return x } } // CHECK: [[GET_REF:%[0-9]+]] = function_ref [[PROP_GET_CLOSURE:@\$s10properties17logical_local_getyS2iF4propL_Sivg]] // CHECK: apply [[GET_REF]](%0) return prop } // CHECK-: sil private [[PROP_GET_CLOSURE]] // CHECK: bb0(%{{[0-9]+}} : $Int): func logical_generic_local_get<T>(_ x: Int, _: T) { var prop1: Int { get { return x } } _ = prop1 var prop2: Int { get { _ = T.self return x } } _ = prop2 } // CHECK-LABEL: sil hidden [ossa] @$s10properties26logical_local_captured_get{{[_0-9a-zA-Z]*}}F func logical_local_captured_get(_ x: Int) -> Int { var prop : Int { get { return x } } func get_prop() -> Int { return prop } return get_prop() // CHECK: [[FUNC_REF:%[0-9]+]] = function_ref @$s10properties26logical_local_captured_getyS2iF0E5_propL_SiyF // CHECK: apply [[FUNC_REF]](%0) } // CHECK: sil private [ossa] @$s10properties26logical_local_captured_get{{.*}}vg // CHECK: bb0(%{{[0-9]+}} : $Int): func inout_arg(_ x: inout Int) {} // CHECK-LABEL: sil hidden [ossa] @$s10properties14physical_inout{{[_0-9a-zA-Z]*}}F func physical_inout(_ x: Int) { var x = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XADDR]] inout_arg(&x) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: [[INOUT_ARG:%[0-9]+]] = function_ref @$s10properties9inout_arg{{[_0-9a-zA-Z]*}}F // CHECK: apply [[INOUT_ARG]]([[WRITE]]) } /* TODO check writeback to more complex logical prop, check that writeback * reuses temporaries */ // CHECK-LABEL: sil hidden [ossa] @$s10properties17val_subscript_get{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Val, Int) -> Float // CHECK: bb0([[VVAL:%[0-9]+]] : @guaranteed $Val, [[I:%[0-9]+]] : $Int): func val_subscript_get(_ v: Val, i: Int) -> Float { return v[i] // CHECK: [[SUBSCRIPT_GET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV{{[_0-9a-zA-Z]*}}ig // CHECK: [[RET:%[0-9]+]] = apply [[SUBSCRIPT_GET_METHOD]]([[I]], [[VVAL]]) : $@convention(method) (Int, @guaranteed Val) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s10properties17val_subscript_set{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @guaranteed $Val, [[I:%[0-9]+]] : $Int, [[X:%[0-9]+]] : $Float): func val_subscript_set(_ v: Val, i: Int, x: Float) { var v = v v[i] = x // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[VADDR]] // CHECK: [[PB:%.*]] = project_box [[LIFETIME]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: [[SUBSCRIPT_SET_METHOD:%[0-9]+]] = function_ref @$s10properties3ValV{{[_0-9a-zA-Z]*}}is // CHECK: apply [[SUBSCRIPT_SET_METHOD]]([[X]], [[I]], [[WRITE]]) } struct Generic<T> { var mono_phys:Int var mono_log: Int { get {} set {} } var typevar_member:T subscript(x: Int) -> Float { get {} set {} } subscript(x: T) -> T { get {} set {} } // CHECK-LABEL: sil hidden [ossa] @$s10properties7GenericV19copy_typevar_member{{[_0-9a-zA-Z]*}}F mutating func copy_typevar_member(_ x: Generic<T>) { typevar_member = x.typevar_member } } // CHECK-LABEL: sil hidden [ossa] @$s10properties21generic_mono_phys_get{{[_0-9a-zA-Z]*}}F func generic_mono_phys_get<T>(_ g: Generic<T>) -> Int { return g.mono_phys // CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys } // CHECK-LABEL: sil hidden [ossa] @$s10properties20generic_mono_log_get{{[_0-9a-zA-Z]*}}F func generic_mono_log_get<T>(_ g: Generic<T>) -> Int { return g.mono_log // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @$s10properties7GenericV8mono_log{{[_0-9a-zA-Z]*}}vg // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden [ossa] @$s10properties20generic_mono_log_set{{[_0-9a-zA-Z]*}}F func generic_mono_log_set<T>(_ g: Generic<T>, x: Int) { var g = g g.mono_log = x // CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @$s10properties7GenericV8mono_log{{[_0-9a-zA-Z]*}}vs // CHECK: apply [[GENERIC_SET_METHOD]]< } // CHECK-LABEL: sil hidden [ossa] @$s10properties26generic_mono_subscript_get{{[_0-9a-zA-Z]*}}F func generic_mono_subscript_get<T>(_ g: Generic<T>, i: Int) -> Float { return g[i] // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @$s10properties7GenericV{{[_0-9a-zA-Z]*}}ig // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden [ossa] @{{.*}}generic_mono_subscript_set func generic_mono_subscript_set<T>(_ g: inout Generic<T>, i: Int, x: Float) { g[i] = x // CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @$s10properties7GenericV{{[_0-9a-zA-Z]*}}is // CHECK: apply [[GENERIC_SET_METHOD]]< } // CHECK-LABEL: sil hidden [ossa] @{{.*}}bound_generic_mono_phys_get func bound_generic_mono_phys_get(_ g: inout Generic<UnicodeScalar>, x: Int) -> Int { return g.mono_phys // CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys } // CHECK-LABEL: sil hidden [ossa] @$s10properties26bound_generic_mono_log_get{{[_0-9a-zA-Z]*}}F func bound_generic_mono_log_get(_ g: Generic<UnicodeScalar>, x: Int) -> Int { return g.mono_log // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @$s10properties7GenericV8mono_log{{[_0-9a-zA-Z]*}}vg // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden [ossa] @$s10properties22generic_subscript_type{{[_0-9a-zA-Z]*}}F func generic_subscript_type<T>(_ g: Generic<T>, i: T, x: T) -> T { var g = g g[i] = x return g[i] } /*TODO: archetype and existential properties and subscripts */ struct StaticProperty { static var foo: Int { get { return zero } set {} } } // CHECK-LABEL: sil hidden [ossa] @$s10properties10static_get{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s10properties14StaticPropertyV3foo{{[_0-9a-zA-Z]*}}vgZ : $@convention(method) (@thin StaticProperty.Type) -> Int func static_get() -> Int { return StaticProperty.foo } // CHECK-LABEL: sil hidden [ossa] @$s10properties10static_set{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s10properties14StaticPropertyV3foo{{[_0-9a-zA-Z]*}}vsZ : $@convention(method) (Int, @thin StaticProperty.Type) -> () func static_set(_ x: Int) { StaticProperty.foo = x } // Superclass init methods should not get direct access to be class properties. // rdar://16151899 class rdar16151899Base { var x: Int = zero { willSet { use(x) } } } class rdar16151899Derived : rdar16151899Base { // CHECK-LABEL: sil hidden [ossa] @$s10properties19rdar16151899DerivedC{{[_0-9a-zA-Z]*}}fc override init() { super.init() // CHECK: upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base // CHECK: function_ref @$s10properties16rdar16151899BaseCACycfc : $@convention(method) (@owned rdar16151899Base) -> @owned rdar16151899Base // This should not be a direct access, it should call the setter in the // base. x = zero // CHECK: [[BASEPTR:%[0-9]+]] = upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base // CHECK: load{{.*}}Int // CHECK-NEXT: end_access {{.*}} : $*Int // CHECK-NEXT: [[SETTER:%[0-9]+]] = class_method {{.*}} : $rdar16151899Base, #rdar16151899Base.x!setter : (rdar16151899Base) // CHECK-NEXT: apply [[SETTER]]({{.*}}, [[BASEPTR]]) } } class BaseProperty { var x : Int { get {} set {} } } class DerivedProperty : BaseProperty { override var x : Int { get {} set {} } func super_property_reference() -> Int { return super.x } } // rdar://16381392 - Super property references in non-objc classes should be direct. // CHECK-LABEL: sil hidden [ossa] @$s10properties15DerivedPropertyC24super_property_referenceSiyF : $@convention(method) (@guaranteed DerivedProperty) -> Int { // CHECK: bb0([[SELF:%.*]] : @guaranteed $DerivedProperty): // CHECK: [[SELF_COPY:%[0-9]+]] = copy_value [[SELF]] // CHECK: [[BASEPTR:%[0-9]+]] = upcast [[SELF_COPY]] : $DerivedProperty to $BaseProperty // CHECK: [[BORROW:%[0-9]+]] = begin_borrow [[BASEPTR]] // CHECK: [[FN:%[0-9]+]] = function_ref @$s10properties12BasePropertyC1xSivg : $@convention(method) (@guaranteed BaseProperty) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[BORROW]]) : $@convention(method) (@guaranteed BaseProperty) -> Int // CHECK: destroy_value [[BASEPTR]] // CHECK: return [[RESULT]] : $Int // CHECK: } // end sil function '$s10properties15DerivedPropertyC24super_property_referenceSiyF' // <rdar://problem/16411449> ownership qualifiers don't work with non-mutating struct property struct ReferenceStorageTypeRValues { unowned var p1 : Ref func testRValueUnowned() -> Ref { return p1 } // CHECK: sil hidden [ossa] @{{.*}}testRValueUnowned{{.*}} : $@convention(method) (@guaranteed ReferenceStorageTypeRValues) -> @owned Ref { // CHECK: bb0([[ARG:%.*]] : @guaranteed $ReferenceStorageTypeRValues): // CHECK-NEXT: debug_value [[ARG]] : $ReferenceStorageTypeRValues // CHECK-NEXT: [[UNOWNED_ARG_FIELD:%.*]] = struct_extract [[ARG]] : $ReferenceStorageTypeRValues, #ReferenceStorageTypeRValues.p1 // CHECK-NEXT: [[COPIED_VALUE:%.*]] = strong_copy_unowned_value [[UNOWNED_ARG_FIELD]] // CHECK-NEXT: return [[COPIED_VALUE]] : $Ref init() { } } // <rdar://problem/16554876> property accessor synthesization of weak variables doesn't work protocol WeakPropertyProtocol { var maybePresent : Ref? { get set } } struct WeakPropertyStruct : WeakPropertyProtocol { weak var maybePresent : Ref? init() { maybePresent = nil } } // <rdar://problem/16629598> direct property accesses to generic struct // properties were being mischecked as computed property accesses. struct SomeGenericStruct<T> { var x: Int } // CHECK-LABEL: sil hidden [ossa] @$s10properties4getX{{[_0-9a-zA-Z]*}}F // CHECK: struct_extract {{%.*}} : $SomeGenericStruct<T>, #SomeGenericStruct.x func getX<T>(_ g: SomeGenericStruct<T>) -> Int { return g.x } /// <rdar://problem/16953517> Class properties should be allowed in protocols, even without stored class properties protocol ProtoWithClassProp { static var x: Int { get } } class ClassWithClassProp : ProtoWithClassProp { class var x: Int { return 42 } } struct StructWithClassProp : ProtoWithClassProp { static var x: Int { return 19 } } func getX<T : ProtoWithClassProp>(_ a : T) -> Int { return T.x } func testClassPropertiesInProtocol() -> Int { return getX(ClassWithClassProp())+getX(StructWithClassProp()) } class GenericClass<T> { var x: T var y: Int final let z: T init() { fatalError("scaffold") } } // CHECK-LABEL: sil hidden [ossa] @$s10properties12genericPropsyyAA12GenericClassCySSGF : $@convention(thin) (@guaranteed GenericClass<String>) -> () { func genericProps(_ x: GenericClass<String>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $GenericClass<String>): // CHECK: class_method [[ARG]] : $GenericClass<String>, #GenericClass.x!getter // CHECK: apply {{.*}}<String>({{.*}}, [[ARG]]) : $@convention(method) <τ_0_0> (@guaranteed GenericClass<τ_0_0>) -> @out τ_0_0 let _ = x.x // CHECK: class_method [[ARG]] : $GenericClass<String>, #GenericClass.y!getter // CHECK: apply {{.*}}<String>([[ARG]]) : $@convention(method) <τ_0_0> (@guaranteed GenericClass<τ_0_0>) -> Int let _ = x.y // CHECK: [[Z:%.*]] = ref_element_addr [[ARG]] : $GenericClass<String>, #GenericClass.z // CHECK: [[LOADED_Z:%.*]] = load [copy] [[Z]] : $*String // CHECK: destroy_value [[LOADED_Z]] // CHECK-NOT: destroy_value [[ARG]] let _ = x.z } // CHECK-LABEL: sil hidden [ossa] @$s10properties28genericPropsInGenericContext{{[_0-9a-zA-Z]*}}F func genericPropsInGenericContext<U>(_ x: GenericClass<U>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $GenericClass<U>): // CHECK: [[Z:%.*]] = ref_element_addr [[ARG]] : $GenericClass<U>, #GenericClass.z // CHECK: copy_addr [[Z]] {{.*}} : $*U let _ = x.z } // <rdar://problem/18275556> 'let' properties in a class should be implicitly final class ClassWithLetProperty { let p = 42 @objc dynamic let q = 97 // We shouldn't have any dynamic dispatch within this method, just load p. func ReturnConstant() -> Int { return p } // CHECK-LABEL: sil hidden [ossa] @$s10properties20ClassWithLetPropertyC14ReturnConstant{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithLetProperty): // CHECK-NEXT: debug_value // CHECK-NEXT: [[PTR:%[0-9]+]] = ref_element_addr [[ARG]] : $ClassWithLetProperty, #ClassWithLetProperty.p // CHECK-NEXT: [[VAL:%[0-9]+]] = load [trivial] [[PTR]] : $*Int // CHECK-NEXT: return [[VAL]] : $Int // This property is marked dynamic, so go through the getter, always. func ReturnDynamicConstant() -> Int { return q } // CHECK-LABEL: sil hidden [ossa] @$s10properties20ClassWithLetPropertyC21ReturnDynamicConstant{{[_0-9a-zA-Z]*}}F // CHECK: objc_method %0 : $ClassWithLetProperty, #ClassWithLetProperty.q!getter.foreign } // <rdar://problem/19254812> DI bug when referencing let member of a class class r19254812Base {} class r19254812Derived: r19254812Base{ let pi = 3.14159265359 init(x : ()) { use(pi) } // Accessing the "pi" property should not copy_value/release self. // CHECK-LABEL: sil hidden [ossa] @$s10properties16r19254812DerivedC{{[_0-9a-zA-Z]*}}fc // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] // CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[LIFETIME]] // Initialization of the pi field: no copy_values/releases. // CHECK: [[SELF:%[0-9]+]] = load_borrow [[PB_BOX]] : $*r19254812Derived // CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi // CHECK: [[FN:%[0-9]+]] = function_ref @$s10properties16r19254812DerivedC2piSdvpfi : $@convention(thin) () -> Double // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[FN]]() : $@convention(thin) () -> Double // CHECK-NEXT: store [[RESULT]] to [trivial] [[PIPTR]] : $*Double // CHECK-NOT: destroy_value // CHECK-NOT: copy_value // Load of the pi field: no copy_values/releases. // CHECK: [[SELF:%[0-9]+]] = load_borrow [[PB_BOX]] : $*r19254812Derived // CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi // CHECK-NEXT: {{.*}} = load [trivial] [[PIPTR]] : $*Double // CHECK: return } class RedundantSelfRetains { final var f : RedundantSelfRetains init() { f = RedundantSelfRetains() } // <rdar://problem/19275047> Extraneous copy_values/releases of self are bad func testMethod1() { f = RedundantSelfRetains() } // CHECK-LABEL: sil hidden [ossa] @$s10properties20RedundantSelfRetainsC11testMethod1{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @guaranteed $RedundantSelfRetains): // CHECK-NOT: copy_value // CHECK: [[FPTR:%[0-9]+]] = ref_element_addr %0 : $RedundantSelfRetains, #RedundantSelfRetains.f // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[FPTR]] : $*RedundantSelfRetains // CHECK-NEXT: assign {{.*}} to [[WRITE]] : $*RedundantSelfRetains // CHECK: return } class RedundantRetains { final var field = 0 } func testRedundantRetains() { let a = RedundantRetains() a.field = 4 // no copy_value/release of a necessary here. } // CHECK-LABEL: sil hidden [ossa] @$s10properties20testRedundantRetainsyyF : $@convention(thin) () -> () { // CHECK: [[A:%[0-9]+]] = apply // CHECK-NOT: copy_value // CHECK: destroy_value [[A]] : $RedundantRetains // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: return struct AddressOnlyNonmutatingSet<T> { var x: T init(x: T) { self.x = x } var prop: Int { get { return 0 } nonmutating set { } } } func addressOnlyNonmutatingProperty<T>(_ x: AddressOnlyNonmutatingSet<T>) -> Int { x.prop = 0 return x.prop } // CHECK-LABEL: sil hidden [ossa] @$s10properties30addressOnlyNonmutatingProperty{{[_0-9a-zA-Z]*}}F // CHECK: [[SET:%.*]] = function_ref @$s10properties25AddressOnlyNonmutatingSetV4propSivs // CHECK: apply [[SET]]<T>({{%.*}}, [[TMP:%[0-9]*]]) // CHECK: destroy_addr [[TMP]] // CHECK: dealloc_stack [[TMP]] // CHECK: [[GET:%.*]] = function_ref @$s10properties25AddressOnlyNonmutatingSetV4propSivg // CHECK: apply [[GET]]<T>([[TMP:%[0-9]*]]) // CHECK: destroy_addr [[TMP]] // CHECK: dealloc_stack [[TMP]] protocol MakeAddressOnly {} struct AddressOnlyReadOnlySubscript { var x: MakeAddressOnly? subscript(z: Int) -> Int { return z } } // CHECK-LABEL: sil hidden [ossa] @$s10properties015addressOnlyReadC24SubscriptFromMutableBase // CHECK: [[BASE:%.*]] = alloc_box ${ var AddressOnlyReadOnlySubscript } // CHECK: copy_addr [[BASE:%.*]] to [init] [[COPY:%.*]] : // CHECK: copy_addr [[COPY:%.*]] to [init] [[COPY2:%.*]] : // CHECK: [[GETTER:%.*]] = function_ref @$s10properties015AddressOnlyReadC9SubscriptV{{[_0-9a-zA-Z]*}}ig // CHECK: apply [[GETTER]]({{%.*}}, [[COPY2]]) func addressOnlyReadOnlySubscriptFromMutableBase(_ x: Int) { var base = AddressOnlyReadOnlySubscript() _ = base[x] } /// <rdar://problem/20912019> passing unmaterialized r-value as inout argument struct MutatingGetterStruct { var write: Int { mutating get { } } // CHECK-LABEL: sil hidden [ossa] @$s10properties20MutatingGetterStructV4test // CHECK: [[X:%.*]] = alloc_box ${ var MutatingGetterStruct }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK: store {{.*}} to [trivial] [[PB]] : $*MutatingGetterStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: apply {{%.*}}([[WRITE]]) : $@convention(method) (@inout MutatingGetterStruct) -> Int static func test() { var x = MutatingGetterStruct() _ = x.write } } protocol ProtocolWithReadWriteSubscript { subscript(i: Int) -> Int { get set } } struct CrashWithUnnamedSubscript : ProtocolWithReadWriteSubscript { subscript(_: Int) -> Int { get { } set { } } } // Make sure that we can handle this AST: // (load_expr // (open_existential_expr // (opaque_expr A) // ... // (load_expr // (opaque_expr )))) class ReferenceType { var p: NonmutatingProtocol init(p: NonmutatingProtocol) { self.p = p } } protocol NonmutatingProtocol { var x: Int { get nonmutating set } } // sil hidden [ossa] @$s10properties19overlappingLoadExpr1cyAA13ReferenceTypeCz_tF : $@convention(thin) (@inout ReferenceType) -> () { // CHECK: [[C_INOUT:%.*]] = begin_access [read] [unknown] %0 : $*ReferenceType // CHECK-NEXT: [[C:%.*]] = load [copy] [[C_INOUT:%.*]] : $*ReferenceType // CHECK-NEXT: end_access [[C_INOUT]] : $*ReferenceType // CHECK-NEXT: [[C_BORROW:%.*]] = begin_borrow [[C]] // CHECK-NEXT: [[C_FIELD_BOX:%.*]] = alloc_stack $any NonmutatingProtocol // CHECK-NEXT: [[GETTER:%.*]] = class_method [[C_BORROW]] : $ReferenceType, #ReferenceType.p!getter : (ReferenceType) -> () -> any NonmutatingProtocol, $@convention(method) (@guaranteed ReferenceType) -> @out any NonmutatingProtocol // CHECK-NEXT: apply [[GETTER]]([[C_FIELD_BOX]], [[C_BORROW]]) : $@convention(method) (@guaranteed ReferenceType) -> @out any NonmutatingProtocol // CHECK-NEXT: end_borrow [[C_BORROW]] // CHECK-NEXT: [[C_FIELD_PAYLOAD:%.*]] = open_existential_addr immutable_access [[C_FIELD_BOX]] : $*any NonmutatingProtocol to $*@opened("{{.*}}", any NonmutatingProtocol) Self // CHECK-NEXT: [[C_FIELD_COPY:%.*]] = alloc_stack $@opened("{{.*}}", any NonmutatingProtocol) Self // CHECK-NEXT: copy_addr [[C_FIELD_PAYLOAD]] to [init] [[C_FIELD_COPY]] : $*@opened("{{.*}}", any NonmutatingProtocol) Self // CHECK-NEXT: destroy_value [[C]] : $ReferenceType // CHECK-NEXT: [[C_FIELD_BORROW:%.*]] = alloc_stack // CHECK-NEXT: copy_addr [[C_FIELD_COPY]] to [init] [[C_FIELD_BORROW]] // CHECK-NEXT: [[GETTER:%.*]] = witness_method $@opened("{{.*}}", any NonmutatingProtocol) Self, #NonmutatingProtocol.x!getter : <Self where Self : NonmutatingProtocol> (Self) -> () -> Int, [[C_FIELD_PAYLOAD]] : $*@opened("{{.*}}", any NonmutatingProtocol) Self : $@convention(witness_method: NonmutatingProtocol) <τ_0_0 where τ_0_0 : NonmutatingProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[GETTER]]<@opened("{{.*}}", any NonmutatingProtocol) Self>([[C_FIELD_BORROW]]) : $@convention(witness_method: NonmutatingProtocol) <τ_0_0 where τ_0_0 : NonmutatingProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK-NEXT: destroy_addr [[C_FIELD_BORROW]] // CHECK-NEXT: destroy_addr [[C_FIELD_COPY]] : $*@opened("{{.*}}", any NonmutatingProtocol) Self // CHECK-NEXT: dealloc_stack [[C_FIELD_BORROW]] // CHECK-NEXT: dealloc_stack [[C_FIELD_COPY]] : $*@opened("{{.*}}", any NonmutatingProtocol) Self // CHECK-NEXT: destroy_addr [[C_FIELD_BOX]] : $*any NonmutatingProtocol // CHECK-NEXT: dealloc_stack [[C_FIELD_BOX]] : $*any NonmutatingProtocol // CHECK-NEXT: tuple () // CHECK-NEXT: return func overlappingLoadExpr(c: inout ReferenceType) { _ = c.p.x } var globalOptionalComputed: Int? { didSet { print("hello") } } func updateGlobalOptionalComputed() { globalOptionalComputed? = 123 } struct TupleStruct { var v: (Int, Int) { get { } set { } } var vv: (w: Int, h: Int) { get { } set { } } } func assign_to_tuple() { var s = TupleStruct() s.v = (1, 2) let v = (3, 4) s.vv = v } // CHECK-LABEL: sil private [ossa] @$s10properties8myglobalSivW // CHECK-LABEL: sil [ossa] @$s10properties8myglobalSivg // CHECK-LABEL: sil [ossa] @$s10properties8myglobalSivs public var myglobal : Int = 1 { didSet { print("myglobal.didSet") } } // CHECK-LABEL: sil private [ossa] @$s10properties9myglobal2Sivw // CHECK-LABEL: sil [ossa] @$s10properties9myglobal2Sivg // CHECK-LABEL: sil [ossa] @$s10properties9myglobal2Sivs public var myglobal2 : Int = 1 { willSet { print("myglobal.willSet") } } // CHECK-LABEL: sil private [ossa] @$s10properties9myglobal3Sivw // CHECK-LABEL: sil private [ossa] @$s10properties9myglobal3SivW // CHECK-LABEL: sil [ossa] @$s10properties9myglobal3Sivg // CHECK-LABEL: sil [ossa] @$s10properties9myglobal3Sivs public var myglobal3 : Int = 1 { willSet { print("myglobal.willSet") } didSet { print("myglobal.didSet") } }
apache-2.0
9e84836a1b5caa8aeb728f60996cda3d
37.372222
387
0.612538
3.079083
false
false
false
false
apple/swift
test/IDE/complete_lazy_initialized_var.swift
39
668
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=LAZY_IN_CLASS_1 | %FileCheck %s -check-prefix=LAZYVAR1 class FooClass1 { lazy var lazyVar1 = 0 } func lazyInClass1(a: FooClass1) { a.#^LAZY_IN_CLASS_1^# } // This test checks that we don't include extra hidden declarations into code completion results. If you add more declarations to the type, update this test properly. // LAZYVAR1: Begin completions, 2 items // LAZYVAR1-NEXT: Keyword[self]/CurrNominal: self[#FooClass1#]; name=self // LAZYVAR1-NEXT: Decl[InstanceVar]/CurrNominal: lazyVar1[#Int#]{{; name=.+$}} // LAZYVAR1-NEXT: End completions
apache-2.0
d7afab0534d6f621f4bf641a373885e8
46.714286
167
0.714072
3.196172
false
true
false
false
CharlinFeng/PhotoBrowser
PhotoBrowser/AppDelegate.swift
1
2640
// // AppDelegate.swift // PhotoBrowser // // Created by 冯成林 on 15/8/14. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // window = UIWindow(frame: UIScreen.mainScreen().bounds) // window?.backgroundColor = UIColor.whiteColor() // let displayVC = DisplayVC() // // displayVC.tabBarItem.title = "Charlin Feng" // //// let navVC = UINavigationController(rootViewController: displayVC) //// // let tabVC = UITabBarController() //// // tabVC.viewControllers = [displayVC] // // window?.rootViewController = tabVC // // window?.makeKeyAndVisible() 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:. } }
mit
f2ab7782b202791c4d9b7e6f19f95668
41.354839
285
0.71249
5.337398
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Feature layer extrusion/FeatureLayerExtrusionViewController.swift
1
4098
// Copyright 2017 Esri. // // 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 UIKit import ArcGIS /// A view controller that manages the interface of the Feature Layer Extrusion /// sample. class FeatureLayerExtrusionViewController: UIViewController { /// The scene displayed in the scene view. let scene: AGSScene /// The renderer of the feature layer. let renderer: AGSRenderer required init?(coder: NSCoder) { scene = AGSScene(basemapStyle: .arcGISTopographic) /// The url of the States layer of the Census Map Service. let censusMapServiceStatesLayerURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3")! // Create service feature table from US census feature service. let table = AGSServiceFeatureTable(url: censusMapServiceStatesLayerURL) // Create feature layer from service feature table. let layer = AGSFeatureLayer(featureTable: table) // Feature layer must be rendered dynamically for extrusion to work. layer.renderingMode = .dynamic // Setup the symbols used to display the features (US states) from the table. let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: .blue, width: 1.0) let fillSymbol = AGSSimpleFillSymbol(style: .solid, color: .blue, outline: lineSymbol) renderer = AGSSimpleRenderer(symbol: fillSymbol) if let sceneProperties = renderer.sceneProperties { sceneProperties.extrusionMode = .absoluteHeight sceneProperties.extrusionExpression = Statistic.totalPopulation.extrusionExpression } // Set the renderer on the layer and add the layer to the scene. layer.renderer = renderer scene.operationalLayers.add(layer) super.init(coder: coder) } /// The scene view managed by the view controller. @IBOutlet weak var sceneView: AGSSceneView! override func viewDidLoad() { super.viewDidLoad() // Adds the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FeatureLayerExtrusionViewController"] sceneView.scene = scene // Set the scene view's viewpoint. let distance = 12_940_924.0 let point = AGSPoint(x: -99.659448, y: 20.513652, z: distance, spatialReference: .wgs84()) let camera = AGSCamera(lookAt: point, distance: 0, heading: 0, pitch: 15, roll: 0) let viewpoint = AGSViewpoint(center: point, scale: distance, camera: camera) sceneView.setViewpoint(viewpoint) } enum Statistic: Int { case totalPopulation case populationDensity /// The extrusion expression for the statistic. var extrusionExpression: String { switch self { case .totalPopulation: return "[POP2007]/ 10" case .populationDensity: // The offset makes the extrusion look better over Alaska. let offset = 100_000 return "([POP07_SQMI] * 5000) + \(offset)" } } } @IBAction func extrusionAction(_ sender: UISegmentedControl) { if let statistic = Statistic(rawValue: sender.selectedSegmentIndex) { renderer.sceneProperties?.extrusionExpression = statistic.extrusionExpression } else { assertionFailure("Selected segment does not correspond to a statistic") } } }
apache-2.0
23197001fd056fbf539e0f057c827d91
41.6875
139
0.668131
4.721198
false
false
false
false
tardieu/swift
validation-test/compiler_crashers_2_fixed/0047-sr1307.swift
27
960
// RUN: %target-swift-frontend %s -emit-ir enum SampleType: UInt8 { case Value = 1 case Array case Dictionary } protocol ByteConvertible { init?(bytes: [UInt8], startOffset: Int) func rawBytes() -> [UInt8] func bytesNeeded() -> Int } protocol TypeRequestable { static func containerType() -> SampleType } struct Sample<T, C where T: ByteConvertible, C: TypeRequestable> { let numberOfRecords: UInt32 let sizeInBytes: UInt64 var records: [T] = [] // problem line init(records: [T]) { numberOfRecords = 0 sizeInBytes = 0 self.records.reserveCapacity(records.count) self.records += records } } extension Sample: ByteConvertible { init?(bytes: [UInt8], startOffset: Int = 0) { numberOfRecords = 0 sizeInBytes = 0 records = [] } func rawBytes() -> [UInt8] { return [] } func bytesNeeded() -> Int { return 0 } }
apache-2.0
c75d9e8f606e3b834a61ee20e154b2ef
19.425532
66
0.602083
3.934426
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/Schema.swift
1
1436
// // Schema.swift // RealmModelGenerator // // Created by Brandon Erbschloe on 3/3/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Foundation class Schema { static let TAG = NSStringFromClass(Schema.self) var name:String private(set) var models:[Model] = [] let observable:Observable init(name:String = "") { self.name = name self.observable = BaseObservable() } func createModel() -> Model { return createModel(build: {_ in}); } func createModel( build: (Model) throws -> Void) rethrows -> Model { var version = 1 while self.models.contains(where: {$0.version == "\(version)"}) { version += 1 } let model = Model(version: "\(version)", schema:self) try build(model) models.append(model) return model } func setName(name:String) { self.name = name } @discardableResult func increaseVersion() throws -> Model { let currentModelDict = currentModel.toDictionary() self.models.forEach({$0.isModifiable = false}) let model = createModel() try model.map(dictionary: currentModelDict, increaseVersion: true) return model } var currentModel:Model { return self.models.filter({return $0.isModifiable}).first ?? createModel() } }
mit
721b4454519795041623770be65ec035
22.916667
82
0.581185
4.361702
false
false
false
false
jtrudell/LateDBC
LateDBC/ViewController.swift
1
1644
// // ViewController.swift // LateDBC // // Created by Jen Trudell on 11/14/15. // Copyright © 2015 Jen Trudell. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { // vars for various elements from view @IBOutlet var whoLabel: UILabel! @IBOutlet var enterNameField: UITextField! @IBOutlet var resetButton: UIButton! // add audio functionality to play I'm late var audioPlayer = AVAudioPlayer() var lateSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("late", ofType: "mp3")!) func playMySound(){ do { audioPlayer = try AVAudioPlayer(contentsOfURL: lateSound, fileTypeHint: nil) } catch _ { return } audioPlayer.prepareToPlay() audioPlayer.play() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // when name is entered and returned, change top label text @IBAction func enterNameAction(sender: UITextField) { if sender.text == "" { sender.text = "Eileen" } whoLabel.text = sender.text! + " is late today!" playMySound() } // when reset button is pressed, reset top label and text entry field @IBAction func resetButtonPressed(sender: AnyObject) { self.whoLabel.text = "Who is late today?" self.enterNameField.text = "" } }
mit
c4931fcd646e9ac73c9c80ba3ad9c56d
26.383333
110
0.643944
4.641243
false
false
false
false
karivalkama/Agricola-Scripture-Editor
Pods/QRCodeReader.swift/Sources/ReaderOverlayView.swift
1
2659
/* * QRCodeReader.swift * * Copyright 2014-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 /// Overlay over the camera view to display the area (a square) where to scan the code. public final class ReaderOverlayView: UIView { private var overlay: CAShapeLayer = { var overlay = CAShapeLayer() overlay.backgroundColor = UIColor.clear.cgColor overlay.fillColor = UIColor.clear.cgColor overlay.strokeColor = UIColor.white.cgColor overlay.lineWidth = 3 overlay.lineDashPattern = [7.0, 7.0] overlay.lineDashPhase = 0 return overlay }() override init(frame: CGRect) { super.init(frame: frame) setupOverlay() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupOverlay() } private func setupOverlay() { layer.addSublayer(overlay) } var overlayColor: UIColor = UIColor.white { didSet { self.overlay.strokeColor = overlayColor.cgColor self.setNeedsDisplay() } } public override func draw(_ rect: CGRect) { var innerRect = rect.insetBy(dx: 50, dy: 50) let minSize = min(innerRect.width, innerRect.height) if innerRect.width != minSize { innerRect.origin.x += (innerRect.width - minSize) / 2 innerRect.size.width = minSize } else if innerRect.height != minSize { innerRect.origin.y += (innerRect.height - minSize) / 2 innerRect.size.height = minSize } overlay.path = UIBezierPath(roundedRect: innerRect, cornerRadius: 5).cgPath } }
mit
ca7f4b4937806dca3914fc14f1f274ee
31.426829
87
0.703272
4.402318
false
false
false
false
JasonChen2015/Paradise-Lost
Paradise Lost/Classes/ViewControllers/Tool/MarqueeVC.swift
3
3718
// // MarqueeVC.swift // Paradise Lost // // Created by jason on 10/8/2016. // Copyright © 2016 Jason Chen. All rights reserved. // import UIKit class MarqueeVC: UIViewController, MarqueeViewDelegate { var mainView: MarqueeView! // MARK: life cycle override var shouldAutorotate : Bool { return true } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .portrait } override func viewDidLoad() { super.viewDidLoad() mainView = MarqueeView(frame: UIScreen.main.bounds) mainView.delegate = self view.addSubview(mainView) // initialise mainView.setColorSegment(0) mainView.setSpeedSegment(1) mainView.refreshPreview() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // diable back swipe gesture navigationController?.interactivePopGestureRecognizer?.isEnabled = false } override func viewWillDisappear(_ animated: Bool) { navigationController?.interactivePopGestureRecognizer?.isEnabled = true super.viewWillDisappear(animated) } // MARK: MarqueeViewDelegate func willShowFullScreenMarquee(_ text: String, colorText: UIColor, colorBackground: UIColor, speedMode: MarqueeLabel.SpeedLimit) { let newViewCtrl = MarqueeFullVC() newViewCtrl.initialText(text, textColor: colorText, backgroundColor: colorBackground) newViewCtrl.initialRunMode(speedMode) present(newViewCtrl, animated: false, completion: nil) } } class MarqueeFullVC: UIViewController { fileprivate var mainLabel: MarqueeLabel! fileprivate var textColor: UIColor! fileprivate var backgroundColor: UIColor! fileprivate var mainText: String! fileprivate var speedLimit: MarqueeLabel.SpeedLimit! // MARK: life cycle override var prefersStatusBarHidden : Bool { return true } override var shouldAutorotate : Bool { return true } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .landscapeRight } override func viewDidLoad() { super.viewDidLoad() let rect = UIScreen.main.bounds // show in landscape right mainLabel = MarqueeLabel(frame: CGRect(x: 0, y: 0, width: rect.height, height: rect.width)) mainLabel.font = UIFont.boldSystemFont(ofSize: 230) mainLabel.textColor = textColor mainLabel.backgroundColor = backgroundColor mainLabel.text = mainText mainLabel.speed = speedLimit mainLabel.animationCurve = .linear mainLabel.animationDelay = 0.0 view.addSubview(mainLabel) let viewGesture = UITapGestureRecognizer(target: self, action: #selector(MarqueeFullVC.viewTouchDown(_:))) view.addGestureRecognizer(viewGesture) // do not let the screen display closed until dismiss UIApplication.shared.isIdleTimerDisabled = true } // MARK: event response @objc func viewTouchDown(_ recognizer: UITapGestureRecognizer) { UIApplication.shared.isIdleTimerDisabled = false dismiss(animated: false, completion: nil) } // MARK: getters and setters func initialText(_ mainText: String, textColor: UIColor, backgroundColor: UIColor) { self.textColor = textColor self.backgroundColor = backgroundColor self.mainText = mainText } func initialRunMode(_ speedLimit: MarqueeLabel.SpeedLimit) { self.speedLimit = speedLimit } }
mit
8c40ec5eafcf8c7fe8bcfea291c3de5f
29.467213
134
0.664783
5.41048
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Fitting/Cargo/FittingCargo.swift
2
3453
// // FittingCargo.swift // Neocom // // Created by Artem Shimanski on 4/17/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import Expressible struct FittingCargo: View { @ObservedObject var ship: DGMShip @Environment(\.managedObjectContext) var managedObjectContext @Environment(\.self) private var environment @Environment(\.typePicker) private var typePicker @EnvironmentObject private var sharedState: SharedState @State private var isTypePickerPresented = false private func typePicker(_ group: SDEDgmppItemGroup) -> some View { typePicker.get(group, environment: environment, sharedState: sharedState) { self.isTypePickerPresented = false guard let type = $0 else {return} DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { try? self.ship.add(DGMCargo(typeID: DGMTypeID(type.typeID))) } } } struct Row { var type: SDEInvType? var cargo: DGMCargo } struct CargoSection { var category: SDEInvCategory? var rows: [Row] } private var group: SDEDgmppItemGroup? { try? self.managedObjectContext.fetch(SDEDgmppItemGroup.rootGroup(categoryID: .cargo)).first } var body: some View { let cargo = ship.cargo let invTypes = cargo.map{$0.typeID}.compactMap{try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32($0)).first()} let types = Dictionary(invTypes.map{($0.typeID, $0)}) {a, _ in a} let rows = cargo.map{Row(type: types[Int32($0.typeID)], cargo: $0)} let sections = Dictionary(grouping: rows) {$0.type?.group?.category} .sorted{($0.key?.categoryName ?? "") < ($1.key?.categoryName ?? "")} .map{ (category, rows) -> CargoSection in let rows = rows.sorted{($0.type?.typeName ?? "", $0.cargo.hashValue) < ($1.type?.typeName ?? "", $1.cargo.hashValue)} return CargoSection(category: category, rows: rows) } return VStack(spacing: 0) { FittingCargoHeader(ship: ship).padding(8) Divider() List { ForEach(sections, id: \.category) { section in Section(header: section.category?.categoryName.map{Text($0.uppercased())}) { ForEach(section.rows, id: \.cargo) { row in FittingCargoCell(ship: self.ship, cargo: row.cargo) } } } Section { Button(NSLocalizedString("Add Cargo", comment: "")) { self.isTypePickerPresented = true } .frame(maxWidth: .infinity) .adaptivePopover(isPresented: $isTypePickerPresented, arrowEdge: .leading) { self.group.map{self.typePicker($0)} } } } .listStyle(GroupedListStyle()) } } } #if DEBUG struct FittingCargo_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() return FittingCargo(ship: gang.pilots[0].ship!) .environmentObject(gang) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
d554af827b4a38aad9f153847a5f20e3
34.587629
152
0.569235
4.536137
false
false
false
false
Monapp/Hryvna-backend
Sources/App/Avarage.swift
1
1313
// // Account.swift // InstaSchedule // // Created by Vladimir Hulchenko on 12/27/16. // // import Vapor import HTTP import Foundation let kCreatedDate = "createdDate" let kData = "data" let kid = "id" let kAvarage = "Avarage" final class Avarage: Model { var id: Node? var createdDate: Int64 var data: Node var exists: Bool = false init(data: Node) { self.id = nil self.createdDate = Int64(Date().timeIntervalSince1970) self.data = data } init(node: Node, in context: Context) throws { self.id = try node.extract(kid) self.createdDate = try node.extract(kCreatedDate) self.data = try node.extract(kData) } func makeNode(context: Context) throws -> Node { return try Node.init(node:[kid: id, kData: data, kCreatedDate: createdDate]) } static func prepare(_ database: Database) throws{ try database.create(kAvarage, closure: { (users) in users.id() users.int(kCreatedDate) users.string(kData) }) } static func revert(_ database: Database) throws { try database.delete(kAvarage) } }
mit
b18c7f50dcf75f00ad28dd08af88bc47
20.177419
62
0.548363
4.090343
false
false
false
false
getwagit/Baya
Baya/BayaLayoutable.swift
1
4113
// // Copyright (c) 2016-2017 wag it GmbH. // License: MIT // import Foundation import UIKit /** Something that you can layout. Can be a UIView or another Layout. */ public protocol BayaLayoutable { var bayaMargins: UIEdgeInsets {get} var frame: CGRect {get} var bayaModes: BayaLayoutOptions.Modes {get} mutating func sizeThatFits(_ size: CGSize) -> CGSize mutating func layoutWith(frame: CGRect) } /** Public helper. */ public extension BayaLayoutable { var bayaModes: BayaLayoutOptions.Modes { return BayaLayoutOptions.Modes.default } } /** Internal helper. */ internal extension BayaLayoutable { var verticalMargins: CGFloat { return bayaMargins.top + bayaMargins.bottom } var horizontalMargins: CGFloat { return bayaMargins.left + bayaMargins.right } var heightWithMargins: CGFloat { return frame.height + verticalMargins } var widthWithMargins: CGFloat { return frame.width + horizontalMargins } mutating func sizeThatFitsWithMargins(_ size: CGSize) -> CGSize { return sizeThatFits(size.subtractMargins(ofElement: self)) } mutating func subtractMarginsAndLayoutWith(frame: CGRect) { layoutWith(frame: frame.subtractMargins(ofElement: self)) } } // MARK: Sequence Helper /** Converts any sequence into an array if it is not an Array already. Needed because we ca not extend an Array with BayaLayoutable as generic parameter. */ internal extension Sequence where Iterator.Element == BayaLayoutable { func array() -> [BayaLayoutable] { if let array = self as? [BayaLayoutable] { return array } return Array(self) } } /** Upcast a sequence of a type that implements BayaLayoutable. And convert to Array. */ internal extension Sequence where Iterator.Element: BayaLayoutable { func array() -> [BayaLayoutable] { if let array = self as? [Iterator.Element] { return upcast(array: array) } return upcast(array: Array(self)) } func upcast<T: BayaLayoutable>(array: [T]) -> [BayaLayoutable] { return array.map { $0 as BayaLayoutable } } } // MARK: UIKit specific extensions /** Apply LayoutTarget to UIView. */ extension UIView: BayaLayoutable { public var bayaMargins: UIEdgeInsets { return UIEdgeInsets.zero } public func layoutWith(frame: CGRect) { setFrameSafely(frame) } } /** Helper for safely setting the frame on LayoutTargets. */ internal extension UIView { /** Use this method to set a frame safely if other transformations might have been applied. See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/frame - Parameter frame: The same frame you would normally set via LayoutTarget.frame . */ func setFrameSafely(_ frame: CGRect) { if transform == CGAffineTransform.identity { self.frame = frame } else { let bounds = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) self.bounds = bounds self.center = CGPoint(x: frame.minX + bounds.midX, y: frame.minY + bounds.midY) } } } // MARK: CGRect and CGSize internal extension CGSize { func subtractMargins(ofElement element: BayaLayoutable) -> CGSize { return CGSize( width: max(width - element.horizontalMargins, 0), height: max(height - element.verticalMargins, 0)) } func addMargins(ofElement element: BayaLayoutable) -> CGSize { return CGSize( width: width + element.horizontalMargins, height: height + element.verticalMargins) } } internal extension CGRect { func subtractMargins(ofElement element: BayaLayoutable) -> CGRect { return CGRect( origin: CGPoint( x: minX + element.bayaMargins.left, y: minY + element.bayaMargins.top), size: size.subtractMargins(ofElement: element)) } }
mit
2d5e529e52c7bf81065aa1424c10670d
25.882353
130
0.653538
4.222793
false
false
false
false
davidahouse/chute
chute/ChuteDetailDifference/ViewDifference.swift
1
1570
// // ViewDifference.swift // chute // // Created by David House on 11/12/17. // Copyright © 2017 David House. All rights reserved. // import Foundation struct ViewDifference { let newViews: [ChuteTestAttachment] let changedViews: [(ChuteTestAttachment, ChuteTestAttachment)] init(detail: DataCapture, comparedTo: DataCapture, detailAttachmentURL: URL, comparedToAttachmentURL: URL) { var newViews = [ChuteTestAttachment]() var changedViews = [(ChuteTestAttachment, ChuteTestAttachment)]() for attachment in comparedTo.attachments { let found = detail.attachments.filter { $0.testIdentifier == attachment.testIdentifier && $0.attachmentName == attachment.attachmentName } if let foundAttachment = found.first { let originFileURL = detailAttachmentURL.appendingPathComponent(foundAttachment.attachmentFileName) let comparedToFileURL = comparedToAttachmentURL.appendingPathComponent(attachment.attachmentFileName) if let originData = try? Data(contentsOf: originFileURL), let comparedToData = try? Data(contentsOf: comparedToFileURL) { if originData != comparedToData { changedViews.append((attachment, foundAttachment)) } } } else { newViews.append(attachment) } } self.newViews = newViews self.changedViews = changedViews } }
mit
e5d1990f6acfaa41960e7e8061a8fa51
36.357143
150
0.625876
5.06129
false
true
false
false
narner/AudioKit
Examples/macOS/AudioUnitManager/AudioUnitManager/ViewController - Effects.swift
1
12953
// // ViewController - AudioUnits.swift // AudioUnitManager // // Created by Ryan Francesconi on 10/6/17. // Copyright © 2017 Ryan Francesconi. All rights reserved. // import Cocoa import AVFoundation import AudioKit extension ViewController { internal func initManager() { internalManager = AKAudioUnitManager(inserts: 6) internalManager?.delegate = self internalManager?.requestEffects(completionHandler: { audioUnits in self.updateEffectsUI(audioUnits: audioUnits) }) internalManager?.requestInstruments(completionHandler: { audioUnits in self.updateInstrumentsUI(audioUnits: audioUnits) }) } internal func initUI() { // let colors = [NSColor(calibratedRed: 0.888, green: 0.888, blue: 0.888, alpha: 1), // NSColor(calibratedRed: 0.748, green: 0.748, blue: 0.748, alpha: 1), // NSColor(calibratedRed: 0.612, green: 0.612, blue: 0.612, alpha: 1), // NSColor(calibratedRed: 0.558, green: 0.558, blue: 0.558, alpha: 1), // NSColor(calibratedRed: 0.483, green: 0.483, blue: 0.483, alpha: 1), // NSColor(calibratedRed: 0.35, green: 0.35, blue: 0.35, alpha: 1)] let colors = [NSColor(calibratedRed: 1, green: 0.652, blue: 0, alpha: 1), NSColor(calibratedRed: 0.32, green: 0.584, blue: 0.8, alpha: 1), NSColor(calibratedRed: 0.79, green: 0.372, blue: 0.191, alpha: 1), NSColor(calibratedRed: 0.676, green: 0.537, blue: 0.315, alpha: 1), NSColor(calibratedRed: 0.431, green: 0.701, blue: 0.407, alpha: 1), NSColor(calibratedRed: 0.59, green: 0.544, blue: 0.763, alpha: 1)] var counter = 0 var buttons = effectsContainer.subviews.filter { $0 as? MenuButton != nil } buttons.sort { $0.tag < $1.tag } for sv in buttons { guard let b = sv as? MenuButton else { continue } b.bgColor = colors[counter] counter += 1 if counter > colors.count { counter = 0 } } } //////////////////////////// func showEffect( at auIndex: Int, state: Bool ) { if auIndex > internalManager!.effectsChain.count - 1 { AKLog("index is out of range") return } if state { // get audio unit at the specified index if let au = internalManager?.effectsChain[auIndex] { showAudioUnit(au, identifier: auIndex) } else { AKLog("Nothing at this index") } } else { if let w = getWindowFromIndentifier(auIndex) { w.close() } } } func handleEffectSelected(_ auname: String, identifier: Int) { guard internalManager != nil else { return } AKLog("\(identifier) \(auname)") if auname == "-" { let blankName = "▼ Insert \(identifier + 1)" if let button = getEffectsButtonFromIdentifier(identifier) { button.state = .off } if let menu = getMenuFromIdentifier(identifier) { selectEffectInMenu(name: "-", identifier: identifier) menu.title = blankName } if let win = getWindowFromIndentifier(identifier) { win.close() } internalManager!.removeEffect(at: identifier) return } internalManager!.insertAudioUnit(name: auname, at: identifier) // select the item in the menu selectEffectInMenu(name: auname, identifier: identifier) } func selectEffectInMenu(name: String, identifier: Int) { guard let button = getMenuFromIdentifier(identifier) else { return } guard let menu = button.menu else { return } var parentMenu: NSMenuItem? for man in menu.items { guard let sub = man.submenu else { continue } man.state = .off for item in sub.items { item.state = (item.title == name) ? .on : .off if item.state == .on { parentMenu = man } } } if let pm = parentMenu { pm.state = .on button.title = "▶︎ \(name)" } } // MARK: - Build the effects menus fileprivate func updateEffectsUI( audioUnits: [AVAudioUnitComponent] ) { guard internalManager != nil else { return } var manufacturers = [String]() for component in audioUnits { let man = component.manufacturerName if !manufacturers.contains(man) { manufacturers.append(man) } } // going to put internal AUs in here manufacturers.append( akInternals ) manufacturers.sort() // fill all the menus with the same list for sv in effectsContainer.subviews { guard let b = sv as? MenuButton else { continue } if b.menu == nil { let theMenu = NSMenu(title: "Effects") theMenu.font = NSFont.systemFont(ofSize: 10) b.menu = theMenu } b.menu?.removeAllItems() b.title = "▼ Insert \(b.tag + 1)" let blankItem = ClosureMenuItem(title: "-", closure: { [weak self] in guard let strongSelf = self else { return } strongSelf.handleEffectSelected("-", identifier: b.tag) }) b.menu?.addItem(blankItem) // first make a menu of manufacturers for man in manufacturers { let manItem = NSMenuItem() manItem.title = man manItem.submenu = NSMenu(title: man) b.menu?.addItem(manItem) } // then add each AU into it's parent folder for component in audioUnits { let item = ClosureMenuItem(title: component.name, closure: { [weak self] in guard let strongSelf = self else { return } strongSelf.handleEffectSelected(component.name, identifier: b.tag) }) // manufacturer list for man in b.menu!.items { if man.title == component.manufacturerName { man.submenu?.addItem(item) } } } let internalSubmenu = b.menu?.items.filter { $0.title == akInternals }.first for name in internalManager!.internalAudioUnits { let item = ClosureMenuItem(title: name, closure: { [weak self] in guard let strongSelf = self else { return } strongSelf.handleEffectSelected(name, identifier: b.tag) }) internalSubmenu?.submenu?.addItem(item) } } } internal func getMenuFromIdentifier(_ id: Int ) -> MenuButton? { guard effectsContainer != nil else { return nil } for sv in effectsContainer.subviews { guard let b = sv as? MenuButton else { continue } if b.tag == id { return b } } return nil } internal func getWindowFromIndentifier(_ tag: Int ) -> NSWindow? { let identifier = windowPrefix + String(tag) guard let windows = self.view.window?.childWindows else { return nil } for w in windows { if w.identifier?.rawValue == identifier { return w } } return nil } internal func getEffectsButtonFromIdentifier(_ id: Int ) -> NSButton? { guard effectsContainer != nil else { return nil } for sv in effectsContainer.subviews { if sv.isKind(of: NSButton.self) && !sv.isKind(of: NSPopUpButton.self) { let b = sv as! NSButton if b.tag == id { return b } } } return nil } public func showAudioUnit(_ audioUnit: AVAudioUnit, identifier: Int ) { // first we ask the audio unit if it has a view controller audioUnit.auAudioUnit.requestViewController { [weak self] viewController in var ui = viewController guard let strongSelf = self else { return } guard let auName = audioUnit.auAudioUnit.audioUnitName else { return } DispatchQueue.main.async { // if it doesn't - then the host's job is to create one for it if ui == nil { //AKLog("No ViewController for \(audioUnit.name )") ui = NSViewController() ui!.view = AudioUnitGenericView(au: audioUnit) } guard ui != nil else { return } let incomingFrame = ui!.view.frame AKLog("Audio Unit incoming frame: \(incomingFrame)") guard let selfWindow = strongSelf.view.window else { return } //let unitWindow = NSWindow(contentViewController: ui!) let unitWindowController = AudioUnitGenericWindow(audioUnit: audioUnit) guard let unitWindow = unitWindowController.window else { return } unitWindow.title = "\(auName)" unitWindow.delegate = self unitWindow.identifier = NSUserInterfaceItemIdentifier(strongSelf.windowPrefix + String(identifier)) var windowColor = NSColor.darkGray if let buttonColor = strongSelf.getMenuFromIdentifier(identifier)?.bgColor { windowColor = buttonColor } unitWindowController.scrollView.documentView = ui!.view NSLayoutConstraint.activateConstraintsEqualToSuperview(child: ui!.view) unitWindowController.toolbar?.backgroundColor = windowColor.withAlphaComponent(0.9) if let gauv = ui?.view as? AudioUnitGenericView { gauv.backgroundColor = windowColor } let toolbarHeight: CGFloat = 20 let f = NSMakeRect(unitWindow.frame.origin.x, unitWindow.frame.origin.y, ui!.view.frame.width, ui!.view.frame.height + toolbarHeight + 20) unitWindow.setFrame(f, display: true) let uiFrame = NSMakeRect(0, 0, incomingFrame.width, incomingFrame.height + toolbarHeight) ui!.view.frame = uiFrame // } else { // unitWindow.contentViewController = ui! // } if let w = strongSelf.getWindowFromIndentifier(identifier) { unitWindow.setFrameOrigin( w.frame.origin ) w.close() } selfWindow.addChildWindow(unitWindow, ordered: NSWindow.OrderingMode.above) unitWindow.setFrameOrigin(NSPoint(x:selfWindow.frame.origin.x, y:selfWindow.frame.origin.y - unitWindow.frame.height)) if let button = strongSelf.getEffectsButtonFromIdentifier(identifier) { button.state = .on } } //dispatch } } fileprivate func reconnect() { // is FM playing? if fm != nil && fm!.isStarted { internalManager!.connectEffects(firstNode: fm!, lastNode: mixer) return } else if auInstrument != nil && !(player?.isStarted ?? false) { internalManager!.connectEffects(firstNode: auInstrument!, lastNode: mixer) return } else if player != nil { let playing = player!.isStarted if playing { player!.stop() } internalManager!.connectEffects(firstNode: player, lastNode: mixer) if playing { player!.start() } } } } extension ViewController: AKAudioUnitManagerDelegate { func handleAudioUnitNotification(type: AKAudioUnitManager.Notification, object: Any?) { guard internalManager != nil else { return } if type == AKAudioUnitManager.Notification.changed { updateEffectsUI( audioUnits: internalManager!.availableEffects ) } } func handleEffectAdded( at auIndex: Int ) { showEffect(at: auIndex, state: true) guard internalManager != nil else { return } guard mixer != nil else { return } reconnect() } func handleEffectRemoved(at auIndex: Int) { reconnect() } }
mit
a644c52f3b165fa9712028d10546d3ed
34.269755
134
0.539632
4.888218
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/AppDelegate.swift
1
5710
// // AppDelegate.swift // WISData.JunZheng // // Created by Jingwei Wu on 8/15/16. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit import DrawerController import SVProgressHUD import Ruler @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Setup HUD SVProgressHUD.setForegroundColor(UIColor(white: 1, alpha: 1)) SVProgressHUD.setBackgroundColor(UIColor(white: 0.15, alpha: 0.85)) SVProgressHUD.setDefaultStyle(.Custom) SVProgressHUD.setMinimumDismissTimeInterval(1.5) SVProgressHUD.setDefaultMaskType(.Clear) SVProgressHUD.setDefaultAnimationType(.Native) // Observe notification for HUD NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didDisappearProgressHUD), name: SVProgressHUDDidDisappearNotification, object: nil) // Config global window appearance UINavigationBar.appearance().barTintColor = UIColor.wisLogoColor() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() if User.obtainRecentUserName() == nil { if !currentDevice.isPad { UIApplication.sharedApplication().setStatusBarOrientation(.Portrait, animated: false) } // no effect if you don't rotate statusbar 2016.09.10 // UIDevice.currentDevice().setValue(NSNumber.init(long: UIDeviceOrientation.Portrait.rawValue), forKey: "orientation") self.window!.rootViewController = LoginViewController() } else { startMainStory() } return true } // Mark: Function func didDisappearProgressHUD() { SVProgressHUD.setDefaultMaskType(.Clear) } func initialDefaultSearchParameter() { let dateForSearch = NSDate.today.dateByAddingTimeInterval(-16*60*60) // 获得当前时间,并转化格式 SearchParameter["date"] = dateFormatterForSearch(dateForSearch) // 判断 UserDefaults 中是否储存了当前炉号,如果没储存,默认显示 1#炉 的生产数据 if let lNo = NSUserDefaults.standardUserDefaults().objectForKey("lNo") as? String { SearchParameter["lNo"] = lNo } else { SearchParameter["lNo"] = "1" } // 获取班次号 SearchParameter["shiftNo"] = getShiftNo(dateFormatterGetHour(dateForSearch)) } func startMainStory() { initialDefaultSearchParameter() let centerNav = UINavigationController(rootViewController: DataHomeViewController()) let leftViewController = LeftMenuViewController() let drawerController = DrawerController(centerViewController: centerNav, leftDrawerViewController: leftViewController) drawerController.maximumLeftDrawerWidth = Ruler.iPhoneVertical(150, 150, 200, 220).value drawerController.openDrawerGestureModeMask = OpenDrawerGestureMode.PanningCenterView drawerController.closeDrawerGestureModeMask = CloseDrawerGestureMode.All drawerController.animationVelocity = 420.0 drawerController.shouldStretchDrawer = false drawerController.showsShadows = true self.window!.rootViewController = drawerController WISClient.sharedInstance.drawerController = drawerController WISClient.sharedInstance.centerViewController = centerNav.viewControllers[0] as? DataHomeViewController WISClient.sharedInstance.centerNavigation = centerNav } 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:. } }
mit
7e4a097e9ea6a030d22551f641e10e12
44.666667
285
0.712302
5.662298
false
false
false
false
mogstad/Delta
sources/data_structures/collection_record.swift
1
4700
public typealias CollectionItem = (section: Int, index: Int) /// A `CollectionRecord` describe one change in your dataset. Delta uses it to /// describe the changes to perform to the old dataset to turn it into the new /// dataset. Each case has assoicated values to best describe the change for /// that type of change. public enum CollectionRecord: Equatable { /// Item is added into an existing section. /// /// - parameter section: The section the item is added to. /// - parameter index: Index the item is added to. case addItem(section: Int, index: Int) /// Item is removed from an existing section. /// /// - parameter section: The section the item is removed from. /// - parameter index: Index the item is removed from. case removeItem(section: Int, index: Int) /// Describes that an item is moved in-between an existing section. Due to /// limitations with Delta, we don’t currently support creating move records /// between sections. Instead we generate two record: one remove record from /// the old section, and one add record to the new section. /// /// - parameter from: A tuple, with the section and the index of the item /// where it used to be. /// - parameter to: A tuple, with the section and the index of the item, /// where it’s move to. case moveItem(from: CollectionItem, to: CollectionItem) /// Describes that an item has been changed. Its identifier is equal, but the /// model’s equality test fails. Due to internals in Apple’s display classes, /// it’s required to query for the old cell with the original index path, and /// update it with data from the new index path. /// /// - parameter from: A tuple, with the section and the index of the item /// where it used to be. Depending on the UI implementation, you might want /// to query the cell with these values. /// - parameter to: A tuple, with the section and the index of the item, /// where it’s ended up being. Use these values to query your data. case changeItem(from: CollectionItem, to: CollectionItem) /// Describes that a section is to be added. /// /// - parameter section: Index of the newly inserted section. case addSection(section: Int) /// Describes that a section is to be moved. /// /// - parameter section: Index of the sections new location. /// - parameter from: Index where the section used to be located. case moveSection(section: Int, from: Int) /// Describes that a section is to be removed. /// /// - parameter section: Index of the section to remove. case removeSection(section: Int) /// Describes a section that requires a reload. This is mainly needed when /// using cells as empty states. As Delta won’t support multiple types of /// data in the same section. And therefor can’t generate an insert item /// record for the empty state. /// /// - parameter section: Index of the section to reload case reloadSection(section: Int) } /// Returns whether the two `CollectionRecord` records are equal. /// /// - note: Mostly here to make it easier to write tests. /// /// - parameter lhs: The left-hand side value to compare /// - parameter rhs: The Right-hand side value to compare /// - returns: Returns `true` iff `lhs` is identical to `rhs`. public func ==(lhs: CollectionRecord, rhs: CollectionRecord) -> Bool { switch (lhs, rhs) { case (let .addItem(lhsSection, lhsIndex), let .addItem(rhsSection, rhsIndex)): return lhsSection == rhsSection && lhsIndex == rhsIndex case (let .removeItem(lhsSection, lhsIndex), let .removeItem(rhsSection, rhsIndex)): return lhsSection == rhsSection && lhsIndex == rhsIndex case (let .moveItem(lhsFrom, lhsTo), let .moveItem(rhsFrom, rhsTo)): return ( lhsFrom.section == rhsFrom.section && lhsFrom.index == rhsFrom.index && lhsTo.section == rhsTo.section && lhsTo.index == rhsTo.index) case (let .changeItem(lhsFrom, lhsTo), let .changeItem(rhsFrom, rhsTo)): return ( lhsFrom.section == rhsFrom.section && lhsFrom.index == rhsFrom.index && lhsTo.section == rhsTo.section && lhsTo.index == rhsTo.index) case (let .addSection(lhsIndex), let .addSection(rhsIndex)): return lhsIndex == rhsIndex case (let .removeSection(lhsIndex), let .removeSection(rhsIndex)): return lhsIndex == rhsIndex case (let .moveSection(lhsIndex, lhsFrom), let .moveSection(rhsIndex, rhsFrom)): return lhsIndex == rhsIndex && lhsFrom == rhsFrom case (let .reloadSection(lhsIndex), let .reloadSection(rhsIndex)): return lhsIndex == rhsIndex default: return false } }
mit
c55a4818e1857e03916b5d838f5eaf1e
41.581818
88
0.685952
4.182143
false
false
false
false
JmoVxia/CLPlayer
CLHomeController/View/Cell/CLListCell.swift
1
2608
// // CLListCell.swift // CLPlayer // // Created by Chen JmoVxia on 2021/10/26. // import UIKit // MARK: - JmoVxia---类-属性 class CLListCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initUI() makeConstraints() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var titleLabel: UILabel = { let view = UILabel() view.textColor = .hex("#343434") view.font = .systemFont(ofSize: 15) return view }() private lazy var arrowImageView: UIImageView = { let view = UIImageView() view.image = UIImage(named: "meArrowRight") return view }() private lazy var lineView: UIView = { let view = UIView() view.backgroundColor = .hex("#F0F0F0") return view }() } // MARK: - JmoVxia---布局 private extension CLListCell { private func initUI() { isExclusiveTouch = true selectionStyle = .none contentView.addSubview(titleLabel) contentView.addSubview(arrowImageView) contentView.addSubview(lineView) arrowImageView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) arrowImageView.setContentHuggingPriority(.defaultHigh, for: .horizontal) } private func makeConstraints() { arrowImageView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.right.equalTo(-15) } titleLabel.snp.makeConstraints { make in make.left.equalTo(15) make.right.equalTo(arrowImageView.snp.left).offset(-15) make.centerY.equalToSuperview() } lineView.snp.makeConstraints { make in make.left.equalTo(15) make.right.bottom.equalToSuperview() make.height.equalTo(0.5) } } } // MARK: - JmoVxia---CLCellProtocol extension CLListCell: CLCellProtocol { func setItem(_ item: CLCellItemProtocol) { guard let item = item as? CLListItem else { return } titleLabel.text = item.title } } // MARK: - JmoVxia---数据 private extension CLListCell { func initData() {} } // MARK: - JmoVxia---override extension CLListCell {} // MARK: - JmoVxia---objc @objc private extension CLListCell {} // MARK: - JmoVxia---私有方法 private extension CLListCell {} // MARK: - JmoVxia---公共方法 extension CLListCell {}
mit
caf14767291e772324ab8c2394b7c078
23.788462
94
0.631109
4.261157
false
false
false
false
kstaring/swift
test/SourceKit/CursorInfo/cursor_info_container.swift
11
2630
struct S { func getArray() -> [S] { return [] } func getInstance() -> S { return self } static var Instance : S = S() } class C { func getArray() -> [C] { return [] } func getInstance() -> C { return self } static var Instance : C = C() } enum E { case CASE1 func getArray() -> [E] { return [] } func getInstance() -> E { return self } static var Instance : E = E.CASE1 } func SGen() -> S { return S() } func CGen() -> C { return C() } func EGen() -> E { return .CASE1} func foo(s : S, c : C, e: E) { _ = s.getArray() _ = s.getInstance() _ = S.Instance _ = c.getArray() _ = c.getInstance() _ = C.Instance _ = e.getInstance() _ = e.getArray() _ = E.CASE1 _ = E.Instance _ = SGen().getArray() _ = CGen().getInstance() _ = EGen().getArray() _ = SArrayGen().count } func SArrayGen() -> [S] { return [] } // RUN: %sourcekitd-test -req=cursor -pos=24:12 %s -- %s | %FileCheck -check-prefix=CHECK1 %s // RUN: %sourcekitd-test -req=cursor -pos=25:12 %s -- %s | %FileCheck -check-prefix=CHECK1 %s // RUN: %sourcekitd-test -req=cursor -pos=34:19 %s -- %s | %FileCheck -check-prefix=CHECK1 %s // CHECK1: <Container>_TtV21cursor_info_container1S</Container> // RUN: %sourcekitd-test -req=cursor -pos=26:12 %s -- %s | %FileCheck -check-prefix=CHECK2 %s // CHECK2: <Container>_TtMV21cursor_info_container1S</Container> // RUN: %sourcekitd-test -req=cursor -pos=27:12 %s -- %s | %FileCheck -check-prefix=CHECK3 %s // RUN: %sourcekitd-test -req=cursor -pos=28:12 %s -- %s | %FileCheck -check-prefix=CHECK3 %s // RUN: %sourcekitd-test -req=cursor -pos=35:19 %s -- %s | %FileCheck -check-prefix=CHECK3 %s // CHECK3: <Container>_TtC21cursor_info_container1C</Container> // RUN: %sourcekitd-test -req=cursor -pos=29:12 %s -- %s | %FileCheck -check-prefix=CHECK4 %s // CHECK4: <Container>_TtMC21cursor_info_container1C</Container> // RUN: %sourcekitd-test -req=cursor -pos=30:12 %s -- %s | %FileCheck -check-prefix=CHECK5 %s // RUN: %sourcekitd-test -req=cursor -pos=31:12 %s -- %s | %FileCheck -check-prefix=CHECK5 %s // RUN: %sourcekitd-test -req=cursor -pos=36:19 %s -- %s | %FileCheck -check-prefix=CHECK5 %s // CHECK5: <Container>_TtO21cursor_info_container1E</Container> // RUN: %sourcekitd-test -req=cursor -pos=32:12 %s -- %s | %FileCheck -check-prefix=CHECK6 %s // RUN: %sourcekitd-test -req=cursor -pos=33:12 %s -- %s | %FileCheck -check-prefix=CHECK6 %s // CHECK6: <Container>_TtMO21cursor_info_container1E</Container> // RUN: %sourcekitd-test -req=cursor -pos=37:22 %s -- %s | %FileCheck -check-prefix=CHECK7 %s // CHECK7: <Container>_TtGSaV21cursor_info_container1S_</Container>
apache-2.0
1da7fb87d43b86e453c7fe3f3375519b
37.676471
93
0.639544
2.812834
false
true
false
false
davecom/SwiftSimpleNeuralNetwork
SwiftSimpleNeuralNetworkTests/WineTest.swift
1
3502
// // WineTest.swift // SwiftSimpleNeuralNetwork // // Copyright 2016-2019 David Kopec // // 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. // Wine data set courtsey of: // Lichman, M. (2013). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science. import XCTest import Foundation /// Train on 150 wines and then successfully classify /// 28 previously unseen wines. class WineTest: XCTestCase { var network: Network = Network(layerStructure: [13,7,3], learningRate: 0.3, hasBias: true) // for training var wineParameters: [[Double]] = [[Double]]() var wineClassifications: [[Double]] = [[Double]]() // for testing/validation var wineSamples: [[Double]] = [[Double]]() var wineCultivars: [Int] = [Int]() func parseWineCSV() { let myBundle = Bundle.init(for: WineTest.self) let urlpath = myBundle.path(forResource: "wine", ofType: "csv") let url = URL(fileURLWithPath: urlpath!) let csv = try! String.init(contentsOf: url) let lines = csv.components(separatedBy: "\n") let shuffledLines = lines.shuffled for line in shuffledLines { if line == "" { continue } let items = line.components(separatedBy: ",") let parameters = items[1...13].map{ Double($0)! } wineParameters.append(parameters) let species = Int(items[0])! if species == 1 { wineClassifications.append([1.0, 0.0, 0.0]) } else if species == 2 { wineClassifications.append([0.0, 1.0, 0.0]) } else { wineClassifications.append([0.0, 0.0, 1.0]) } wineCultivars.append(species) } normalizeByColumnMax(dataset: &wineParameters) wineSamples = Array(wineParameters.dropFirst(150)) wineCultivars = Array(wineCultivars.dropFirst(150)) wineParameters = Array(wineParameters.dropLast(28)) } func interpretOutput(output: [Double]) -> Int { if output.max()! == output[0] { return 1 } else if output.max()! == output[1] { return 2 } else { return 3 } } override func setUp() { super.setUp() parseWineCSV() // train over entire data set 200 times for _ in 0..<200 { network.train(inputs: wineParameters, expecteds: wineClassifications, printError: false) } } override func tearDown() { super.tearDown() } func testSamples() { let results = network.validate(inputs: wineSamples, expecteds: wineCultivars, interpretOutput: interpretOutput) print("\(results.correct) correct of \(results.total) = \(results.percentage * 100)%") XCTAssertEqual(results.percentage, 1.00, accuracy: 0.05, "Did not come within a 95% confidence interval") } }
apache-2.0
424fa48fec6cd2318f160ae0b9fde135
35.863158
169
0.622216
4.062645
false
true
false
false
notonthehighstreet/swift-mysql
Sources/Example/main.swift
1
2433
import Foundation import MySQL print("Running test client") MySQLConnectionPool.setConnectionProvider() { return MySQL.MySQLConnection() } var connection_noDB: MySQLConnectionProtocol do { // get a connection from the pool with no database connection_noDB = try MySQLConnectionPool.getConnection(host: "127.0.0.1", user: "root", password: "my-secret-pw", port: 3306, database: "")! defer { MySQLConnectionPool.releaseConnection(connection: connection_noDB) // release the connection back to the pool } } catch { print("Unable to create connection") exit(0) } // create a new client using the leased connection var client = MySQLClient(connection: connection_noDB) print("MySQL Client Info: " + client.info()!) print("MySQL Client Version: " + String(client.version())) client.execute(query: "DROP DATABASE IF EXISTS testdb") client.execute(query: "CREATE DATABASE testdb") var connection_withDB: MySQLConnectionProtocol do { // get a connection from the pool connecting to a specific database connection_withDB = try MySQLConnectionPool.getConnection(host: "127.0.0.1", user: "root", password: "my-secret-pw", port: 3306, database: "testdb")! defer { MySQLConnectionPool.releaseConnection(connection: connection_withDB) } } catch { print("Unable to create connection") exit(0) } client = MySQLClient(connection: connection_withDB) client.execute(query: "DROP TABLE IF EXISTS Cars") client.execute(query: "CREATE TABLE Cars(Id INT, Name TEXT, Price INT)") // use query builder to insert data var queryBuilder = MySQLQueryBuilder() .insert(data: ["Id": "1", "Name": "Audi", "Price": "52642"], table: "Cars") client.execute(builder: queryBuilder) queryBuilder = MySQLQueryBuilder() .insert(data: ["Id": "2", "Name": "Mercedes", "Price": "72341"], table: "Cars") client.execute(builder: queryBuilder) // create query to select data from the database queryBuilder = MySQLQueryBuilder() .select(fields: ["Id", "Name", "Price"], table: "Cars") var ret = client.execute(builder: queryBuilder) // returns a tuple (MySQLResult, MySQLError) if let result = ret.0 { var r = result.nextResult() // get the first result from the result set if r != nil { repeat { for value in r! { print(value) } r = result.nextResult() // get the next result from the result set } while(r != nil) // loop while there are results } else { print("No results") } }
mit
571a5d86825e5febaddfba353d337f58
31.013158
151
0.710645
3.725881
false
true
false
false
firebase/friendlypix-ios
FriendlyPix/FPPost.swift
1
1987
// // Copyright (c) 2018 Google 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 Firebase class FPPost { var postID: String var postDate: Date var thumbURL: URL var fullURL: URL var author: FPUser var text: String var comments: [FPComment] var isLiked = false var mine = false var likeCount = 0 convenience init(snapshot: DataSnapshot, andComments comments: [FPComment], andLikes likes: [String: Any]?) { self.init(id: snapshot.key, value: snapshot.value as! [String : Any], andComments: comments, andLikes: likes) } init(id: String, value: [String: Any], andComments comments: [FPComment], andLikes likes: [String: Any]?) { self.postID = id self.text = value["text"] as! String let timestamp = value["timestamp"] as! Double self.postDate = Date(timeIntervalSince1970: (timestamp / 1_000.0)) let author = value["author"] as! [String: String] self.author = FPUser(dictionary: author) self.thumbURL = URL(string: value["thumb_url"] as! String)! self.fullURL = URL(string: value["full_url"] as! String)! self.comments = comments if let likes = likes { likeCount = likes.count if let uid = Auth.auth().currentUser?.uid { isLiked = (likes.index(forKey: uid) != nil) } } self.mine = self.author == Auth.auth().currentUser! } } extension FPPost: Equatable { static func ==(lhs: FPPost, rhs: FPPost) -> Bool { return lhs.postID == rhs.postID } }
apache-2.0
094a25d98be80048bc16e3788803730b
32.677966
113
0.680423
3.720974
false
false
false
false
moudd974/uCAB
Clients/Tablette/Client.swift
1
3198
// // Client.swift // graphique // // Created by Rémi LAVIELLE on 20/10/2015. // Copyright © 2015 Rémi LAVIELLE. All rights reserved. // import Foundation import Socket_IO_Client_Swift import SwiftyJSON import UIKit public class Client { var name : String = "" // Dimension du point let pointSize = CGSize(width: 30, height: 30) var message: String = "" public var cercle = [CGPoint(x: 0.0, y: 0.0)] let mySocket=SocketIOClient(socketURL: "192.168.2.1:9740") init(name: String = "John Doe") { self.name = name connexionServeur() topic() addNewMap() } func connexionServeur() { self.mySocket.connect() print("Connexion reussit") } func addNewMap() { self.mySocket.on("new map") { data, ack in // On parse la reponse en chaine de caractère self.message = data[0] as! String print(self.message) self.ajoutCoordPoint(self.message) } } func sendNeedMap() { self.mySocket.emit("get my map") } func topic() { self.mySocket.joinNamespace("/client") } func dialogueServeur() { sendNeedMap() } func ajoutCoordPoint(message: String) { if let test = self.message.dataUsingEncoding(NSUTF8StringEncoding) { print(" ") let json = JSON(data: test) // On récupère la taille des éléments let taille = json["map"]["vertices"].count print(taille) print("") for item in json["map"]["vertices"].arrayValue { var i : Int = 0 let axeX = item["x"].floatValue let axeY = item["y"].floatValue let coordX = self.reDimensionnementX(axeX) let coordY = self.reDimensionnementX(axeY) print(coordX) print(coordY) cercle[i].x = CGFloat(coordX) cercle[i].y = CGFloat(coordY) let newPoint = CGPoint(x: cercle[i].x, y: cercle[i].y) let newCercle = UIBezierPath(ovalInRect: CGRect(origin: newPoint, size: pointSize)) newCercle.fill() i++ } } } func reDimensionnementX(nombreX: Float)->Float { let maxServeur : Float = 1 let maxTablette : Float = 750 let resultAxeX : Float = (nombreX * maxTablette) / maxServeur return resultAxeX } func reDimensionnementY(nombreY: Float)->Float { let maxServeur : Float = 1 let maxTablette : Float = 1000 let resultAxeY : Float = (nombreY * maxTablette) / maxServeur return resultAxeY } }
gpl-3.0
672f0148a4549d85821450f5146e8193
21.152778
99
0.475862
4.393939
false
false
false
false
alecananian/osx-coin-ticker
CoinTicker/Source/CurrencyPair.swift
1
2831
// // CurrencyPair.swift // CoinTicker // // Created by Alec Ananian on 11/19/17. // Copyright © 2017 Alec Ananian. // // 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 struct CurrencyPair: Comparable, Codable { var baseCurrency: Currency var quoteCurrency: Currency var customCode: String init(baseCurrency: Currency, quoteCurrency: Currency, customCode: String? = nil) { self.baseCurrency = baseCurrency self.quoteCurrency = quoteCurrency if let customCode = customCode { self.customCode = customCode } else { self.customCode = "\(baseCurrency.code)\(quoteCurrency.code)" } } init?(baseCurrency: String?, quoteCurrency: String?, customCode: String? = nil) { guard let baseCurrency = Currency(code: baseCurrency), let quoteCurrency = Currency(code: quoteCurrency) else { return nil } self = CurrencyPair(baseCurrency: baseCurrency, quoteCurrency: quoteCurrency, customCode: customCode) } } extension CurrencyPair: CustomStringConvertible { var description: String { return "\(baseCurrency.code)\(quoteCurrency.code)" } } extension CurrencyPair: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(String(describing: self)) } } extension CurrencyPair: Equatable { static func <(lhs: CurrencyPair, rhs: CurrencyPair) -> Bool { if lhs.baseCurrency == rhs.baseCurrency { return lhs.quoteCurrency < rhs.quoteCurrency } return lhs.baseCurrency < rhs.baseCurrency } static func == (lhs: CurrencyPair, rhs: CurrencyPair) -> Bool { return (lhs.baseCurrency == rhs.baseCurrency && lhs.quoteCurrency == rhs.quoteCurrency) } }
mit
59486b1bc4a9dbf58523e40d8ebf768e
31.906977
119
0.697527
4.477848
false
false
false
false
ryet231ere/DouYuSwift
douyu/douyu/Classes/Tools/NetworkTools.swift
1
909
// // NetworkTools.swift // douyu // // Created by 练锦波 on 2017/2/14. // Copyright © 2017年 练锦波. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(_ type:MethodType, URLString:String, parameters:[String:Any]? = nil, finishedCallback:@escaping (_ result:Any) ->()) { //1.获取类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post //2.发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in //3.获取结果 guard let result = response.result.value else { print(response.result.error ?? "") return } //4.将结果回调出去 finishedCallback(result) } } }
mit
c8a877321c9e1cc2ca491031fef41362
23.342857
145
0.573944
4.30303
false
false
false
false
hyukhur/libphonenumber-swift
LibPhoneNumberSwift/LibPhoneNumberSwift/PhoneNumberUtil.swift
1
16163
// // PhoneNumberUtil.swift // LibPhoneNumberSwift // // Created by Hyuk Hur on 12/31/14. // Copyright (c) 2014 Hyuk Hur. All rights reserved. // import Foundation /** * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation * E123. For example, the number of the Google Switzerland office will be written as * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format. * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g. * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other * separating symbols replaced with a hyphen, and with any phone number extension appended with * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800". * * Note: If you are considering storing the number in a neutral format, you are highly advised to * use the PhoneNumber class. */ public enum PhoneNumberFormat:Int, Printable { case E164 = 0, INTERNATIONAL, NATIONAL, RFC3966 static let strings = ["E164", "INTERNATIONAL", "NATIONAL", "RFC3966"] public func toString() -> String { return PhoneNumberFormat.strings[self.rawValue] } public var description: String { get { return self.toString() } } } public let ErrorDomain = "LibPhoneNumberErrorDomain" public enum ErrorType:Int, Printable { case UNKOWN = -1 case INVALID_COUNTRY_CODE = 0 // This generally indicates the string passed in had less than 3 digits in it. More // specifically, the number failed to match the regular expression VALID_PHONE_NUMBER in // PhoneNumberUtil.java. case NOT_A_NUMBER // This indicates the string started with an international dialing prefix, but after this was // stripped from the number, had less digits than any valid phone number (including country // code) could have. case TOO_SHORT_AFTER_IDD // This indicates the string, after any country code has been stripped, had less digits than any // valid phone number could have. case TOO_SHORT_NSN // This indicates the string had more digits than any valid phone number could have. case TOO_LONG static let strings = ["Invalid country calling code", "The string supplied did not seem to be a phone number", "Phone number too short after IDD", "The string supplied is too short to be a phone number", "The string supplied is too long to be a phone number"] public static func parse(text:String) -> ErrorType { if let index = find(self.strings, text), result = self(rawValue: index) { return result } else { return UNKOWN } } public var description: String { get { return ErrorType.strings[self.rawValue] } } } /** * Types of phone number matches. See detailed description beside the isNumberMatch() method. */ public enum MatchType:Int, Printable { case NOT_A_NUMBER = 0, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH static let strings = ["NOT_A_NUMBER", "NO_MATCH", "SHORT_NSN_MATCH", "NSN_MATCH", "EXACT_MATCH"] public var description: String { get { return MatchType.strings[self.rawValue] } } } /** * Possible outcomes when testing if a PhoneNumber is possible. */ public enum ValidationResult:Int, Printable { case IS_POSSIBLE = 0, INVALID_COUNTRY_CODE, TOO_SHORT, TOO_LONG static let strings = ["IS_POSSIBLE", "INVALID_COUNTRY_CODE", "TOO_SHORT", "TOO_LONG"] public var description: String { get { return ValidationResult.strings[self.rawValue] } } } /** * Type of phone numbers. */ public enum PhoneNumberType:Int, Equatable, Printable { case FIXED_LINE = 0, MOBILE, // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and // mobile numbers by looking at the phone number itself. FIXED_LINE_OR_MOBILE, // Freephone lines TOLL_FREE, PREMIUM_RATE, // The cost of this call is shared between the caller and the recipient, and is hence typically // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for // more information. SHARED_COST, // Voice over IP numbers. This includes TSoIP (Telephony Service over IP). VOIP, // A personal number is associated with a particular person, and may be routed to either a // MOBILE or FIXED_LINE number. Some more information can be found here: // http://en.wikipedia.org/wiki/Personal_Numbers PERSONAL_NUMBER, PAGER, // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to // specific offices, but allow one number to be used for a company. UAN, // Used for "Voice Mail Access Numbers". VOICEMAIL, // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a // specific region. UNKNOWN = -1 static let strings = ["FIXED_LINE", "MOBILE", "FIXED_LINE_OR_MOBILE", "TOLL_FREE", "PREMIUM_RATE", "SHARED_COST", "VOIP", "PERSONAL_NUMBER", "PAGER", "UAN", "VOICEMAIL"] public func toString() -> String { if self == UNKNOWN { return "UNKNOWN" } return PhoneNumberType.strings[self.rawValue] } public var description: String { get { return self.toString() } } } public func == (lhs: PhoneNumberType, rhs: PhoneNumberType) -> Bool { let result = lhs.rawValue == rhs.rawValue return result } public class PhoneNumberUtil { public static let REGION_CODE_FOR_NON_GEO_ENTITY = "001" public static let NANPA_COUNTRY_CODE = 1 public class var DEFAULT_METADATA_LOADER:MetadataLoader { // TODO: should be implemented get { return MetadataLoader() } } var metaData:Array<Dictionary<String, AnyObject>> = [] let countryCodeToRegionCodeMap:[Int:[String]] var countryCodesForNonGeographicalRegion:Set<Int> = Set<Int>() var supportedRegions:[String] = [] var nanpaRegions:[String] = [] public init(URL:NSURL, countryCodeToRegionCodeMap:[Int:[String]]) { if let metaData = NSArray(contentsOfURL: URL) as? Array<Dictionary<String, AnyObject>> { self.metaData = metaData; } self.countryCodeToRegionCodeMap = countryCodeToRegionCodeMap for (key:Int, value:[String]) in countryCodeToRegionCodeMap { if (value.count == 1 && PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY == value.first ) { self.countryCodesForNonGeographicalRegion.insert(key) } else { self.supportedRegions += value; } } if let founded = find(self.supportedRegions, PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY) { self.supportedRegions.removeAtIndex(founded) NSLog("invalid metadata (country calling code was mapped to the non-geo entity as well as specific region(s))"); } if let founded = countryCodeToRegionCodeMap[PhoneNumberUtil.NANPA_COUNTRY_CODE] { self.nanpaRegions += founded } } public func loadMetadataFromFile(#filePrefix:String, regionCode:String, countryCallingCode:Int, metadataLoader:MetadataLoader, error:NSErrorPointer) { // TODO: should be implemented error.memory = NSError(domain: "", code: -1, userInfo:[NSLocalizedDescriptionKey:""]) } // MARK: - Public instance APIs public func getSupportedRegions() -> [String] { return metaData.reduce([], combine: { (var result:[String], each) -> [String] in result.append(each["id"] as! String) return result }) } public func getSupportedGlobalNetworkCallingCodes() -> [Int] { // TODO: should be implemented return [] } public func getRegionCodeForCountryCode(callingCode:Int) -> String { // TODO: should be implemented return "" } public func getCountryCodeForRegion(countryCode:String) -> Int{ // TODO: should be implemented return -1 } public func getMetadataForRegion(regionCode:String) -> PhoneMetadata? { // TODO: should be implemented return PhoneMetadata() } public func getMetadataForNonGeographicalRegion(countryCallingCode:Int) -> PhoneMetadata? { // TODO: should be implemented return PhoneMetadata() } public func isNumberGeographical(phoneNumber:PhoneNumber) -> Bool { // TODO: should be implemented return false } public func isLeadingZeroPossible(countryCallingCode:Int) -> Bool { // TODO: should be implemented return false } public func getLengthOfGeographicalAreaCode(phoneNumber:PhoneNumber) -> Int { // TODO: should be implemented return -1 } public func getLengthOfNationalDestinationCode(phoneNumber:PhoneNumber) -> Int { // TODO: should be implemented return -1 } public func getNationalSignificantNumber(phoneNumber:PhoneNumber) -> String { // TODO: should be implemented return "" } public func getExampleNumber(regionCode:String) -> PhoneNumber? { // TODO: should be implemented return PhoneNumber() } public func getExampleNumberForType(regionCode:String, phoneNumberType:PhoneNumberType) -> PhoneNumber? { // TODO: should be implemented return PhoneNumber() } public func getExampleNumberForNonGeoEntity(countryCallingCode:Int) -> PhoneNumber { // TODO: should be implemented return PhoneNumber() } public func format(number:PhoneNumber, numberFormat:PhoneNumberFormat) -> String { // TODO: should be implemented return "" } public func formatOutOfCountryCallingNumber(number:PhoneNumber, regionCallingFrom:String) -> String { // TODO: should be implemented return "" } public func formatOutOfCountryKeepingAlphaChars(number:PhoneNumber, regionCallingFrom:String) -> String { // TODO: should be implemented return "" } public func formatNationalNumberWithCarrierCode(number:PhoneNumber, carrierCode:String) -> String { // TODO: should be implemented return "" } public func formatNationalNumberWithPreferredCarrierCode(number:PhoneNumber, fallbackCarrierCode:String) -> String { // TODO: should be implemented return "" } public func formatNumberForMobileDialing(number:PhoneNumber, regionCallingFrom:String, withFormatting:Bool) -> String { // TODO: should be implemented return "" } public func formatByPattern(number:PhoneNumber, numberFormat:PhoneNumberFormat, userDefinedFormats:[NumberFormat]) -> String { // TODO: should be implemented return "" } public func parseAndKeepRawInput(numberToParse:String, defaultRegion:String, error:NSErrorPointer) -> PhoneNumber { // TODO: should be implemented error.memory = NSError(domain: "", code: -1, userInfo:[NSLocalizedDescriptionKey:""]) return PhoneNumber() } public func formatInOriginalFormat(number:PhoneNumber, regionCallingFrom:String) -> String { // TODO: should be implemented return "" } public func parse(numberToParse:String, defaultRegion:String, error:NSErrorPointer) -> PhoneNumber { // TODO: should be implemented error.memory = NSError(domain: "", code: -1, userInfo:[NSLocalizedDescriptionKey:""]) return PhoneNumber() } public func getNumberType(number:PhoneNumber) -> PhoneNumberType { // TODO: should be implemented return PhoneNumberType.UNKNOWN } public func isValidNumber(number:PhoneNumber) -> Bool { // TODO: should be implemented return false } public func isValidNumberForRegion(number:PhoneNumber, regionCode:String) -> Bool { // TODO: should be implemented return false } public func getRegionCodeForNumber(number:PhoneNumber) -> String { // TODO: should be implemented return "" } public func getRegionCodesForCountryCode(countryCallingCode:Int) -> [String] { // TODO: should be implemented return [""] } public func getNddPrefixForRegion(regionCode:String, stripNonDigits:Bool) -> String { // TODO: should be implemented return "" } public func isNANPACountry(regionCode:String) -> Bool { // TODO: should be implemented return false } public func isPossibleNumber(number:PhoneNumber) -> Bool { // TODO: should be implemented return false } public func isPossibleNumber(number:String, regionDialingFrom:String) -> Bool { // TODO: should be implemented return false } public func isPossibleNumberWithReason(number:PhoneNumber) -> ValidationResult { // TODO: should be implemented return ValidationResult.TOO_SHORT } public func truncateTooLongNumber(number:PhoneNumber) -> Bool { // TODO: should be implemented return false } public func maybeStripNationalPrefixAndCarrierCode(number:String, metadata:PhoneMetadata, carrierCode:String) -> Bool { // TODO: should be implemented return false } public func maybeStripInternationalPrefixAndNormalize(number:String, possibleIddPrefix:String) -> CountryCodeSource { // TODO: should be implemented return CountryCodeSource.FROM_DEFAULT_COUNTRY } public func maybeExtractCountryCode(number:String, defaultRegionMetadata:PhoneMetadata, keepRawInput:Bool, phoneNumber:PhoneNumber, error:NSErrorPointer) -> (countryCallingCode:Int, nationalNumber:String, phoneNumber:PhoneNumber) { // TODO: should be implemented error.memory = NSError(domain: "", code: -1, userInfo:[NSLocalizedDescriptionKey:""]) return (-1, "", phoneNumber) } public func isNumberMatch(firstString:String, secondString:String) -> MatchType { // TODO: should be implemented return MatchType.NOT_A_NUMBER } public func isNumberMatch(firstNumber:PhoneNumber, secondString:String) -> MatchType { // TODO: should be implemented return MatchType.NOT_A_NUMBER } public func isNumberMatch(firstNumber:PhoneNumber, secondNumber:PhoneNumber) -> MatchType { // TODO: should be implemented return MatchType.NOT_A_NUMBER } public func canBeInternationallyDialled(number:PhoneNumber) -> Bool { // TODO: should be implemented return false } public func isAlphaNumber(number:String) -> Bool { // TODO: should be implemented return false } public func isMobileNumberPortableRegion(regionCode:String) -> Bool { // TODO: should be implemented return false } // MARK: - Class APIs public class func getCountryMobileToken(countryCode:Int) -> String { // TODO: should be implemented return "" } public class func convertAlphaCharactersInNumber(input:String) -> String { // TODO: should be implemented return "" } public class func normalize(phoneNumberString:String) -> String { // TODO: should be implemented return "" } public class func normalizeDigitsOnly(inputNumber:String) -> String { // TODO: should be implemented return "" } public class func normalizeDiallableCharsOnly(inputNumber:String) -> String { // TODO: should be implemented return "" } public class func isViablePhoneNumber(number:String) -> Bool { // TODO: should be implemented return false } public class func extractPossibleNumber(number:String) -> String { // TODO: should be implemented return "" } public class func nsNumberMatch(firstNumberIn:PhoneNumber, secondNumberIn:PhoneNumber) -> MatchType { // TODO: should be implemented return MatchType.NO_MATCH } }
mit
34ce1b40f1ab4c487d4e68285104cfe5
37.575179
235
0.667698
4.489722
false
false
false
false
asyl/Weather
Weather/Networking/Networking.swift
1
2363
// // Networking.swift // Weather // // Created by Asyl Isakov on 2017/08/18. // Copyright © 2017年 asyl. All rights reserved. // import Moya import MoyaSugar import RxSwift final class Networking<Target: SugarTargetType> : RxMoyaSugarProvider<Target> { init() { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders configuration.timeoutIntervalForRequest = 10 let manager = Manager(configuration: configuration) manager.startRequestsImmediately = false super.init(manager: manager) } @available(*, unavailable) override func request(_ token: Target) -> Observable<Response> { return super.request(token) } func request( _ token: Target, file: StaticString = #file, function: StaticString = #function, line: UInt = #line ) -> Observable<Response> { let requestString = "\(token.method) \(token.path)" return super.request(token) .filterSuccessfulStatusCodes() .do( onNext: { value in let message = "SUCCESS: \(requestString) (\(value.statusCode))" log.debug(message, file: file, function: function, line: line) }, onError: { error in if let response = (error as? MoyaError)?.response { if let jsonObject = try? response.mapJSON(failsOnEmptyData: false) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(jsonObject)" log.warning(message, file: file, function: function, line: line) } else if let rawString = String(data: response.data, encoding: .utf8) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(rawString)" log.warning(message, file: file, function: function, line: line) } else { let message = "FAILURE: \(requestString) (\(response.statusCode))" log.warning(message, file: file, function: function, line: line) } } else { let message = "FAILURE: \(requestString)\n\(error)" log.warning(message, file: file, function: function, line: line) } }, onSubscribe: { let message = "REQUEST: \(requestString)" log.debug(message, file: file, function: function, line: line) } ) } }
mit
3c3b6aa42b8057038ed52bf9b47537f5
33.202899
95
0.625
4.444444
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/Services/Upgrade/Workflows/Version3Workflow.swift
1
4607
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import Localization /// Upgrades the wallet to version 3 /// /// Going from version 2 to 3 we need the following steps /// - generate a mnemonic /// - create an hd wallet /// - add a legacy xpriv/xpub /// /// - Note: At the time of writing this we already support `v4`. /// This means that we don't create the correct json format for `v3`, since we do not support it anymore. /// Instead we use this workflow to generate the mnemonic, provide the seed hex and create the legacy derivation, /// which we'll use to easily upgrade to `v4`. /// For context the `Account` model on `v3` did not had the `derivations` object. /// final class Version3Workflow: WalletUpgradeWorkflow { private let entropyService: RNGServiceAPI private let operationQueue: DispatchQueue private let logger: NativeWalletLoggerAPI init( entropyService: RNGServiceAPI, logger: NativeWalletLoggerAPI, operationQueue: DispatchQueue ) { self.entropyService = entropyService self.operationQueue = operationQueue self.logger = logger } static var supportedVersion: WalletPayloadVersion { .v3 } func shouldPerformUpgrade(wrapper: Wrapper) -> Bool { !wrapper.wallet.isHDWallet } func upgrade(wrapper: Wrapper) -> AnyPublisher<Wrapper, WalletUpgradeError> { provideMnemonic( strength: .normal, queue: operationQueue, entropyProvider: entropyService.generateEntropy(count:) ) .logMessageOnOutput(logger: logger, message: { mnemonic in "[v3 Upgrade] Mnemonic \(mnemonic)" }) .mapError(WalletUpgradeError.mnemonicFailure) .receive(on: operationQueue) .flatMap { [provideAccount, logger] mnemonic -> AnyPublisher<HDWallet, WalletUpgradeError> in getHDWallet(from: mnemonic) .flatMap { hdWallet -> Result<(account: Account, seedHex: String), WalletCreateError> in let seedHex = hdWallet.entropy.toHexString() let masterNode = hdWallet.seed.toHexString() let account = provideAccount(masterNode) logger.log(message: "[v3 Upgrade] Account created: \(account)", metadata: nil) return .success((account, seedHex)) } .map { account, seedHex in HDWallet( seedHex: seedHex, passphrase: "", mnemonicVerified: false, defaultAccountIndex: 0, accounts: [account] ) } .mapError(WalletUpgradeError.walletCreateError) .publisher .eraseToAnyPublisher() } .map { hdWallet -> Wrapper in let wallet = NativeWallet( guid: wrapper.wallet.guid, sharedKey: wrapper.wallet.sharedKey, doubleEncrypted: wrapper.wallet.doubleEncrypted, doublePasswordHash: wrapper.wallet.doublePasswordHash, metadataHDNode: wrapper.wallet.metadataHDNode, options: wrapper.wallet.options, hdWallets: [hdWallet], addresses: wrapper.wallet.addresses, txNotes: wrapper.wallet.txNotes, addressBook: wrapper.wallet.addressBook ) return Wrapper( pbkdf2Iterations: Int(wrapper.pbkdf2Iterations), version: Version3Workflow.supportedVersion.rawValue, payloadChecksum: wrapper.payloadChecksum, language: wrapper.language, syncPubKeys: wrapper.syncPubKeys, wallet: wallet ) } .logMessageOnOutput(logger: logger, message: { wrapper in "[v3 Upgrade] Wrapper: \(wrapper)" }) .eraseToAnyPublisher() } // As part of v3 upgrade we create a legacy derivation and assign it to a new Account // again, we don't adhere to the version 3 json format. private func provideAccount(masterNode: String) -> Account { let legacyDerivation = generateDerivation( type: .legacy, index: 0, masterNode: masterNode ) return createAccount( label: LocalizationConstants.Account.myWallet, index: 0, derivations: [legacyDerivation] ) } }
lgpl-3.0
f97f0283864063f59d73afb4b630bebd
38.033898
113
0.598133
5.001086
false
false
false
false
kaneshin/ActiveRecord
Tests/CRUD/ReadTests.swift
1
4368
// ReadTests.swift // // Copyright (c) 2014 Kenji Tayame // Copyright (c) 2014 Shintaro Kaneko // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import CoreData import ActiveRecord class ReadTests: ActiveRecordTestCase { func testRead() { let eventEntityName = "Event" var events = Event.find(entityName: eventEntityName) XCTAssertNotNil(events, "find does not fail") println("events count : \(events?.count)") if let events = events { XCTAssertTrue(events.count == 0, "should find none") } // create var newEvent = Event.create(entityName: eventEntityName) as? Event XCTAssertNotNil(newEvent, "create does not fail") if let event = newEvent { event.title = "eat" event.timeStamp = NSDate() event.save() } // read var fetchedEvent = Event.findFirst(entityName: eventEntityName) as? Event XCTAssertNotNil(fetchedEvent, "should find created event") if let fetchedEvent = fetchedEvent { XCTAssertEqual(fetchedEvent.title, "eat", "title should be eat") } // create newEvent = Event.create(entityName: eventEntityName) as? Event XCTAssertNotNil(newEvent, "create does not fail") if let event = newEvent { event.title = "sleep" event.timeStamp = NSDate() event.save() } // create newEvent = Event.create(entityName: eventEntityName) as? Event XCTAssertNotNil(newEvent, "create does not fail") if let event = newEvent { event.title = "play" event.timeStamp = NSDate() event.save() } // find with predicate fetchedEvent = Event.findFirst(entityName: eventEntityName, predicate: NSPredicate(format: "SELF.title = %@", "play")) as? Event XCTAssertNotNil(fetchedEvent, "should find created event") if let fetchedEvent = fetchedEvent { XCTAssertEqual(fetchedEvent.title, "play", "title should be play") } // find with predicate and sortDescriptor let sortDescriptors: [NSSortDescriptor] = [NSSortDescriptor(key: "title", ascending: false)] fetchedEvent = Event.findFirst(entityName: eventEntityName, sortDescriptors:sortDescriptors) as? Event if let fetchedEvent = fetchedEvent { XCTAssertEqual(fetchedEvent.title, "sleep", "title should be sleep") } // update if let event = fetchedEvent { event.title = "work" event.save() } // find updated fetchedEvent = Event.findFirst(entityName: eventEntityName, predicate: NSPredicate(format: "SELF.title = %@", "work")) as? Event XCTAssertNotNil(fetchedEvent, "should find updated event") if let fetchedEvent = fetchedEvent { XCTAssertEqual(fetchedEvent.title, "work", "title should be work") } // delete if let event = fetchedEvent { event.delete() } // cannot find deleted fetchedEvent = Event.findFirst(entityName: eventEntityName, predicate: NSPredicate(format: "SELF.title = %@", "work")) as? Event XCTAssertNil(fetchedEvent, "should not find deleted event") } }
mit
abacfecb8edeb29353cad909bf2abeb1
38.351351
136
0.65293
4.8
false
false
false
false
Karumi/MarvelApiClient
MarvelApiClientTests/FutureMatchers.swift
1
953
// // FutureMatchers.swift // MarvelAPIClient // // Created by Pedro Vicente on 14/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation import Nimble import Result import BothamNetworking @testable import MarvelAPIClient func beSuccess<T>() -> MatcherFunc<T?> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be success" let result = try actualExpression.evaluate() as? Result<HTTPResponse, NSError> return result?.value != nil } } func failWithError<T>(expectedError: NSError) -> MatcherFunc<T?> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "has error" let result = try actualExpression.evaluate() as? Result<HTTPResponse, NSError> if let error = result?.error { return expectedError == error } else { return false } } }
apache-2.0
9b9130dcbbc5f34dfd905be3729fc248
27.848485
86
0.679622
4.712871
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBCipher/GRDBiOS/GRDBiOS/Person.swift
1
1591
import GRDBCipher class Person: Record { var id: Int64? var name: String var score: Int init(name: String, score: Int) { self.name = name self.score = score super.init() } // MARK: Record overrides override class var databaseTableName: String { return "persons" } required init(row: Row) { id = row.value(named: "id") name = row.value(named: "name") score = row.value(named: "score") super.init(row: row) } override var persistentDictionary: [String : DatabaseValueConvertible?] { return [ "id": id, "name": name, "score": score] } override func didInsert(with rowID: Int64, for column: String?) { id = rowID } // MARK: Random private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"] class func randomName() -> String { return names[Int(arc4random_uniform(UInt32(names.count)))] } class func randomScore() -> Int { return 10 * Int(arc4random_uniform(101)) } }
mit
18b68c0125c6cc1e86ff6e794e8ab627
30.78
525
0.557583
3.352321
false
false
false
false
tjw/swift
test/ClangImporter/macros.swift
2
5777
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s // XFAIL: linux @_exported import macros func circle_area(_ radius: CDouble) -> CDouble { return M_PI * radius * radius } func circle_area2(_ radius: CDouble) -> CDouble { return A_PI * radius * radius } func circle_area3(_ radius: CFloat) -> CFloat { return M_PIf * radius * radius } func convertGLBool(_ b: CInt) -> Bool { return b != GL_FALSE } func pixelFormat(_ alpha: Bool) -> CInt { if alpha { return GL_RGBA } else { return GL_RGB } } func boundsCheckU32(_ x: CUnsignedInt) -> Bool { return x >= 0 && x <= UINT32_MAX } func boundsCheckS64(_ x: CLongLong) -> Bool { return x <= INT64_MAX } func isEOF(_ c: CInt) -> Bool { return c == EOF } func subThree(_ x: CInt) -> CInt { return x + MINUS_THREE } // true/false are keywords, so they shouldn't conflict with the true/false in // the C header. func testTrueFalse() { var x : Bool = true var y : Bool = false _ = true // should not result in ambiguous use error _ = false _ = TRUE // expected-error {{use of unresolved identifier 'TRUE'}} _ = FALSE // expected-error {{use of unresolved identifier 'FALSE'}} _ = `true` // expected-error {{use of unresolved identifier 'true'}} _ = `false` // expected-error {{use of unresolved identifier 'false'}} } func testCStrings() -> Bool { var str: String = UTF8_STRING str = VERSION_STRING _ = str } func testObjCString() -> String { let str: String = OBJC_STRING return str } func testCFString() -> String { let str: String = CF_STRING return str } func testInvalidIntegerLiterals() { var l1 = INVALID_INTEGER_LITERAL_1 // expected-error {{use of unresolved identifier 'INVALID_INTEGER_LITERAL_1'}} // FIXME: <rdar://problem/16445608> Swift should set up a DiagnosticConsumer for Clang // var l2 = INVALID_INTEGER_LITERAL_2 // FIXME {{use of unresolved identifier 'INVALID_INTEGER_LITERAL_2'}} } func testUsesMacroFromOtherModule() { let m1 = USES_MACRO_FROM_OTHER_MODULE_1 let m2 = macros.USES_MACRO_FROM_OTHER_MODULE_1 let m3 = USES_MACRO_FROM_OTHER_MODULE_2 // expected-error {{use of unresolved identifier 'USES_MACRO_FROM_OTHER_MODULE_2'}} let m4 = macros.USES_MACRO_FROM_OTHER_MODULE_2 // expected-error {{module 'macros' has no member named 'USES_MACRO_FROM_OTHER_MODULE_2'}} } func testSuppressed() { let m1 = NS_BLOCKS_AVAILABLE // expected-error {{use of unresolved identifier 'NS_BLOCKS_AVAILABLE'}} let m2 = CF_USE_OSBYTEORDER_H // expected-error {{use of unresolved identifier 'CF_USE_OSBYTEORDER_H'}} } func testNil() { var localNil: () localNil = NULL_VIA_NAME // expected-error {{'NULL_VIA_NAME' is unavailable: use 'nil' instead of this imported macro}} localNil = NULL_VIA_VALUE // expected-error {{'NULL_VIA_VALUE' is unavailable: use 'nil' instead of this imported macro}} localNil = NULL_AS_NIL // expected-error {{'NULL_AS_NIL' is unavailable: use 'nil' instead of this imported macro}} localNil = NULL_AS_CLASS_NIL // expected-error {{'NULL_AS_CLASS_NIL' is unavailable: use 'nil' instead of this imported macro}} localNil = Nil // expected-error {{use of unresolved identifier 'Nil'}} } func testBitwiseOps() { _ = DISPATCH_TIME_FOREVER as CUnsignedLongLong _ = (BIT_SHIFT_1 | BIT_SHIFT_2) as CInt _ = BIT_SHIFT_3 as CLongLong _ = BIT_SHIFT_4 as CUnsignedInt _ = RSHIFT_ONE as CUnsignedInt _ = RSHIFT_INVALID // expected-error {{use of unresolved identifier 'RSHIFT_INVALID'}} _ = XOR_HIGH as CUnsignedLongLong var attributes = 0 as CInt attributes |= ATTR_BOLD attributes |= ATTR_ITALIC attributes |= ATTR_UNDERLINE attributes |= ATTR_INVALID // expected-error {{use of unresolved identifier 'ATTR_INVALID'}} } func testIntegerArithmetic() { _ = ADD_ZERO as CInt _ = ADD_ONE as CInt _ = ADD_TWO as CInt _ = ADD_MINUS_TWO as CInt _ = ADD_MIXED_WIDTH as CLongLong _ = ADD_MIXED_SIGN as CLongLong _ = ADD_UNDERFLOW as CUnsignedInt _ = ADD_OVERFLOW as CUnsignedInt _ = SUB_ONE as CInt _ = SUB_ZERO as CInt _ = SUB_MINUS_ONE as CInt _ = SUB_MIXED_WIDTH as CLongLong _ = SUB_MIXED_SIGN as CUnsignedInt _ = SUB_UNDERFLOW as CUnsignedInt _ = SUB_OVERFLOW as CUnsignedInt _ = MULT_POS as CInt _ = MULT_NEG as CInt _ = MULT_MIXED_TYPES as CLongLong _ = DIVIDE_INTEGRAL as CInt _ = DIVIDE_NONINTEGRAL as CInt _ = DIVIDE_MIXED_TYPES as CLongLong _ = DIVIDE_INVALID // expected-error {{use of unresolved identifier 'DIVIDE_INVALID'}} } func testIntegerComparisons() { if EQUAL_FALSE, EQUAL_TRUE, EQUAL_TRUE_MIXED_TYPES, GT_FALSE, GT_TRUE, GTE_FALSE, GTE_TRUE, LT_FALSE, LT_TRUE, LTE_FALSE, LTE_TRUE { fatalError("You hit the jackpot!") } } func testLogicalComparisons() { if L_AND_TRUE, L_AND_FALSE, L_AND_TRUE_B, L_AND_FALSE_B, L_OR_TRUE, L_OR_FALSE, L_OR_TRUE_B, L_OR_FALSE_B { fatalError("Yet again!") } } func testRecursion() { _ = RECURSION // expected-error {{use of unresolved identifier 'RECURSION'}} _ = REF_TO_RECURSION // expected-error {{use of unresolved identifier 'REF_TO_RECURSION'}} _ = RECURSION_IN_EXPR // expected-error {{use of unresolved identifier 'RECURSION_IN_EXPR'}} _ = RECURSION_IN_EXPR2 // expected-error {{use of unresolved identifier 'RECURSION_IN_EXPR2'}} _ = RECURSION_IN_EXPR3 // expected-error {{use of unresolved identifier 'RECURSION_IN_EXPR3'}} } func testNulls() { let _: Int = UNAVAILABLE_ONE // expected-error {{use of unresolved identifier 'UNAVAILABLE_ONE'}} let _: Int = DEPRECATED_ONE // expected-error {{use of unresolved identifier 'DEPRECATED_ONE'}} let _: Int = OKAY_TYPED_ONE // expected-error {{cannot convert value of type 'okay_t' (aka 'UInt32') to specified type 'Int'}} }
apache-2.0
b7add889cf91b326d94e052b73b825d0
31.094444
139
0.681322
3.360675
false
true
false
false
openshopio/openshop.io-ios
OpenShopUITests/OpenShopUITests.swift
1
3094
// // OpenShopUITests.swift // OpenShopUITests // // Created by Petr Škorňok on 02.03.16. // Copyright © 2016 Business-Factory. All rights reserved. // import XCTest class OpenShopUITests: XCTestCase { let loginEmail = "[email protected]"; let loginPassword = "aa"; override func setUp() { super.setUp() let app = XCUIApplication() setupSnapshot(app) app.launch() } override func tearDown() { super.tearDown() } func testScreenshots() { XCUIDevice.shared().orientation = .portrait let app = XCUIApplication() let existsPredicate = NSPredicate(format: "exists == 1") // Initial start with country screen sleep(1) // let continueButton = app.buttons["CONTINUE"] // if (XCUIApplication().buttons["CONTINUE"].exists) { XCUIApplication().buttons["CONTINUE"].tap() // } // Email/FB login screen sleep(1) // let emailButton = app.buttons["EMAIL"] // XCUIApplication().buttons["EMAIL"].tap() if (XCUIApplication().buttons["EMAIL"].exists) { snapshot("Login") XCUIApplication().buttons["EMAIL"].tap() let eMailTextField = app.textFields["E-mail"] eMailTextField.tap() eMailTextField.typeText(loginEmail) let passwordSecureTextField = app.secureTextFields["Password"] passwordSecureTextField.tap() passwordSecureTextField.typeText(loginPassword) app.buttons["LOGIN"].tap() } // Banners screen let firstBanner = app.tables.children(matching: .cell).element(boundBy: 0) expectation(for: existsPredicate, evaluatedWith: firstBanner, handler: nil) waitForExpectations(timeout: 20, handler: nil) // dismiss APNS alert firstBanner.forceTapElement() snapshot("Banners") firstBanner.tap() // Products screen let firstProduct = app.cells.element(boundBy: 0) expectation(for: existsPredicate, evaluatedWith: firstProduct, handler: nil) waitForExpectations(timeout: 10, handler: nil) snapshot("Products") firstProduct.tap() // Add product to the cart let addToCartButton = app.tables.buttons["ADDTOCART"] expectation(for: existsPredicate, evaluatedWith: addToCartButton, handler: nil) waitForExpectations(timeout: 10, handler: nil) snapshot("Product Detail") addToCartButton.tap() sleep(2) // sleep for a while to give some time to the request // Cart screen let cartTabBar = app.tabBars.buttons["Cart"] let cartTabBarHittable = NSPredicate(format: "hittable == 1") expectation(for: cartTabBarHittable, evaluatedWith: cartTabBar, handler: nil) waitForExpectations(timeout: 10, handler: nil) cartTabBar.forceTapElement() cartTabBar.forceTapElement() sleep(5) snapshot("Cart") } }
mit
59247b946b748609ed325a815323ef93
31.882979
87
0.607247
4.704718
false
true
false
false
tjw/swift
test/Migrator/string-representable.swift
1
1525
// REQUIRES: objc_interop // RUN: %empty-directory(%t.mod) // RUN: %target-swift-frontend -emit-module -o %t.mod/Cities.swiftmodule %S/Inputs/Cities.swift -module-name Cities -parse-as-library // RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -I %t.mod -api-diff-data-file %S/Inputs/string-representable.json -emit-migrated-file-path %t/string-representable.swift.result -disable-migrator-fixits -o /dev/null // RUN: diff -u %S/string-representable.swift.expected %t/string-representable.swift.result import Cities func foo(_ c: Container) -> String { c.Value = "" c.addingAttributes(["a": "b", "a": "b", "a": "b"]) c.addingAttributes(["a": "b", "a": "b", "a": "b"]) c.adding(attributes: ["a": 1, "a": 2, "a": 3]) c.adding(optionalAttributes: ["a": 1, "a": 2, "a": 3]) _ = Container(optionalAttributes: nil) _ = Container(optionalAttrArray: nil) c.adding(attrArray: ["key1", "key2"]) c.add(single: "") c.add(singleOptional: nil) _ = c.getAttrDictionary() _ = c.getOptionalAttrDictionary() _ = c.getSingleAttr() _ = c.getOptionalSingleAttr() _ = c.getAttrArray() _ = c.getOptionalAttrArray() c.addingAttributes(c.getAttrDictionary()) c.adding(optionalAttributes: c.getAttrDictionary()) c.attrDict = ["a": "b", "a": "b", "a": "b"] c.attrArr = ["key1", "key2"] _ = c.attrArr _ = c.attrDict c.adding(attributes: c.attrDict) _ = Container(optionalAttrArray: c.attrArr) c.adding(optionalAttributes: c.optionalAttrDict) return c.Value }
apache-2.0
808b4e5acfdfd0d8042c6d41b0e95559
39.131579
254
0.664262
2.893738
false
false
false
false
dunkelstern/twohundred
TwoHundred/http_defs.swift
1
2481
// // http_defs.swift // twohundred // // Created by Johannes Schriewer on 25/11/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // /// Valid HTTP methods public enum HTTPMethod: String { case GET = "GET" case PUT = "PUT" case POST = "POST" case PATCH = "PATCH" case DELETE = "DELETE" case OPTIONS = "OPTIONS" case HEAD = "HEAD" case TRACE = "TRACE" case INVALID } /// Valid HTTP versions public enum HTTPVersion: String { case v10 = "HTTP/1.0" case v11 = "HTTP/1.1" case v2 = "HTTP/2" case Invalid } /// Available HTTP status codes public enum HTTPStatusCode: String { // Success case Ok = "200 ok" case Created = "201 created" case Accepted = "202 accepted" case NonAuthoritative = "203 non-authoritative information" case NoContent = "204 no content" case ResetContent = "205 reset content" case PartialContent = "206 partial content" // Redirect case MultipleChoices = "300 multiple choices" case MovedPermanently = "301 moved permanently" case Found = "302 found" case SeeOther = "303 see other" case NotModified = "304 not modified" case TemporaryRedirect = "307 temporary redirect" case PermanentRedirect = "308 permanent redirect" // Error case BadRequest = "400 bad request" case Unauthorized = "401 unauthorized" case Forbidden = "403 forbidden" case NotFound = "404 not found" case MethodNotAllowed = "405 method not allowed" case NotAcceptable = "406 not acceptable" case RequestTimeout = "408 request timeout" case Conflict = "409 conflict" case Gone = "410 gone" case LengthRequired = "411 length required" case PreconditionFailed = "412 precondition failed" case RequestTooLarge = "413 request entity too large" case RequestURITooLong = "414 request uri too long" case UnsupportedMediaType = "415 unsupported media type" case RequestRangeNotSatisfiable = "416 request range not satisfiable" case ExpectationFailed = "417 expectation failed" case TooManyRequests = "429 too many requests" // Server Error case InternalServerError = "500 internal server error" case NotImplemented = "501 not implemented" case BadGateway = "502 bad gateway" case ServiceUnavailable = "503 service unavailable" case GatewayTimeout = "504 gateway timeout" case HTTPVersionNotSupported = "505 http version not supported" }
bsd-3-clause
51b37061bf531730ff90ec8d3ebce038
30.807692
73
0.684677
4.343257
false
false
false
false
MBKwon/TestAppStore
TestAppStore/TestAppStore/APIController.swift
1
1723
// // APIController.swift // TestAppStore // // Created by Moonbeom Kyle KWON on 2017. 4. 16.. // Copyright © 2017년 Kyle. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper class APIController { let APP_LIST_URL = "https://itunes.apple.com/kr/rss/topfreeapplications/limit=50/genre=6015/json" let APP_INFO_TEMPALTE = "https://itunes.apple.com/lookup?id={id}&country=kr" //MARK: Shared Instance fileprivate init() { } static let sharedInstance: APIController = APIController() } extension APIController { func getAppListFromAppStore(_ callback: @escaping ([AppListModel]?)->()) { Alamofire.request(APP_LIST_URL).responseArray(keyPath: "feed.entry") { (response: DataResponse<[AppListModel]>) in guard let listModel = response.result.value else { callback(nil) return } callback(listModel) } } func getAppInfo(_ appId: String, callback: @escaping (AppDetailModel?)->()) { let appInfoUrl: String = APP_INFO_TEMPALTE.replacingOccurrences(of: "{id}", with: appId) Alamofire.request(appInfoUrl).responseObject { (response: DataResponse<AppDetailResults>) in guard let detailResponse = response.result.value else { callback(nil) return } guard let appDetailResults = detailResponse.results else { callback(nil) return } callback(appDetailResults.first) } } }
mit
a1eef68bfe8177d87a2adffcb014d983
25.875
122
0.572674
4.764543
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/RAM/RAM_Error.swift
1
6607
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for RAM public struct RAMErrorType: AWSErrorType { enum Code: String { case idempotentParameterMismatchException = "IdempotentParameterMismatchException" case invalidClientTokenException = "InvalidClientTokenException" case invalidMaxResultsException = "InvalidMaxResultsException" case invalidNextTokenException = "InvalidNextTokenException" case invalidParameterException = "InvalidParameterException" case invalidResourceTypeException = "InvalidResourceTypeException" case invalidStateTransitionException = "InvalidStateTransitionException" case malformedArnException = "MalformedArnException" case missingRequiredParameterException = "MissingRequiredParameterException" case operationNotPermittedException = "OperationNotPermittedException" case resourceArnNotFoundException = "ResourceArnNotFoundException" case resourceShareInvitationAlreadyAcceptedException = "ResourceShareInvitationAlreadyAcceptedException" case resourceShareInvitationAlreadyRejectedException = "ResourceShareInvitationAlreadyRejectedException" case resourceShareInvitationArnNotFoundException = "ResourceShareInvitationArnNotFoundException" case resourceShareInvitationExpiredException = "ResourceShareInvitationExpiredException" case resourceShareLimitExceededException = "ResourceShareLimitExceededException" case serverInternalException = "ServerInternalException" case serviceUnavailableException = "ServiceUnavailableException" case tagLimitExceededException = "TagLimitExceededException" case tagPolicyViolationException = "TagPolicyViolationException" case unknownResourceException = "UnknownResourceException" } private let error: Code public let context: AWSErrorContext? /// initialize RAM public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// A client token input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. public static var idempotentParameterMismatchException: Self { .init(.idempotentParameterMismatchException) } /// A client token is not valid. public static var invalidClientTokenException: Self { .init(.invalidClientTokenException) } /// The specified value for MaxResults is not valid. public static var invalidMaxResultsException: Self { .init(.invalidMaxResultsException) } /// The specified value for NextToken is not valid. public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) } /// A parameter is not valid. public static var invalidParameterException: Self { .init(.invalidParameterException) } /// The specified resource type is not valid. public static var invalidResourceTypeException: Self { .init(.invalidResourceTypeException) } /// The requested state transition is not valid. public static var invalidStateTransitionException: Self { .init(.invalidStateTransitionException) } /// The format of an Amazon Resource Name (ARN) is not valid. public static var malformedArnException: Self { .init(.malformedArnException) } /// A required input parameter is missing. public static var missingRequiredParameterException: Self { .init(.missingRequiredParameterException) } /// The requested operation is not permitted. public static var operationNotPermittedException: Self { .init(.operationNotPermittedException) } /// An Amazon Resource Name (ARN) was not found. public static var resourceArnNotFoundException: Self { .init(.resourceArnNotFoundException) } /// The invitation was already accepted. public static var resourceShareInvitationAlreadyAcceptedException: Self { .init(.resourceShareInvitationAlreadyAcceptedException) } /// The invitation was already rejected. public static var resourceShareInvitationAlreadyRejectedException: Self { .init(.resourceShareInvitationAlreadyRejectedException) } /// The Amazon Resource Name (ARN) for an invitation was not found. public static var resourceShareInvitationArnNotFoundException: Self { .init(.resourceShareInvitationArnNotFoundException) } /// The invitation is expired. public static var resourceShareInvitationExpiredException: Self { .init(.resourceShareInvitationExpiredException) } /// The requested resource share exceeds the limit for your account. public static var resourceShareLimitExceededException: Self { .init(.resourceShareLimitExceededException) } /// The service could not respond to the request due to an internal problem. public static var serverInternalException: Self { .init(.serverInternalException) } /// The service is not available. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// The requested tags exceed the limit for your account. public static var tagLimitExceededException: Self { .init(.tagLimitExceededException) } /// The specified tag is a reserved word and cannot be used. public static var tagPolicyViolationException: Self { .init(.tagPolicyViolationException) } /// A specified resource was not found. public static var unknownResourceException: Self { .init(.unknownResourceException) } } extension RAMErrorType: Equatable { public static func == (lhs: RAMErrorType, rhs: RAMErrorType) -> Bool { lhs.error == rhs.error } } extension RAMErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
cc5066d0534caab08b514ee3daa39d79
55.470085
169
0.744059
5.584954
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/VoiceMessages/VoiceMessageAttachmentCacheManager.swift
1
15537
// // Copyright 2021 New Vector Ltd // // 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 DSWaveformImage enum VoiceMessageAttachmentCacheManagerError: Error { case invalidEventId case invalidAttachmentType case decryptionError(Error) case preparationError(Error) case conversionError(Error) case durationError(Error?) case invalidNumberOfSamples case samplingError case cancelled } /** Swift optimizes the callbacks to be the same instance. Wrap them so we can store them in an array. */ private class CompletionWrapper { let completion: (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void init(_ completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { self.completion = completion } } private struct CompletionCallbackKey: Hashable { let eventIdentifier: String let requiredNumberOfSamples: Int } struct VoiceMessageAttachmentCacheManagerLoadResult { let eventIdentifier: String let url: URL let duration: TimeInterval let samples: [Float] } @objc class VoiceMessageAttachmentCacheManagerBridge: NSObject { @objc static func clearCache() { VoiceMessageAttachmentCacheManager.sharedManager.clearCache() } } class VoiceMessageAttachmentCacheManager { private struct Constants { static let taskSemaphoreTimeout = 5.0 } static let sharedManager = VoiceMessageAttachmentCacheManager() private var completionCallbacks = [CompletionCallbackKey: [CompletionWrapper]]() private var samples = [String: [Int: [Float]]]() private var durations = [String: TimeInterval]() private var finalURLs = [String: URL]() private let workQueue: DispatchQueue private let operationQueue: OperationQueue private var temporaryFilesFolderURL: URL { return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("VoiceMessages") } private init() { workQueue = DispatchQueue(label: "io.element.VoiceMessageAttachmentCacheManager.queue", qos: .userInitiated) operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 } func loadAttachment(_ attachment: MXKAttachment, numberOfSamples: Int, completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { guard attachment.type == .voiceMessage || attachment.type == .audio else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidAttachmentType)) MXLog.error("[VoiceMessageAttachmentCacheManager] Invalid attachment type, ignoring request.") return } guard let identifier = attachment.eventId else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidEventId)) MXLog.error("[VoiceMessageAttachmentCacheManager] Invalid event id, ignoring request.") return } guard numberOfSamples > 0 else { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.invalidNumberOfSamples)) MXLog.error("[VoiceMessageAttachmentCacheManager] Invalid number of samples, ignoring request.") return } do { try setupTemporaryFilesFolder() } catch { completion(Result.failure(VoiceMessageAttachmentCacheManagerError.preparationError(error))) MXLog.error("[VoiceMessageAttachmentCacheManager] Failed creating temporary files folder with error: \(error)") return } operationQueue.addOperation { MXLog.debug("[VoiceMessageAttachmentCacheManager] Started task") if let finalURL = self.finalURLs[identifier], let duration = self.durations[identifier], let samples = self.samples[identifier]?[numberOfSamples] { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished task - using cached results") let result = VoiceMessageAttachmentCacheManagerLoadResult(eventIdentifier: identifier, url: finalURL, duration: duration, samples: samples) DispatchQueue.main.async { completion(Result.success(result)) } return } self.enqueueLoadAttachment(attachment, identifier: identifier, numberOfSamples: numberOfSamples, completion: completion) } } func clearCache() { for key in completionCallbacks.keys { invokeFailureCallbacksForIdentifier(key.eventIdentifier, requiredNumberOfSamples: key.requiredNumberOfSamples, error: VoiceMessageAttachmentCacheManagerError.cancelled) } operationQueue.cancelAllOperations() samples.removeAll() durations.removeAll() finalURLs.removeAll() do { try FileManager.default.removeItem(at: temporaryFilesFolderURL) } catch { MXLog.error("[VoiceMessageAttachmentCacheManager] Failed clearing cached disk files with error: \(error)") } } private func enqueueLoadAttachment(_ attachment: MXKAttachment, identifier: String, numberOfSamples: Int, completion: @escaping (Result<VoiceMessageAttachmentCacheManagerLoadResult, Error>) -> Void) { let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: numberOfSamples) if var callbacks = completionCallbacks[callbackKey] { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished task - cached completion callback") callbacks.append(CompletionWrapper(completion)) completionCallbacks[callbackKey] = callbacks return } else { completionCallbacks[callbackKey] = [CompletionWrapper(completion)] } let semaphore = DispatchSemaphore(value: 0) if let finalURL = finalURLs[identifier], let duration = durations[identifier] { sampleFileAtURL(finalURL, duration: duration, numberOfSamples: numberOfSamples, identifier: identifier, semaphore: semaphore) let result = semaphore.wait(timeout: .now() + Constants.taskSemaphoreTimeout) if case DispatchTimeoutResult.timedOut = result { MXLog.error("[VoiceMessageAttachmentCacheManager] Timed out waiting for tasks to finish.") } return } DispatchQueue.main.async { // These don't behave accordingly if called from a background thread if attachment.isEncrypted { attachment.decrypt(toTempFile: { filePath in self.workQueue.async { self.convertFileAtPath(filePath, numberOfSamples: numberOfSamples, identifier: identifier, semaphore: semaphore) } }, failure: { error in // A nil error in this case is a cancellation on the MXMediaLoader if let error = error { MXLog.error("[VoiceMessageAttachmentCacheManager] Failed decrypting attachment with error: \(String(describing: error))") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.decryptionError(error)) } semaphore.signal() }) } else { attachment.prepare({ self.workQueue.async { self.convertFileAtPath(attachment.cacheFilePath, numberOfSamples: numberOfSamples, identifier: identifier, semaphore: semaphore) } }, failure: { error in // A nil error in this case is a cancellation on the MXMediaLoader if let error = error { MXLog.error("[VoiceMessageAttachmentCacheManager] Failed preparing attachment with error: \(String(describing: error))") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.preparationError(error)) } semaphore.signal() }) } } let result = semaphore.wait(timeout: .now() + Constants.taskSemaphoreTimeout) if case DispatchTimeoutResult.timedOut = result { MXLog.error("[VoiceMessageAttachmentCacheManager] Timed out waiting for tasks to finish.") } } private func convertFileAtPath(_ path: String?, numberOfSamples: Int, identifier: String, semaphore: DispatchSemaphore) { guard let filePath = path else { return } let newURL = temporaryFilesFolderURL.appendingPathComponent(identifier).appendingPathExtension("m4a") let conversionCompletion: (Result<Void, VoiceMessageAudioConverterError>) -> Void = { result in self.workQueue.async { switch result { case .success: MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished converting voice message") self.finalURLs[identifier] = newURL VoiceMessageAudioConverter.mediaDurationAt(newURL) { result in self.workQueue.async { MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished retrieving media duration") switch result { case .success: if let duration = try? result.get() { self.durations[identifier] = duration self.sampleFileAtURL(newURL, duration: duration, numberOfSamples: numberOfSamples, identifier: identifier, semaphore: semaphore) } else { MXLog.error("[VoiceMessageAttachmentCacheManager] Failed retrieving media duration") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.durationError(nil)) semaphore.signal() } case .failure(let error): MXLog.error("[VoiceMessageAttachmentCacheManager] Failed retrieving audio duration with error: \(error)") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.durationError(error)) semaphore.signal() } } } case .failure(let error): MXLog.error("[VoiceMessageAttachmentCacheManager] Failed converting voice message with error: \(error)") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.conversionError(error)) semaphore.signal() } } } if FileManager.default.fileExists(atPath: newURL.path) { conversionCompletion(Result.success(())) } else { VoiceMessageAudioConverter.convertToMPEG4AAC(sourceURL: URL(fileURLWithPath: filePath), destinationURL: newURL, completion: conversionCompletion) } } private func sampleFileAtURL(_ url: URL, duration: TimeInterval, numberOfSamples: Int, identifier: String, semaphore: DispatchSemaphore) { let analyser = WaveformAnalyzer(audioAssetURL: url) analyser?.samples(count: numberOfSamples, completionHandler: { samples in self.workQueue.async { guard let samples = samples else { MXLog.debug("[VoiceMessageAttachmentCacheManager] Failed sampling voice message") self.invokeFailureCallbacksForIdentifier(identifier, requiredNumberOfSamples: numberOfSamples, error: VoiceMessageAttachmentCacheManagerError.samplingError) semaphore.signal() return } MXLog.debug("[VoiceMessageAttachmentCacheManager] Finished sampling voice message") if var existingSamples = self.samples[identifier] { existingSamples[numberOfSamples] = samples self.samples[identifier] = existingSamples } else { self.samples[identifier] = [numberOfSamples: samples] } self.invokeSuccessCallbacksForIdentifier(identifier, url: url, duration: duration, samples: samples) semaphore.signal() } }) } private func invokeSuccessCallbacksForIdentifier(_ identifier: String, url: URL, duration: TimeInterval, samples: [Float]) { let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: samples.count) guard let callbacks = completionCallbacks[callbackKey] else { return } let result = VoiceMessageAttachmentCacheManagerLoadResult(eventIdentifier: identifier, url: url, duration: duration, samples: samples) let copy = callbacks.map { $0 } DispatchQueue.main.async { for wrapper in copy { wrapper.completion(Result.success(result)) } } self.completionCallbacks[callbackKey] = nil MXLog.debug("[VoiceMessageAttachmentCacheManager] Successfully finished task") } private func invokeFailureCallbacksForIdentifier(_ identifier: String, requiredNumberOfSamples: Int, error: Error) { let callbackKey = CompletionCallbackKey(eventIdentifier: identifier, requiredNumberOfSamples: requiredNumberOfSamples) guard let callbacks = completionCallbacks[callbackKey] else { return } let copy = callbacks.map { $0 } DispatchQueue.main.async { for wrapper in copy { wrapper.completion(Result.failure(error)) } } self.completionCallbacks[callbackKey] = nil MXLog.debug("[VoiceMessageAttachmentCacheManager] Failed task with error: \(error)") } private func setupTemporaryFilesFolder() throws { let url = temporaryFilesFolderURL try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } }
apache-2.0
723a0bbdf123f4eaf22b6ca5d5165392
46.513761
204
0.641179
5.92789
false
false
false
false
csync/csync-swift
Tests/CSyncSDKTests/KeyTests.swift
1
11163
/* * Copyright IBM Corporation 2016 * * 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 XCTest #if DEBUG @testable import CSyncSDK #else import CSyncSDK #endif class KeyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testValidKeys() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) // simple key do { let k1 = app.key(["foo", "bar", "baz"]) XCTAssertEqual(k1.key, "foo.bar.baz") XCTAssertEqual(k1.lastComponent, "baz") XCTAssertEqual(k1.app, app) XCTAssertFalse(k1.isKeyPattern) // root key let k2 = app.key([]) XCTAssertEqual(k2.key, "") XCTAssertEqual(k2.lastComponent, nil) XCTAssertEqual(k2.app, app) XCTAssertFalse(k2.isKeyPattern) // Key with max (16) components let k3 = app.key(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]) XCTAssertEqual(k3.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p") XCTAssertEqual(k3.lastComponent, "p") XCTAssertEqual(k3.app, app) XCTAssertFalse(k3.isKeyPattern) // Key with max (200) size _ = app.key(["ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuv"]) // 47 chars } // Use keyString intializer do { let k1 = app.key("foo.bar.baz") XCTAssertEqual(k1.components, ["foo", "bar", "baz"]) XCTAssertEqual(k1.app, app) XCTAssertFalse(k1.isKeyPattern) // root key let k2 = app.key("") XCTAssertEqual(k2.components, []) XCTAssertEqual(k2.app, app) XCTAssertFalse(k2.isKeyPattern) // Key with max (16) components let k3 = app.key("a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p") XCTAssertEqual(k3.components, ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]) XCTAssertEqual(k3.app, app) XCTAssertFalse(k3.isKeyPattern) } } func testWildcards() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) do { // asterisk let k1 = app.key(["foo", "*", "baz"]) XCTAssertEqual(k1.key, "foo.*.baz") XCTAssertTrue(k1.isKeyPattern) // pound let k2 = app.key(["foo", "bar", "#"]) XCTAssertEqual(k2.key, "foo.bar.#") XCTAssertEqual(k2.lastComponent, "#") XCTAssertTrue(k2.isKeyPattern) // multiple asterisk let k3 = app.key(["foo", "*", "*"]) XCTAssertEqual(k3.key, "foo.*.*") XCTAssertEqual(k3.lastComponent, "*") XCTAssertTrue(k3.isKeyPattern) // max asterisk let k4 = app.key(["*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]) XCTAssertEqual(k4.key, "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*") XCTAssertTrue(k4.isKeyPattern) // max components with # let k5 = app.key(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "#"]) XCTAssertEqual(k5.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.#") XCTAssertTrue(k5.isKeyPattern) // max compoents with * and # let k6 = app.key(["a", "b", "c", "*", "e", "f", "g", "*", "i", "j", "k", "*", "m", "n", "o", "#"]) XCTAssertEqual(k6.key, "a.b.c.*.e.f.g.*.i.j.k.*.m.n.o.#") XCTAssertTrue(k6.isKeyPattern) } // Use keyString intializer do { // asterisk let k1 = app.key("foo.*.baz") XCTAssertEqual(k1.key, "foo.*.baz") XCTAssertTrue(k1.isKeyPattern) // pound let k2 = app.key("foo.bar.#") XCTAssertEqual(k2.key, "foo.bar.#") XCTAssertTrue(k2.isKeyPattern) // multiple asterisk let k3 = app.key("foo.*.*") XCTAssertEqual(k3.key, "foo.*.*") XCTAssertTrue(k3.isKeyPattern) // max asterisk let k4 = app.key("*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*") XCTAssertEqual(k4.key, "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*") XCTAssertTrue(k4.isKeyPattern) // max components with # let k5 = app.key("a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.#") XCTAssertEqual(k5.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.#") XCTAssertTrue(k5.isKeyPattern) // max compoents with * and # let k6 = app.key("a.b.c.*.e.f.g.*.i.j.k.*.m.n.o.#") XCTAssertEqual(k6.key, "a.b.c.*.e.f.g.*.i.j.k.*.m.n.o.#") XCTAssertTrue(k6.isKeyPattern) } } func testErrorKeys() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) // too many components let k1 = app.key(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q"]) XCTAssertNotNil(k1.error) // empty string component let k2 = app.key(["a", "", "c"]) XCTAssertNotNil(k2.error) let k2a = app.key("a..c") XCTAssertNotNil(k2a.error) // pound not final component let k3 = app.key(["a", "#", "c"]) XCTAssertNotNil(k3.error) // wildcard does not appear alone let k4 = app.key(["a", "b*", "c"]) XCTAssertNotNil(k4.error) // key exceeds maximum size (200 chars) let k5 = app.key(["ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxy", // 50 chars "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvw"]) // 48 chars XCTAssertNotNil(k5.error) // component contains illegal character (.) let k6 = app.key(["a", "b.c", "d"]) XCTAssertNotNil(k6.error) // component contains illegal character (:) let k7 = app.key(["abcdefghijklm:nopqrstuvwxyz"]) XCTAssertNotNil(k7.error) // component contains all illegal characters let k7a = app.key(["[]()&%$"]) XCTAssertNotNil(k7a.error) // too many components let k8 = app.key("a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p") let k9 = k8.child("q") XCTAssertNotNil(k9.error) // key with only separator let k10 = app.key(".") XCTAssertNotNil(k10.error) // key starts or ends with a separator let k11 = app.key(".abc") XCTAssertNotNil(k11.error) let k12 = app.key("abc.") XCTAssertNotNil(k12.error) } func testParent() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) let k16 = app.key(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]) let k15 = k16.parent XCTAssertEqual(k15.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o") let k14 = k15.parent XCTAssertEqual(k14.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n") let k13 = k14.parent XCTAssertEqual(k13.key, "a.b.c.d.e.f.g.h.i.j.k.l.m") let k2 = k13.parent.parent.parent.parent.parent.parent.parent.parent.parent.parent.parent XCTAssertEqual(k2.key, "a.b") let k1 = k2.parent XCTAssertEqual(k1.key, "a") let k0 = k1.parent XCTAssertEqual(k0.key, "") let k = k0.parent XCTAssertEqual(k.key, "") } func testChild() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) let k0 = app.key([]) let k1 = k0.child("a") XCTAssertEqual(k1.key, "a") let k2 = k1.child("b") XCTAssertEqual(k2.key, "a.b") let k3 = k1.child() XCTAssertEqual(k3.parent.key, k1.key) let k13 = k2.child("c").child("d").child("e").child("f").child("g").child("h").child("i").child("j").child("k").child("l").child("m") XCTAssertEqual(k13.key, "a.b.c.d.e.f.g.h.i.j.k.l.m") let k14 = k13.child("n") XCTAssertEqual(k14.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n") let k15 = k14.child("o") XCTAssertEqual(k15.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o") let k16 = k15.child("p") XCTAssertEqual(k16.key, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p") } func testCornerCases() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) // Test for key immutability var a = "a", b = "b" let k1 = app.key([a, b]) XCTAssertEqual(k1.key, "a.b") a = "c" b = "d" XCTAssertEqual(k1.key, "a.b") } #if DEBUG func testMatches() { // Connect to the CSync store let config = getConfig() let app = App(host: config.host, port: config.port, options: config.options) // Test concrete keys do { let k = app.key("foo.bar.baz") // Matches XCTAssertTrue(k.matches("foo.bar.baz")) // Non-matches XCTAssertFalse(k.matches("foo.bar")) XCTAssertFalse(k.matches("foo.bar.baz.qux")) XCTAssertFalse(k.matches("foo.#")) XCTAssertFalse(k.matches("foo.*.baz")) XCTAssertFalse(k.matches("")) } do { let k = app.key("") // Matches XCTAssertTrue(k.matches("")) // Non-matches XCTAssertFalse(k.matches("foo")) XCTAssertFalse(k.matches("foo.bar")) } // Test keys with "*" do { let k = app.key("foo.*.baz") // Matches XCTAssertTrue(k.matches("foo.bar.baz")) XCTAssertTrue(k.matches("foo.foo.baz")) XCTAssertTrue(k.matches("foo.foo-foo-foo-foo-foo-foo-foo-foo-foo.baz")) // Non-matches XCTAssertFalse(k.matches("foo.bar")) XCTAssertFalse(k.matches("foo.bar.baz.qux")) XCTAssertFalse(k.matches("foo.#")) //XCTAssertFalse(k.matches("foo.*.baz")) // Invalid test since other is not valid concrete key } // Test keys with "#" do { let k = app.key("foo.bar.#") // Matches XCTAssertTrue(k.matches("foo.bar.baz")) XCTAssertTrue(k.matches("foo.bar")) XCTAssertTrue(k.matches("foo.bar.2.3.4.5.6.7.8.9.a.b.c.d.e.f")) // Non-matches XCTAssertFalse(k.matches("foo")) XCTAssertFalse(k.matches("foo.baz")) XCTAssertFalse(k.matches("foo.baz.bar")) } // Test keys with multiple "*" do { let k = app.key("foo.*.baz.*") // Matches XCTAssertTrue(k.matches("foo.bar.baz.qux")) XCTAssertTrue(k.matches("foo.a.baz.b")) // Non-matches XCTAssertFalse(k.matches("foo.bar")) XCTAssertFalse(k.matches("foo.bar.baz")) XCTAssertFalse(k.matches("foo.bar.bar.bar")) XCTAssertFalse(k.matches("foo.bar.baz.bar.baz")) } // Test keys with "*" and "#" do { let k = app.key("foo.*.baz.#") // Matches XCTAssertTrue(k.matches("foo.bar.baz.qux")) XCTAssertTrue(k.matches("foo.a.baz.b")) XCTAssertTrue(k.matches("foo.bar.baz")) XCTAssertTrue(k.matches("foo.bar.baz.3.4.5.6.7.8.9.a.b.c.d.e.f")) // Non-matches XCTAssertFalse(k.matches("foo.bar")) XCTAssertFalse(k.matches("foo.bar.bar.bar")) } } #endif }
apache-2.0
c5e98af083d3eccb86c15126d179d6c5
27.118388
135
0.619099
2.73335
false
true
false
false
soapyigu/LeetCode_Swift
DFS/NumberofIslands.swift
1
1171
/** * Question Link: https://leetcode.com/problems/number-of-islands/ * Primary idea: Classic Depth-first Search, go up, down, left, right four directions * * Time Complexity: O(mn), Space Complexity: O(1) * */ class NumberofIslands { func numIslands(grid: [[Character]]) -> Int { guard grid.count > 0 && grid[0].count > 0 else { return 0 } var grid = grid let m = grid.count let n = grid[0].count var count = 0 for i in 0..<m { for j in 0..<n { if String(grid[i][j]) == "1" { count += 1 _dfs(&grid, m, n, i, j) } } } return count } private func _dfs(inout grid: [[Character]], _ m: Int, _ n: Int, _ i: Int, _ j: Int) { guard i >= 0 && i < m && j >= 0 && j < n && String(grid[i][j]) == "1" else { return } grid[i][j] = Character("0") _dfs(&grid, m, n, i + 1, j) _dfs(&grid, m, n, i - 1, j) _dfs(&grid, m, n, i, j + 1) _dfs(&grid, m, n, i, j - 1) } }
mit
cd4aaff6a63a56b53fd2a8887559e8b9
25.636364
90
0.4193
3.355301
false
false
false
false
AfricanSwift/TUIKit
TUIKit/Source/UIElements/Widgets/TUITable.swift
1
2987
// // File: TUITable.swift // Created by: African Swift import Darwin public struct TUITable { /// Progress view // private var view: TUIView public var value = "" public init(_ v: [String]) { let width = maxWidth(v) guard let box = TUIBorder.single.toTUIBox() else { exit(EXIT_FAILURE) } let topMiddle = String(repeating: box.horizontal.top, count: width + 2) let middleMiddle = String(repeating: box.horizontal.middle, count: width + 2) let bottomMiddle = String(repeating: box.horizontal.bottom, count: width + 2) let top = "\(box.top.left)\(topMiddle)\(box.top.right)\n" let middle = "\(box.middle.left)\(middleMiddle)\(box.middle.right)\n" let bottom = "\(box.bottom.left)\(bottomMiddle)\(box.bottom.right)\n" self.value += top self.value += v .map { text in var result = String(box.vertical.left) + " " result += String(text).padding(toLength: width, withPad: " ", startingAt: 0) result += " " + String(box.vertical.right) return result } .joined(separator: "\n\(middle)") self.value += "\n\(bottom)" } public init (_ v: [[String]]) { var widths = Array<Int>(repeating: 0, count: v[0].count) guard let box = TUIBorder.single.toTUIBox() else { exit(EXIT_FAILURE) } for c in 0..<v[0].count { var width = 0 for r in 0..<v.count { let count = v[r][c].characters.count if count > width { width = count } } widths[c] = width } var top = "\(box.top.left)" var bottom = "\(box.bottom.left)" var middle = "\(box.middle.left)" for c in 0..<v[0].count { top += String(repeating: box.horizontal.top, count: widths[c] + 2) if c < v[0].count - 1 { top += "\(box.top.middle)" } bottom += String(repeating: box.horizontal.bottom, count: widths[c] + 2) if c < v[0].count - 1 { bottom += "\(box.bottom.middle)" } middle += String(repeating: box.horizontal.middle, count: widths[c] + 2) if c < v[0].count - 1 { middle += "\(box.middle.middle)" } } top += "\(box.top.right)" bottom += "\(box.bottom.right)" middle += "\(box.middle.right)" var data = "" for r in 0..<v.count { data += "\(box.vertical.left)" for c in 0..<v[0].count { data += " " + String(v[r][c]).padding(toLength: widths[c], withPad: " ", startingAt: 0) + " " if c < v[0].count - 1 { data += "\(box.vertical.middle)" } } data += "\(box.vertical.right)\n" if r < v.count - 1 { data += "\(middle)\n" } } let result = "\(top)\n\(data)\(bottom)\n" print(result) } func maxWidth(_ values: [String]) -> Int { var width = 0 for v in values { let count = v.characters.count if count > width { width = count } } return width } }
mit
0a25a67f98c8e6e204fe5ae61128f75f
25.90991
101
0.536324
3.481352
false
false
false
false
caronae/caronae-ios
Caronae/Services/PlaceService.swift
1
6004
import RealmSwift class PlaceService { static let instance = PlaceService() private let api = CaronaeAPIHTTPSessionManager.instance private init() { // This prevents others from using the default '()' initializer for this class. } struct Institution { private init() {} fileprivate(set) static var name: String! { get { return UserDefaults.standard.string(forKey: "institutionName") ?? "UFRJ" } set { UserDefaults.standard.set(newValue, forKey: "institutionName") } } fileprivate(set) static var goingLabel: String! { get { return UserDefaults.standard.string(forKey: "institutionGoingLabel") ?? "Chegando na UFRJ" } set { UserDefaults.standard.set(newValue, forKey: "institutionGoingLabel") } } fileprivate(set) static var leavingLabel: String! { get { return UserDefaults.standard.string(forKey: "institutionLeavingLabel") ?? "Saindo da UFRJ" } set { UserDefaults.standard.set(newValue, forKey: "institutionLeavingLabel") } } } func getCampi(hubTypeDirection: HubSelectionViewController.HubTypeDirection, success: @escaping (_ campi: [String], _ options: [String: [String]], _ colors: [String: UIColor], _ shouldReload: Bool) -> Void, error: @escaping (_ error: Error) -> Void) { if let realm = try? Realm(), realm.objects(Place.self).isEmpty { updatePlaces(success: { let (campi, options, colors) = self.loadCampiFromRealm(hubTypeDirection: hubTypeDirection) success(campi, options, colors, true) }, error: { err in error(err) return }) } else { let (campi, options, colors) = self.loadCampiFromRealm(hubTypeDirection: hubTypeDirection) success(campi, options, colors, false) } } private func loadCampiFromRealm(hubTypeDirection: HubSelectionViewController.HubTypeDirection) -> ([String], [String: [String]], [String: UIColor]) { let realm = try! Realm() let campusObjects = realm.objects(Campus.self) let campi = campusObjects.map { $0.name }.sortedCaseInsensitive() var options = [String: [String]]() if hubTypeDirection == .hubs { campusObjects.forEach { options[$0.name] = $0.hubs } } else { campusObjects.forEach { options[$0.name] = $0.centers } } var colors = [String: UIColor]() campusObjects.forEach { colors[$0.name] = $0.color } return (campi, options, colors) } func getZones(success: @escaping (_ zones: [String], _ options: [String: [String]], _ colors: [String: UIColor], _ shouldReload: Bool) -> Void, error: @escaping (_ error: Error) -> Void) { if let realm = try? Realm(), realm.objects(Place.self).isEmpty { updatePlaces(success: { let (zones, options, colors) = self.loadZonesFromRealm() success(zones, options, colors, true) }, error: { err in error(err) return }) } else { let (zones, options, colors) = self.loadZonesFromRealm() success(zones, options, colors, false) } } private func loadZonesFromRealm() -> ([String], [String: [String]], [String: UIColor]) { let realm = try! Realm() let zoneObjects = realm.objects(Zone.self) var zones = zoneObjects.map { $0.name }.sortedCaseInsensitive() var options = [String: [String]]() zoneObjects.forEach { options[$0.name] = $0.neighborhoods } var colors = [String: UIColor]() zoneObjects.forEach { colors[$0.name] = $0.color } zones.append(CaronaeOtherNeighborhoodsText) colors[CaronaeOtherNeighborhoodsText] = OtherZoneColor return (zones, options, colors) } func color(forZone zone: String) -> UIColor { let realm = try! Realm() return realm.objects(Zone.self).first(where: { $0.name == zone })?.color ?? OtherZoneColor } func updatePlaces(success: @escaping () -> Void, error: @escaping (_ error: Error) -> Void) { let request = api.request("/api/v1/places") request.validate().responseCaronae { response in switch response.result { case .success(let responseObject): guard let response = responseObject as? [String: Any], let campiJson = response["campi"] as? [[String: Any]], let zonesJson = response["zones"] as? [[String: Any]], let institution = response["institution"] as? [String: String] else { error(CaronaeError.invalidResponse) return } // Update the current institution Institution.name = institution["name"] Institution.goingLabel = institution["going_label"] Institution.leavingLabel = institution["leaving_label"] let campi = campiJson.compactMap { Campus(JSON: $0) } let zones = zonesJson.compactMap { Zone(JSON: $0) } do { let realm = try Realm() // Clear old places and add new ones try realm.write { realm.delete(realm.objects(Campus.self)) realm.delete(realm.objects(Zone.self)) realm.delete(realm.objects(Place.self)) realm.add(campi) realm.add(zones) } } catch let realmError { error(realmError) } success() case .failure(let err): error(err) } } } }
gpl-3.0
77e476631014ffef57caac48cc7f30cc
43.80597
255
0.556629
4.483943
false
false
false
false
fahidattique55/FAPanels
FAPanels/Classes/FAPanel+Animations.swift
1
31703
// // FAPanel+Animations.swift // FAPanels // // Created by Fahid Attique on 25/06/2017. // Copyright © 2017 Fahid Attique. All rights reserved. // import Foundation import UIKit extension FAPanelController { // Swap Center Panel internal func swapCenter(animated:Bool, FromVC fromVC: UIViewController?, withVC nextVC: UIViewController?){ if fromVC != nextVC { if nextVC != nil { if !animated { swap(fromVC, withVC: nextVC) } else { let transitionOption = configs.centerPanelTransitionType.transitionOption() if transitionOption is UIView.AnimationOptions { swap(fromVC, withVC: nextVC) performNativeTransition() } else { let snapshot = self.snapshot swap(fromVC, withVC: nextVC) let transOption = transitionOption as! FAPanelTransitionType switch transOption { case .moveRight: moveRight(snapshot) break case .moveLeft: moveLeft(snapshot) break case .moveUp: moveUp(snapshot) break case .moveDown: moveDown(snapshot) break case .splitHorizontally: splitHorizontally(snapshot) break case .splitVertically: splitVertically(snapshot) break case .dumpFall: dumpFall(snapshot) break case .boxFade: let snapshotAfterSwap = self.snapshot boxFade(snapshot, to: snapshotAfterSwap) break default: return } } } } } } private func swap( _ fromVC: UIViewController?, withVC toVC: UIViewController?) { fromVC?.willMove(toParent: nil) fromVC?.view.removeFromSuperview() fromVC?.removeFromParent() loadCenterPanel() addChild(toVC!) centerPanelContainer.addSubview(toVC!.view) if tapView != nil { centerPanelContainer.bringSubviewToFront(tapView!) } toVC!.didMove(toParent: self) } private func performNativeTransition() { let transitionOption = configs.centerPanelTransitionType.transitionOption() as! UIView.AnimationOptions UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: transitionOption, animations: nil, completion: nil) } private func moveRight( _ snapShot: UIImage) { let snapShotView = UIImageView(frame: view.frame) snapShotView.image = snapShot view.addSubview(snapShotView) UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: [], animations: { var origin = snapShotView.frame.origin origin.x = snapShotView.frame.size.width snapShotView.frame.origin = origin }, completion: { (finished) in snapShotView.removeFromSuperview() }) } private func moveLeft( _ snapShot: UIImage) { let snapShotView = UIImageView(frame: view.frame) snapShotView.image = snapShot view.addSubview(snapShotView) UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: [], animations: { var origin = snapShotView.frame.origin origin.x = -snapShotView.frame.size.width snapShotView.frame.origin = origin }, completion: { (finished) in snapShotView.removeFromSuperview() }) } private func moveUp( _ snapShot: UIImage) { let snapShotView = UIImageView(frame: view.frame) snapShotView.image = snapShot view.addSubview(snapShotView) UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: [], animations: { var origin = snapShotView.frame.origin origin.y = -snapShotView.frame.size.height snapShotView.frame.origin = origin }, completion: { (finished) in snapShotView.removeFromSuperview() }) } private func moveDown( _ snapShot: UIImage) { let snapShotView = UIImageView(frame: view.frame) snapShotView.image = snapShot view.addSubview(snapShotView) UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: [], animations: { var origin = snapShotView.frame.origin origin.y = snapShotView.frame.size.height snapShotView.frame.origin = origin }, completion: { (finished) in snapShotView.removeFromSuperview() }) } private func splitHorizontally( _ snapShot: UIImage) { let slicedImages = snapShot.slicesWith(rows: 1, AndColumns: 2) let leftSnapShotView = slicedImages[0] let rightSnapShotView = slicedImages[1] view.addSubviews(slicedImages) UIView.animate(withDuration: configs.centerPanelTransitionDuration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: { var leftSnapOrigin = leftSnapShotView.frame.origin leftSnapOrigin.x = -leftSnapShotView.frame.size.width leftSnapShotView.frame.origin = leftSnapOrigin var rightSnapOrigin = rightSnapShotView.frame.origin rightSnapOrigin.x = rightSnapShotView.frame.size.width*2 rightSnapShotView.frame.origin = rightSnapOrigin }) { (finished) in UIView.removeAllFromSuperview(slicedImages) } } private func splitVertically( _ snapShot: UIImage) { let slicedImages = snapShot.slicesWith(rows: 2, AndColumns: 1) let topSnapShotView = slicedImages[0] let bottomSnapShotView = slicedImages[1] view.addSubviews(slicedImages) UIView.animate(withDuration: configs.centerPanelTransitionDuration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: { var topSnapOrigin = topSnapShotView.frame.origin topSnapOrigin.y = -topSnapShotView.frame.size.height topSnapShotView.frame.origin = topSnapOrigin var bottomSnapOrigin = bottomSnapShotView.frame.origin bottomSnapOrigin.y = bottomSnapShotView.frame.size.height*2 bottomSnapShotView.frame.origin = bottomSnapOrigin }) { (finished) in UIView.removeAllFromSuperview(slicedImages) } } private func dumpFall( _ snapShot: UIImage) { var rows : UInt = 17 var colms: UInt = 11 if UIDevice.current.orientation != .portrait { colms = 17 rows = 11 } let slicedImages = snapShot.slicesWith(rows: rows, AndColumns: colms, borderWidth: 0.5) view.addSubviews(slicedImages) let shuffledImages = slicedImages.shuffled() UIView.transition(with: view, duration: configs.centerPanelTransitionDuration, options: [], animations: { for (index, element) in shuffledImages.enumerated() { var elemenOrigin = element.frame.origin if index % 2 == 0 { element.transform = CGAffineTransform(rotationAngle: 10.0) elemenOrigin.x = self.view.frame.size.width * 2 } else { element.transform = CGAffineTransform(rotationAngle: -10.0) elemenOrigin.x = -self.view.frame.size.width * 2 } elemenOrigin.y = self.view.frame.size.height * 3 element.frame.origin = elemenOrigin } }, completion: { (finished) in UIView.removeAllFromSuperview(slicedImages) }) } private func boxFade( _ snapShot: UIImage, to snapshotAfterSwap: UIImage) { let imageBeforeSwap = view.addImage(snapShot) var rows : UInt = 20 var colms: UInt = 11 if UIDevice.current.orientation != .portrait { colms = 20 rows = 11 } let slicedImages = snapshotAfterSwap.slicesWith(rows: rows, AndColumns: colms, alpha: 0.0) view.addSubviews(slicedImages) view.isUserInteractionEnabled = false DispatchQueue.main.async { let serviceGroup = DispatchGroup() let shuffledImages = slicedImages.shuffled() var delayForOddImages = 0.0 var delayForEvenImages = 0.0 var delay = 0.0 for index in 0..<shuffledImages.count { serviceGroup.enter() let view = shuffledImages[index] view.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) delayForOddImages = (0.5...3.0).random() delayForEvenImages = (0.1...1.3).random() if index % 2 == 0 { delay = delayForEvenImages } else { delay = delayForOddImages } UIView.animate(withDuration: self.configs.centerPanelTransitionDuration, delay: TimeInterval(delay), options: .curveEaseIn, animations: { view.alpha = 1 view.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: { (finished) in serviceGroup.leave() }) } serviceGroup.notify(queue: DispatchQueue.main) { imageBeforeSwap.removeFromSuperview() UIView.removeAllFromSuperview(slicedImages) self.view.isUserInteractionEnabled = true } } } // Loading of panels internal func loadCenterPanel() { centerPanelVC!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] centerPanelVC!.view.frame = centerPanelContainer.bounds applyStyle(onView: centerPanelVC!.view) } internal func loadLeftPanel() { rightPanelContainer.isHidden = true if leftPanelContainer.isHidden && leftPanelVC != nil { if leftPanelVC!.view.superview == nil { layoutSidePanelVCs() leftPanelVC!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] applyStyle(onView: leftPanelVC!.view) leftPanelContainer.addSubview(leftPanelVC!.view) } leftPanelContainer.isHidden = false } if isLeftPanelOnFront { view.bringSubviewToFront(leftPanelContainer) } else { view.sendSubviewToBack(leftPanelContainer) } } internal func loadRightPanel() { leftPanelContainer.isHidden = true if rightPanelContainer.isHidden && rightPanelVC != nil { if rightPanelVC!.view.superview == nil { layoutSidePanelVCs() rightPanelVC!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] applyStyle(onView: rightPanelVC!.view) rightPanelContainer.addSubview(rightPanelVC!.view) } rightPanelContainer.isHidden = false } if isRightPanelOnFront { view.bringSubviewToFront(rightPanelContainer) } else { view.sendSubviewToBack(rightPanelContainer) } } // Showing panels internal func openLeft(animated: Bool, shouldBounce bounce:Bool) { if leftPanelVC != nil { centerPanelVC?.view.endEditing(true) state = .left loadLeftPanel() if isLeftPanelOnFront { slideLeftPanelIn(animated: animated) } else { slideCenterPanel(animated: animated, bounce: bounce) handleScrollsToTopForContainers(centerEnabled: false, leftEnabled: true, rightEnabled: false) } } } internal func openRight(animated: Bool, shouldBounce bounce:Bool) { if rightPanelVC != nil { centerPanelVC?.view.endEditing(true) state = .right loadRightPanel() if isRightPanelOnFront { slideRightPanelIn(animated: animated) } else { slideCenterPanel(animated: animated, bounce: bounce) handleScrollsToTopForContainers(centerEnabled: false, leftEnabled: false, rightEnabled: true) } } } internal func openCenter(animated: Bool, shouldBounce bounce: Bool, afterThat completion: (() -> Void)?) { state = .center _ = updateCenterPanelSlidingFrame() if animated { animateCenterPanel(shouldBounce: bounce, completion: { (finished) in self.leftPanelContainer.isHidden = true self.rightPanelContainer.isHidden = true self.unloadPanels() completion?() }) } else { updateCenterPanelContainer() leftPanelContainer.isHidden = true rightPanelContainer.isHidden = true unloadPanels() completion?() } // tapView = nil tapView?.alpha = 0.0 handleScrollsToTopForContainers(centerEnabled: true, leftEnabled: false, rightEnabled: false) } private func slideCenterPanel(animated: Bool, bounce:Bool) { _ = updateCenterPanelSlidingFrame() if animated { animateCenterPanel(shouldBounce: bounce, completion: { (finished) in }) } else { updateCenterPanelContainer() } // tapView = UIView() handleTapViewOpacity() } internal func slideLeftPanelIn(animated: Bool) { if animated { let duration: TimeInterval = TimeInterval(configs.maxAnimDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: { var frame = self.leftPanelContainer.frame frame.origin.x = 0.0 self.leftPanelContainer.frame = frame }, completion:{ (finished) in }) } else { var frame = self.leftPanelContainer.frame frame.origin.x = 0.0 self.leftPanelContainer.frame = frame } // tapView = UIView() handleTapViewOpacity() } internal func slideLeftPanelOut(animated: Bool, afterThat completion: (() -> Void)?) { if animated { let duration: TimeInterval = TimeInterval(configs.maxAnimDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: { var frame = self.leftPanelContainer.frame frame.origin.x = -self.widthForLeftPanelVC self.leftPanelContainer.frame = frame }, completion:{ (finished) in self.view.sendSubviewToBack(self.leftPanelContainer) self.unloadPanels() self.state = .center completion?() }) } else { var frame = leftPanelContainer.frame frame.origin.x = -widthForLeftPanelVC leftPanelContainer.frame = frame view.sendSubviewToBack(leftPanelContainer) unloadPanels() state = .center completion?() } // tapView = nil tapView?.alpha = 0.0 handleScrollsToTopForContainers(centerEnabled: true, leftEnabled: false, rightEnabled: false) } internal func slideRightPanelIn(animated: Bool) { if animated { let duration: TimeInterval = TimeInterval(configs.maxAnimDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: { var frame = self.rightPanelContainer.frame frame.origin.x = self.view.frame.size.width - self.widthForRightPanelVC self.rightPanelContainer.frame = frame }, completion:{ (finished) in }) } else { var frame = self.rightPanelContainer.frame frame.origin.x = self.view.frame.size.width - widthForRightPanelVC self.rightPanelContainer.frame = frame } // tapView = UIView() handleTapViewOpacity() } internal func slideRightPanelOut(animated: Bool, afterThat completion: (() -> Void)?) { if animated { let duration: TimeInterval = TimeInterval(configs.maxAnimDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: { var frame = self.rightPanelContainer.frame frame.origin.x = self.view.frame.size.width self.rightPanelContainer.frame = frame }, completion:{ (finished) in self.view.sendSubviewToBack(self.rightPanelContainer) self.unloadPanels() self.state = .center completion?() }) } else { var frame = rightPanelContainer.frame frame.origin.x = self.view.frame.size.width rightPanelContainer.frame = frame view.sendSubviewToBack(rightPanelContainer) unloadPanels() state = .center completion?() } // tapView = nil tapView?.alpha = 0.0 handleScrollsToTopForContainers(centerEnabled: true, leftEnabled: false, rightEnabled: false) } private func updateCenterPanelContainer() { centerPanelContainer.frame = centeralPanelSlidingFrame if configs.pusheSidePanels { layoutSideContainers(withDuration: 0.0, animated: false) } } // Hiding panels internal func hideCenterPanel() { centerPanelContainer.isHidden = true if centerPanelVC!.isViewLoaded { centerPanelVC!.view.removeFromSuperview() } } internal func unhideCenterPanel() { centerPanelContainer.isHidden = false if centerPanelVC!.view.superview == nil { centerPanelVC!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] centerPanelVC!.view.frame = centerPanelContainer.bounds applyStyle(onView: centerPanelVC!.view) centerPanelContainer.addSubview(centerPanelVC!.view) } } // Unloading Panels internal func unloadPanels() { if configs.unloadLeftPanel { if leftPanelVC != nil { if leftPanelVC!.isViewLoaded { leftPanelVC!.view.removeFromSuperview() } } } if configs.unloadRightPanel { if rightPanelVC != nil { if rightPanelVC!.isViewLoaded { rightPanelVC!.view.removeFromSuperview() } } } } // Layout Containers & Panels internal func layoutSideContainers( withDuration: TimeInterval, animated: Bool) { var rightFrame: CGRect = rightPanelContainer.frame var leftFrame: CGRect = leftPanelContainer.frame if !isLeftPanelOnFront { leftFrame = view.bounds } if !isRightPanelOnFront { rightFrame = view.bounds } if (configs.pusheSidePanels && !centerPanelHidden) { leftFrame.origin.x = centerPanelContainer.frame.origin.x - widthForLeftPanelVC rightFrame.origin.x = centerPanelContainer.frame.origin.x + centerPanelContainer.frame.size.width } leftPanelContainer.frame = leftFrame rightPanelContainer.frame = rightFrame } internal func layoutSidePanelVCs() { if let rightPanelVC = self.rightPanelVC { if rightPanelVC.isViewLoaded { var frame: CGRect = rightPanelContainer.bounds if configs.resizeRightPanel { if !configs.pusheSidePanels { frame.origin.x = rightPanelContainer.bounds.size.width - widthForRightPanelVC } frame.size.width = widthForRightPanelVC } rightPanelVC.view.frame = frame } } if let leftPanelVC = self.leftPanelVC { if leftPanelVC.isViewLoaded { var frame: CGRect = leftPanelContainer.bounds if configs.resizeLeftPanel { frame.size.width = widthForLeftPanelVC } leftPanelVC.view.frame = frame } } } internal func updateCenterPanelSlidingFrame() -> CGRect{ var frame: CGRect = view.bounds switch state { case .center: frame.origin.x = 0.0 break case .left: if leftPanelPosition == .front { frame.origin.x = 0 } else { frame.origin.x = widthForLeftPanelVC } break case .right: if rightPanelPosition == .front { frame.origin.x = 0 } else { frame.origin.x = -widthForRightPanelVC } break } centeralPanelSlidingFrame = frame return centeralPanelSlidingFrame } // Handle Scrolling internal func handleScrollsToTopForContainers(centerEnabled: Bool, leftEnabled:Bool, rightEnabled:Bool) { if UIDevice().userInterfaceIdiom == .phone { _ = handleScrollsToTop(enabled: centerEnabled, forView: centerPanelContainer) _ = handleScrollsToTop(enabled: leftEnabled, forView: leftPanelContainer) _ = handleScrollsToTop(enabled: rightEnabled, forView: rightPanelContainer) } } internal func handleScrollsToTop(enabled: Bool, forView view: UIView) -> Bool { if view is UIScrollView { let scrollView: UIScrollView = view as! UIScrollView scrollView.scrollsToTop = enabled return true } else{ for subView: UIView in view.subviews { if handleScrollsToTop(enabled: enabled, forView: subView) { return true } } } return false } // Panel Animations internal func animateCenterPanel(shouldBounce: Bool, completion: @escaping (_ finished: Bool) -> Void) { var bounceAllowed = shouldBounce let bounceDistance: CGFloat = (centeralPanelSlidingFrame.origin.x - centerPanelContainer.frame.origin.x) * configs.bouncePercentage if centeralPanelSlidingFrame.size.width > centerPanelContainer.frame.size.width { bounceAllowed = false } let duration: TimeInterval = TimeInterval(configs.maxAnimDuration) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear, .layoutSubviews], animations: { self.centerPanelContainer.frame = self.centeralPanelSlidingFrame if self.configs.pusheSidePanels { self.layoutSideContainers(withDuration: 0.0, animated: false) } }, completion:{ (finished) in if (bounceAllowed) { if self.state == .center { if bounceDistance > 0.0 { self.loadLeftPanel() } else { self.loadRightPanel() } } UIView.animate(withDuration: TimeInterval(self.configs.bounceDuration), delay: 0.0, options: .curveEaseInOut, animations: { var bounceFrame: CGRect = self.centeralPanelSlidingFrame bounceFrame.origin.x += bounceDistance self.centerPanelContainer.frame = bounceFrame }, completion: { (finished) in UIView.animate(withDuration: TimeInterval(self.configs.bounceDuration), delay: 0.0, options: .curveEaseIn, animations: { self.centerPanelContainer.frame = self.centeralPanelSlidingFrame }, completion: completion) }) } else { completion(finished) } }) } internal func xPositionFor( _ translationInX: CGFloat) -> CGFloat { let position: CGFloat = centeralPanelSlidingFrame.origin.x + translationInX if state == .center { if (position > 0.0 && self.leftPanelVC == nil) || (position < 0.0 && self.rightPanelVC == nil) { return 0.0 } else if position > widthForLeftPanelVC { return widthForLeftPanelVC } else if position < -widthForRightPanelVC { return -widthForRightPanelVC } } else if state == .right { if position < -widthForRightPanelVC { return 0.0 } else if configs.pusheSidePanels && position > 0.0 { return -centeralPanelSlidingFrame.origin.x } else if position > rightPanelContainer.frame.origin.x { return rightPanelContainer.frame.origin.x - centeralPanelSlidingFrame.origin.x } } else if state == .left { if position > widthForLeftPanelVC { return 0.0 } else if configs.pusheSidePanels && position < 0.0 { return -centeralPanelSlidingFrame.origin.x } else if position < leftPanelContainer.frame.origin.x { return leftPanelContainer.frame.origin.x - centeralPanelSlidingFrame.origin.x } } return translationInX } internal func xPositionForLeftPanel( _ translationInX: CGFloat) -> CGFloat { if state == .center { let newPosition = -widthForLeftPanelVC + translationInX if newPosition > 0.0 { return 0.0 } else if newPosition < -widthForLeftPanelVC { return -widthForLeftPanelVC } else { return newPosition } } else if state == .left { if translationInX > 0.0 { return 0.0 } else if translationInX < -widthForLeftPanelVC { return -widthForLeftPanelVC } else { return translationInX } } else { return 0.0 } } internal func xPositionForRightPanel( _ translationInX: CGFloat) -> CGFloat { let widthOfView = view.frame.size.width if state == .center { let newPosition = widthOfView + translationInX if newPosition > widthOfView { return widthOfView } else if newPosition < (widthOfView - widthForRightPanelVC) { return (widthOfView - widthForRightPanelVC) } else { return newPosition } } else if state == .right { let leftBareer = widthOfView - widthForRightPanelVC let newPosition = leftBareer + translationInX if translationInX < 0.0 { return leftBareer } else if translationInX > widthForRightPanelVC { return widthOfView } else { return newPosition } } else { return 0.0 } } // Handle Panning Decisions internal func shouldCompletePanFor(movement: CGFloat) -> Bool { let minimum: CGFloat = CGFloat(floorf(Float(view.bounds.size.width * configs.minMovePercentage))) switch state { case .left: return movement <= -minimum case .center: return fabsf(Float(movement)) >= Float(minimum) case .right: return movement >= minimum } } }
apache-2.0
98db590789c3406dbe4f4a0b1ac073c4
29.45341
179
0.516876
5.677292
false
false
false
false
nirmankarta/eddystone
tools/gatt-config/ios/Beaconfig/Beaconfig/CustomViews.swift
2
12132
// Copyright 2016 Google Inc. 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 UIKit import Foundation let kTableViewCellMargin: CGFloat = 4 let kFrameDescriptionWidth: CGFloat = 250 let kFrameTitleWidth: CGFloat = 50 let kUIDRequiredLength = 32 let kShadowOpacity: Float = 0.5 let kShadowOffsetWidth: CGFloat = 0.3 let kShadowOffsetHeight: CGFloat = 0.7 let kTitleFontSize: CGFloat = 15 let kTextFontSize: CGFloat = 14 let kTextFieldFontSize: CGFloat = 12.5 let kLabelFontSize: CGFloat = 11 /// /// Class that enables setting constraints to views and placing them in /// certain places of the screen, in relation to other views; this is useful /// because it makes layout easier - all views are designed using this class /// which saves from a lot of repetitive code. /// class CustomViews { /// /// Places the current view inside the holder view, surrounded by the top, left and right views, /// with a certain margin constraint. In order to establish the size of the holderView, /// if the current view is the last one, then bottom constraints must be set. /// class func setConstraints(view: UIView, holderView: UIView, topView: UIView, leftView: UIView?, rightView: UIView?, height: CGFloat?, width: CGFloat?, pinTopAttribute: NSLayoutAttribute, setBottomConstraints: Bool, marginConstraint: CGFloat) { if rightView == nil { if leftView == nil { let leadingConstraint = NSLayoutConstraint(item: view, attribute:.LeadingMargin, relatedBy: .Equal, toItem: holderView, attribute: .LeadingMargin, multiplier: 1.0, constant: marginConstraint) NSLayoutConstraint.activateConstraints([leadingConstraint]) } else { let leadingConstraint = NSLayoutConstraint(item: view, attribute:.LeadingMargin, relatedBy: .Equal, toItem: leftView, attribute: .TrailingMargin, multiplier: 1.0, constant: marginConstraint * 2) NSLayoutConstraint.activateConstraints([leadingConstraint]) } } if width != nil { let widthConstraint = NSLayoutConstraint(item: view, attribute:.Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width!) NSLayoutConstraint.activateConstraints([widthConstraint]) } else if rightView == nil { let trailingConstraints = NSLayoutConstraint(item: view, attribute:.TrailingMargin, relatedBy: .Equal, toItem: holderView, attribute: .TrailingMargin, multiplier: 1.0, constant: -marginConstraint) NSLayoutConstraint.activateConstraints([trailingConstraints]) } if rightView != nil { let marginAttribute: NSLayoutAttribute! if rightView == holderView { marginAttribute = .TrailingMargin } else { marginAttribute = .LeadingMargin } let trailingConstraints = NSLayoutConstraint(item: view, attribute:.TrailingMargin, relatedBy: .Equal, toItem: rightView, attribute: marginAttribute, multiplier: 1.0, constant: -marginConstraint) NSLayoutConstraint.activateConstraints([trailingConstraints]) } if height != nil { let heightConstraint = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height!) NSLayoutConstraint.activateConstraints([heightConstraint]) } let pinTopConstraints = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: topView, attribute: pinTopAttribute, multiplier: 1.0, constant: marginConstraint) if setBottomConstraints { let bottomConstraints = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: holderView, attribute: .Bottom, multiplier: 1.0, constant: -marginConstraint) NSLayoutConstraint.activateConstraints([bottomConstraints]) } view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activateConstraints([pinTopConstraints]) } class func createFrameDisplayView(type: BeaconInfo.EddystoneFrameType, data: String, holder: UIView, topView: UIView, pinTop: NSLayoutAttribute, setBottomConstraints: Bool) -> UIView { var title: String var description: String var dataDescription: String switch type { case .UIDFrameType: title = "UID" description = "Namespace: \nInstance:" dataDescription = getUIDDescription(data) case .URLFrameType: title = "URL" description = "Link:" dataDescription = data case .TelemetryFrameType: title = "TLM" description = "Battery:\nTemperature:\nTime working:\nPDU Count:" dataDescription = data case .EIDFrameType: title = "EID" description = "Ephemeral ID:" dataDescription = data default: return UIView() } let titleLabel = UILabel() holder.addSubview(titleLabel) titleLabel.font = UIFont(name: "Arial-BoldMT", size: kTitleFontSize) CustomViews.setConstraints(titleLabel, holderView: holder, topView: topView, leftView: nil, rightView: nil, height: nil, width: kFrameTitleWidth, pinTopAttribute: pinTop, setBottomConstraints: setBottomConstraints, marginConstraint: kTableViewCellMargin) titleLabel.text = title titleLabel.textColor = UIColor.darkGrayColor() let infoLabel = UILabel() holder.addSubview(infoLabel) CustomViews.setConstraints(infoLabel, holderView: holder, topView: topView, leftView: titleLabel, rightView: nil, height: nil, width: kFrameDescriptionWidth, pinTopAttribute: pinTop, setBottomConstraints: setBottomConstraints, marginConstraint: kTableViewCellMargin) infoLabel.text = description infoLabel.numberOfLines = 4 infoLabel.font = UIFont(name: "Arial", size: kLabelFontSize) infoLabel.textColor = UIColor.darkGrayColor() let dataLabel = UILabel() holder.addSubview(dataLabel) CustomViews.setConstraints(dataLabel, holderView: holder, topView: topView, leftView: infoLabel, rightView: holder, height: nil, width: nil, pinTopAttribute: pinTop, setBottomConstraints: setBottomConstraints, marginConstraint: kTableViewCellMargin) dataLabel.text = dataDescription dataLabel.textAlignment = .Right dataLabel.numberOfLines = 4 dataLabel.font = UIFont(name: "Arial", size: kLabelFontSize) dataLabel.textColor = UIColor.darkGrayColor() return dataLabel } class func getUIDDescription(data: String) -> String { var description = "" if data.characters.count == kUIDRequiredLength { /// /// The first 20 characters represent the 10 bytes of namespace, /// the following 12 characters are the 6 bytes of instance. /// let namespace = (data as NSString).substringWithRange(NSRange(location: 0, length: 20)) let instance = (data as NSString).substringWithRange(NSRange(location: 20, length: 12)) description = "\(namespace)\n\(instance)" } return description } class func displayConfigurableBeacon(holder: UIView, topView: UIView, pinTop: NSLayoutAttribute) { let textLabel = UILabel() holder.addSubview(textLabel) textLabel.font = UIFont(name: "Arial", size: kTextFieldFontSize) CustomViews.setConstraints(textLabel, holderView: holder, topView: topView, leftView: nil, rightView: nil, height: nil, width: kFrameDescriptionWidth, pinTopAttribute: pinTop, setBottomConstraints: true, marginConstraint: kTableViewCellMargin) textLabel.text = "Configurable beacon" textLabel.textColor = UIColor.darkGrayColor() } class func addShadow(view: UIView) { view.layer.shadowColor = UIColor.darkGrayColor().CGColor view.layer.shadowOpacity = kShadowOpacity view.layer.shadowOffset = CGSize(width: kShadowOffsetWidth, height: kShadowOffsetHeight) view.layer.shadowRadius = 1 } }
apache-2.0
8c09317337d8a106881a17ea7208c584
44.954545
100
0.501319
6.654964
false
false
false
false
HelloSunnyX/douyu-demo
douyu-demo/douyu-demo/Classes/Controllers/Home/HomeViewController.swift
1
2313
// // HomeViewController.swift // douyu-demo // // Created by Aidan on 2017/9/10. // Copyright © 2017年 Aidan. All rights reserved. // import UIKit private let kPageTitleViewH: CGFloat = 40 class HomeViewController: UIViewController { lazy var pageTitleView: PageTitleView = {[weak self] in let frame = CGRect(x: 0, y: kStatusBarH + kNavBarH, width: kScreenW, height: kPageTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let view = PageTitleView(frame: frame, titles: titles) view.delegate = self return view; }() lazy var pageContentView: PageContentView = {[weak self] in let contentH = kScreenH - kStatusBarH - kNavBarH - kPageTitleViewH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavBarH + kPageTitleViewH, width: kScreenW, height: contentH) var childrenVC = [UIViewController]() for _ in 0..<4 { let vc = UIViewController() vc.view.backgroundColor = getRandomColor() childrenVC.append(vc) } let view = PageContentView(frame: contentFrame, childrenVC: childrenVC, parentVC: self) return view }() override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { automaticallyAdjustsScrollViewInsets = false setupNavBarButton() view.addSubview(pageTitleView) view.addSubview(pageContentView) } func setupNavBarButton() { navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "logo") let rightItemSize = CGSize.init(width: 40, height: 40) let scan = UIBarButtonItem.init(imageName: "Image_scan", hlImageName: "Image_scan_click", size: rightItemSize) let search = UIBarButtonItem.init(imageName: "btn_search", hlImageName: "btn_search_clicked", size: rightItemSize) let history = UIBarButtonItem.init(imageName: "image_my_history", hlImageName: "Image_my_history_click", size: rightItemSize) navigationItem.rightBarButtonItems = [history, search, scan] } } extension HomeViewController: PageTitleViewDelegate { func onSelectTitle(titleView: PageTitleView, index: Int) { pageContentView.setPage(index: index) } }
mit
c554ecb6ba9b2ea9958ec262acfb7a7d
32.735294
133
0.652572
4.542574
false
false
false
false
nyin005/Forecast-App
Forecast/Forecast/Class/Summary/CustomView/SummaryTableViewCell.swift
1
1635
// // SummaryTableViewCell.swift // Forecast // // Created by appledev110 on 11/22/16. // Copyright © 2016 appledev110. All rights reserved. // import UIKit class SummaryTableViewCell: UITableViewCell { @IBOutlet weak var dateLalel: UILabel! var onBenchClickedHandler: ButtonTouchUpBlock? var customDetailView: CustomDetailView? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.selectionStyle = .none } func initDetailUI(listModel: SummaryTimeModel) { for i in 0..<listModel.values.count { dateLalel.text = listModel.date let containerView = self.viewWithTag(i+11) self.customDetailView = Bundle.loadView(fromNib: "CustomDetailView", withType: CustomDetailView.self) self.customDetailView?.initValue(listModel: listModel.values[i]) self.customDetailView?.frame = (containerView?.bounds)! self.customDetailView?.layer.borderColor = UIColor.gray.cgColor self.customDetailView?.layer.borderWidth = 0.5 if i == 1 { customDetailView?.backgroundColor = UIColor.yellow let tapGesturer = UITapGestureRecognizer(target: self, action: #selector(selectOnbench)) customDetailView?.addGestureRecognizer(tapGesturer) } containerView?.addSubview(self.customDetailView!) } } func selectOnbench(sender: UITapGestureRecognizer) { if onBenchClickedHandler != nil { self.onBenchClickedHandler!() } } }
gpl-3.0
b22b03d940f92147cd7ad8c195113adf
32.346939
113
0.643819
4.820059
false
false
false
false
tensorflow/swift-apis
Sources/x10/swift_bindings/apis/CrossReplicaSum.swift
1
2594
// Copyright 2019 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. /// Implements crossReplicaSum. protocol CrossReplicaSummable { /// A cross replica sum is an operation that runs simultaneously on multiple threads on /// multiple devices and replaces the value on each thread with a sum of all the other values. mutating func crossReplicaSum(_ scale: Double) } extension CrossReplicaSummable { /// Helper that applies a cross replica sum operation to a particular keypath. static func _doCrossReplicaSum<Root>( _ root: inout Root, _ partialKeyPath: PartialKeyPath<Root>, _ scale: Double ) { guard let keyPath = partialKeyPath as? WritableKeyPath<Root, Self> else { fatalError("Key path \(partialKeyPath) not writeable cannot copy to device") } root[keyPath: keyPath].crossReplicaSum(scale) } } extension Tensor: CrossReplicaSummable where Scalar: TensorFlowNumeric { /// Runs a cross replica sum for this tensor. The same cross replica sum /// must happen on each of the other devices participating in the sum. public mutating func crossReplicaSum(_ scale: Double) { self = _Raw.crossReplicaSum([self], scale).first! } } extension _KeyPathIterableBase { /// Helper that iterates over all key paths and applies cross replica sum. func crossReplicaSumChild<Root>( _ root: inout Root, _ kp: PartialKeyPath<Root>, _ scale: Double ) { for nkp in _allKeyPathsTypeErased { let joinedkp = kp.appending(path: nkp)! if let valueType = type(of: joinedkp).valueType as? CrossReplicaSummable.Type { valueType._doCrossReplicaSum(&root, joinedkp, scale) } else if let value = self[keyPath: nkp], let nested = value as? _KeyPathIterableBase { nested.crossReplicaSumChild(&root, joinedkp, scale) } } } } extension KeyPathIterable { /// Runs a cross replica sum over all of the tensors found through key path /// iteration. public mutating func crossReplicaSum(_ scale: Double) { crossReplicaSumChild(&self, \.self, scale) } }
apache-2.0
c4afb2a5313b9b540f29b7135248b3e3
38.907692
96
0.725906
4.217886
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Stack/QStackContainerViewController.swift
1
24722
// // Quickly // open class QStackContainerViewController : QViewController, IQStackContainerViewController, IQModalContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController { open var viewControllers: [IQStackViewController] { set(value) { self.set(viewControllers: value, animated: false, completion: nil) } get { return self._viewControllers } } open var rootViewController: IQStackViewController? { get { return self._viewControllers.first } } open var currentViewController: IQStackViewController? { get { return self._viewControllers.last } } open var previousViewController: IQStackViewController? { get { guard self._viewControllers.count > 1 else { return nil } return self._viewControllers[self._viewControllers.endIndex - 2] } } open var presentAnimation: IQStackViewControllerPresentAnimation open var dismissAnimation: IQStackViewControllerDismissAnimation open var interactiveDismissAnimation: IQStackViewControllerInteractiveDismissAnimation? open var hidesGroupbarWhenPushed: Bool open private(set) var isAnimating: Bool public private(set) lazy var interactiveDismissGesture: UIScreenEdgePanGestureRecognizer = { let gesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(self._handleInteractiveDismissGesture(_:))) gesture.delaysTouchesBegan = true gesture.edges = [ .left ] gesture.delegate = self return gesture }() private var _viewControllers: [IQStackViewController] private var _activeInteractiveCurrentViewController: IQStackViewController? private var _activeInteractivePreviousViewController: IQStackViewController? private var _activeInteractiveDismissAnimation: IQStackViewControllerInteractiveDismissAnimation? public init( viewControllers: [IQStackViewController] = [], presentAnimation: IQStackViewControllerPresentAnimation = QStackViewControllerPresentAnimation(), dismissAnimation: IQStackViewControllerDismissAnimation = QStackViewControllerDismissAnimation(), interactiveDismissAnimation: IQStackViewControllerInteractiveDismissAnimation? = QStackViewControllerinteractiveDismissAnimation() ) { self._viewControllers = viewControllers self.presentAnimation = presentAnimation self.dismissAnimation = dismissAnimation self.interactiveDismissAnimation = interactiveDismissAnimation self.hidesGroupbarWhenPushed = false self.isAnimating = false super.init() viewControllers.forEach({ self._add(childViewController: $0) }) } open override func didLoad() { self.view.addGestureRecognizer(self.interactiveDismissGesture) if let vc = self.currentViewController { self._present(viewController: vc, animated: false, completion: nil) } } open override func layout(bounds: CGRect) { guard self.isAnimating == false else { return } if let vc = self.currentViewController { vc.view.frame = bounds } } open override func prepareInteractivePresent() { super.prepareInteractivePresent() if let vc = self.currentViewController { vc.prepareInteractivePresent() } } open override func cancelInteractivePresent() { super.cancelInteractivePresent() if let vc = self.currentViewController { vc.cancelInteractivePresent() } } open override func finishInteractivePresent() { super.finishInteractivePresent() if let vc = self.currentViewController { vc.finishInteractivePresent() } } open override func willPresent(animated: Bool) { super.willPresent(animated: animated) if let vc = self.currentViewController { vc.willPresent(animated: animated) } } open override func didPresent(animated: Bool) { super.didPresent(animated: animated) if let vc = self.currentViewController { vc.didPresent(animated: animated) } } open override func prepareInteractiveDismiss() { super.prepareInteractiveDismiss() if let vc = self.currentViewController { vc.prepareInteractiveDismiss() } } open override func cancelInteractiveDismiss() { super.cancelInteractiveDismiss() if let vc = self.currentViewController { vc.cancelInteractiveDismiss() } } open override func finishInteractiveDismiss() { super.finishInteractiveDismiss() if let vc = self.currentViewController { vc.finishInteractiveDismiss() } } open override func willDismiss(animated: Bool) { super.willDismiss(animated: animated) if let vc = self.currentViewController { vc.willDismiss(animated: animated) } } open override func didDismiss(animated: Bool) { super.didDismiss(animated: animated) if let vc = self.currentViewController { vc.didDismiss(animated: animated) } } open override func willTransition(size: CGSize) { super.willTransition(size: size) if let vc = self.currentViewController { vc.willTransition(size: size) } } open override func didTransition(size: CGSize) { super.didTransition(size: size) if let vc = self.currentViewController { vc.didTransition(size: size) } } open override func supportedOrientations() -> UIInterfaceOrientationMask { guard let vc = self.currentViewController else { return super.supportedOrientations() } return vc.supportedOrientations() } open override func preferedStatusBarHidden() -> Bool { guard let vc = self.currentViewController else { return super.preferedStatusBarHidden() } return vc.preferedStatusBarHidden() } open override func preferedStatusBarStyle() -> UIStatusBarStyle { guard let vc = self.currentViewController else { return super.preferedStatusBarStyle() } return vc.preferedStatusBarStyle() } open override func preferedStatusBarAnimation() -> UIStatusBarAnimation { guard let vc = self.currentViewController else { return super.preferedStatusBarAnimation() } return vc.preferedStatusBarAnimation() } open func set(viewControllers: [IQStackViewController], animated: Bool, completion: (() -> Swift.Void)?) { if self.isLoaded == true { self._viewControllers.forEach({ self._disappear(viewController: $0) self._remove(childViewController: $0) }) self._viewControllers = viewControllers self._viewControllers.forEach({ self._add(childViewController: $0) }) if let vc = self.currentViewController { self._present(viewController: vc, animated: false, completion: completion) } else { completion?() } } else { self._viewControllers.forEach({ self._remove(childViewController: $0) }) self._viewControllers = viewControllers self._viewControllers.forEach({ self._add(childViewController: $0) }) completion?() } } open func push(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { self._viewControllers.append(viewController) self._add(childViewController: viewController) self._present(viewController: viewController, animated: animated, completion: completion) } open func push(viewController: IQStackContentViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { let stackViewController = QStackViewController(viewController: viewController) self.push(viewController: stackViewController, animated: animated, completion: completion) } open func replace(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)?) { let currentViewController = self.currentViewController self.push(viewController: viewController, animated: animated, completion: { [weak self] in guard let self = self else { return } if let currentViewController = currentViewController { self.pop(viewController: currentViewController, animated: false) } }) } open func replace(viewController: IQStackContentViewController, animated: Bool, completion: (() -> Swift.Void)?) { let stackViewController = QStackViewController(viewController: viewController) self.replace(viewController: stackViewController, animated: animated, completion: completion) } open func replaceAll(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)?) { let popViewControllers = self.viewControllers.count > 1 ? self.viewControllers[1..<self.viewControllers.count] : ArraySlice< IQStackViewController >() self.push(viewController: viewController, animated: animated, completion: { [weak self] in guard let self = self else { return } for popViewController in popViewControllers { self.pop(viewController: popViewController, animated: false) } }) } open func replaceAll(viewController: IQStackContentViewController, animated: Bool, completion: (() -> Swift.Void)?) { let stackViewController = QStackViewController(viewController: viewController) self.replaceAll(viewController: stackViewController, animated: animated, completion: completion) } open func pop(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { self._dismiss(viewController: viewController, animated: animated, completion: completion) } open func pop(viewController: IQStackContentViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { guard let stackViewController = viewController.stackViewController else { return } self.pop(viewController: stackViewController, animated: animated, completion: completion) } open func popTo(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { if self.currentViewController === viewController { completion?() return } if self.previousViewController === viewController { self._dismiss(viewController: self.currentViewController!, animated: animated, completion: completion) } else if self._viewControllers.count > 2 { if let index = self._viewControllers.firstIndex(where: { return $0 === viewController }) { let startIndex = self._viewControllers.index(index, offsetBy: 1) let endIndex = self._viewControllers.index(self._viewControllers.endIndex, offsetBy: -1) if endIndex - startIndex > 0 { let hiddenViewControllers = self._viewControllers[startIndex..<endIndex] hiddenViewControllers.forEach({ (hiddenViewController) in self._dismiss(viewController: hiddenViewController, animated: false, completion: nil) }) } self._dismiss(viewController: self.currentViewController!, animated: animated, completion: completion) } } } open func popTo(viewController: IQStackContentViewController, animated: Bool, completion: (() -> Swift.Void)? = nil) { guard let stackPageViewController = viewController.stackViewController else { return } self.popTo(viewController: stackPageViewController, animated: animated, completion: completion) } // MARK: IQContentViewController public var contentOffset: CGPoint { get { return CGPoint.zero } } public var contentSize: CGSize { get { return CGSize.zero } } open func notifyBeginUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.beginUpdateContent() } } open func notifyUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.updateContent() } } open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? { if let viewController = self.contentOwnerViewController { return viewController.finishUpdateContent(velocity: velocity) } return nil } open func notifyEndUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.endUpdateContent() } } // MARK: IQModalContentViewController open func modalShouldInteractive() -> Bool { guard let currentViewController = self.currentViewController as? IQModalContentViewController else { return false } return currentViewController.modalShouldInteractive() } // MARK: IQHamburgerContentViewController open func hamburgerShouldInteractive() -> Bool { guard let currentViewController = self.currentViewController as? IQHamburgerContentViewController else { return false } return currentViewController.hamburgerShouldInteractive() } // MARK: IQJalousieContentViewController open func jalousieShouldInteractive() -> Bool { guard let currentViewController = self.currentViewController as? IQJalousieContentViewController else { return false } return currentViewController.jalousieShouldInteractive() } } // MARK: Private private extension QStackContainerViewController { func _present(viewController: IQStackViewController, animated: Bool, completion: (() -> Swift.Void)?) { if self.isLoaded == true { if let previousViewController = self.previousViewController { self._appear(viewController: viewController) self.setNeedUpdateOrientations() self.setNeedUpdateStatusBar() self.isAnimating = true let presentAnimation = self._presentAnimation(viewController: viewController) presentAnimation.animate( containerViewController: self, contentView: self.view, currentViewController: previousViewController, currentGroupbarVisibility: self._groupbarVisibility(viewController: previousViewController), nextViewController: viewController, nextGroupbarVisibility: self._groupbarVisibility(viewController: viewController), animated: animated, complete: { [weak self] in if let self = self { self._disappear(viewController: previousViewController) self.isAnimating = false } completion?() } ) } else { self._appear(viewController: viewController) if self.isPresented == true { viewController.willPresent(animated: false) viewController.didPresent(animated: false) } self.setNeedUpdateOrientations() self.setNeedUpdateStatusBar() completion?() } } else { completion?() } } func _dismiss(viewController: IQStackViewController, animated: Bool, completion: (() -> Void)?) { if let index = self._viewControllers.firstIndex(where: { return $0 === viewController }) { let currentViewController = self.currentViewController let previousViewController = self.previousViewController self._viewControllers.remove(at: index) if self.isLoaded == true { self.setNeedUpdateOrientations() self.setNeedUpdateStatusBar() if currentViewController === viewController, let previousViewController = previousViewController { if self.interactiveDismissGesture.state != .possible { let enabled = self.interactiveDismissGesture.isEnabled self.interactiveDismissGesture.isEnabled = false self.interactiveDismissGesture.isEnabled = enabled } self._appear(viewController: previousViewController) self.isAnimating = true let dismissAnimation = self._dismissAnimation(viewController: previousViewController) dismissAnimation.animate( containerViewController: self, contentView: self.view, currentViewController: viewController, currentGroupbarVisibility: self._groupbarVisibility(viewController: viewController), previousViewController: previousViewController, previousGroupbarVisibility: self._groupbarVisibility(viewController: previousViewController), animated: animated, complete: { [weak self] in if let self = self { self._disappear(viewController: viewController) self._remove(childViewController: viewController) self.isAnimating = false } completion?() } ) } else { if self.isPresented == true { viewController.willDismiss(animated: false) viewController.didDismiss(animated: false) } self._disappear(viewController: viewController) self._remove(childViewController: viewController) completion?() } } else { completion?() } } else { completion?() } } func _add(childViewController: IQStackViewController) { childViewController.parentViewController = self } func _remove(childViewController: IQStackViewController) { childViewController.parentViewController = nil } func _appear(viewController: IQStackViewController) { viewController.view.bounds = self.view.bounds self.view.addSubview(viewController.view) } func _disappear(viewController: IQStackViewController) { viewController.view.removeFromSuperview() } func _groupbarVisibility(viewController: IQStackViewController) -> CGFloat { if self.hidesGroupbarWhenPushed == true { return self._viewControllers.first === viewController ? 1 : 0 } return 1 } func _presentAnimation(viewController: IQStackViewController) -> IQStackViewControllerPresentAnimation { if let animation = viewController.presentAnimation { return animation } return self.presentAnimation } func _dismissAnimation(viewController: IQStackViewController) -> IQStackViewControllerDismissAnimation { if let animation = viewController.dismissAnimation { return animation } return self.dismissAnimation } func _interactiveDismissAnimation(viewController: IQStackViewController) -> IQStackViewControllerInteractiveDismissAnimation? { if let animation = viewController.interactiveDismissAnimation { return animation } return self.interactiveDismissAnimation } @objc func _handleInteractiveDismissGesture(_ sender: Any) { let position = self.interactiveDismissGesture.location(in: nil) let velocity = self.interactiveDismissGesture.velocity(in: nil) switch self.interactiveDismissGesture.state { case .began: guard let currentViewController = self.currentViewController, let previousViewController = self.previousViewController, let dismissAnimation = self._interactiveDismissAnimation(viewController: currentViewController) else { return } self._activeInteractiveCurrentViewController = currentViewController self._activeInteractivePreviousViewController = previousViewController self._activeInteractiveDismissAnimation = dismissAnimation self._appear(viewController: previousViewController) self.isAnimating = true dismissAnimation.prepare( containerViewController: self, contentView: self.view, currentViewController: currentViewController, currentGroupbarVisibility: self._groupbarVisibility(viewController: currentViewController), previousViewController: previousViewController, previousGroupbarVisibility: self._groupbarVisibility(viewController: previousViewController), position: position, velocity: velocity ) break case .changed: guard let dismissAnimation = self._activeInteractiveDismissAnimation else { return } dismissAnimation.update(position: position, velocity: velocity) break case .ended, .failed, .cancelled: guard let dismissAnimation = self._activeInteractiveDismissAnimation else { return } if dismissAnimation.canFinish == true { dismissAnimation.finish({ [weak self] (completed: Bool) in guard let self = self else { return } self._finishInteractiveDismiss() }) } else { dismissAnimation.cancel({ [weak self] (completed: Bool) in guard let self = self else { return } self._cancelInteractiveDismiss() }) } break default: break } } func _finishInteractiveDismiss() { if let vc = self._activeInteractiveCurrentViewController { if let index = self._viewControllers.firstIndex(where: { return $0 === vc }) { self._viewControllers.remove(at: index) } self._disappear(viewController: vc) self._remove(childViewController: vc) } self.setNeedUpdateOrientations() self.setNeedUpdateStatusBar() self._endInteractiveDismiss() } func _cancelInteractiveDismiss() { if let vc = self._activeInteractivePreviousViewController { self._disappear(viewController: vc) } self._endInteractiveDismiss() } func _endInteractiveDismiss() { self._activeInteractiveCurrentViewController = nil self._activeInteractivePreviousViewController = nil self._activeInteractiveDismissAnimation = nil self.isAnimating = false } } // MARK: UIGestureRecognizerDelegate extension QStackContainerViewController : UIGestureRecognizerDelegate { open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == self.interactiveDismissGesture else { return false } guard self._viewControllers.count > 1 else { return false } return true } open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == self.interactiveDismissGesture else { return false } guard let gestureRecognizerView = gestureRecognizer.view, let otherGestureRecognizerView = otherGestureRecognizer.view else { return false } return otherGestureRecognizerView.isDescendant(of: gestureRecognizerView) } open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard gestureRecognizer == self.interactiveDismissGesture else { return false } let location = touch.location(in: self.view) return self.view.point(inside: location, with: nil) } }
mit
e11e248cd81ef52acbdd5144a0f4bcf4
41.920139
189
0.646226
5.981611
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Settings/TeamSettingsViewController.swift
1
9990
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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. **/ import UIKit import NotificationCenter class TeamSettingsViewController: TableViewController { weak var headerCellReference: TeamSettingsHeaderCell? private let activityView = UIActivityIndicatorView(style: .gray) private let imagePicker = UIImagePickerController() override func commonInit() { super.commonInit() title = Strings.TeamSettings.title dataSource = TeamSettingsDataSource() (dataSource as? TeamSettingsDataSource)?.delegate = self _ = NotificationCenter.default.addObserver(forName: .teamChanged, object: nil, queue: nil) { [weak self] (_) in self?.reload() } view.addSubview(activityView) { $0.centerX.centerY.equalToSuperview() } } deinit { NotificationCenter.default.removeObserver(self) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { super.tableView(tableView, willDisplay: cell, forRowAt: indexPath) if let cell = cell as? SettingsActionCell { cell.delegate = self } if let cell = cell as? TeamSettingsMemberCell { cell.delegate = self } if let cell = cell as? TeamSettingsHeaderCell { cell.delegate = self } } } extension TeamSettingsViewController: SettingsActionCellDelegate { func settingsActionCellTapped(context: Context?, button: UIButton) { guard let context = context as? TeamSettingsContext else { return } switch context { case .invite: let ds = dataSource as? TeamSettingsDataSource let context = ds?.cells[safe: 0]?[safe: 0] as? TeamSettingsHeaderCellContext let teamName = context?.team AppController.shared.shareTapped( viewController: self, shareButton: button, string: Strings.Share.item(teamName: teamName ?? "")) case .editname: AKFCausesService.getParticipant(fbid: User.id) { (result) in guard let participant = Participant(json: result.response), let team = participant.team, let teamId = team.id else { return } let alert = TextAlertViewController() alert.title = Strings.TeamSettings.editTeamName alert.body = Strings.TeamSettings.editTeamNameMessage alert.value = team.name alert.add(.init(title: Strings.TeamSettings.update, handler: { guard let newName = alert.value else { return } AKFCausesService.editTeamName(teamId: teamId, name: newName) { (result) in guard !result.isSuccess else { return } NotificationCenter.default.post(name: .teamChanged, object: nil) } })) alert.add(.cancel()) AppController.shared.present(alert: alert, in: self, completion: nil) } case .delete: AKFCausesService.getParticipant(fbid: User.id) { (result) in guard let participant = Participant(json: result.response) else { return } guard let teamId = participant.team?.id else { return } let alert: AlertViewController = AlertViewController() alert.title = Strings.TeamSettings.deleteTeam alert.body = Strings.TeamSettings.deleteTeamBody alert.add(AlertAction.cancel()) alert.add(AlertAction(title: "Delete", style: .destructive, shouldDismiss: false) { [weak self] in AKFCausesService.deleteTeam(team: teamId) { (_) in onMain { alert.dismiss(animated: true, completion: nil) self?.navigationController?.popViewController(animated: true) NotificationCenter.default.post(name: .teamChanged, object: nil) } } }) AppController.shared.present(alert: alert, in: self, completion: nil) } } } } extension TeamSettingsViewController: TeamSettingsMemberCellDelegate { func removeTapped(context: Context?, button: UIButton) { guard let context = context as? TeamMembersContext else { return } switch context { case .remove(let fbid, let name): let alert: AlertViewController = AlertViewController() alert.title = "Remove \(name)" alert.body = "\(name) will be permanently removed from your team" alert.add(AlertAction.cancel()) alert.add(AlertAction(title: "Remove", style: .destructive, shouldDismiss: false) { AKFCausesService.leaveTeam(fbid: fbid) { (result) in if !result.isSuccess { alert.dismiss(animated: true) { let alert: AlertViewController = AlertViewController() alert.title = "Remove Failed" alert.body = "Could not remove \(name). Please try again later." alert.add(AlertAction.okay()) onMain { AppController.shared.present(alert: alert, in: self, completion: nil) } } return } onMain { alert.dismiss(animated: true, completion: nil) NotificationCenter.default.post(name: .teamChanged, object: nil) } } }) AppController.shared.present(alert: alert, in: self, completion: nil) } } } extension TeamSettingsViewController: TeamSettingsDataSourceDelegate { func updated(team: Team?) { onMain { if team?.creator == User.id && team?.members.count ?? 0 > 1 { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.TeamSettings.edit, style: .plain, target: self, action: #selector(self.editTapped)) } else { self.navigationItem.rightBarButtonItem = nil } } } @objc private func editTapped() { guard let data = dataSource as? TeamSettingsDataSource else { return } onMain { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.TeamSettings.done, style: .plain, target: self, action: #selector(self.doneTapped)) } data.editing = true data.configure() tableView.reloadOnMain() } @objc private func doneTapped() { guard let data = dataSource as? TeamSettingsDataSource else { return } onMain { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.TeamSettings.edit, style: .plain, target: self, action: #selector(self.editTapped)) } data.editing = false data.configure() tableView.reloadOnMain() } } extension TeamSettingsViewController: TeamSettingsHeaderCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { func editImageButtonPressed(cell: TeamSettingsHeaderCell) { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) { print("Button capture") imagePicker.delegate = self imagePicker.sourceType = .photoLibrary imagePicker.allowsEditing = false headerCellReference = cell present(imagePicker, animated: true, completion: nil) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { print("\(info)") if let image = info[.originalImage] as? UIImage { if let cell = headerCellReference { cell.teamImageView.contentMode = .scaleAspectFill cell.teamImageView.image = image activityView.startAnimating() guard let imageData = image.jpegData(compressionQuality: 0.25), let teamName = cell.teamLabel.text else { return } AZSClient.uploadImage(data: imageData, teamName: teamName) { (error, success) in if let err = error { print("Image cannot be uploaded: \(err)") self.showErrorAlert() onMain { self.activityView.stopAnimating() } } else { onMain { self.activityView.stopAnimating() } } } } dismiss(animated: true, completion: nil) } } private func showErrorAlert() { let alert = AlertViewController() alert.title = Strings.Challenge.CreateTeam.errorTitle alert.body = Strings.Challenge.CreateTeam.errorBody alert.add(.okay()) AppController.shared.present(alert: alert, in: self, completion: nil) } }
bsd-3-clause
3cbfab1698b52fcdc2a7b91c59f351a6
36.837121
135
0.662429
4.834947
false
false
false
false
NikitaAsabin/pdpDecember
DayPhoto/DayPhotoLayout.swift
1
4468
// // DayPhotoLayout.swift // DayPhoto // // Created by Nikita Asabin on 3.12.15. // Copyright (c) 2015 Flatstack. All rights reserved. // import UIKit protocol DayPhotoLayoutDelegate { // 1. Method to ask the delegate for the height of the image func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath , withWidth:CGFloat) -> CGFloat // 2. Method to ask the delegate for the height of the annotation text func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat } class DayPhotoLayoutAttributes:UICollectionViewLayoutAttributes { // 1. Custom attribute var photoHeight: CGFloat = 0.0 // 2. Override copyWithZone to conform to NSCopying protocol override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! DayPhotoLayoutAttributes copy.photoHeight = photoHeight return copy } // 3. Override isEqual override func isEqual(object: AnyObject?) -> Bool { if let attributtes = object as? DayPhotoLayoutAttributes { if( attributtes.photoHeight == photoHeight ) { return super.isEqual(object) } } return false } } class DayPhotoLayout: UICollectionViewLayout { //1. DayPhoto Layout Delegate var delegate:DayPhotoLayoutDelegate! //2. Configurable properties var numberOfColumns = 2 var cellPadding: CGFloat = 6.0 //3. Array to keep a cache of attributes. private var cache = [DayPhotoLayoutAttributes]() //4. Content height and size private var contentHeight:CGFloat = 0.0 private var contentWidth: CGFloat { let insets = collectionView!.contentInset return CGRectGetWidth(collectionView!.bounds) - (insets.left + insets.right) } override class func layoutAttributesClass() -> AnyClass { return DayPhotoLayoutAttributes.self } override func prepareLayout() { // 1. Only calculate once if cache.isEmpty { // 2. Pre-Calculates the X Offset for every column and adds an array to increment the currently max Y Offset for each column let columnWidth = contentWidth / CGFloat(numberOfColumns) var xOffset = [CGFloat]() for column in 0 ..< numberOfColumns { xOffset.append(CGFloat(column) * columnWidth ) } var column = 0 var yOffset = [CGFloat](count: numberOfColumns, repeatedValue: 0) // 3. Iterates through the list of items in the first section for item in 0 ..< collectionView!.numberOfItemsInSection(0) { let indexPath = NSIndexPath(forItem: item, inSection: 0) // 4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame. let width = columnWidth - cellPadding*2 let photoHeight = delegate.collectionView(collectionView!, heightForPhotoAtIndexPath: indexPath , withWidth:width) let annotationHeight = delegate.collectionView(collectionView!, heightForAnnotationAtIndexPath: indexPath, withWidth: width) let height = cellPadding + photoHeight + annotationHeight + cellPadding let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height) let insetFrame = CGRectInset(frame, cellPadding, cellPadding) // 5. Creates an UICollectionViewLayoutItem with the frame and add it to the cache let attributes = DayPhotoLayoutAttributes(forCellWithIndexPath: indexPath) attributes.photoHeight = photoHeight attributes.frame = insetFrame cache.append(attributes) // 6. Updates the collection view content height contentHeight = max(contentHeight, CGRectGetMaxY(frame)) yOffset[column] = yOffset[column] + height column = column >= (numberOfColumns - 1) ? 0 : ++column } } } override func collectionViewContentSize() -> CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() // Loop through the cache and look for items in the rect for attributes in cache { if CGRectIntersectsRect(attributes.frame, rect ) { layoutAttributes.append(attributes) } } return layoutAttributes } }
mit
efbbb0a42795fcf3c8bf8c74b0e02b76
35.325203
147
0.70479
5.054299
false
false
false
false
ivankorobkov/net
swift/Netx/MuxReader.swift
2
5437
// // MuxReader.swift // Netx // // Created by Ivan Korobkov on 14/02/16. // Copyright © 2016 Ivan Korobkov. All rights reserved. // import Foundation // MuxReader is a thread-safe stream reader which buffers data and uses a window to control flow. class MuxReader: Reader { // Some fields are visible for testing. private let queue: dispatch_queue_t private var error: ErrorType? private var callbacks: [(buf: NSMutableData, callback: ReadCallback, n: Int)] var buffers: [NSData] var window: UInt32 var maxWindow: UInt32 init(queue: dispatch_queue_t) { self.queue = queue self.buffers = [] self.callbacks = [] self.window = WindowInit self.maxWindow = WindowInit } // Appends a pending buffer and a callback and flushes the callbacks. func read(data: NSMutableData, callback: ReadCallback) { dispatch_async(self.queue) { self.callbacks.append((data, callback, 0)) self.flush() } } // All methods below must be executed from the stream inside its queue. // Sets a new max window and returns an optional delta. func setMaxWindowReturnDelta(window: UInt32) throws -> UInt32 { guard window > 0 else { throw MuxError.Error(.FlowControlError, "Stream max read window must be > 0") } guard window <= WindowMax else { throw MuxError.Error(.FlowControlError, "Stream max read window must be <= \(WindowMax), got=\(window)") } self.maxWindow = window return self.maybeIncrementWindow() } // Appends a buffer and returns an optional window delta. func append(buffer: NSData) throws -> UInt32 { assert(self.error == nil, "Tried to append a buffer to a closed streamReader") let size = UInt32(buffer.length) if size > self.window { throw MuxError.Error( .FlowControlError, "Incoming stream data overflowed a read window overflow, length=\(size), window=\(self.window)") } self.window -= size let delta = self.maybeIncrementWindow() self.buffers.append(buffer) self.flush() return delta } private func maybeIncrementWindow() -> UInt32 { if self.window > (self.maxWindow / 2) { return 0 } let delta = self.maxWindow - self.window self.window += delta return delta } // Sets an error and flushes the callbacks. func close(error: ErrorType) { guard self.error == nil else { return } self.error = error self.flush() } private func flush() { // While the callbacks are not empty: // // If the buffers are empty: // If an error: // Remove the first callback and notify it. // Continue. // Else: // Return, i.e. wait for more data. // // Get the first callback. // While the buffers are not empty and the callback buffer is not full: // Get a data buffer. // Copy it to the callback buffer. // // If the data buffer has been copied completely: // Remove the data buffer. // Else: // Slice the data buffer. // // Update the callback n counter and slice its buffer. // // If the callback buffer is full: // Remove the callback and notify it. // // Continue. while self.callbacks.count > 0 { guard self.buffers.count > 0 else { // No data. guard self.error == nil else { let (_, cb, n) = self.callbacks.removeFirst() cb(n, self.error) continue } // Wait for more data. return } var (buf, cb, n) = self.callbacks[0] // Copy data to the callback buffer. while (n < buf.length) && self.buffers.count > 0 { let data = self.buffers[0] let bytes = buf.mutableBytes + n // Copy the min number of bytes. var len = buf.length - n if len > data.length { len = data.length } memcpy(bytes, data.bytes, len) n += len // If complete remove the data, else slice it. if len == data.length { self.buffers.removeFirst() } else { self.buffers[0] = data.subdataWithRange(NSMakeRange(len, data.length - len)) } } // If the buffer is full, remove and notify the callback. if buf.length == n { self.callbacks.removeFirst() cb(n, nil) continue } // Else update the callback read counter and the remaining buffer. self.callbacks[0].buf = buf self.callbacks[0].n = n } } }
apache-2.0
308582d73a1194e113b3641147e1a592
30.610465
131
0.508094
4.793651
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/Classes/LiquidFloatingActionButton.swift
1
18537
// // LiquidFloatingActionButton.swift // Pods // // Created by Takuma Yoshida on 2015/08/25. // // import CoreGraphics import Foundation import QuartzCore import UIKit // LiquidFloatingButton DataSource methods @objc public protocol LiquidFloatingActionButtonDataSource { func numberOfCells(liquidFloatingActionButton: LiquidFloatingActionButton) -> Int func cellForIndex(index: Int) -> LiquidFloatingCell } @objc public protocol LiquidFloatingActionButtonDelegate { // selected method optional func liquidFloatingActionButton(liquidFloatingActionButton: LiquidFloatingActionButton, didSelectItemAtIndex index: Int) } public enum LiquidFloatingActionButtonAnimateStyle : Int { case Up case Right case Left case Down } @IBDesignable public class LiquidFloatingActionButton : UIView { public var clearColor: UIColor = UIColor.clearColor() private let internalRadiusRatio: CGFloat = 20.0 / 42.0 public var cellRadiusRatio: CGFloat = 0.5 public var animateStyle: LiquidFloatingActionButtonAnimateStyle = .Up { didSet { baseView.animateStyle = animateStyle } } public var enableShadow = true { didSet { setNeedsDisplay() } } public var delegate: LiquidFloatingActionButtonDelegate? public var dataSource: LiquidFloatingActionButtonDataSource? public var responsible = true public var isClosed: Bool { get { return plusRotation == 0 } } @IBInspectable public var color: UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0) { didSet { baseView.color = color } } private let plusLayer = CAShapeLayer() private let circleLayer = CAShapeLayer() private var touching = false private var plusRotation: CGFloat = 0 private var baseView = CircleLiquidBaseView() private let liquidView = UIView() public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } private func insertCell(cell: LiquidFloatingCell) { cell.color = self.color cell.radius = self.frame.width * cellRadiusRatio cell.center = self.center.minus(self.frame.origin) cell.actionButton = self insertSubview(cell, aboveSubview: baseView) } private func cellArray() -> [LiquidFloatingCell] { var result: [LiquidFloatingCell] = [] if let source = dataSource { for i in 0..<source.numberOfCells(self) { result.append(source.cellForIndex(i)) } } return result } // open all cells public func open() { // rotate plus icon self.plusLayer.addAnimation(plusKeyframe(true), forKey: "plusRot") self.plusRotation = CGFloat(M_PI * 0.25) // 45 degree let cells = cellArray() for cell in cells { insertCell(cell) } self.baseView.open(cells) setNeedsDisplay() } // close all cells public func close() { // rotate plus icon self.plusLayer.addAnimation(plusKeyframe(false), forKey: "plusRot") self.plusRotation = 0 self.baseView.close(cellArray()) setNeedsDisplay() } // MARK: draw icon public override func drawRect(rect: CGRect) { drawCircle() drawShadow() //drawPlus(plusRotation) } private func drawCircle() { self.circleLayer.frame = CGRect(origin: CGPointZero, size: self.frame.size) self.circleLayer.cornerRadius = self.frame.width * 0.5 self.circleLayer.masksToBounds = true if touching && responsible { self.circleLayer.backgroundColor = self.color.white(0.5).CGColor } else { self.circleLayer.backgroundColor = self.clearColor.CGColor } } private func drawPlus(rotation: CGFloat) { plusLayer.frame = CGRect(origin: CGPointZero, size: self.frame.size) plusLayer.lineCap = kCALineCapRound plusLayer.strokeColor = UIColor.whiteColor().CGColor // TODO: customizable plusLayer.lineWidth = 2.0 plusLayer.path = pathPlus(rotation).CGPath } private func drawShadow() { if enableShadow { circleLayer.appendShadow() } } // draw button plus or close face private func pathPlus(rotation: CGFloat) -> UIBezierPath { let radius = self.frame.width * internalRadiusRatio * 0.5 let center = self.center.minus(self.frame.origin) let points = [ CGMath.circlePoint(center, radius: radius, rad: rotation), CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) + rotation), CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) * 2 + rotation), CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) * 3 + rotation) ] let path = UIBezierPath() path.moveToPoint(points[0]) path.addLineToPoint(points[2]) path.moveToPoint(points[1]) path.addLineToPoint(points[3]) return path } private func plusKeyframe(closed: Bool) -> CAKeyframeAnimation { let paths = closed ? [ pathPlus(CGFloat(M_PI * 0)), pathPlus(CGFloat(M_PI * 0.125)), pathPlus(CGFloat(M_PI * 0.25)), ] : [ pathPlus(CGFloat(M_PI * 0.25)), pathPlus(CGFloat(M_PI * 0.125)), pathPlus(CGFloat(M_PI * 0)), ] let anim = CAKeyframeAnimation(keyPath: "path") anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) anim.values = paths.map { $0.CGPath } anim.duration = 0.5 anim.removedOnCompletion = true anim.fillMode = kCAFillModeForwards anim.delegate = self return anim } // MARK: Events public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.touching = true setNeedsDisplay() } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.touching = false setNeedsDisplay() didTapped() } public override func touchesCancelled(touches: Set<UITouch>!, withEvent event: UIEvent!) { self.touching = false setNeedsDisplay() } public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { for cell in cellArray() { let pointForTargetView = cell.convertPoint(point, fromView: self) if (CGRectContainsPoint(cell.bounds, pointForTargetView)) { if cell.userInteractionEnabled { return cell.hitTest(pointForTargetView, withEvent: event) } } } return super.hitTest(point, withEvent: event) } // MARK: private methods private func setup() { self.backgroundColor = UIColor.clearColor() self.clipsToBounds = false baseView.setup(self) addSubview(baseView) liquidView.frame = baseView.frame liquidView.userInteractionEnabled = false addSubview(liquidView) liquidView.layer.addSublayer(circleLayer) circleLayer.addSublayer(plusLayer) } private func didTapped() { if isClosed { open() } else { close() } } public func didTappedCell(target: LiquidFloatingCell) { if let _ = dataSource { let cells = cellArray() for i in 0..<cells.count { let cell = cells[i] if target === cell { delegate?.liquidFloatingActionButton?(self, didSelectItemAtIndex: i) } } } } } class ActionBarBaseView : UIView { var opening = false func setup(actionButton: LiquidFloatingActionButton) { } func translateY(layer: CALayer, duration: CFTimeInterval, f: (CABasicAnimation) -> ()) { let translate = CABasicAnimation(keyPath: "transform.translation.y") f(translate) translate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) translate.removedOnCompletion = false translate.fillMode = kCAFillModeForwards translate.duration = duration layer.addAnimation(translate, forKey: "transYAnim") } } class CircleLiquidBaseView : ActionBarBaseView { let openDuration: CGFloat = 0.8 let closeDuration: CGFloat = 0.2 let viscosity: CGFloat = 0.6 var animateStyle: LiquidFloatingActionButtonAnimateStyle = .Up var color: UIColor = UIColor.clearColor() { didSet { engine?.color = color bigEngine?.color = color } } var baseLiquid: LiquittableCircle? var baseLiquidOpen: LiquittableCircle? var engine: SimpleCircleLiquidEngine? var bigEngine: SimpleCircleLiquidEngine? var enableShadow = true private var openingCells: [LiquidFloatingCell] = [] private var keyDuration: CGFloat = 0 private var displayLink: CADisplayLink? override func setup(actionButton: LiquidFloatingActionButton) { self.frame = actionButton.frame self.center = actionButton.center.minus(actionButton.frame.origin) self.animateStyle = actionButton.animateStyle let radius = min(self.frame.width, self.frame.height) * 0.5 self.engine = SimpleCircleLiquidEngine(radiusThresh: radius * 0.73, angleThresh: 0.45) engine?.viscosity = viscosity self.bigEngine = SimpleCircleLiquidEngine(radiusThresh: radius, angleThresh: 0.55) bigEngine?.viscosity = viscosity self.engine?.color = actionButton.color self.bigEngine?.color = actionButton.color baseLiquid = LiquittableCircle(center: self.center.minus(self.frame.origin), radius: radius, color: self.color) baseLiquidOpen = LiquittableCircle(center: self.center.minus(self.frame.origin), radius: radius, color: actionButton.color) baseLiquid?.clipsToBounds = false baseLiquid?.layer.masksToBounds = false baseLiquidOpen?.clipsToBounds = false baseLiquidOpen?.layer.masksToBounds = false baseLiquidOpen?.hidden = true clipsToBounds = false layer.masksToBounds = false addSubview(baseLiquid!) addSubview(baseLiquidOpen!) } func open(cells: [LiquidFloatingCell]) { stop() //let distance: CGFloat = self.frame.height * 1.25 displayLink = CADisplayLink(target: self, selector: Selector("didDisplayRefresh:")) displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) opening = true for cell in cells { cell.layer.removeAllAnimations() cell.layer.eraseShadow() openingCells.append(cell) } } func close(cells: [LiquidFloatingCell]) { stop() //let distance: CGFloat = self.frame.height * 1.25 opening = false displayLink = CADisplayLink(target: self, selector: Selector("didDisplayRefresh:")) displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) for cell in cells { cell.layer.removeAllAnimations() cell.layer.eraseShadow() openingCells.append(cell) cell.userInteractionEnabled = false } } func didFinishUpdate() { if opening { for cell in openingCells { cell.userInteractionEnabled = true } } else { for cell in openingCells { cell.removeFromSuperview() } } } func update(delay: CGFloat, duration: CGFloat, f: (LiquidFloatingCell, Int, CGFloat) -> ()) { if openingCells.isEmpty { return } let maxDuration = duration + CGFloat(openingCells.count) * CGFloat(delay) let t = keyDuration let allRatio = easeInEaseOut(t / maxDuration) if allRatio >= 1.0 { didFinishUpdate() stop() return } engine?.clear() bigEngine?.clear() for i in 0..<openingCells.count { let liquidCell = openingCells[i] let cellDelay = CGFloat(delay) * CGFloat(i) let ratio = easeInEaseOut((t - cellDelay) / duration) f(liquidCell, i, ratio) } if let firstCell = openingCells.first { bigEngine?.push(baseLiquid!, other: firstCell) } for i in 1..<openingCells.count { let prev = openingCells[i - 1] let cell = openingCells[i] engine?.push(prev, other: cell) } if opening { engine?.draw(baseLiquidOpen!) bigEngine?.draw(baseLiquidOpen!) baseLiquidOpen?.hidden = false baseLiquid?.hidden = true } else { engine?.draw(baseLiquid!) bigEngine?.draw(baseLiquid!) baseLiquidOpen?.hidden = true baseLiquid?.hidden = false } } func updateOpen() { update(0.1, duration: openDuration) { cell, i, ratio in let posRatio = ratio > CGFloat(i) / CGFloat(self.openingCells.count) ? ratio : 0 let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * posRatio cell.center = self.center.plus(self.differencePoint(distance)) cell.update(ratio, open: true) } } func updateClose() { update(0, duration: closeDuration) { cell, i, ratio in let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * (0.9935 - ratio) cell.center = self.center.plus(self.differencePoint(distance)) cell.update(ratio, open: false) } } func differencePoint(distance: CGFloat) -> CGPoint { switch animateStyle { case .Up: return CGPoint(x: 0, y: -distance) case .Right: return CGPoint(x: distance, y: 0) case .Left: return CGPoint(x: -distance, y: 0) case .Down: return CGPoint(x: 0, y: distance) } } func stop() { for cell in openingCells { if enableShadow { cell.layer.appendShadow() } } openingCells = [] keyDuration = 0 displayLink?.invalidate() } func easeInEaseOut(t: CGFloat) -> CGFloat { if t >= 1.0 { return 1.0 } if t < 0 { return 0 } _ = t * 2 return -1 * t * (t - 2) } func didDisplayRefresh(displayLink: CADisplayLink) { if opening { keyDuration += CGFloat(displayLink.duration) updateOpen() } else { keyDuration += CGFloat(displayLink.duration) updateClose() } } } public class LiquidFloatingCell : LiquittableCircle { let internalRatio: CGFloat = 0.75 public var responsible = true public var imageView = UIImageView() public var imageLabel = UILabel() weak var actionButton: LiquidFloatingActionButton? // for implement responsible color private var originalColor: UIColor public override var frame: CGRect { didSet { resizeSubviews() } } init(center: CGPoint, radius: CGFloat, color: UIColor, icon: UIImage, label: String) { self.originalColor = color super.init(center: center, radius: radius, color: color) setup(icon, text: label) } init(center: CGPoint, radius: CGFloat, color: UIColor, view: UIView) { self.originalColor = color super.init(center: center, radius: radius, color: color) setupView(view) } public init(icon: UIImage, label: String) { self.originalColor = UIColor.clearColor() super.init() setup(icon, text: label) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(image: UIImage, tintColor: UIColor = UIColor.whiteColor(), text: String) { imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) imageView.tintColor = tintColor imageLabel.textColor = tintColor imageLabel.textAlignment = .Center imageLabel.font = UIFont(name: "AvenirNext-Regular", size: 12) imageLabel.text = text setupView(imageView) } func setupView(view: UIView) { userInteractionEnabled = false addSubview(view) addSubview(imageLabel) resizeSubviews() } private func resizeSubviews() { let size = CGSize(width: frame.width * 0.5, height: frame.height * 0.5) let labelSize = CGSize(width: frame.width, height: frame.height * 0.3) imageView.frame = CGRect(x: frame.width - frame.width * internalRatio, y: frame.height - frame.height * internalRatio, width: size.width, height: size.height) imageLabel.frame = CGRect(x: -20, y: frame.height + 5, width: frame.width + 40, height: labelSize.height) } func update(key: CGFloat, open: Bool) { for subview in self.subviews { if let view = subview as UIView! { let ratio = max(2 * (key * key - 0.5), 0) view.alpha = open ? ratio : -ratio } } } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if responsible { originalColor = color color = originalColor.white(1.0) setNeedsDisplay() } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { if responsible { color = originalColor setNeedsDisplay() } } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { color = originalColor actionButton?.didTappedCell(self) } }
mit
c11f424f903a98b2b8bed346c90ff8bb
31.409091
166
0.605815
4.809808
false
false
false
false
anndse/SwiftStudy
InitTest/InitTest/main.swift
1
8541
// // main.swift // InitTest // // Created by 王惠 on 15/3/28. // Copyright (c) 2015年 王惠. All rights reserved. // import Foundation println("Hello, World!") struct Fahrenheit { var temperature: Double init(){ temperature = 32.0 } } var f = Fahrenheit() println("The default temperature is \(f.temperature)° fahrenheit") //Type alias just same as typedef in the C language typealias F = Fahrenheit typealias Count = Int64 //for example to use it var af = F() println("The max of Count is \(Count.max) and the min of Count is \(Count.min)") //closed range operator (a...b) //how to use it, for example, with a for-in loop for index in 1...5 { println("\(index) times 5 is \(index * 5)") } //halt-open range operator (a..<b) let names = ["simon", "andy", "Alex", "Jack"] for index in 0..<names.count { println("Person \(index+1) is called \(names[index])") } //switch of swift // Range matching let count = 3_00 let countedThings = "stars in the Milky Way" var naturalCount: String switch count { case 0: naturalCount="0" case 1...3: naturalCount="a few" case 4...9: naturalCount="several" case 10...99: naturalCount="tens of" case 100...999: naturalCount="hundreds of" case 1000...999_999: naturalCount="thousands of" default: naturalCount="millions of millions of" } println("There are \(naturalCount) \(countedThings)") //use tuples for switch let somePoint=(9,-1) switch somePoint { case (0, 0): println("(0,0) is at the origin") case (_, 0): println("\(somePoint) is on the x-axis") case (0, _): println("\(somePoint) is on the y-axis") case (-2...2, -2...2): println("\(somePoint) is inside the box") default: println("\(somePoint) is outside the box") } //use Value Bindings for switch let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): println("on the x-axis with an x value of \(x)") case (0, let y): println("on the y-axis with a y value of \(y)") case let (x, y): println("somewhere else at \(anotherPoint)") } //where case let yetAnotherPoint=(1, 0) switch yetAnotherPoint { case let (x, y) where x == y : println("\(yetAnotherPoint) is on the line x == y") case let (x, y) where x == -y: println("\(yetAnotherPoint) is on the line x == -y") case let (x, y): println("\(yetAnotherPoint) is just some arbitrary point") } //use Funcations func sayHello(personName:String)->String{ return "Hello, \(personName)!" } println(sayHello("simon")) //multiple return values func findMinMax(a:[Int])->(min:Int, max:Int){ var curMin = a[0] var curmax = a[0] for value in a[1..<a.count] { if(curmax < value){ curmax = value } if(curMin > value){ curMin = value } } return (curMin, curmax) } //test it let a=[4,5,2,6,6,33,96,3,75] println("The max value of array is \(findMinMax(a).max)") //Enumerations //case one enum CompassPoint{ case North case South case East case West } //case two enum Planet{ case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Nepture } var directionToHead = CompassPoint.East //or directionToHead = .East println(directionToHead) //“define Swift enumerations to store associated values” //摘录来自: Apple Inc. “The Swift Programming Language”。 iBooks. https://itun.es/cn/jEUH0.l enum Barcode{ case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) func DisplayProuctBarcode(code:Barcode){ switch code { case let .UPCA(numberSystem, manufacturer, product, check): println("UPC-A:\(numberSystem) \(manufacturer) \(product) \(check)") case let .QRCode(code): println("QRCode:\(code)") } } DisplayProuctBarcode(productBarcode) productBarcode = Barcode.QRCode("ABCDEFGHIJKLMNOPQ") DisplayProuctBarcode(productBarcode) //Raw values for enum enum ASCIIControlCharacter : Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" } enum PlanetInt:Int{ case Mercury=1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Nepture } print(PlanetInt.Earth.rawValue) print(ASCIIControlCharacter.CarriageReturn.rawValue) //for study Classes and structures struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } //use it as: let someResolution = Resolution() let someVideoMode = VideoMode() println("The width of resolution is \(someResolution.width)") println("The width of someVideoMode is \(someVideoMode.resolution.width)") someVideoMode.resolution.width = 1280 println("The width of someVideoMode is now \(someVideoMode.resolution.width)") //To init its //“Structures and Enumerations Are Value Types” let vga = Resolution(width: 640, height: 480) println("vga: \(vga.width) * \(vga.height)") let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 println("width of hd is \(hd.width), and width of cinema is \(cinema.width)") //Classes are Reference Types let teneighty = VideoMode() teneighty.resolution = hd teneighty.interlaced = true teneighty.name = "1080i" teneighty.frameRate = 25.0 let alsoTeneighty = teneighty alsoTeneighty.frameRate = 30.0 println("frame of tenEighty is \(teneighty.frameRate), frame of alsoTeneighty is \(alsoTeneighty.frameRate)") //Identity operator === and !== //identical to(===), Not identical to(!==) if(teneighty === alsoTeneighty){ println("teneighty and alsoTeneighty refer to the same VideoMode instance") } //Stored Properties struct FixedLengthRange { var firstValue: Int let length:Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 //cannot assign to length, it's const //rangeOfThreeItems.length = 4 //Computed Properties struct Point{ var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center:Point{ get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } //set (newCenter) { //also can write as this: set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } func area()->Double{ return size.height * size.width } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) println("The center of square is (\(square.center.x), \(square.center.y))") println("And the area of square is \(square.area())") square.center = Point(x: 20.0, y: 20.0) println("square.origin is (\(square.origin.x), \(square.origin.y))") //Property Observers //willSet and didSet class StepCounter{ var totalsetps: Int = 0 { willSet { println("About to set totalsteps to \(newValue)") } didSet { if totalsetps > oldValue { println("Add \(totalsetps - oldValue) steps") } } } } //test it let stepCounter = StepCounter() stepCounter.totalsetps = 100 stepCounter.totalsetps = 50 //modifying value types from within instance methods //keyword mutating //eg: struct NewPoint { var x = 0.0, y = 0.0 mutating func moveBy(dx:Double, dy:Double){ self = NewPoint(x: x+dx, y: y+dy) } } var newpoint = NewPoint(x: 5.0, y: 1.0) newpoint.moveBy(1.0, dy: 5.0) println("After call moveBy: (\(newpoint.x), \(newpoint.y))") //Subscript Options struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns self.grid = Array(count: rows * columns, repeatedValue: 0.0) } func indexIsValid(row: Int, column: Int)->Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int, column: Int) -> Double { get { assert(indexIsValid(row, column: column), "Index out of range") return grid[(row * columns) + column] } set{ assert(indexIsValid(row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } } } //test it var matrix = Matrix(rows: 5, columns: 5) matrix[2,3] = 50 println(matrix[2,3])
gpl-2.0
1f6d9734e3575e723204e4e4337ec71f
23.804665
109
0.643277
3.4265
false
false
false
false
haawa799/WaniKani-iOS
WaniKani/ViewControllers/BrowserViewController.swift
1
3427
// // BrowserViewController.swift // WaniKani // // Created by Andriy K. on 9/28/15. // Copyright © 2015 Andriy K. All rights reserved. // import UIKit import WebKit import NJKScrollFullScreen class BrowserViewController: UIViewController { private struct Constants { private static let homeLink = "https://www.wanikani.com/dashboard" private static let forumLink = "https://www.wanikani.com/community" } var webView: WKWebView! var scrollProxy: NJKScrollFullScreen! @IBOutlet weak var forumsButton: UIBarButtonItem! @IBOutlet weak var homeButton: UIBarButtonItem! @IBOutlet weak var nextButton: UIBarButtonItem! @IBOutlet weak var backButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() let userScript = WKUserScript(source: hideSubscribitionsSkript, injectionTime: .AtDocumentEnd, forMainFrameOnly: true) let userContentController = WKUserContentController() userContentController.addUserScript(userScript) let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController webView = WKWebView(frame: self.view.bounds, configuration: configuration) webView.navigationDelegate = self view = webView loadURL(Constants.homeLink) scrollProxy = NJKScrollFullScreen(forwardTarget: self) webView.scrollView.delegate = scrollProxy scrollProxy.delegate = self updateButtonsState() } func loadURL(url: String) { if let requestURL = NSURL(string: url) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true let request = NSURLRequest(URL: requestURL, cachePolicy: .ReloadRevalidatingCacheData, timeoutInterval: 15.0) webView.loadRequest(request) } } } extension BrowserViewController: NJKScrollFullscreenDelegate { func scrollFullScreen(fullScreenProxy: NJKScrollFullScreen!, scrollViewDidScrollUp deltaY: CGFloat) { moveNavigationBar(deltaY, animated: true) } func scrollFullScreen(fullScreenProxy: NJKScrollFullScreen!, scrollViewDidScrollDown deltaY: CGFloat) { moveNavigationBar(deltaY, animated: true) } func scrollFullScreenScrollViewDidEndDraggingScrollUp(fullScreenProxy: NJKScrollFullScreen!) { hideNavigationBar(true) } func scrollFullScreenScrollViewDidEndDraggingScrollDown(fullScreenProxy: NJKScrollFullScreen!) { showNavigationBar(true) } } extension BrowserViewController { @IBAction func nextPressed(sender: UIBarButtonItem) { webView.goForward() } @IBAction func previousPressed(sender: UIBarButtonItem) { webView.goBack() } @IBAction func homePressed(sender: UIBarButtonItem) { loadURL(Constants.homeLink) } @IBAction func forumPressed(sender: UIBarButtonItem) { loadURL(Constants.forumLink) } } extension BrowserViewController: WKNavigationDelegate { private func updateButtonsState() { backButton.enabled = webView.canGoBack nextButton.enabled = webView.canGoForward } func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { updateButtonsState() UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { updateButtonsState() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
gpl-3.0
fdd098f0736271c7e212f08dbddd131f
29.318584
122
0.758611
5.128743
false
false
false
false
kevindelord/DKDBManager
Example/DBSwiftTest/ViewControllers/PlaneViewController.swift
1
2856
// // ViewController.swift // DBSwiftTest // // Created by kevin delord on 01/10/14. // Copyright (c) 2014 Smart Mobile Factory. All rights reserved. // import UIKit import DKDBManager class PlaneViewController : TableViewController { // MARK: - UITableView override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Plane.count() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if let plane = (Plane.all() as? [Plane])?[indexPath.row] { cell.textLabel?.text = "\(plane.origin ?? "n/a") -> \(plane.destination ?? "n/a")" cell.detailTextLabel?.text = "\(plane.allPassengersCount) passenger(s)" } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.performSegue(withIdentifier: Segue.OpenPassengers, sender: (Plane.all() as? [Plane])?[indexPath.row]) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete), let plane = (Plane.all() as? [Plane])?[indexPath.row] { DKDBManager.save({ (savingContext: NSManagedObjectContext) -> Void in // Background Thread plane.deleteEntity(withReason: "Selective delete button pressed", in: savingContext) }, completion: { (didSave: Bool, error: Error?) -> Void in // Main Thread self.didDeleteItemAtIndexPath(indexPath) }) } } // MARK: - Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == Segue.OpenPassengers) { let vc = segue.destination as? PassengerViewController vc?.plane = sender as? Plane } } // MARK: - IBAction @IBAction func editButtonPressed() { self.tableView.setEditing(!self.tableView.isEditing, animated: true) } @IBAction func removeAllEntitiesButtonPressed() { DKDBManager.save({ (savingContext: NSManagedObjectContext) -> Void in // background thread for plane in (Plane.all() as? [Plane] ?? []) { if let plane = plane.entity(in: savingContext) { plane.deleteEntity(withReason: "Remove all planes button pressed", in: savingContext) } } }, completion: { (contextDidSave: Bool, error: Error?) -> Void in // main thread self.tableView.reloadData() }) } @IBAction func addEntitiesButtonPressed() { let json = MockManager.randomPlaneJSON() DKDBManager.save({ (savingContext: NSManagedObjectContext) -> Void in // background thread Plane.crudEntities(with: json, in: savingContext) }, completion: { (contextDidSave: Bool, error: Error?) -> Void in // main thread self.tableView.reloadData() }) } }
mit
717ef75fadf54accc8d3443f87667d9d
29.063158
133
0.706933
3.828418
false
false
false
false
appfoundry/DRYLogging
Example/Tests/LoggingConcurrencySpec.swift
1
6062
// // LoggingConcurrencySpec.swift // DRYLogging // // Created by Michael Seghers on 16/11/2016. // Copyright © 2016 Michael Seghers. All rights reserved. // import Foundation import Quick import Nimble @testable import DRYLogging class LoggingConcurrencySpec : QuickSpec { override func spec() { describe("logging concurrency checks") { let numberOfThreadsToSpawn = 20 let numberOfMessagesToLog = 50 var cachedRootAppenders:[LoggingAppender]! var documentPath:String! var path:String! var logger:Logger! var fileAppender:LoggingAppender! func spawnThreadsAndWait() { waitUntil(timeout: 100) { done in var loggerThreads:[LoggerThread] = []; for i in (0..<numberOfThreadsToSpawn) { let thread = LoggerThread(name: "LoggerThread \(i)", numberOfMessagesToLog: numberOfMessagesToLog) loggerThreads.append(thread) thread.start() } let waiter = WaiterThread(loggerThreads: loggerThreads, doneHandler: done) waiter.start() } } beforeEach { cachedRootAppenders = LoggerFactory.rootLogger.appenders for appender in LoggerFactory.rootLogger.appenders { LoggerFactory.rootLogger.remove(appender: appender) } documentPath = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String])[0]) path = documentPath.stringByAppendingPathComponent(path: "file.txt") logger = LoggerFactory.logger(named: "threadlogger") logger.logLevel = .info } context("spawn log thread without roller") { beforeEach { let formatter = ClosureBasedMessageFormatter { return "[\($0.date)] - [\($0.threadName)] \($0.message)" } fileAppender = FileAppender(formatter: formatter, filePath: path, rollerPredicate: SizeLoggingRollerPredicate(maxSizeInBytes: Int.max), roller: BackupRoller()) logger.add(appender: fileAppender) } it("should log the expected amount of log lines") { spawnThreadsAndWait() let contents = try? String(contentsOfFile: path) let lines = contents?.components(separatedBy: "\n") let numberOfMessageTimesNumberOfThreadsPlusEmptyLine = numberOfThreadsToSpawn * numberOfMessagesToLog + 1 expect(lines?.count) == numberOfMessageTimesNumberOfThreadsPlusEmptyLine } } context("spawn log thread with fast roller") { beforeEach { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" let formatter = ClosureBasedMessageFormatter { return "[\(dateFormatter.string(from: $0.date))] - [\($0.threadName)] \($0.message)" } fileAppender = FileAppender(formatter: formatter, filePath: path, rollerPredicate: SizeLoggingRollerPredicate(maxSizeInBytes: 100), roller: BackupRoller(maximumNumberOfFiles: 10)) logger.add(appender: fileAppender) } it("should have created the expected amount of files with the expected amount of lines in them") { spawnThreadsAndWait() for index in 1..<10 { let filePath = documentPath.stringByAppendingPathComponent(path: "file\(index).txt") let contents = try? String(contentsOfFile: filePath) let lines = contents?.components(separatedBy: "\n") expect(lines?.count) == 3 } } } afterEach { for appender in cachedRootAppenders { LoggerFactory.rootLogger.add(appender: appender) } do { let manager = FileManager.default for filePath in try manager.contentsOfDirectory(atPath: documentPath) { try manager.removeItem(atPath: documentPath.stringByAppendingPathComponent(path: filePath)) } } catch { fail("could not remove files in document path \(documentPath): \(error)") } logger.remove(appender: fileAppender) } } } } class LoggerThread : Thread { let numberOfMessagesToLog:Int var done:Bool init(name: String, numberOfMessagesToLog: Int) { self.done = false self.numberOfMessagesToLog = numberOfMessagesToLog super.init() self.name = name } override func main() { let logger = LoggerFactory.logger(named: "threadlogger") for i in (0..<self.numberOfMessagesToLog) { logger.info("This is message \(i)") Thread.sleep(forTimeInterval: (Double(arc4random_uniform(10)) / 10)) } done = true } } class WaiterThread : Thread { let loggerThreads:[LoggerThread] let doneHandler:() -> () init(loggerThreads:[LoggerThread], doneHandler: @escaping () -> ()) { self.loggerThreads = loggerThreads self.doneHandler = doneHandler } override func main() { while !loggerThreads.reduce(true, { return $0 && $1.done }) { Thread.sleep(forTimeInterval: 0.5) } doneHandler() } }
mit
9263c3ae8d7fb0400354374cbbc33d3d
39.406667
199
0.541
5.401961
false
false
false
false
kildevaeld/FASlideView
Pod/Classes/FASlideView.swift
1
4680
// // FASlideView.swift // Pods // // Created by Rasmus Kildevæld on 19/06/15. // // import Foundation import UIKit @objc public protocol FASlideViewDelegate { func slideView(slideView: FASlideView, didTouchView: UIView, atIndex:Int) } @objc public protocol FASlideViewDataSource { func numberOfViews(slideView: FASlideView) -> Int func slideView(slideView: FASlideView, viewForViewAtIndex: Int) -> UIView func slideView(slideView: FASlideView, transitionFromView:UIView, toView: UIView, complete: () -> Void) func slideView(slideView: FASlideView, didTouchView: UIView, atIndex:Int) } public class FASlideView : UIView { public var delegate : FASlideViewDelegate? public var dataSource : FASlideViewDataSource? public var randomize : Bool = false public var defaultView : UIView? { didSet (view) { if self.currentView != nil { return } for subview in self.subviews { subview.removeFromSuperview() } if view != nil { self.addSubview(view!) } } } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.commonInit() } public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } func commonInit () { let gesture = UITapGestureRecognizer() self.addGestureRecognizer(gesture) gesture.addTarget(self, action: "onClick:") } func onClick(sender: UIView) { if self.currentView == nil { return } else if self.currentView! === self.defaultView { return } self.dataSource?.slideView(self, didTouchView: self.currentView!, atIndex: currentIndex - 1) } public var transition : UIViewAnimationTransition? = UIViewAnimationTransition.FlipFromLeft public var interval: NSTimeInterval = 10 private var currentIndex : Int = 0 private var currentView : UIView? private var timer : NSTimer? public func start () { self.stop() if self.dataSource == nil { return } self.timer = NSTimer.scheduledTimerWithTimeInterval(self.interval, target: self, selector: "onTimerFired:", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(self.timer!, forMode:NSRunLoopCommonModes) self.onTimerFired(self.timer!) } public func stop () { if self.timer != nil { self.timer!.invalidate() self.timer = nil } } func onTimerFired(time:NSTimer) { let count = self.dataSource!.numberOfViews(self) if count == 0 { self.useDefaultView() return } let next = self.nextIndex(count) let view = self.dataSource?.slideView(self, viewForViewAtIndex: next) if view != nil { self.setView(view!) } else { self.useDefaultView() } } private func useDefaultView () { if self.defaultView == nil || self.currentView === self.defaultView { return } self.setView(self.defaultView!) } private func setView (view: UIView) { func clear () { for view in self.subviews { view.removeFromSuperview() } } if self.currentView === view { return } view.frame = self.bounds if self.currentView != nil { clear() self.addSubview(view) self.currentView = view } else { self.addSubview(view) self.dataSource!.slideView(self, transitionFromView: self.currentView!, toView: view, complete: { () -> Void in self.currentView?.removeFromSuperview() self.currentView = view }) } } private func nextIndex (count: Int) -> Int { let next : Int if self.randomize { var rnd = 0 if count > 1 { rnd = Int(rand()) % (count - 1) } if rnd == currentIndex && count != 1 { rnd = nextIndex(count) } next = rnd } else { if currentIndex == count { currentIndex = 0 } next = currentIndex++ } return next } deinit { self.stop() } }
mit
6258b76a03ecee1aad9cf65e3a92d80f
23.888298
145
0.539432
4.930453
false
false
false
false
jack-cox-captech/HomeKitBrowser
HomeKitBrowser/HKBAddHomeViewController.swift
1
2451
// // HKBAddRoomViewController.swift // HomeKitBrowser // // Created by Jack Cox on 1/31/15. // Copyright (c) 2015 CapTech Consulting. All rights reserved. // import UIKit import HomeKit class HKBAddHomeViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var doneButton: UIBarButtonItem! @IBOutlet weak var homeNameField: UITextField! @IBOutlet weak var primarySwitch: UISwitch! var homeManager:HMHomeManager! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func cancelPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func donePressed(sender: AnyObject) { if let realHomeManager = self.homeManager { realHomeManager.addHomeWithName(homeNameField.text) {(home, error) in if (self.primarySwitch.on) { realHomeManager.updatePrimaryHome(home, completionHandler: { (error) -> Void in if (error != nil) { var alertCtl = UIAlertController(title: "Error", message: "Error adding home \(self.homeNameField.text)\n\(error.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alertCtl.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: { (action) -> Void in // Do something appropriate })) self.presentViewController(alertCtl, animated: true, completion: nil) } else { self.dismissViewControllerAnimated(true, completion: nil) } }) } else { self.dismissViewControllerAnimated(true, completion: nil) } } } } // MARK: UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if (textField.text.isEmpty) { self.doneButton.enabled = false } else { self.doneButton.enabled = true } return true } }
mit
776c70a9f5e89b1b5ff2f048b28449b9
33.041667
141
0.562627
5.634483
false
false
false
false
robertofrontado/RxGcm-iOS
iOS/Pods/Nimble/Sources/Nimble/Matchers/Match.swift
46
1018
import Foundation #if _runtime(_ObjC) /// A Nimble matcher that succeeds when the actual string satisfies the regular expression /// described by the expected string. public func match(_ expectedValue: String?) -> NonNilMatcherFunc<String> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "match <\(stringify(expectedValue))>" if let actual = try actualExpression.evaluate() { if let regexp = expectedValue { return actual.range(of: regexp, options: .regularExpression) != nil } } return false } } extension NMBObjCMatcher { public class func matchMatcher(_ expected: NSString) -> NMBMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let actual = actualExpression.cast { $0 as? String } return try! match(expected.description).matches(actual, failureMessage: failureMessage) } } } #endif
apache-2.0
5450527774a4ceeed864cb17656afea4
32.933333
99
0.671906
5.329843
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Data/Networking/Model/Line.swift
1
2216
// // Created by Alex Lardschneider on 24/03/2017. // Copyright (c) 2017 SASA AG. All rights reserved. // import Foundation import UIKit import SwiftyJSON final class Line: JSONable, JSONCollection { let id: Int let days: Int let name: String let shortName: String let origin: String let destination: String let city: String let info: String fileprivate let zone: String let variants: [Int] required init(parameter: JSON) { id = parameter["id"].int ?? parameter["LI_NR"].intValue days = parameter["days"].intValue name = parameter["name"].string ?? parameter["LIDNAME"].stringValue shortName = parameter["LI_KUERZEL"].stringValue origin = parameter["origin"].stringValue destination = parameter["destination"].stringValue city = parameter["city"].stringValue info = parameter["info"].stringValue zone = parameter["zone"].stringValue variants = parameter["varlist"].arrayValue.map { $0.intValue } } init(shortName: String, name: String, variants: [Int], number: Int) { self.id = number self.name = name self.shortName = shortName self.variants = variants days = 0 origin = "" destination = "" city = "" info = "" zone = "" } static func collection(parameter: JSON) -> [Line] { var items: [Line] = [] for itemRepresentation in parameter.arrayValue { items.append(Line(parameter: itemRepresentation)) } return items } func getArea() -> String { let shortNameParts = shortName.characters.split { $0 == " " } switch String(shortNameParts[0]) { case "201": return "OTHER" case "248": return "OTHER" case "300": return "OTHER" case "5000": return "OTHER" case "227": return "ME" default: break } if shortNameParts.count > 1 { return String(shortNameParts[1]) } else { return "OTHER" } } }
gpl-3.0
bb2caf0e080260eceeb4c42e0f37048a
20.72549
75
0.551444
4.616667
false
false
false
false
keshavvishwkarma/KVRootBaseUniversalSideMenu
KVRootBaseSideMenu-Swift/KVRootBaseSideMenu-Swift/SideMenuViewController.swift
2
2474
// // SideMenuViwController.swift // KVRootBaseSideMenu-Swift // // Created by Keshav on 7/3/16. // Copyright © 2016 Keshav. All rights reserved. // public extension KVSideMenu { // Here define the roots identifier of side menus that must be connected from KVRootBaseSideMenuViewController // In Storyboard using KVCustomSegue static public let leftSideViewController = "LeftSideViewController" static public let rightSideViewController = "RightSideViewController" struct RootsIdentifiers { static public let initialViewController = "SecondViewController" // All roots viewcontrollers static public let firstViewController = "FirstViewController" static public let secondViewController = "SecondViewController" } } class SideMenuViewController: KVRootBaseSideMenuViewController { override func viewDidLoad() { super.viewDidLoad() // Configure The SideMenu leftSideMenuViewController = self.storyboard?.instantiateViewController(withIdentifier: KVSideMenu.leftSideViewController) rightSideMenuViewController = self.storyboard?.instantiateViewController(withIdentifier: KVSideMenu.rightSideViewController) // Set default root self.changeSideMenuViewControllerRoot(KVSideMenu.RootsIdentifiers.initialViewController) // Set freshRoot value to true/false according to your roots managment polity. By Default value is false. // If freshRoot value is ture then we will always create a new instance of every root viewcontroller. // If freshRoot value is ture then we will reuse already created root viewcontroller if exist otherwise create it. // self.freshRoot = true self.menuContainerView?.delegate = self } } extension SideMenuViewController: KVRootBaseSideMenuDelegate { func willOpenSideMenuView(_ sideMenuView: KVMenuContainerView, state: KVSideMenu.SideMenuState) { print(#function) } func didOpenSideMenuView(_ sideMenuView: KVMenuContainerView, state: KVSideMenu.SideMenuState){ print(#function) } func willCloseSideMenuView(_ sideMenuView: KVMenuContainerView, state: KVSideMenu.SideMenuState){ print(#function) } func didCloseSideMenuView(_ sideMenuView: KVMenuContainerView, state: KVSideMenu.SideMenuState){ print(#function) } }
mit
caed971458166f31234ce53c9684676c
33.347222
133
0.716539
5.329741
false
false
false
false
ahoppen/swift
test/Parse/pattern_without_variables.swift
11
1301
// RUN: %target-typecheck-verify-swift -parse-as-library let _ = 1 // expected-error{{global variable declaration does not bind any variables}} func foo() { let _ = 1 // OK } struct Foo { let _ = 1 // expected-error{{property declaration does not bind any variables}} var (_, _) = (1, 2) // expected-error{{property declaration does not bind any variables}} func foo() { let _ = 1 // OK } } // <rdar://problem/19786845> Warn on "let" and "var" when no data is bound in a pattern enum SimpleEnum { case Bar } func testVarLetPattern(a : SimpleEnum) { switch a { case let .Bar: break // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{8-12=}} } switch a { case let x: _ = x; break // Ok. } switch a { case let _: break // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{8-12=}} } switch (a, 42) { case let (_, x): _ = x; break // ok } // expected-warning @+1 {{'if' condition is always true}} if case let _ = "str" {} // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{11-15=}} } class SR10903 { static var _: Int { 0 } //expected-error {{getter/setter can only be defined for a single variable}} }
apache-2.0
2c5ed762f69bee692f2a6f971d01a304
29.255814
129
0.623367
3.47861
false
false
false
false
miroslavkovac/Lingo
Sources/Lingo/Pluralization/Common/OneTwoOther.swift
1
484
import Foundation /// Used for Cornish, Inari Sami, Inuktitut, Lule Sami, Nama, Northern Sami, Skolt Sami, Southern Sami class OneTwoOther: AbstractPluralizationRule { let availablePluralCategories: [PluralCategory] = [.one, .two, .other] func pluralCategory(forNumericValue n: UInt) -> PluralCategory { if n == 1 { return .one } if n == 2 { return .two } return .other } }
mit
db6ec70daf0bad6a91bda8dfd09144f2
23.2
102
0.570248
4.033333
false
false
false
false
eoger/firefox-ios
Shared/Prefs.swift
2
6869
/* 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 public struct PrefsKeys { public static let KeyLastRemoteTabSyncTime = "lastRemoteTabSyncTime" public static let KeyLastSyncFinishTime = "lastSyncFinishTime" public static let KeyDefaultHomePageURL = "KeyDefaultHomePageURL" public static let KeyNoImageModeStatus = "NoImageModeStatus" public static let KeyNightModeButtonIsInMenu = "NightModeButtonIsInMenuPrefKey" public static let KeyNightModeStatus = "NightModeStatus" public static let KeyMailToOption = "MailToOption" public static let HasFocusInstalled = "HasFocusInstalled" public static let HasPocketInstalled = "HasPocketInstalled" public static let IntroSeen = "IntroViewControllerSeen" //Activity Stream public static let KeyTopSitesCacheIsValid = "topSitesCacheIsValid" public static let KeyTopSitesCacheSize = "topSitesCacheSize" public static let KeyNewTab = "NewTabPrefKey" public static let ASPocketStoriesVisible = "ASPocketStoriesVisible" public static let ASRecentHighlightsVisible = "ASRecentHighlightsVisible" public static let ASBookmarkHighlightsVisible = "ASBookmarkHighlightsVisible" public static let ASLastInvalidation = "ASLastInvalidation" public static let KeyUseCustomSyncService = "useCustomSyncService" public static let KeyCustomSyncToken = "customSyncTokenServer" public static let KeyCustomSyncProfile = "customSyncProfileServer" public static let KeyCustomSyncOauth = "customSyncOauthServer" public static let KeyCustomSyncAuth = "customSyncAuthServer" public static let KeyCustomSyncWeb = "customSyncWebServer" public static let UseStageServer = "useStageSyncService" public static let AppExtensionTelemetryOpenUrl = "AppExtensionTelemetryOpenUrl" public static let AppExtensionTelemetryEventArray = "AppExtensionTelemetryEvents" } public struct PrefsDefaults { public static let ChineseHomePageURL = "http://mobile.firefoxchina.cn/" public static let ChineseNewTabDefault = "HomePage" } public protocol Prefs { func getBranchPrefix() -> String func branch(_ branch: String) -> Prefs func setTimestamp(_ value: Timestamp, forKey defaultName: String) func setLong(_ value: UInt64, forKey defaultName: String) func setLong(_ value: Int64, forKey defaultName: String) func setInt(_ value: Int32, forKey defaultName: String) func setString(_ value: String, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) func setObject(_ value: Any?, forKey defaultName: String) func stringForKey(_ defaultName: String) -> String? func objectForKey<T: Any>(_ defaultName: String) -> T? func boolForKey(_ defaultName: String) -> Bool? func intForKey(_ defaultName: String) -> Int32? func timestampForKey(_ defaultName: String) -> Timestamp? func longForKey(_ defaultName: String) -> Int64? func unsignedLongForKey(_ defaultName: String) -> UInt64? func stringArrayForKey(_ defaultName: String) -> [String]? func arrayForKey(_ defaultName: String) -> [Any]? func dictionaryForKey(_ defaultName: String) -> [String: Any]? func removeObjectForKey(_ defaultName: String) func clearAll() } open class MockProfilePrefs: Prefs { let prefix: String open func getBranchPrefix() -> String { return self.prefix } // Public for testing. open var things: NSMutableDictionary = NSMutableDictionary() public init(things: NSMutableDictionary, prefix: String) { self.things = things self.prefix = prefix } public init() { self.prefix = "" } open func branch(_ branch: String) -> Prefs { return MockProfilePrefs(things: self.things, prefix: self.prefix + branch + ".") } private func name(_ name: String) -> String { return self.prefix + name } open func setTimestamp(_ value: Timestamp, forKey defaultName: String) { self.setLong(value, forKey: defaultName) } open func setLong(_ value: UInt64, forKey defaultName: String) { setObject(NSNumber(value: value as UInt64), forKey: defaultName) } open func setLong(_ value: Int64, forKey defaultName: String) { setObject(NSNumber(value: value as Int64), forKey: defaultName) } open func setInt(_ value: Int32, forKey defaultName: String) { things[name(defaultName)] = NSNumber(value: value as Int32) } open func setString(_ value: String, forKey defaultName: String) { things[name(defaultName)] = value } open func setBool(_ value: Bool, forKey defaultName: String) { things[name(defaultName)] = value } open func setObject(_ value: Any?, forKey defaultName: String) { things[name(defaultName)] = value } open func stringForKey(_ defaultName: String) -> String? { return things[name(defaultName)] as? String } open func boolForKey(_ defaultName: String) -> Bool? { return things[name(defaultName)] as? Bool } open func objectForKey<T: Any>(_ defaultName: String) -> T? { return things[name(defaultName)] as? T } open func timestampForKey(_ defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } open func unsignedLongForKey(_ defaultName: String) -> UInt64? { return things[name(defaultName)] as? UInt64 } open func longForKey(_ defaultName: String) -> Int64? { return things[name(defaultName)] as? Int64 } open func intForKey(_ defaultName: String) -> Int32? { return things[name(defaultName)] as? Int32 } open func stringArrayForKey(_ defaultName: String) -> [String]? { if let arr = self.arrayForKey(defaultName) { if let arr = arr as? [String] { return arr } } return nil } open func arrayForKey(_ defaultName: String) -> [Any]? { let r: Any? = things.object(forKey: name(defaultName)) as Any? if r == nil { return nil } if let arr = r as? [Any] { return arr } return nil } open func dictionaryForKey(_ defaultName: String) -> [String: Any]? { return things.object(forKey: name(defaultName)) as? [String: Any] } open func removeObjectForKey(_ defaultName: String) { self.things.removeObject(forKey: name(defaultName)) } open func clearAll() { let dictionary = things as! [String: Any] let keysToDelete: [String] = dictionary.keys.filter { $0.hasPrefix(self.prefix) } things.removeObjects(forKeys: keysToDelete) } }
mpl-2.0
875ef1a303be5c9c5a2f705e10593ab7
36.12973
89
0.687582
4.58851
false
false
false
false
sugarso/WWDC
WWDC/PartyTableViewCell.swift
2
1827
// // PartyTableViewCell.swift // SFParties // // Created by Genady Okrain on 4/27/16. // Copyright © 2016 Okrain. All rights reserved. // import UIKit import PINRemoteImage class PartyTableViewCell: UITableViewCell { var party: Party? { didSet { if let party = party { iconImageView.image = nil iconImageView.pin_setImage(from: party.icon) hoursLabel.text = party.hours goingImageView.isHidden = !party.isGoing badgeView.isHidden = party.isOld titleLabel.text = party.title if party.promoted == true { backgroundColor = UIColor(red: 106.0/255.0, green: 118.0/255.0, blue: 220.0/255.0, alpha: 1.0) titleLabel.textColor = .white hoursLabel.textColor = UIColor(white: 1.0, alpha: 0.9) } else { backgroundColor = .white titleLabel.textColor = .black hoursLabel.textColor = UIColor(red: 171.0/255.0, green: 171.0/255.0, blue: 171.0/255.0, alpha: 1.0) } } } } override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) if party?.promoted == true { badgeView.backgroundColor = .white } else { badgeView.backgroundColor = UIColor(red: 106.0/255.0, green: 118.0/255.0, blue: 220.0/255.0, alpha: 1.0) } } @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var hoursLabel: UILabel! @IBOutlet weak var goingImageView: UIImageView! @IBOutlet weak var badgeView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var separatorView: UIView! }
mit
c190ccfda58f5488a06868b7416f9123
34.115385
119
0.582147
4.226852
false
false
false
false
swiftsocket/SwiftChatClient
AppleChat/ysocket.swift
2
6531
/* Copyright (c) <2014>, skysent All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by skysent. 4. Neither the name of the skysent 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 skysent ''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 skysent 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. */ import Foundation @asmname("ysocket_connect") func c_ysocket_connect(host:ConstUnsafePointer<Int8>,port:Int32,timeout:Int32) -> Int32 @asmname("ysocket_close") func c_ysocket_close(fd:Int32) -> Int32 @asmname("ysocket_send") func c_ysocket_send(fd:Int32,ConstUnsafePointer<UInt8>,len:Int32) -> Int32 @asmname("ysocket_pull") func c_ysocket_pull(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32) -> Int32 @asmname("ysocket_listen") func c_ysocket_listen(addr:ConstUnsafePointer<Int8>,port:Int32)->Int32 @asmname("ysocket_accept") func c_ysocket_accept(onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 class YSocket{ var addr:String var port:Int var fd:Int32? init(){ self.addr="" self.port=0 } init(addr a:String,port p:Int){ self.addr=a self.port=p } } class TCPClient:YSocket{ /* * connect to server * return success or fail with message */ func connect(timeout t:Int)->(Bool,String){ var rs:Int32=c_ysocket_connect(self.addr, Int32(self.port),Int32(t)) if rs>0{ self.fd=rs return (true,"connect success") }else{ switch rs{ case -1: return (false,"qeury server fail") case -2: return (false,"connection closed") case -3: return (false,"connect timeout") case -4: return (false,"server not available") default: return (false,"unknow err.") } } } /* * close socket * return success or fail with message */ func close()->(Bool,String){ if let fd:Int32=self.fd{ c_ysocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } /* * send data * return success or fail with message */ func send(data d:[UInt8])->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_ysocket_send(fd, d, Int32(d.count)) if Int(sendsize)==d.count{ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * send string * return success or fail with message */ func send(str s:String)->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_ysocket_send(fd, s, Int32(strlen(s))) if sendsize==Int32(strlen(s)){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * * send nsdata */ func send(data d:NSData)->(Bool,String){ if let fd:Int32=self.fd{ var buff:[UInt8] = [UInt8](count:d.length,repeatedValue:0x0) d.getBytes(&buff, length: d.length) var sendsize:Int32=c_ysocket_send(fd, buff, Int32(d.length)) if sendsize==Int32(d.length){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * read data with expect length * return success or fail with message */ func read(expectlen:Int)->[UInt8]?{ if let fd:Int32 = self.fd{ var buff:[UInt8] = [UInt8](count:expectlen,repeatedValue:0x0) var readLen:Int32=c_ysocket_pull(fd, &buff, Int32(expectlen)) var rs=buff[0...Int(readLen-1)] var data:[UInt8] = Array(rs) return data } return nil } } class TCPServer:YSocket{ func listen()->(Bool,String){ var fd:Int32=c_ysocket_listen(self.addr, Int32(self.port)) if fd>0{ self.fd=fd return (true,"listen success") }else{ return (false,"listen fail") } } func accept()->TCPClient?{ if let serferfd=self.fd{ var buff:[Int8] = [Int8](count:16,repeatedValue:0x0) var port:Int32=0 var clientfd:Int32=c_ysocket_accept(serferfd, &buff,&port) if clientfd<0{ return nil } var tcpClient:TCPClient=TCPClient() tcpClient.fd=clientfd tcpClient.port=Int(port) if let addr=String.stringWithUTF8String(buff){ tcpClient.addr=addr } return tcpClient } return nil } func close()->(Bool,String){ if let fd:Int32=self.fd{ c_ysocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } }
bsd-2-clause
7284d8f8762262c95344400e8beba9f5
32.152284
124
0.599143
3.967801
false
false
false
false
BGDigital/mcwa
mcwa/mcwa/rankinglistController.swift
1
11361
// // rankinglistController.swift // mcwa // // Created by XingfuQiu on 15/10/10. // Copyright © 2015年 XingfuQiu. All rights reserved. // import UIKit class rankinglistController: UITableViewController { let cellIdentifier = "rankinglistCell" var isFirstLoad = true var manager = AFHTTPRequestOperationManager() var page: PageInfo! var json: JSON! { didSet { if "ok" == self.json["state"].stringValue { page = PageInfo(j: self.json["dataObject", "list", "pageBean"]) if let d = self.json["dataObject", "list", "data"].array { if page.currentPage == 1 { // println("刷新数据") self.datasource = d } else { // println("加载更多") self.datasource = self.datasource + d } } //个人信息 self.user = self.json["dataObject", "user"] } } } var user: JSON? var datasource: Array<JSON>! = Array() { didSet { if self.datasource.count < page.allCount { self.tableView.footer.hidden = self.datasource.count < page.pageSize print("没有达到最大值 \(self.tableView.footer.hidden)") } else { print("最大值了,noMoreData") self.tableView.footer.endRefreshingWithNoMoreData() } self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "排行榜" self.view.layer.contents = UIImage(named: "other_bg")!.CGImage self.tableView.header = MJRefreshNormalHeader(refreshingBlock: {self.loadNewData()}) self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: {self.loadMoreData()}) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() loadNewData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadNewData() { //开始刷新 //http://221.237.152.39:8081/interface.do?act=rankList&userId=1&page=1 self.pleaseWait() let dict = ["act":"rankList", "userId": appUserIdSave, "page": 1] manager.GET(URL_MC, parameters: dict, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in //println(responseObject) self.isFirstLoad = false self.json = JSON(responseObject) self.tableView.header.endRefreshing() // self.hud?.hide(true) self.clearAllNotice() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in // println("Error: " + error.localizedDescription) self.tableView.header.endRefreshing() // self.hud?.hide(true) self.clearAllNotice() MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error) }) } func loadMoreData() { // println("开始加载\(self.page.currentPage+1)页") let dict = ["act":"rankList", "userId": appUserIdSave, "page": page.currentPage+1] //println("加载:\(self.liveType),\(self.liveOrder)======") //开始刷新 manager.GET(URL_MC, parameters: dict, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in //println(responseObject) self.json = JSON(responseObject) self.tableView.footer.endRefreshing() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in // println("Error: " + error.localizedDescription) self.tableView.footer.endRefreshing() MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error) }) } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if (!self.datasource.isEmpty) { self.tableView.backgroundView = nil return self.datasource.count } else { MCUtils.showEmptyView(self.tableView, aImg: UIImage(named: "empty_data")!, aText: "什么也没有,下拉刷新试试?") return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! rankinglistCell // Configure the cell let j = self.datasource[indexPath.row] as JSON cell.update(j) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 65 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if appUserLogined { return 56 } else { return 0 } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // var transform: CATransform3D // transform = CATransform3DMakeRotation(CGFloat((90.0*M_PI) / 180), 0.0, 0.7, 0.4) // transform.m34 = 1.0 / -600 // // cell.layer.shadowColor = UIColor.blackColor().CGColor // cell.layer.shadowOffset = CGSizeMake(10, 10) // cell.alpha = 0 // cell.layer.transform = transform // cell.layer.anchorPoint = CGPointMake(0, 0.5) // // UIView.beginAnimations("transform", context: nil) // UIView.setAnimationDuration(0.5) // cell.layer.transform = CATransform3DIdentity // cell.alpha = 1 // cell.layer.shadowOffset = CGSizeMake(0, 0) // cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height) // UIView.commitAnimations() //拉伸效果 cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1, 1, 1)}) } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if (self.user == nil) { return nil } else { if appUserLogined { let headView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 56)) headView.backgroundColor = UIColor(hexString: "#2C1B49") //我的排名前面那个No. let lb_no = UILabel(frame: CGRectMake(14, 8, 30, 17)) lb_no.textAlignment = .Center lb_no.font = UIFont(name: lb_no.font.fontName, size: 13) lb_no.textColor = UIColor.whiteColor() lb_no.text = "No." headView.addSubview(lb_no) //我的排名 let lb_rankNo = UILabel(frame: CGRectMake(12, 25, 33, 24)) lb_rankNo.textAlignment = .Center lb_rankNo.font = UIFont(name: lb_rankNo.font.fontName, size: 20) lb_rankNo.textColor = UIColor.whiteColor() lb_rankNo.text = self.user!["scoreRank"].stringValue headView.addSubview(lb_rankNo) //添加用户头像 let img_Avatar = UIImageView(frame: CGRectMake(56, 8, 40, 40)) let avater_Url = self.user!["headImg"].stringValue print(avater_Url) img_Avatar.yy_imageURL = NSURL(string: avater_Url) // img_Avatar.yy_setImageWithURL(NSURL(string: avater_Url)) img_Avatar.layer.masksToBounds = true img_Avatar.layer.cornerRadius = 20 headView.addSubview(img_Avatar) //添加用户名称 let lb_userName = UILabel(frame: CGRectMake(104, 18, 186, 21)) lb_userName.textColor = UIColor.whiteColor() lb_userName.text = "自己"//self.user!["nickName"].stringValue headView.addSubview(lb_userName) //添加用户分数 let lb_userSource = UILabel(frame: CGRectMake(tableView.bounds.size.width - 74, 18, 71, 21)) lb_userSource.textColor = UIColor.whiteColor() lb_userSource.textAlignment = .Center lb_userSource.text = self.user!["allScore"].stringValue+" 分" headView.addSubview(lb_userSource) return headView } else { return nil } } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Delete the row from the data source self.datasource.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func viewWillAppear(animated: Bool) { MobClick.beginLogPageView("rankinglistController") } override func viewWillDisappear(animated: Bool) { MobClick.endLogPageView("rankinglistController") } }
mit
85a15ed35f44bc5182c30b35337ca42b
39.086331
157
0.584261
4.820069
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/RocketChatViewController/Composer/Classes/Addons/Hints/HintsView.swift
1
5444
// // HintsView.swift // RocketChatViewController Example // // Created by Matheus Cardoso on 9/12/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit public protocol HintsViewDelegate: class { func numberOfHints(in hintsView: HintsView) -> Int func maximumHeight(for hintsView: HintsView) -> CGFloat func hintsView(_ hintsView: HintsView, cellForHintAt index: Int) -> UITableViewCell func title(for hintsView: HintsView) -> String? func hintsView(_ hintsView: HintsView, didSelectHintAt index: Int) } public extension HintsViewDelegate { func title(for hintsView: HintsView) -> String? { return "Suggestions" } func maximumHeight(for hintsView: HintsView) -> CGFloat { return 300 } } private final class HintsViewFallbackDelegate: HintsViewDelegate { func numberOfHints(in hintsView: HintsView) -> Int { return 0 } func hintsView(_ hintsView: HintsView, cellForHintAt index: Int) -> UITableViewCell { return UITableViewCell() } func hintsView(_ hintsView: HintsView, didSelectHintAt index: Int) { } } public class HintsView: UITableView { public weak var hintsDelegate: HintsViewDelegate? private var fallbackDelegate: HintsViewDelegate = HintsViewFallbackDelegate() private var currentDelegate: HintsViewDelegate { return hintsDelegate ?? fallbackDelegate } public override var contentSize: CGSize { didSet { invalidateIntrinsicContentSize() UIView.animate(withDuration: 0.2) { self.layoutIfNeeded() } } } public override var intrinsicContentSize: CGSize { if numberOfRows(inSection: 0) == 0 { return CGSize(width: contentSize.width, height: 0) } return CGSize(width: contentSize.width, height: min(contentSize.height, currentDelegate.maximumHeight(for: self))) } public init() { super.init(frame: .zero, style: .plain) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public func registerCellTypes(_ cellType: UITableViewCell.Type...) { cellType.forEach { register($0, forCellReuseIdentifier: "\($0)") } } public func dequeueReusableCell<T: UITableViewCell>(withType cellType: T.Type) -> T { let dequeue = { self.dequeueReusableCell(withIdentifier: "\(cellType)") as? T } if let cell = dequeue() { return cell } else { registerCellTypes(cellType) } if let cell = dequeue() { return cell } fatalError("[HintsView] Could not dequeue cell of type: '\(cellType)'") } /** Shared initialization procedures. */ private func commonInit() { NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: nil, queue: nil, using: { [weak self] _ in self?.beginUpdates() self?.endUpdates() }) dataSource = self delegate = self rowHeight = UITableViewAutomaticDimension estimatedRowHeight = 44 separatorInset = UIEdgeInsets( top: 0, left: 8, bottom: 0, right: 0 ) register( UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "header" ) addSubviews() setupConstraints() } /** Adds buttons and other UI elements as subviews. */ private func addSubviews() { } /** Sets up constraints between the UI elements in the composer. */ private func setupConstraints() { translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ ]) } } extension HintsView: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentDelegate.numberOfHints(in: self) } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = currentDelegate.hintsView(self, cellForHintAt: indexPath.row) cell.separatorInset = UIEdgeInsets( top: 0, left: 54, bottom: 0, right: 0 ) return cell } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return currentDelegate.title(for: self) } } extension HintsView: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) currentDelegate.hintsView(self, didSelectHintAt: indexPath.row) } public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let header = view as? UITableViewHeaderFooterView else { return } header.backgroundView?.backgroundColor = backgroundColor header.textLabel?.text = currentDelegate.title(for: self) header.textLabel?.textColor = #colorLiteral(red: 0.6196078431, green: 0.6352941176, blue: 0.6588235294, alpha: 1) } }
mit
e8901766d7459cdec9fe6867e76c87e2
27.952128
139
0.643395
4.984432
false
false
false
false
jalehman/twitter-clone
TwitterClient/AppDelegate.swift
1
3697
// // AppDelegate.swift // TwitterClient // // Created by Josh Lehman on 2/19/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController! var viewModel: AuthViewModel! var viewModelServices: ViewModelServices! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { navigationController = UINavigationController() viewModelServices = ViewModelServices(navigationController: navigationController) viewModel = AuthViewModel(services: viewModelServices) let viewController = AuthViewController(viewModel: viewModel) navigationController.pushViewController(viewController, animated: false) window = UIWindow(frame: UIScreen.mainScreen().bounds) window!.makeKeyAndVisible() window!.rootViewController = navigationController UINavigationBar.appearance().barTintColor = UIColor(red: 0.361, green: 0.686, blue: 0.925, alpha: 1) let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().titleTextAttributes = titleTextAttributes UINavigationBar.appearance().tintColor = UIColor.whiteColor() UIBarButtonItem.appearance().tintColor = UIColor.whiteColor() UIBarButtonItem.appearance().setTitleTextAttributes(titleTextAttributes, forState: UIControlState.Normal) UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false) 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:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { viewModelServices.twitterService.executeOpenURL.execute(url) return true } }
gpl-2.0
e89077270046fc922e3798b375dd33a5
47.012987
285
0.731945
5.991896
false
false
false
false
Pursuit92/antlr4
runtime/Swift/Antlr4/org/antlr/v4/runtime/LexerInterpreter.swift
3
3006
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ public class LexerInterpreter: Lexer { internal final var grammarFileName: String internal final var atn: ATN ////@Deprecated internal final var tokenNames: [String?]? internal final var ruleNames: [String] internal final var modeNames: [String] private final var vocabulary: Vocabulary? internal final var _decisionToDFA: [DFA] internal final var _sharedContextCache: PredictionContextCache = PredictionContextCache() // public override init() { // super.init()} // public convenience init(_ input : CharStream) { // self.init() // self._input = input; // self._tokenFactorySourcePair = (self, input); // } //@Deprecated public convenience init(_ grammarFileName: String, _ tokenNames: Array<String?>?, _ ruleNames: Array<String>, _ modeNames: Array<String>, _ atn: ATN, _ input: CharStream) throws { try self.init(grammarFileName, Vocabulary.fromTokenNames(tokenNames), ruleNames, modeNames, atn, input) } public init(_ grammarFileName: String, _ vocabulary: Vocabulary, _ ruleNames: Array<String>, _ modeNames: Array<String>, _ atn: ATN, _ input: CharStream) throws { self.grammarFileName = grammarFileName self.atn = atn self.tokenNames = [String?]() //new String[atn.maxTokenType]; let length = tokenNames!.count for i in 0..<length { tokenNames![i] = vocabulary.getDisplayName(i) } self.ruleNames = ruleNames self.modeNames = modeNames self.vocabulary = vocabulary self._decisionToDFA = [DFA]() //new DFA[atn.getNumberOfDecisions()]; let _decisionToDFALength = _decisionToDFA.count for i in 0..<_decisionToDFALength { _decisionToDFA[i] = DFA(atn.getDecisionState(i)!, i) } super.init() self._input = input self._tokenFactorySourcePair = (self, input) self._interp = LexerATNSimulator(self, atn, _decisionToDFA, _sharedContextCache) if atn.grammarType != ATNType.lexer { throw ANTLRError.illegalArgument(msg: "The ATN must be a lexer ATN.") } } override public func getATN() -> ATN { return atn } override public func getGrammarFileName() -> String { return grammarFileName } override ////@Deprecated public func getTokenNames() -> [String?]? { return tokenNames } override public func getRuleNames() -> [String] { return ruleNames } override public func getModeNames() -> [String] { return modeNames } override public func getVocabulary() -> Vocabulary { if vocabulary != nil { return vocabulary! } return super.getVocabulary() } }
bsd-3-clause
ecd8d2bcfeeaa1484596099fc3a6bb4d
29.06
183
0.630406
4.381924
false
false
false
false
prolificinteractive/Yoshi
Yoshi/Yoshi/Menus/YoshiDateSelectorMenu/YoshiDateSelectorMenuCellDataSource.swift
1
1349
// // YoshiDateSelectorMenuCellDataSource.swift // Yoshi // // Created by Kanglei Fang on 24/02/2017. // Copyright © 2017 Prolific Interactive. All rights reserved. // /// Cell data source defining the layout for YoshiDateSelectorMenu's cell struct YoshiDateSelectorMenuCellDataSource: YoshiReusableCellDataSource { private let title: String private let date: Date private var dateFormatter: DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short return dateFormatter } /// Intialize the YoshiDateSelectorMenuCellDataSource instance /// /// - Parameters: /// - title: Main title for the cell /// - date: Selected Date init(title: String, date: Date) { self.title = title self.date = date } func cellFor(tableView: UITableView) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier) cell.textLabel?.text = title cell.detailTextLabel?.text = dateFormatter.string(from: date) cell.accessoryType = .disclosureIndicator return cell } }
mit
f6d5630905984a3570dc166ab40ab6cc
28.955556
120
0.697329
5.048689
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/DesignPatterns/DesignPatterns/CMS/Manager.swift
1
908
// // Manager.swift // DesignPatterns // // Created by 朱双泉 on 2018/4/23. // Copyright © 2018 Castie!. All rights reserved. // import Foundation protocol ManagerInterface { var fixedSalary: Int? {set get} } class Manager: Employee { var fixedSalary: Int? override func two_stage_init() { fixedSalary = 8000 Employee.startNumber += 1 num = Employee.startNumber level = 1; print("请输入经理的姓名: ", terminator: "") name = scanf() } override func promote() { level! += 4 } override func calcSalary() { salary = Float(fixedSalary!) } override func disInfor() { print("姓名: \(name!)") print("工号: \(num!)") print("级别: \(level!)") print("本月结算的薪水: \(salary!)") print("========================") } }
mit
f3041a9426d6cb24694eef7ae236b1f3
18.976744
50
0.520373
3.767544
false
false
false
false
joerocca/GitHawk
Classes/Views/UIView+BottomBorder.swift
1
2086
// // UIView+BottomBorder.swift // Freetime // // Created by Ryan Nystrom on 5/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit extension UIView { public enum Position { case left case top case right case bottom } @discardableResult public func addBorder( _ position: Position, left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0, useSafeMargins: Bool = true ) -> UIView { let view = UIView() view.backgroundColor = Styles.Colors.Gray.border.color addSubview(view) view.snp.makeConstraints { make in let size = 1.0 / UIScreen.main.scale switch position { case .top, .bottom: make.height.equalTo(size) if useSafeMargins, #available(iOS 11.0, *) { make.left.equalTo(safeAreaLayoutGuide.snp.leftMargin).offset(left) make.right.equalTo(safeAreaLayoutGuide.snp.rightMargin).offset(right) } else { make.left.equalTo(left) make.right.equalTo(right) } case .left, .right: make.width.equalTo(size) make.top.equalTo(top) make.bottom.equalTo(bottom) } switch position { case .top: make.top.equalTo(self) case .bottom: make.bottom.equalTo(self) case .left: if useSafeMargins, #available(iOS 11.0, *) { make.left.equalTo(safeAreaLayoutGuide.snp.leftMargin) } else { make.left.equalTo(self) } case .right: if useSafeMargins, #available(iOS 11.0, *) { make.right.equalTo(safeAreaLayoutGuide.snp.rightMargin) } else { make.right.equalTo(self) } } } return view } }
mit
f33d012b32cadf88c52ed2e880de7f83
27.958333
89
0.509353
4.633333
false
false
false
false
Loannes/Swift3-OperationQueue
Swift3-OperationQueue/CustomQueue.swift
1
3660
// // SomeWork.swift // Swift3-OperationQueue // // Created by loannes on 2016. 12. 31.. // Copyright © 2016년 dev_sinu. All rights reserved. // import Foundation import UIKit class CustomQueue { let queue = OperationQueue() let container: UIView = UIView() let notiCenter = NotificationCenter.default init() { self.queue.maxConcurrentOperationCount = 1 self.notiCenter.addObserver(self, selector: #selector(startIndicator), name: NSNotification.Name(rawValue: "startIndicator"), object: nil) self.notiCenter.addObserver(self, selector: #selector(stopIndicator), name: NSNotification.Name(rawValue: "stopIndicator"), object: nil) } func addTask(task: @escaping () -> Void) { let operation = BlockOperation(block: { DispatchQueue.main.async(execute: { self.notiCenter.post(name: NSNotification.Name(rawValue: "startIndicator"), object: nil) UIApplication.shared.isNetworkActivityIndicatorVisible = true }) task() DispatchQueue.main.async(execute: { self.notiCenter.post(name: NSNotification.Name(rawValue: "stopIndicator"), object: nil) UIApplication.shared.isNetworkActivityIndicatorVisible = false }) Thread.sleep(forTimeInterval: 1.0) }) self.queue.addOperation(operation) } @objc func startIndicator() { if let rootView = UIApplication.shared.keyWindow?.rootViewController?.view! { container.frame = rootView.frame container.center = rootView.center container.alpha = 0.8 let loadingView: UIView = UIView() loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80) loadingView.center = rootView.center loadingView.backgroundColor = UIColor(netHex:0x000000) loadingView.alpha = 0.8 loadingView.clipsToBounds = true loadingView.layer.cornerRadius = 20 let actInd: UIActivityIndicatorView = UIActivityIndicatorView() actInd.frame = CGRect(x: 0, y: 0, width: 40, height: 40) actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge actInd.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2) loadingView.addSubview(actInd) container.addSubview(loadingView) rootView.addSubview(container) actInd.startAnimating() } } @objc func stopIndicator() { if let rootView = UIApplication.shared.keyWindow?.rootViewController?.view! { for view in rootView.subviews { if (view == container) { view.removeFromSuperview() } } } } } extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
mit
6ac84341589656136a340fd539d3dfc6
35.939394
116
0.573694
4.88251
false
false
false
false
wuleijun/Zeus
Zeus/ViewControllers/活动/AuthSignUserVC.swift
1
2365
// // AuthSignUserVC.swift // Zeus // // Created by 吴蕾君 on 16/5/9. // Copyright © 2016年 rayjuneWu. All rights reserved. // import UIKit /// 授权签到VC class AuthSignUserVC: BaseViewController { let relatedUserCellId = "MyRelatedUserCell" @IBOutlet weak var tableView: UITableView!{ didSet{ tableView.registerNib(UINib(nibName: relatedUserCellId, bundle: nil), forCellReuseIdentifier: relatedUserCellId) tableView.rowHeight = MyRelatedUserCell.heightOfCell() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func addSignUser_Touch(sender: AnyObject) { let chooseUserVC = UIViewController.controllerWith(storyboardName: "ChooseMemberVC", viewControllerId: "ChooseMemberVC") as! ChooseMemberVC navigationController?.pushViewController(chooseUserVC, animated: true) } } // MARK: TableView DataSource extension AuthSignUserVC : UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let signUserCell = tableView.dequeueReusableCellWithIdentifier(relatedUserCellId) as! MyRelatedUserCell signUserCell.cellType = RelatedUserCellType.Nomal return signUserCell } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { ZeusAlert.alertConfirmOrCancel(title: "提示", message: "确定要取消该用户的签到权限吗?", confirmTitle: "确定", cancelTitle: "取消", inViewController: self, withConfirmAction: { print("deleted") }, cancelAction: {}) } } } // MARK: TableView Delegate extension AuthSignUserVC : UITableViewDelegate { func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Delete } }
mit
2927f663291d903a97c0bd3fc915dec3
31.478873
167
0.697311
5.068132
false
false
false
false
dnseitz/YAPI
YAPI/YAPITests/YelpHTTPClientTests.swift
1
1624
// // YelpHTTPClientTests.swift // Chowroulette // // Created by Daniel Seitz on 7/29/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import XCTest @testable import YAPI class YelpHTTPClientTests: YAPIXCTestCase { var subject: YelpHTTPClient! let session = MockURLSession() override func setUp() { super.setUp() subject = YelpHTTPClient(session: session) } override func tearDown() { session.nextData = nil session.nextError = nil super.tearDown() } func test_Send_RequestsTheURL() { let url = URL(string: "http://yelp.com")! subject.send(url) { (_, _, _) -> Void in } XCTAssertNotNil(session.lastURL) XCTAssert(session.lastURL == url) } func test_Send_StartsTheRequest() { let dataTask = MockURLSessionDataTask() session.nextDataTask = dataTask subject.send(URL(fileURLWithPath: "")) { (_, _, _) -> Void in } XCTAssert(dataTask.resumeWasCalled) } func test_Send_WithResponseData_ReturnsTheData() { let expectedData = "{}".data(using: String.Encoding.utf8) session.nextData = expectedData var actualData: Data? subject.send(URL(fileURLWithPath: "")) { (data, _, _) -> Void in actualData = data } XCTAssertEqual(actualData, expectedData) } func test_Send_WithANetworkError_ReturnsANetworkError() { session.nextError = NSError(domain: "error", code: 0, userInfo: nil) var error: Error? subject.send(URL(fileURLWithPath: "")) { (_, _, theError) -> Void in error = theError } XCTAssertNotNil(error) } }
mit
2700a5bb7d8d446aa243acea414be497
22.521739
72
0.640173
4.077889
false
true
false
false
XeresRazor/SwiftNES
SwiftNES/ui/Texture.swift
1
3502
// // Texture.swift // SwiftNES // // Created by Articulate on 5/27/15. // Copyright (c) 2015 DigitalWorlds. All rights reserved. // import Cocoa import OpenGL let textureSize = 4096 let textureDim = textureSize / 256 let textureCount = textureDim * textureDim class Texture { var texture: UInt32 var lookup = [String: Int]() var reverse = Array<String>(count: textureCount, repeatedValue: "") var access = Array<Int>(count: textureCount, repeatedValue: -1) var counter: Int = 0 var ch: EBChannel = EBChannel(bufferCapacity: 1024) init() { let texture = createTexture() glBindTexture(GLenum(GL_TEXTURE_2D), texture) glTexImage2D(GLenum(GL_TEXTURE_2D), GLint(0), GLint(GL_RGBA), GLsizei(textureSize), GLsizei(textureSize), 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), nil) glBindTexture(GLenum(GL_TEXTURE_2D), 0) self.texture = texture } func purge() { while true { var path: AnyObject? let r = self.ch.tryRecv(&path) if r == .OK { let pathString = path as! String self.lookup.removeValueForKey(pathString) } else { return } } } func bind() { glBindTexture(GLenum(GL_TEXTURE_2D), self.texture) } func unbind() { glBindTexture(GLenum(GL_TEXTURE_2D), 0) } func lookup(path: String) -> (x: Float32, y: Float32, dx: Float32, dy: Float32) { if let index = self.lookup[path] { return self.coord(index) } else { return self.coord(self.load(path)) } } func mark(index: Int) { self.counter++ self.access[index] = self.counter } func lru() -> Int { var minIndex = 0 var minValue = self.counter + 1 for (i, n) in self.access.enumerate() { if n < minValue{ minIndex = i minValue = n } } return minIndex } func coord(index: Int) -> (x: Float32, y: Float32, dx: Float32, dy: Float32) { let x = Float32(index % textureDim) / Float32(textureDim) let y = Float32(index / textureDim) / Float32(textureDim) let dx = 1.0 / Float32(textureDim) let dy = dx * Float32(240) / Float32(256) return (x, y, dx, dy) } func load(path: String) -> Int { let index = self.lru() self.lookup.removeValueForKey(self.reverse[index]) self.mark(index) self.lookup[path] = index self.reverse[index] = path let x = Int32((index % textureDim) * 256) let y = Int32((index / textureDim) * 256) let im = self.loadThumbnail(path) let size = im.Rect.Size() glTexSubImage2D(GLenum(GL_TEXTURE_2D), 0, x, y, Int32(size.X), Int32(size.Y), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), im.Pix) return index } func loadThumbnail(romPath: String) -> RGBAImage { var name = romPath.lastPathComponent name = name.stringByDeletingPathExtension name = name.stringByReplacingOccurrencesOfString("_", withString: " ", options: .LiteralSearch, range: nil) name = name.capitalizedString let im = createGenericThumbnail(name) return im } func downloadThumbnail(romPath: String, hash: String) -> Bool { return false } }
mit
0bb6cbf736b859b77ec463cd7d4eac2f
28.931624
136
0.566819
3.865342
false
false
false
false
xylxi/AnimateCollection
SLStransform3DDemo/SLStransform3DDemo/SLMenuItem.swift
1
1918
// // SLMenuItem.swift // SLStransform3DDemo // // Created by WangZHW on 16/6/12. // Copyright © 2016年 RobuSoft. All rights reserved. // import UIKit let slmenuColors = [ UIColor(red: 249/255, green: 84/255, blue: 7/255, alpha: 1.0), UIColor(red: 69/255, green: 59/255, blue: 55/255, alpha: 1.0), UIColor(red: 249/255, green: 194/255, blue: 7/255, alpha: 1.0), UIColor(red: 32/255, green: 188/255, blue: 32/255, alpha: 1.0), UIColor(red: 207/255, green: 34/255, blue: 156/255, alpha: 1.0), UIColor(red: 14/255, green: 88/255, blue: 149/255, alpha: 1.0), UIColor(red: 15/255, green: 193/255, blue: 231/255, alpha: 1.0) ] class SLMenuItem { let title: String let symbol: String let color: UIColor init(symbol: String, color: UIColor, title: String) { self.symbol = symbol self.color = color self.title = title } class var sharedItems: [SLMenuItem] { struct Static { static let items = SLMenuItem.sharedMenuItems() } return Static.items } class func sharedMenuItems() -> [SLMenuItem] { var items = [SLMenuItem]() items.append(SLMenuItem(symbol: "☎︎", color: slmenuColors[0], title: "Phone book")) items.append(SLMenuItem(symbol: "✉︎", color: slmenuColors[1], title: "Email directory")) items.append(SLMenuItem(symbol: "♻︎", color: slmenuColors[2], title: "Company recycle policy")) items.append(SLMenuItem(symbol: "♞", color: slmenuColors[3], title: "Games and fun")) items.append(SLMenuItem(symbol: "✾", color: slmenuColors[4], title: "Training programs")) items.append(SLMenuItem(symbol: "✈︎", color: slmenuColors[5], title: "Travel")) items.append(SLMenuItem(symbol: "🃖", color: slmenuColors[6], title: "Etc.")) return items } }
mit
9d7cce6ba6faa928772232cac838e797
33.4
103
0.605708
3.239726
false
false
false
false
danielalves/megaman-ios
Megaman/NitroMath.swift
1
10229
/** * @file NitroMath.swift * * @brief Contains mathematical utilities for Swift * * @author Daniel L. Alves, copyright 2014 * * @since 04/06/2014 */ import Foundation /******************************************************* General functions *******************************************************/ /** * Linear interpolation. That is, calculates a value fitted between x and y, * given a percentage of the distance traveled between them. This version is * optmized for floating point values. To avoid conversions when using integer * values, use lerpi. * * @param percent How much of the distance between x and y have been traveled. 0.0f means * 0%, 1.0f means 100%. * @param x The starting point of the linear interpolation * @param y The ending point of the linear interpolation * * @return A value interpolated between x and y * * @see lerpi */ func lerp( percent: CFloat, x: CFloat, y: CFloat ) -> CFloat { return x + ( percent * ( y - x ) ) } /** * Linear interpolation. That is, calculates a value fitted between x and y, * given a percentage of the distance traveled between them. This version is * optmized for integer values. To avoid conversions when using floating point * values, use lerp. * * @param percent How much of the distance between x and y have been traveled. 0 means * 0%, 100 means 100%. * @param x The starting point of the linear interpolation * @param y The ending point of the linear interpolation * * @return A value interpolated between x and y * * @see lerp */ func lerpi( percent: CInt, x: CInt, y: CInt ) -> CInt { return x + (( percent * ( y - x )) / 100 ) } /** * Returns a value clamped between the interval [min, max]. That is, if the value is * lesser than min, the result is min. If the value is greater than max, the result is * max. This version is optmized for floating point values. To avoid conversions when * using integer values, use clampi. * * @param x The value to clamp * @param min The min boundary of the accepted interval * @param max The max boundary of the accepted interval * * @return A value clamped between the interval [min, max] * * @see clampi */ func clamp( x: CFloat, min: CFloat, max: CFloat ) -> CFloat { return x <= min ? min : ( x >= max ? max : x ) } /** * Returns a value clamped between the interval [min, max]. That is, if the value is * lesser than min, the result is min. If the value is greater than max, the result is * max. This version is optmized for integer values. To avoid conversions when using * floating point values, use clamp. * * @param x The value to clamp * @param min The min boundary of the accepted interval * @param max The max boundary of the accepted interval * * @return A value clamped between the interval [min, max] * * @see clamp */ func clampi( x: CInt, min: CInt, max: CInt ) -> CInt { return x <= min ? min : ( x >= max ? max : x ) } /** * Returns the luminance of a RGB color. The results will be incorrect if there are components * with values less than zero or greater than one. * * @param r The red component of the color * @param g The green component of the color * @param b The blue component of the color * * @return The luminance of the color * * @see luminancei */ func luminance( r: CFloat, g: CFloat, b: CFloat ) -> CFloat { return ( r * 0.299 ) + ( g * 0.587 ) + ( b * 0.114 ) } /** * Returns the luminance of a RGB color * * @param r The red component of the color * @param g The green component of the color * @param b The blue component of the color * * @return The luminance of the color * * @see luminance */ func luminancei( r: UInt8, g: UInt8, b: UInt8 ) -> UInt8 { return ( UInt8 )((( r * 76 ) + ( g * 150 ) + ( b * 29 )) / 255 ) } /******************************************************* Conversion functions *******************************************************/ /** * Converts degrees to radians * * @param degrees A value in degrees * * @return A value in radians * * @see radiansToDegrees */ func degreesToRadians( degrees: CFloat ) -> CFloat { return ( degrees * CFloat(M_PI) ) / 180.0 } /** * Converts radians to degrees * * @param radians A value in radians * * @return A value in degrees * * @see degreesToRadians */ func radiansToDegrees( radians: CFloat ) -> CFloat { return ( 180.0 * radians ) / CFloat(M_PI) } /******************************************************* Floating point numbers absolute error comparison utilities Although these functions are not suited for all floating point comparison cases, they will do fine many times. For a more in-depth discussion and other (way better) algorithms, see: - http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ - http://randomascii.wordpress.com/category/floating-point/ - http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm *******************************************************/ /** * Compares two floating point numbers, considering them different only if * the difference between them is greater than epsilon * * @return -1 if f1 is lesser than f2 * @return 0 if f1 and f2 are considered equal * @return 1 if f1 is greater than f2 * * @see fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fcmp_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Int8 { return fabsf( f1 - f2 ) <= epsilon ? 0 : ( f1 > f2 ? 1 : -1 ) } /** * Compares two floating point numbers, considering them different only if * the difference between them is greater than FLT_EPSILON * * @return -1 if f1 is lesser than f2 * @return 0 if f1 and f2 are considered equal * @return 1 if f1 is greater than f2 * * @see fcmp_e, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fcmp( f1: CFloat, f2: CFloat ) -> Int8 { return fcmp_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is equal to f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func feql_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) == 0 } /** * Returns if f1 is equal to f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func feql( f1: CFloat, f2: CFloat ) -> Bool { return feql_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is different from f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql_e, feql, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fdif_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) != 0 } /** * Returns if f1 is different from f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fdif( f1: CFloat, f2: CFloat ) -> Bool { return fdif_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is lesser than f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fltn_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) == -1 } /** * Returns if f1 is lesser than f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fltn( f1: CFloat, f2: CFloat ) -> Bool { return fltn_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is greater than f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fgtn_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) == 1 } /** * Returns if f1 is greater than f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fleq_e, fleq, fgeq_e, fgeq */ func fgtn( f1: CFloat, f2: CFloat ) -> Bool { return fgtn_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is lesser or equal to f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq, fgeq_e, fgeq */ func fleq_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) <= 0 } /** * Returns if f1 is lesser or equal to f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fgeq_e, fgeq */ func fleq( f1: CFloat, f2: CFloat ) -> Bool { return fleq_e( f1, f2: f2, epsilon: FLT_EPSILON ) } /** * Returns if f1 is greater or equal to f2. The numbers are considered different only if * the difference between them is greater than epsilon * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e, fgeq */ func fgeq_e( f1: CFloat, f2: CFloat, epsilon: CFloat ) -> Bool { return fcmp_e( f1, f2: f2, epsilon: epsilon ) >= 0 } /** * Returns if f1 is greater or equal to f2. The numbers are considered different only if * the difference between them is greater than FLT_EPSILON * * @see fcmp_e, fcmp, feql_e, feql, fdif_e, fdif, fltn_e, fltn, fgtn_e, fgtn, fleq_e, fleq, fgeq_e */ func fgeq( f1: CFloat, f2: CFloat ) -> Bool { return fgeq_e( f1, f2: f2, epsilon: FLT_EPSILON ) }
mit
f56dc49b51c8a6f6bf4ebc2feffaf586
36.606618
128
0.656565
2.935151
false
false
false
false
grantmagdanz/InupiaqKeyboard
Keyboard/DefaultKeyboard.swift
1
3216
// // DefaultKeyboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Updated by Grant Magdanz on 9/24/15. // Copyright (c) 2015 Apple. All rights reserved. // import Foundation func defaultKeyboard() -> Keyboard { let defaultKeyboard = Keyboard() for pageNum in 0...2 { for rowNum in 0...3 { let row = NSLocalizedString("page\(pageNum)_row\(rowNum)", comment: "Row number\(rowNum) in page \(pageNum)").characters.split{$0 == " "}.map(String.init) for key in row { // split on commas to get extra characters for that key var charactersForKey = [key]; if key.characters.count > 1 { charactersForKey = key.characters.split{$0 == ","}.map(String.init) } let keyModel: Key if pageNum == 0 { // the first page contains all the letters which are .Character Keys keyModel = makeKey(charactersForKey[0], special: false) } else { // all other characters on other pages are .SpecialCharacter Keys keyModel = makeKey(charactersForKey[0], special: true) } keyModel.extraCharacters = charactersForKey defaultKeyboard.addKey(keyModel, row: rowNum, page: pageNum) } } } return defaultKeyboard } /* Given a value of a key, returns a Key object of the correct type. */ private func makeKey(let value: String, let special: Bool) -> Key { let keyType = Key.KeyType(rawValue: value) if keyType == nil { // This is not a special key (i.e. it types a character) let key: Key if !special { key = Key(.Character) } else { key = Key(.SpecialCharacter) } key.setLetter(value) return key } switch keyType! { case .LetterChange: let key = Key(.LetterChange) key.uppercaseKeyCap = NSLocalizedString("alphabet_change", comment: "The label of the button to switch to letters.") key.toMode = 0 return key case .NumberChange: let key = Key(.NumberChange) key.uppercaseKeyCap = NSLocalizedString("number_change", comment: "The label of the button to switch to numbers and symbols.") key.toMode = 1 return key; case .SpecialCharacterChange: let key = Key(.SpecialCharacterChange) key.uppercaseKeyCap = NSLocalizedString("symbol_change", comment: "The label of the button to switch to extra symbols.") key.toMode = 2 return key case .Space: let key = Key(.Space) key.uppercaseKeyCap = NSLocalizedString("space", comment: "The label of the space button.") key.uppercaseOutput = " " key.lowercaseOutput = " " return key case .Return: let key = Key(.Return) key.uppercaseKeyCap = NSLocalizedString("return", comment: "The label of the return button") key.uppercaseOutput = "\n" key.lowercaseOutput = "\n" return key default: return Key(keyType!) } }
bsd-3-clause
42c8f49d5cc88b9a9cb4478fc2cf35ab
35.545455
166
0.58551
4.62069
false
false
false
false
slekens/BR
BR-AAS/BR-AAS/AccountsPresenter.swift
1
2195
// // AccountsPresenter.swift // BR-AAS // // Created by Abraham Abreu on 04/07/17. // Copyright © 2017 Abraham Abreu. All rights reserved. // import Foundation import UIKit import SwiftyJSON protocol AccountsView : NSObjectProtocol { func startLoading() func finishLoading() func setAccounts(accounts:[Accounts]) func setTransactions(transactions:[Transactions]) } class AccountsPresenter : WSCallerDelegate { var wsCaller : WSCaller = WSCaller() weak fileprivate var accountsView : AccountsView? func attachView(_ view:AccountsView){ accountsView = view } func detachView() { accountsView = nil } func getAccounts() { wsCaller.delegate = self wsCaller.getAccounts(token: Persistance().getToken()) accountsView?.startLoading() } func getTransactions(id: String) { wsCaller.delegate = self wsCaller.getTransactions(token: Persistance().getToken(), id: id) accountsView?.startLoading() } func didReceiveData(data: Data, ws: WS) { if(ws == WS.WSAccounts) { let jsonData = JSON(data) var accounts : [Accounts] = [Accounts()] let arrayAccounts = jsonData["accounts"] for account in arrayAccounts { let acc: Accounts = Accounts() let val = account.1 acc.card_number = val["card_number"].stringValue acc.balance = val["balance"].stringValue acc.account_number = val["account_number"].stringValue acc.id = val["id"].stringValue acc.is_credit = val["is_credit_card"].bool accounts.append(acc) } accountsView?.setAccounts(accounts: accounts) } if(ws == WS.WSTransactions) { let jsonData = JSON(data) print("Data \(jsonData)") } accountsView?.finishLoading() } func didReceiveError(error: Error) { accountsView?.finishLoading() } }
mit
d3f62c69e49a7e5fc180cc777cc9abd1
24.218391
73
0.559708
4.800875
false
false
false
false
dankogai/swift-prime
OSX.playground/Pages/PrimeFactorization.xcplaygroundpage/Contents.swift
1
1273
//: [Previous](@previous) /*: ## Inside prime.swift : Prime Factorization Prime factorization is much harder than primarity test. prime.swift does so as follows. 0. Simple trial division up for `UInt.Prime.tinyPrimes` -- primes less than 2048 0. [Pollard's rho] up to `sqrt(UInt32.max)` 0. [SQUFOF] as a last resort. [Pollard's rho]: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm [SQUFOF]: http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization Because [SQUFOF] is naively implemented within 64-bit signed integer limit (for the time being), it is good only up to `Int.max`. Numbers like multiples of primes near `UInt32.max` fails to factor. In such cases, `.primeFactors` prepend `1` to the result so the axiom: n.primeFactor.reduce(1,combine:*) == n still holds. */ // this one factors nicely. let i32pmax0 = Int(Int32.max).prevPrime let i32pmax1 = i32pmax0.prevPrime (i32pmax1*i32pmax0).primeFactors // this one does not. let u32pmax0 = UInt(UInt32.max).prevPrime let u32pmax1 = u32pmax0.prevPrime (u32pmax1*u32pmax0).primeFactors /*: Since prime.swift only covers 64-bit integers and `UInt` is rarely used in Swift, this should be good enough. To go beyound that we need BigInt support to begin with... */ //: [Next](@next)
mit
7f978614653048e6ce17bfed1bf03079
30.825
198
0.736842
3.104878
false
false
false
false
jmgc/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift
1
7277
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5ValueVys4Int8VGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi8_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys4Int8VGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$ss4Int8VN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVys5UInt8VGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi8_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys5UInt8VGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$ss5UInt8VN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySSGWV" = linkonce_odr hidden constant %swift.vwtable { // CHECK-SAME: i8* bitcast ({{.+}}$s4main5ValueVySSGwCP{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwxx{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwcp{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwca{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwta{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwet{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSGwst{{[^[:space:]]+ to i8\*}}), // CHECK-SAME: [[INT]] {{[0-9]+}}, // CHECK-SAME: [[INT]] {{[0-9]+}}, // CHECK-SAME: i32 {{[0-9]+}}, // CHECK-SAME: i32 {{[0-9]+}} // CHECK-SAME: }, // NOTE: ignore COMDAT on PE/COFF target // CHECK-SAME: align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySSGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSSN", i32 0{{(, \[4 x i8\] zeroinitializer)?}}, i64 3 }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySdGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sBi64_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySdGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSdN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Value<First> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySdGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySSGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys5UInt8VGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys4Int8VGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) consume( Value(first: 13.0) ) consume( Value(first: "13") ) consume( Value(first: 13 as UInt8) ) consume( Value(first: 13 as Int8) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), [[INT]]* @"$s4main5ValueVMz") #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
690dcee5733584bbe921ea386d0b95fd
55.851563
338
0.596262
3.048597
false
false
false
false
Nakama-Project/nakama-ios
nakama-ios/Controllers/HPViewController.swift
1
3320
// // HPViewController.swift // nakama-ios // // Created by Stephen Wong on 1/24/16. // Copyright © 2016 Nakama Project. All rights reserved. // import UIKit import Cartography import ObjectiveDDP private let websocketReadyKey = "websocketReady" class HPViewController: UIViewController { let meteor: MeteorClient let nakamaLabel = UILabel() let hpLabel = UILabel() let ghostImage = UIImageView() private var nakama: M13MutableOrderedDictionary! // MARK: Init init(meteorClient: MeteorClient) { meteor = meteorClient super.init(nibName: nil, bundle: nil) nakama = meteor.collections["hp"] as? M13MutableOrderedDictionary } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Lifecycle override func viewWillAppear(animated: Bool) { let observingOption = NSKeyValueObservingOptions.New meteor.addObserver(self, forKeyPath: websocketReadyKey, options: observingOption, context: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNakamaUpdate:", name: "hp_added", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveHPUpdate:", name: "hp_changed", object: nil) } override func viewDidLoad() { super.viewDidLoad() setupNakamaTest() } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == websocketReadyKey && meteor.websocketReady { print("Websocket is ready") } } // MARK: Notification Handlers dynamic private func didReceiveNakamaUpdate(notification: NSNotification) { // TODO: Figure out when meteor collections actually update so I don't have to do this check if nakama == nil { nakama = meteor.collections["hp"] as? M13MutableOrderedDictionary } guard let newNakama = nakama[0]["nakama"] as? String else { return } nakamaLabel.text = newNakama guard let newHP = nakama[0]["hp"] as? Int else { return } hpLabel.text = "\(newHP)" } dynamic private func didReceiveHPUpdate(notification: NSNotification) { guard let newHP = nakama[0]["hp"] as? Int else { return } hpLabel.text = "\(newHP)" } private func setupNakamaTest() { nakamaLabel.text = "Hello" view.addSubview(nakamaLabel) constrain(nakamaLabel, view) { nakamaLabel, view in nakamaLabel.center == view.center } hpLabel.text = "-1" view.addSubview(hpLabel) constrain(hpLabel, nakamaLabel) { hpLabel, nakamaLabel in hpLabel.centerX == nakamaLabel.centerX hpLabel.top == nakamaLabel.bottom + 40 } ghostImage.image = UIImage(named: "gengar") view.addSubview(ghostImage) constrain(ghostImage, view) { ghostImage, view in ghostImage.centerX == view.centerX } constrain(ghostImage, nakamaLabel) { ghostImage, nakamaLabel in ghostImage.bottom == nakamaLabel.top - 40 } } }
mit
1da8e43f2b074a1c30843196456413f9
32.525253
157
0.641458
4.425333
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Internals/Audio File/AKAudioFile+Utilities.swift
2
4817
// // AKAudioFile+Utilities.swift // AudioKit For iOS // // Created by Laurent Veliscek on 7/4/16. // Copyright © 2016 AudioKit. All rights reserved. // // // import Foundation import AVFoundation extension AKAudioFile { /// returns file Mime Type if exists /// Otherwise, returns nil /// (useful when sending an AKAudioFile by email) public var mimeType: String? { switch self.fileExt.uppercaseString { case "WAV": return "audio/wav" case "CAF": return "audio/x-caf" case "AIF", "AIFF", "AIFC": return "audio/aiff" case "M4R": return "audio/x-m4r" case "M4A": return "audio/x-m4a" case "MP4": return "audio/mp4" case "M2A", "MP2": return "audio/mpeg" case "AAC": return "audio/aac" case "MP3": return "audio/mpeg3" default: return nil } } /// Static function to delete all audiofiles from Temp directory /// /// AKAudioFile.cleanTempDirectory() /// public static func cleanTempDirectory() { var deletedFilesCount = 0 let fileManager = NSFileManager.defaultManager() let tempPath = NSTemporaryDirectory() do { let fileNames = try fileManager.contentsOfDirectoryAtPath("\(tempPath)") // function for deleting files func deleteFileWithFileName(fileName: String) { let filePathName = "\(tempPath)/\(fileName)" do { try fileManager.removeItemAtPath(filePathName) print("\"\(fileName)\" deleted.") deletedFilesCount += 1 } catch let error as NSError { print("Couldn't delete \(fileName) from Temp Directory") print("Error: \(error)") } } // Checks file type (only Audio Files) for fileName in fileNames { let fileNameLowerCase = fileName.lowercaseString if fileNameLowerCase.hasSuffix(".wav") { deleteFileWithFileName(fileName) } if fileNameLowerCase.hasSuffix(".caf") { deleteFileWithFileName(fileName) } if fileNameLowerCase.hasSuffix(".aif") { deleteFileWithFileName(fileName) } if fileNameLowerCase.hasSuffix(".mp4") { deleteFileWithFileName(fileName) } if fileNameLowerCase.hasSuffix(".m4a") { deleteFileWithFileName(fileName) } } // print report switch deletedFilesCount { case 0: print("AKAudioFile.cleanTempDirectory: No file deleted.") case 1: print("AKAudioFile.cleanTempDirectory: \(deletedFilesCount) File deleted.") default: print("AKAudioFile.cleanTempDirectory: \(deletedFilesCount) Files deleted.") } } catch let error as NSError { print("Couldn't access Temp Directory") print("Error: \(error)") } } /// Returns a silent AKAudioFile with a length set in samples. /// /// For a silent file of one second, set samples value to 44100... /// /// - Parameters: /// - samples: the number of samples to generate (equals length in seconds multiplied by sample rate) /// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp /// - name: the name of the file without its extension (String). /// /// - Returns: An AKAudioFile, or nil if init failed. /// static public func silent(samples samples: Int64, baseDir: BaseDirectory = .Temp, name: String = "") throws -> AKAudioFile { if samples < 0 { print( "ERROR AKAudioFile: cannot create silent AKAUdioFile with negative samples count !") throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo:nil) } else if samples == 0 { let emptyFile = try AKAudioFile(writeIn: baseDir, name: name) // we return it as a file for reading return try AKAudioFile(forReading: emptyFile.url) } let array = [Float](zeroes:Int(samples)) let silentFile = try AKAudioFile(createFileFromFloats: [array, array], baseDir: baseDir, name: name) return try AKAudioFile(forReading: silentFile.url) } }
mit
46a2d3b6e906fe4ac6e92ad5f4fd66ca
34.411765
108
0.540075
5.189655
false
false
false
false
roambotics/swift
test/Interop/Cxx/operators/member-inline-typechecker.swift
2
2426
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop import MemberInline var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs - rhs lhs += rhs let resultCall0 = lhs() let resultCall1 = lhs(1) let resultCall2 = lhs(1, 2) var boolWrapper = LoadableBoolWrapper(value: true) let notBoolResult = !boolWrapper var addressOnly = AddressOnlyIntWrapper(42) let addressOnlyResultCall0 = addressOnly() let addressOnlyResultCall1 = addressOnly(1) let addressOnlyResultCall2 = addressOnly(1, 2) var readWriteIntArray = ReadWriteIntArray() readWriteIntArray[2] = 321 let readWriteValue = readWriteIntArray[2] var readOnlyIntArray = ReadOnlyIntArray(3) let readOnlyValue = readOnlyIntArray[1] var writeOnlyIntArray = WriteOnlyIntArray() writeOnlyIntArray[2] = 654 let writeOnlyValue = writeOnlyIntArray[2] var readOnlyRvalueParam = ReadOnlyRvalueParam() let readOnlyRvalueVal = readOnlyRvalueParam[1] // expected-error {{value of type 'ReadOnlyRvalueParam' has no subscripts}} var readWriteRvalueParam = ReadWriteRvalueParam() let readWriteRvalueVal = readWriteRvalueParam[1] // expected-error {{value of type 'ReadWriteRvalueParam' has no subscripts}} var readWriteRvalueGetterParam = ReadWriteRvalueGetterParam() let readWriteRvalueGetterVal = readWriteRvalueGetterParam[1] var diffTypesArray = DifferentTypesArray() let diffTypesResultInt: Int32 = diffTypesArray[0] let diffTypesResultDouble: Double = diffTypesArray[0.5] var nonTrivialIntArrayByVal = NonTrivialIntArrayByVal(3) let nonTrivialValueByVal = nonTrivialIntArrayByVal[1] var diffTypesArrayByVal = DifferentTypesArrayByVal() let diffTypesResultIntByVal: Int32 = diffTypesArrayByVal[0] let diffTypesResultDoubleByVal: Double = diffTypesArrayByVal[0.5] let postIncrement = HasPostIncrementOperator() postIncrement.successor() // expected-error {{value of type 'HasPostIncrementOperator' has no member 'successor'}} let anotherReturnType = HasPreIncrementOperatorWithAnotherReturnType() let anotherReturnTypeResult: HasPreIncrementOperatorWithAnotherReturnType = anotherReturnType.successor() let voidReturnType = HasPreIncrementOperatorWithVoidReturnType() let voidReturnTypeResult: HasPreIncrementOperatorWithVoidReturnType = voidReturnType.successor() let immortalIncrement = myCounter.successor() // expected-error {{value of type 'ImmortalCounter' has no member 'successor'}}
apache-2.0
d9ca71dcf1c69d788647e9a4795398ea
37.507937
125
0.821517
3.925566
false
false
false
false
JesusAntonioGil/Design-Patterns-Swift-2
CreationalPatterns/AbstractFactoryPattern/AbstractFactoryPattern/Model/ProtocolsAndEnums.swift
1
1037
// // ProtocolsAndEnums.swift // AbstractFactoryPattern // // Created by Jesus Antonio Gil on 17/12/15. // Copyright © 2015 Jesus Antonio Gil. All rights reserved. // import UIKit //MARK: ENUMS enum MaterialType: String { case Aluminium = "Aluminium", StainlessSteel = "Stainless Steel", Gold = "Gold" } enum BandType: String { case Milanese = "Milanese", Classic = "Classic", Leather = "Leather", Modern = "Modern", LinkBracelet = "LinkBracelet", SportBand = "SportBand" } enum WatchSize: String { case _38mm = "38mm", _42mm = "42mm" } enum BandSize: String { case SM = "SM", ML = "ML" } //MARK: PROTOCOLS protocol iWatchBand { var color: UIColor {get set} var size: BandSize {get set} var type: BandType {get set} init(size:BandSize) } protocol iWatchDial { var material: MaterialType {get set} var size: WatchSize {get set} init (size:WatchSize) }
mit
df166d6b35bacf2092e2e8663615e6de
13.388889
60
0.584942
3.278481
false
false
false
false
PJayRushton/stats
Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/KaedeTextField.swift
4
5309
// // KaedeTextField.swift // Swish // // Created by Raúl Riera on 20/01/2015. // Copyright (c) 2015 com.raulriera.swishapp. All rights reserved. // import UIKit /** A KaedeTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the foreground of the control. */ @IBDesignable open class KaedeTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor? { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.8 { didSet { updatePlaceholder() } } /** The view’s foreground color. The default value for this property is a clear color. */ @IBInspectable dynamic open var foregroundColor: UIColor? { didSet { updateForegroundColor() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { drawViewsForRect(bounds) } } private let foregroundView = UIView() private let placeholderInsets = CGPoint(x: 10, y: 5) private let textFieldInsets = CGPoint(x: 10, y: 0) // MARK: - TextFieldEffects override open func drawViewsForRect(_ rect: CGRect) { let frame = CGRect(origin: .zero, size: CGSize(width: rect.size.width, height: rect.size.height)) foregroundView.frame = frame foregroundView.isUserInteractionEnabled = false placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateForegroundColor() updatePlaceholder() if text!.isNotEmpty || isFirstResponder { animateViewsForTextEntry() } addSubview(foregroundView) addSubview(placeholderLabel) } override open func animateViewsForTextEntry() { let directionOverride: CGFloat if #available(iOS 9.0, *) { directionOverride = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft ? -1.0 : 1.0 } else { directionOverride = 1.0 } UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .beginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = CGPoint(x: self.frame.size.width * 0.65 * directionOverride, y: self.placeholderInsets.y) }), completion: nil) UIView.animate(withDuration: 0.45, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.5, options: .beginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPoint(x: self.frame.size.width * 0.6 * directionOverride, y: 0) }), completion: { _ in self.animationCompletionHandler?(.textEntry) }) } override open func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .beginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = self.placeholderInsets }), completion: nil) UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2.0, options: .beginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPoint.zero }), completion: { _ in self.animationCompletionHandler?(.textDisplay) }) } } // MARK: - Private private func updateForegroundColor() { foregroundView.backgroundColor = foregroundColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { var frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height)) if #available(iOS 9.0, *) { if UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft { frame.origin = CGPoint(x: bounds.size.width - frame.size.width, y: frame.origin.y) } } return frame.insetBy(dx: textFieldInsets.x, dy: textFieldInsets.y) } override open func textRect(forBounds bounds: CGRect) -> CGRect { return editingRect(forBounds: bounds) } }
mit
4a8e4f5bfb6f82d71f162dbf9a94e976
33.679739
177
0.645496
4.86789
false
false
false
false
KimpossibleG/billfold
BillFoldApp/BillFold/BillFold/TotalViewController.swift
1
3603
// // TotalViewController.swift // BillFold // // Created by Rick Dsida on 7/6/14. // Copyright (c) 2014 Michael Pourhadi. All rights reserved. // import UIKit class TotalViewController: UITableViewController { var cellArray = NSMutableArray() init(style: UITableViewStyle) { super.init(style: style) // Custom initialization } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func viewDidAppear(animated: Bool){ self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // delete item from specific user override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if (editingStyle == UITableViewCellEditingStyle.Delete) { var foodItem = sharedDinerStorage.dinerList[indexPath.section].foodItems[indexPath.row] foodItem.counter -= 1 sharedDinerStorage.dinerList[indexPath.section].foodItems.removeAtIndex(indexPath.row) } tableView.reloadData() } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return sharedDinerStorage.dinerList.count } override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String { tableView.sectionHeaderHeight = 55 var currentDiner = sharedDinerStorage.dinerList[section].name var totalOwed = sharedDinerStorage.dinerList[section].totalOwed var nameAndTotal = "\(currentDiner) — Owes: $\(totalOwed)" return nameAndTotal as String } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return sharedDinerStorage.dinerList[section].foodItems.count } override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? { var totalCell = tableView!.dequeueReusableCellWithIdentifier("dinerAndTotal", forIndexPath: indexPath) as UITableViewCell let specificDiner = sharedDinerStorage.dinerList[indexPath.section] let specificFoodItem = specificDiner.foodItems[indexPath.row].food as String let specificFoodPrice = specificDiner.foodItems[indexPath.row].price as NSString let price = specificFoodPrice.doubleValue let foodCount = specificDiner.foodItems[indexPath.row].counter let yourSplit = price/Double(foodCount) let total = floor(yourSplit * 100)/100 totalCell.textLabel.text = "Total = \(specificDiner.totalOwed)" totalCell.text = specificFoodItem totalCell.detailTextLabel!.text = "Cost: $\(total)" return totalCell } }
mit
eeb8aeaa76fa02e800c571e78d377500
37.308511
159
0.69203
5.188761
false
false
false
false
imkevinxu/Spring
Spring/SpringView.swift
1
2962
// // SpringView.swift // https://github.com/MengTo/Spring // // 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 public class SpringView: UIView, Springable { // MARK: Advanced Values @IBInspectable public var animation: String = "" @IBInspectable public var curve: String = "" @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var force: CGFloat = 1 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var rotateDegrees: CGFloat = 0 @IBInspectable public var repeatCount: Float = 1 // MARK: Basic Values @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring: Spring = Spring(self) // MARK: - View Lifecycle override public func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } override public func didMoveToWindow() { super.didMoveToWindow() self.spring.customDidMoveToWindow() } // MARK: - Animation Methods public func animate() { self.spring.animate() } public func animateNext(completion: () -> ()) { self.spring.animateNext(completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: () -> ()) { self.spring.animateToNext(completion) } }
mit
4b28f07cc5134b93472b1d9caa13bad0
33.057471
82
0.699527
4.508371
false
false
false
false
xivol/Swift-CS333
playgrounds/graphics/NewtonsCradle.playground/Sources/NewtonsCradle.swift
3
7237
import UIKit import PlaygroundSupport public class NewtonsCradle: UIView { private let colors: [UIColor] private var balls: [UIView] = [] private var animator: UIDynamicAnimator? private var ballsToAttachmentBehaviors: [UIView:UIAttachmentBehavior] = [:] private var snapBehavior: UISnapBehavior? public let collisionBehavior: UICollisionBehavior public let gravityBehavior: UIGravityBehavior public let itemBehavior: UIDynamicItemBehavior public init(colors: [UIColor]) { self.colors = colors collisionBehavior = UICollisionBehavior(items: []) gravityBehavior = UIGravityBehavior(items: []) itemBehavior = UIDynamicItemBehavior(items: []) super.init(frame: CGRect(x: 0, y: 0, width: 480, height: 320)) backgroundColor = UIColor.white animator = UIDynamicAnimator(referenceView: self) animator?.addBehavior(collisionBehavior) animator?.addBehavior(gravityBehavior) animator?.addBehavior(itemBehavior) createBallViews() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { for ball in balls { ball.removeObserver(self, forKeyPath: "center") } } // MARK: Ball Views func createBallViews() { for color in colors { let ball = UIView(frame: CGRect.zero) // Observe the center point of the ball view to draw the attachment behavior. ball.addObserver(self, forKeyPath: "center", options: NSKeyValueObservingOptions.init(rawValue: 0), context: nil) // Make the ball view round and set the background ball.backgroundColor = color // Add the balls as a subview before we add it to any UIDynamicBehaviors. addSubview(ball) balls.append(ball) // Layout the balls based on the ballSize and ballPadding. layoutBalls() } } // MARK: Properties public var attachmentBehaviors:[UIAttachmentBehavior] { get { var attachmentBehaviors: [UIAttachmentBehavior] = [] for ball in balls { guard let attachmentBehavior = ballsToAttachmentBehaviors[ball] else { fatalError("Can't find attachment behavior for \(ball)") } attachmentBehaviors.append(attachmentBehavior) } return attachmentBehaviors } } public var useSquaresInsteadOfBalls:Bool = false { didSet { for ball in balls { if useSquaresInsteadOfBalls { ball.layer.cornerRadius = 0 } else { ball.layer.cornerRadius = ball.bounds.width / 2.0 } } } } public var ballSize: CGSize = CGSize(width: 50, height: 50) { didSet { layoutBalls() } } public var ballPadding: Double = 0.0 { didSet { layoutBalls() } } // MARK: Ball Layout private func layoutBalls() { let requiredWidth = CGFloat(balls.count) * (ballSize.width + CGFloat(ballPadding)) for (index, ball) in balls.enumerated() { // Remove any attachment behavior that already exists. if let attachmentBehavior = ballsToAttachmentBehaviors[ball] { animator?.removeBehavior(attachmentBehavior) } // Remove the ball from the appropriate behaviors before update its frame. collisionBehavior.removeItem(ball) gravityBehavior.removeItem(ball) itemBehavior.removeItem(ball) // Determine the horizontal position of the ball based on the number of balls. let ballXOrigin = ((bounds.width - requiredWidth) / 2.0) + (CGFloat(index) * (ballSize.width + CGFloat(ballPadding))) ball.frame = CGRect(x: ballXOrigin, y: bounds.midY, width: ballSize.width, height: ballSize.height) // Create the attachment behavior. let attachmentBehavior = UIAttachmentBehavior(item: ball, attachedToAnchor: CGPoint(x: ball.frame.midX, y: bounds.midY - 50)) ballsToAttachmentBehaviors[ball] = attachmentBehavior animator?.addBehavior(attachmentBehavior) // Add the collision, gravity and item behaviors. collisionBehavior.addItem(ball) gravityBehavior.addItem(ball) itemBehavior.addItem(ball) } } // MARK: Touch Handling override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.location(in: superview) for ball in balls { if (ball.frame.contains(touchLocation)) { snapBehavior = UISnapBehavior(item: ball, snapTo: touchLocation) animator?.addBehavior(snapBehavior!) } } } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.location(in: superview) if let snapBehavior = snapBehavior { snapBehavior.snapPoint = touchLocation } } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let snapBehavior = snapBehavior { animator?.removeBehavior(snapBehavior) } snapBehavior = nil } // MARK: KVO public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (keyPath == "center") { setNeedsDisplay() } } // MARK: Drawing public override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context!.saveGState() for ball in balls { guard let attachmentBehavior = ballsToAttachmentBehaviors[ball] else { fatalError("Can't find attachment behavior for \(ball)") } let anchorPoint = attachmentBehavior.anchorPoint context!.move(to: anchorPoint) context!.addLine(to: ball.center) context!.setStrokeColor(UIColor.darkGray.cgColor) context!.setLineWidth(4.0) context!.strokePath() let attachmentDotWidth:CGFloat = 10.0 let attachmentDotOrigin = CGPoint(x: anchorPoint.x - (attachmentDotWidth / 2), y: anchorPoint.y - (attachmentDotWidth / 2)) let attachmentDotRect = CGRect(x: attachmentDotOrigin.x, y: attachmentDotOrigin.y, width: attachmentDotWidth, height: attachmentDotWidth) context!.setFillColor(UIColor.darkGray.cgColor) context!.fillEllipse(in: attachmentDotRect) } context!.restoreGState() } }
mit
303bf99d1654dc796f26cdc573029926
35.366834
158
0.596103
5.360741
false
false
false
false
cfilipov/MuscleBook
MuscleBook/DebugMenuViewController.swift
1
6479
/* Muscle Book Copyright (C) 2016 Cristian Filipov 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 UIKit import Eureka import JSQNotificationObserverKit class DebugMenuViewController : FormViewController { private let db = DB.sharedInstance private let mainQueue = NSOperationQueue.mainQueue() private var observer: CocoaObserver? = nil override func viewDidLoad() { super.viewDidLoad() let notification = CocoaNotification(name: UIApplicationDidReceiveMemoryWarningNotification) observer = CocoaObserver(notification, queue: self.mainQueue, handler: { (notification: NSNotification) in self.tableView?.reloadData() }) title = "Debug Menu" form +++ Section() { $0.header = HeaderFooterView(title: "Warning") $0.footer = HeaderFooterView(title: "Don't mess with the debug settings unless you know what you are doing.\n\nSome of the options here may cause data loss or other craziness.") } +++ Section() <<< LabelRow() { $0.title = "Timers" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = DebugTimersViewController() self.showViewController(vc, sender: nil) } <<< LabelRow() { $0.title = "Color Palette" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = ColorPaletteViewController() self.showViewController(vc, sender: nil) } <<< LabelRow() { $0.title = "Anatomy" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = AnatomyDebugViewController2() self.showViewController(vc, sender: nil) } // <<< LabelRow("import_csv") { // $0.title = "Import CSV" // $0.disabled = "$import_csv != nil" // $0.hidden = Dropbox.authorizedClient == nil ? true : false // }.onCellSelection(onImportCSV) // // <<< LabelRow("sync_dropbox") { // $0.title = "Sync Dropbox" // $0.disabled = "$sync_dropbox != nil" // $0.hidden = Dropbox.authorizedClient == nil ? true : false // }.onCellSelection(onSyncWithDropbox) +++ Section() <<< ButtonRow() { $0.title = "Recalculate All Workouts" $0.cellUpdate { cell, _ in cell.textLabel?.textColor = UIColor.redColor() } $0.onCellSelection { _, _ in WarnAlert(message: "Are you sure? This will be slow and the UI will be unresponsive while calculating.") { try! self.db.recalculateAll() } } } <<< ButtonRow() { $0.title = "Export Exercises" $0.cellUpdate { cell, _ in cell.textLabel?.textColor = UIColor.redColor() } $0.onCellSelection { _, _ in let url = NSFileManager .defaultManager() .URLsForDirectory( .CachesDirectory, inDomains: .UserDomainMask )[0] .URLByAppendingPathComponent("exercises.yaml") try! self.db.exportYAML(Exercise.self, toURL: url) let vc = UIActivityViewController( activityItems: [url], applicationActivities: nil ) self.presentViewController(vc, animated: true, completion: nil) } } } // private func onSyncWithDropbox(cell: LabelCell, row: LabelRow) { // WarnAlert(message: "Are you sure you want to sync?") { _ in // row.value = "Syncing..." // row.reload() // Workset.importFromDropbox("/WorkoutLog.yaml") { status in // guard .Success == status else { // Alert(message: "Failed to sync with dropbox") // return // } // row.value = nil // row.disabled = false // row.reload() // Alert(message: "Sync Complete") // } // } // } // private func onImportCSV(cell: LabelCell, row: LabelRow) { // guard db.count(Workset) == 0 else { // Alert(message: "Cannot import data, you already have data.") // return // } // WarnAlert(message: "Import Data from Dropbox?") { _ in // row.value = "Importing..." // row.reload() // Workset.downloadFromDropbox("/WorkoutLog.csv") { url in // guard let url = url else { // row.value = nil // row.reload() // Alert(message: "Failed to import CSV data") // return // } // row.value = "Importing..." // row.reload() // do { // let importCount = try self.db.importCSV(Workset.self, fromURL: url) // row.value = nil // row.disabled = false // row.reload() // Alert("Import Complete", message: "\(importCount) records imported.") { _ in //// let vc = VerifyWorksetsViewController() //// self.presentModalViewController(vc) // } // } catch { // row.value = nil // row.reload() // Alert(message: "Failed to import CSV data") // return // } // } // } // } }
gpl-3.0
e4dfcbaf248d8157da01bbe584ed2e9b
35.398876
189
0.528014
4.76047
false
false
false
false
objcio/DominantColor
DominantColor/Shared/Memoization.swift
3
420
// // Memoization.swift // DominantColor // // Created by Emmanuel Odeke on 2014-12-25. // Copyright (c) 2014 Indragie Karunaratne. All rights reserved. // func memoize<T: Hashable, U>(f: T -> U) -> T -> U { var cache = [T : U]() return { key in var value = cache[key] if value == nil { value = f(key) cache[key] = value } return value! } }
mit
9f5aee50d85c96f0419e2e747f9e7217
19
65
0.516667
3.307087
false
false
false
false