repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
borglab/SwiftFusion
Sources/SwiftFusion/Geometry/PinholeCamera.swift
1
3100
import _Differentiation /// Pinhole camera model. public struct PinholeCamera<Calibration: CameraCalibration>: Differentiable { /// Camera pose in the world/reference frame. public var wTc: Pose3 /// Camera calibration. public var calibration: Calibration /// Initializes from camera pose and calibration. @differentiable public init(_ calibration: Calibration, _ wTc: Pose3) { self.calibration = calibration self.wTc = wTc } /// Initializes with identity pose. @differentiable public init(_ calibration: Calibration) { self.init(calibration, Pose3()) } /// Initializes to default. public init() { self.init(Calibration(), Pose3()) } } /// Project and backproject. extension PinholeCamera { /// Projects a 3D point in the world frame to 2D point in the image. @differentiable public func project(_ wp: Vector3) -> Vector2 { let np: Vector2 = projectToNormalized(wp) let ip = calibration.uncalibrate(np) return ip } /// Backprojects a 2D image point into 3D point in the world frame at given depth. @differentiable public func backproject(_ ip: Vector2, _ depth: Double) -> Vector3 { let np = calibration.calibrate(ip) let cp = Vector3(np.x * depth, np.y * depth, depth) let wp = wTc * cp return wp } /// Projects a 3D point in the world frame to 2D normalized coordinate. @differentiable func projectToNormalized(_ wp: Vector3) -> Vector2 { projectToNormalized(wp).ip } /// Computes the derivative of the projection function wrt to self and the point wp. @usableFromInline @derivative(of: projectToNormalized) func vjpProjectToNormalized(_ wp: Vector3) -> (value: Vector2, pullback: (Vector2) -> (TangentVector, Vector3)) { let (ip, cRw, zInv) = projectToNormalized(wp) let (u, v) = (ip.x, ip.y) let R = cRw.coordinate.R return ( value: ip, pullback: { p in let dpose = Vector6( p.x * (u * v) + p.y * (1 + v * v), p.x * -(1 + u * u) + p.y * -(u * v), p.x * v + p.y * -u, p.x * -zInv, p.y * -zInv, p.x * (zInv * u) + p.y * (zInv * v)) let dpoint = zInv * Vector3( p.x * (R[0, 0] - u * R[2, 0]) + p.y * (R[1, 0] - v * R[2, 0]), p.x * (R[0, 1] - u * R[2, 1]) + p.y * (R[1, 1] - v * R[2, 1]), p.x * (R[0, 2] - u * R[2, 2]) + p.y * (R[1, 2] - v * R[2, 2])) return ( TangentVector(wTc: dpose, calibration: calibration.zeroTangentVector()), dpoint) } ) } /// Projects a 3D point in the world frame to 2D normalized coordinate and returns intermediate values. func projectToNormalized(_ wp: Vector3) -> (ip: Vector2, cRw: Rot3, zInv: Double) { // Transform the point to camera coordinate let cTw = wTc.inverse() let cp = cTw * wp // TODO: check for cheirality (whether the point is behind the camera) // Project to normalized coordinate let zInv = 1.0 / cp.z return ( ip: Vector2(cp.x * zInv, cp.y * zInv), cRw: cTw.rot, zInv: zInv) } }
apache-2.0
ab753ffc39bd400e4568eeb7981fc1ef
28.52381
105
0.60129
3.273495
false
false
false
false
lacklock/ZHIconFontKit
Example/DXYIconFont.swift
1
359
// // IconFontEnum.swift // IconFontDemo // // Created by 卓同学 on 16/8/24. // Copyright © 2016年 lacklock@gmail.com. All rights reserved. // import Foundation import IconFontKit public enum DXYIconFont: Int,UnicodeString { case qrcode = 59031 case addChat = 59027 case sign = 59017 case checkBox = 58887 case safari = 58882 }
mit
02916c3b1cba89a7c0f281441a93b1d2
18.444444
62
0.688571
3.301887
false
false
false
false
crspybits/SMCoreLib
Deprecated/HttpOperation.swift
1
2994
// // HttpOperation.swift // WhatDidILike // // Created by Christopher Prince on 9/28/14. // Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved. // import Foundation class HttpOperation { /* Carry out an HTTP GET operation. For a "GET" method, the parameters are sent as part of the URL string. e.g., /test/demo_form.asp?name1=value1&name2=value2 See http://www.w3schools.com/tags/ref_httpmethods.asp */ func get(url: NSURL, parameters: NSDictionary?, extraHeaders: ((request: NSURLRequest?) -> Dictionary<String, String>?)?, completion: (NSDictionary?, NSError?) -> ()) -> NetOp? { var errorResult: NSError? print("parameters: \(parameters)") let urlString: String = url.absoluteString let request: NSMutableURLRequest! do { request = try AFHTTPRequestSerializer().requestWithMethod("GET", URLString: urlString, parameters: parameters) } catch var error as NSError { errorResult = error request = nil } Log.msg("extraHeaders: \(extraHeaders)") var headers: Dictionary<String, String>? if (extraHeaders != nil) { // Call the extraHeaders function, because it was given. headers = extraHeaders!(request: request) for (headerField, fieldValue) in headers! { request.setValue(fieldValue, forHTTPHeaderField: headerField) } } if (nil == request) || (nil != errorResult) { completion(nil, Error.Create("Error executing requestWithMethod")) return nil } func successFunc(operation: AFHTTPRequestOperation?, response: AnyObject?) { if let responseDict = response as? NSDictionary { completion(responseDict, nil) } else { completion(nil, Error.Create("Response was not a dictionary")) } } func failureFunc(operation: AFHTTPRequestOperation?, error: NSError?) { completion(nil, error) } // I thought I was having quoting, but it turned out to be a problem with the oauth signature because I wasn't including the final URL from the NSURLRequest. let operation = AFHTTPRequestOperation(request: request) // 10/5/15; See bridging header. I was having a problem with just AFJSONResponseSerializer() operation.responseSerializer = AFJSONResponseSerializer.sharedSerializer() operation.setCompletionBlockWithSuccess(successFunc, failure: failureFunc) operation.start() let netOp = NetOp(operation: operation) return netOp } func get(url: NSURL, parameters: NSDictionary?, completion: (NSDictionary?, NSError?) -> ()) -> NetOp? { return get(url, parameters: parameters, extraHeaders: nil, completion: completion) } }
gpl-3.0
8ecb58546aaa9cd7b4a4d7e4f5325119
36.4375
165
0.614896
5.006689
false
false
false
false
glennposadas/gpkit-ios
GPKit/Categories/UIDevice+GPKit.swift
1
3387
// // UIDevice+GPKit.swift // GPKit // // Created by Glenn Posadas on 5/28/17. // Copyright © 2017 Citus Labs. All rights reserved. // import UIKit public enum GPDevice: String { case iPhone4 = "iPhone 4" case iPhone4s = "iPhone 4s" case iPhone5 = "iPhone 5" case iPhone5c = "iPhone 5c" case iPhone5s = "iPhone 5s" case iPhone6 = "iPhone 6" case iPhone6plus = "iPhone 6 Plus" case iPhone6s = "iPhone 6s" case iPhone6sPlus = "iPhone 6s Plus" case iPhoneSE = "iPhone SE" case iPhone7 = "iPhone 7" case iPhone7plus = "iPhone 7 Plus" } /** Call: UIDevice.current.modelName */ public extension UIDevice { var modelName: String { var machineString = String() var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) machineString = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch machineString { case "iPod4,1": return "iPod Touch 4G" case "iPod5,1": return "iPod Touch 5G" case "iPod7,1": return "iPod Touch 6G" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7 inch)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9 inch)" case "AppleTV5,3": return "Apple TV" default: return machineString } } }
mit
18423aa30f5e696d9943c02a93d6d543
45.383562
92
0.478736
3.825989
false
false
false
false
mouse-lin/GLCircleScrollView
GLCircleScrollVeiw/AppDelegate.swift
1
2433
// // AppDelegate.swift // GLCircleScrollVeiw // // Created by god、long on 15/7/3. // Copyright (c) 2015年 ___GL___. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.backgroundColor = UIColor.whiteColor() self.window?.makeKeyAndVisible() let firstVC = FirstVC() let naviVC = UINavigationController(rootViewController: firstVC) self.window?.rootViewController = naviVC 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
15713dde17f8881b94216bb2e260e80b
43.163636
285
0.735282
5.48307
false
false
false
false
nthery/SwiftForth
SwiftForthKit/debug.swift
1
448
// // debug.swift // SwiftForth // // Created by Nicolas Thery on 27/07/14. // Copyright (c) 2014 Nicolas Thery. All rights reserved. // import Foundation enum TraceFlag : UInt { case Evaluator = 0b0001 case Compiler = 0b00010 case Vm = 0b00100 } var traceMask : UInt = 0 func debug(condition: TraceFlag, msg: @autoclosure () -> String) { if (condition.rawValue & traceMask) != 0 { println("[DBG] \(msg())") } }
mit
a1352423e2b1772fa24f445e77684a05
18.521739
66
0.629464
3.223022
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/FlyToView.swift
1
1117
// // FlyToView.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML FlyToView /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="flyToView" type="boolean" default="0"/> public class FlyToView:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue { public static var elementName: String = "flyToView" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as NetworkLink: v.value.flyToView = self default: break } } } } public var value:Bool = false // 0 public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = contents == "1" self.parent = parent return parent } }
mit
5b79acc3b4a2679e62f07602e7fd8d27
28.444444
83
0.603774
3.854545
false
false
false
false
pksprojects/ElasticSwift
Sources/ElasticSwiftQueryDSL/Queries/TermLevelQueries.swift
1
31959
// // TermLevelQuery.swift // ElasticSwift // // Created by Prafull Kumar Soni on 4/14/18. // import ElasticSwiftCore import Foundation // MARK: - Term Query public struct TermQuery: Query { public let queryType: QueryType = QueryTypes.term public let field: String public let value: String public var boost: Decimal? public var name: String? public init(field: String, value: String, boost: Decimal? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.name = name } internal init(withBuilder builder: TermQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, name: builder.name) } } public extension TermQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(TermQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let fieldContainer = try? nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) { value = try fieldContainer.decodeString(forKey: .value) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) } else { value = try nested.decodeString(forKey: .key(named: field)) boost = nil name = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil || name != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case boost case value case name } } extension TermQuery: Equatable { public static func == (lhs: TermQuery, rhs: TermQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Terms Query public struct TermsQuery: Query { public let queryType: QueryType = QueryTypes.terms public let field: String public let values: [String] public var boost: Decimal? public var name: String? public init(field: String, values: [String], boost: Decimal? = nil, name: String? = nil) { self.field = field self.values = values self.boost = boost self.name = name } internal init(withBuilder builder: TermsQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard !builder.values.isEmpty else { throw QueryBuilderError.atlestOneElementRequired("values") } self.init(field: builder.field!, values: builder.values, boost: builder.boost, name: builder.name) } } public extension TermsQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(TermsQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue values = try nested.decode([String].self, forKey: .key(named: field)) boost = try nested.decodeDecimalIfPresent(forKey: .key(named: CodingKeys.boost.rawValue)) name = try nested.decodeStringIfPresent(forKey: .key(named: CodingKeys.name.rawValue)) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) try nested.encode(values, forKey: .key(named: field)) try nested.encodeIfPresent(boost, forKey: .key(named: CodingKeys.boost.rawValue)) try nested.encodeIfPresent(name, forKey: .key(named: CodingKeys.name.rawValue)) } internal enum CodingKeys: String, CodingKey { case boost case name } } extension TermsQuery: Equatable { public static func == (lhs: TermsQuery, rhs: TermsQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.values == rhs.values && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Multi Term Query public protocol MultiTermQuery: Query {} // MARK: - Range Query public struct RangeQuery: MultiTermQuery { public let queryType: QueryType = QueryTypes.range public let field: String public let gte: String? public let gt: String? public let lte: String? public let lt: String? public let format: String? public let timeZone: String? public let relation: ShapeRelation? public var boost: Decimal? public var name: String? public init(field: String, gte: String?, gt: String?, lte: String?, lt: String?, format: String? = nil, timeZone: String? = nil, boost: Decimal? = nil, relation: ShapeRelation? = nil, name: String? = nil) { self.field = field self.gte = gte self.gt = gt self.lte = lte self.lt = lt self.format = format self.timeZone = timeZone self.boost = boost self.relation = relation self.name = name } internal init(withBuilder builder: RangeQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.gte != nil || builder.gt != nil || builder.lt != nil || builder.lte != nil else { throw QueryBuilderError.atleastOneFieldRequired(["gte", "gt", "lt", "lte"]) } self.init(field: builder.field!, gte: builder.gte, gt: builder.gt, lte: builder.lte, lt: builder.lt, format: builder.format, timeZone: builder.timeZone, boost: builder.boost, relation: builder.relation, name: builder.name) } } public extension RangeQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(RangeQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue let fieldContainer = try nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) gte = try fieldContainer.decodeStringIfPresent(forKey: .gte) gt = try fieldContainer.decodeStringIfPresent(forKey: .gt) lte = try fieldContainer.decodeStringIfPresent(forKey: .lte) lt = try fieldContainer.decodeStringIfPresent(forKey: .lt) format = try fieldContainer.decodeStringIfPresent(forKey: .format) timeZone = try fieldContainer.decodeStringIfPresent(forKey: .timeZone) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) relation = try fieldContainer.decodeIfPresent(ShapeRelation.self, forKey: .relation) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encodeIfPresent(gt, forKey: .gt) try fieldContainer.encodeIfPresent(gte, forKey: .gte) try fieldContainer.encodeIfPresent(lt, forKey: .lt) try fieldContainer.encodeIfPresent(lte, forKey: .lte) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(format, forKey: .format) try fieldContainer.encodeIfPresent(timeZone, forKey: .timeZone) try fieldContainer.encodeIfPresent(relation, forKey: .relation) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case gt case gte case lt case lte case boost case format case timeZone = "time_zone" case relation case name } } extension RangeQuery: Equatable { public static func == (lhs: RangeQuery, rhs: RangeQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.gt == rhs.gt && lhs.gte == rhs.gte && lhs.lt == rhs.lt && lhs.lte == rhs.lte && lhs.boost == rhs.boost && lhs.relation == rhs.relation && lhs.format == rhs.format && lhs.timeZone == rhs.timeZone && lhs.name == rhs.name } } // MARK: - Exists Query public struct ExistsQuery: Query { public let queryType: QueryType = QueryTypes.exists public let field: String public var boost: Decimal? public var name: String? public init(field: String, boost: Decimal? = nil, name: String? = nil) { self.field = field self.boost = boost self.name = name } internal init(withBuilder builder: ExistsQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } self.init(field: builder.field!, boost: builder.boost, name: builder.name) } } public extension ExistsQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) field = try nested.decodeString(forKey: .field) boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(field, forKey: .field) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case field case boost case name } } extension ExistsQuery: Equatable { public static func == (lhs: ExistsQuery, rhs: ExistsQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Prefix Query public struct PrefixQuery: MultiTermQuery { public let queryType: QueryType = QueryTypes.prefix public let field: String public let value: String public var boost: Decimal? public var name: String? public init(field: String, value: String, boost: Decimal? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.name = name } internal init(withBuilder builder: PrefixQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, name: builder.name) } } public extension PrefixQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(PrefixQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let fieldContainer = try? nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) { value = try fieldContainer.decodeString(forKey: .value) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) } else { value = try nested.decodeString(forKey: .key(named: field)) boost = nil name = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case boost case value case name } } extension PrefixQuery: Equatable { public static func == (lhs: PrefixQuery, rhs: PrefixQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - WildCard Query public struct WildCardQuery: MultiTermQuery { public let queryType: QueryType = QueryTypes.wildcard public let field: String public let value: String public var boost: Decimal? public var name: String? public init(field: String, value: String, boost: Decimal? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.name = name } internal init(withBuilder builder: WildCardQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, name: builder.name) } } public extension WildCardQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(WildCardQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let fieldContainer = try? nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) { value = try fieldContainer.decodeString(forKey: .value) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) } else { value = try nested.decodeString(forKey: .key(named: field)) boost = nil name = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case boost case value case name } } extension WildCardQuery: Equatable { public static func == (lhs: WildCardQuery, rhs: WildCardQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Regexp Query public struct RegexpQuery: MultiTermQuery { public let queryType: QueryType = QueryTypes.regexp public let field: String public let value: String public var boost: Decimal? public let regexFlags: [RegexFlag] public let maxDeterminizedStates: Int? public var name: String? public init(field: String, value: String, boost: Decimal? = nil, regexFlags: [RegexFlag] = [], maxDeterminizedStates: Int? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.regexFlags = regexFlags self.maxDeterminizedStates = maxDeterminizedStates self.name = name } internal init(withBuilder builder: RegexpQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, regexFlags: builder.regexFlags, maxDeterminizedStates: builder.maxDeterminizedStates, name: builder.name) } public var regexFlagsStr: String { return regexFlags.map { flag in flag.rawValue }.joined(separator: "|") } } public extension RegexpQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(RegexpQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let val = try? nested.decodeString(forKey: .key(named: field)) { value = val boost = nil regexFlags = [] maxDeterminizedStates = nil name = nil } else { let fieldContainer = try nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) value = try fieldContainer.decodeString(forKey: .value) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) let regexFlagStr = try fieldContainer.decodeStringIfPresent(forKey: .flags) if let flagStr = regexFlagStr { regexFlags = flagStr.split(separator: "|").map(String.init).map { RegexFlag(rawValue: $0)! } } else { regexFlags = [] } maxDeterminizedStates = try fieldContainer.decodeIntIfPresent(forKey: .maxDeterminizedStates) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil || !regexFlags.isEmpty || maxDeterminizedStates != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(regexFlagsStr, forKey: .flags) try fieldContainer.encodeIfPresent(maxDeterminizedStates, forKey: .maxDeterminizedStates) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case boost case flags case value case maxDeterminizedStates = "max_determinized_states" case name } } extension RegexpQuery: Equatable { public static func == (lhs: RegexpQuery, rhs: RegexpQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.regexFlags == rhs.regexFlags && lhs.boost == rhs.boost && lhs.maxDeterminizedStates == rhs.maxDeterminizedStates && lhs.name == rhs.name } } // MARK: - Fuzzy Query public struct FuzzyQuery: MultiTermQuery { public let queryType: QueryType = QueryTypes.fuzzy public let field: String public let value: String public var boost: Decimal? public let fuzziness: Int? public let prefixLenght: Int? public let maxExpansions: Int? public let transpositions: Bool? public var name: String? public init(field: String, value: String, boost: Decimal? = nil, fuzziness: Int? = nil, prefixLenght: Int? = nil, maxExpansions: Int? = nil, transpositions: Bool? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.fuzziness = fuzziness self.prefixLenght = prefixLenght self.maxExpansions = maxExpansions self.transpositions = transpositions self.name = name } internal init(withBuilder builder: FuzzyQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, fuzziness: builder.fuzziness, prefixLenght: builder.prefixLenght, maxExpansions: builder.maxExpansions, transpositions: builder.transpositions, name: builder.name) } } public extension FuzzyQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(FuzzyQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let val = try? nested.decodeString(forKey: .key(named: field)) { value = val boost = nil fuzziness = nil prefixLenght = nil maxExpansions = nil transpositions = nil name = nil } else { let fieldContainer = try nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) value = try fieldContainer.decodeString(forKey: .value) boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) fuzziness = try fieldContainer.decodeIntIfPresent(forKey: .fuzziness) prefixLenght = try fieldContainer.decodeIntIfPresent(forKey: .prefixLength) maxExpansions = try fieldContainer.decodeIntIfPresent(forKey: .maxExpansions) transpositions = try fieldContainer.decodeBoolIfPresent(forKey: .transpositions) name = try fieldContainer.decodeStringIfPresent(forKey: .name) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil || fuzziness != nil || maxExpansions != nil || prefixLenght != nil || transpositions != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(fuzziness, forKey: .fuzziness) try fieldContainer.encodeIfPresent(maxExpansions, forKey: .maxExpansions) try fieldContainer.encodeIfPresent(prefixLenght, forKey: .prefixLength) try fieldContainer.encodeIfPresent(transpositions, forKey: .transpositions) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case boost case value case fuzziness case prefixLength = "prefix_length" case maxExpansions = "max_expansions" case transpositions case name } } extension FuzzyQuery: Equatable { public static func == (lhs: FuzzyQuery, rhs: FuzzyQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.boost == rhs.boost && lhs.fuzziness == rhs.fuzziness && lhs.maxExpansions == rhs.maxExpansions && lhs.prefixLenght == rhs.prefixLenght && lhs.transpositions == rhs.transpositions && lhs.name == rhs.name } } // MARK: - Type Query public struct TypeQuery: Query { public let queryType: QueryType = QueryTypes.type public let type: String public var boost: Decimal? public var name: String? public init(type: String, boost: Decimal? = nil, name: String? = nil) { self.type = type self.boost = boost self.name = name } internal init(withBuilder builder: TypeQueryBuilder) throws { guard builder.type != nil else { throw QueryBuilderError.missingRequiredField("type") } self.init(type: builder.type!, boost: builder.boost, name: builder.name) } } public extension TypeQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) type = try nested.decodeString(forKey: .value) boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(type, forKey: .value) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case value case boost case name } } extension TypeQuery: Equatable { public static func == (lhs: TypeQuery, rhs: TypeQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.type == rhs.type && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Ids Query public struct IdsQuery: Query { public let queryType: QueryType = QueryTypes.ids public let type: String? public let ids: [String] public var boost: Decimal? public var name: String? public init(ids: [String], type: String? = nil, boost: Decimal? = nil, name: String? = nil) { self.type = type self.ids = ids self.boost = boost self.name = name } public init(ids: String..., type: String? = nil, boost: Decimal? = nil, name: String? = nil) { self.init(ids: ids, type: type, boost: boost, name: name) } internal init(withBuilder builder: IdsQueryBuilder) throws { guard !builder.ids.isEmpty else { throw QueryBuilderError.atlestOneElementRequired("ids") } self.init(ids: builder.ids, type: builder.type, boost: builder.boost, name: builder.name) } } public extension IdsQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) type = try nested.decodeStringIfPresent(forKey: .type) ids = try nested.decode([String].self, forKey: .values) boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(ids, forKey: .values) try nested.encodeIfPresent(type, forKey: .type) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case values case type case boost case name } } extension IdsQuery: Equatable { public static func == (lhs: IdsQuery, rhs: IdsQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.ids == rhs.ids && lhs.type == rhs.type && lhs.boost == rhs.boost && lhs.name == rhs.name } }
mit
fbe560c1368e3e8d6fae062bc1af4677
37.001189
249
0.651335
4.397221
false
false
false
false
AboutObjectsTraining/Swift4Examples
ModelTests/MiscTests.swift
1
2561
// Copyright (C) 2017 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import XCTest fileprivate struct Grocery { let name: String let price: Double let quantity: Int } fileprivate struct Friend { var firstName: String var lastName: String var age: Int } class MiscTests: XCTestCase { override func setUp() { super.setUp(); print() } override func tearDown() { print(); super.tearDown() } func testGroceries() { let groceries = [Grocery(name: "Apples", price: 0.65, quantity: 12), Grocery(name: "Milk", price: 1.25, quantity: 2), Grocery(name: "Crackers", price: 2.35, quantity: 3)] let costs = groceries.map { (name: $0.name, cost: $0.price * Double($0.quantity)) } costs.forEach { print($0) } print(costs) // [(Apples, 7.8), (Milk, 2.5), (Crackers, 7.05)] // [(name: "Apples", cost: 7.8), (name: "Milk", cost: 2.5), (name: "Crackers", cost: 7.05)] let total = groceries.reduce(0.0) { sum, item in sum + (item.price * Double(item.quantity)) } print(total) // 17.35 let string = costs.reduce("") { text, item in "\(text)name: \(item.name), cost: \(item.cost)\n" } print(string) // name: Apples, cost: 7.8 // name: Milk, cost: 2.5 // name: Crackers, cost: 7.05 let header = "Groceries\n--------------\n" let text = costs.reduce(header) { result, item in String(format: "%@%@%6.2f\n", result, item.name.padding(toLength: 8, withPad: " ", startingAt: 0), item.cost) } print(text) // Groceries // -------------- // Apples 7.80 // Milk 2.50 // Crackers 7.05 } func testFriends() { // public convenience init?(_ description: String) let friends = [Friend(firstName: "Fred", lastName: "Smith", age: 27), Friend(firstName: "Janet", lastName: "Wade", age: 31), Friend(firstName: "Gale", lastName: "Dee", age: 42), Friend(firstName: "Jan", lastName: "Grey", age: 29)] let under30 = friends .filter { $0.age < 30 } .map { "\($0.firstName) \($0.lastName), \($0.age)" } print(under30) // ["Fred Smith, 27", "Jan Grey, 29"] } }
mit
c272177dc765674ef89c2f4c21d53b0f
31.833333
99
0.501367
3.794074
false
true
false
false
apple/swift-corelibs-foundation
Tests/Foundation/Tests/TestURLRequest.swift
1
13196
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // class TestURLRequest : XCTestCase { static var allTests: [(String, (TestURLRequest) -> () throws -> Void)] { return [ ("test_construction", test_construction), ("test_mutableConstruction", test_mutableConstruction), ("test_headerFields", test_headerFields), ("test_copy", test_copy), ("test_mutableCopy_1", test_mutableCopy_1), ("test_mutableCopy_2", test_mutableCopy_2), ("test_mutableCopy_3", test_mutableCopy_3), ("test_hash", test_hash), ("test_methodNormalization", test_methodNormalization), ("test_description", test_description), ("test_relativeURL", test_relativeURL), ] } let url = URL(string: "http://swift.org")! func test_construction() { let request = URLRequest(url: url) // Match macOS Foundation responses XCTAssertEqual(request.url, url) XCTAssertEqual(request.httpMethod, "GET") XCTAssertNil(request.allHTTPHeaderFields) XCTAssertNil(request.mainDocumentURL) } func test_mutableConstruction() { let url = URL(string: "http://swift.org")! var request = URLRequest(url: url) //Confirm initial state matches NSURLRequest responses XCTAssertEqual(request.url, url) XCTAssertEqual(request.httpMethod, "GET") XCTAssertNil(request.allHTTPHeaderFields) XCTAssertNil(request.mainDocumentURL) request.mainDocumentURL = url XCTAssertEqual(request.mainDocumentURL, url) request.httpMethod = "POST" XCTAssertEqual(request.httpMethod, "POST") let newURL = URL(string: "http://github.com")! request.url = newURL XCTAssertEqual(request.url, newURL) } func test_headerFields() { var request = URLRequest(url: url) request.setValue("application/json", forHTTPHeaderField: "Accept") XCTAssertNotNil(request.allHTTPHeaderFields) XCTAssertNil(request.allHTTPHeaderFields?["accept"]) XCTAssertEqual(request.allHTTPHeaderFields?["Accept"], "application/json") // Setting "accept" should update "Accept" request.setValue("application/xml", forHTTPHeaderField: "accept") XCTAssertNil(request.allHTTPHeaderFields?["accept"]) XCTAssertEqual(request.allHTTPHeaderFields?["Accept"], "application/xml") // Adding to "Accept" should add to "Accept" request.addValue("text/html", forHTTPHeaderField: "Accept") XCTAssertEqual(request.allHTTPHeaderFields?["Accept"], "application/xml,text/html") } func test_copy() { var mutableRequest = URLRequest(url: url) let urlA = URL(string: "http://swift.org")! let urlB = URL(string: "http://github.com")! let postBody = "here is body".data(using: .utf8) mutableRequest.mainDocumentURL = urlA mutableRequest.url = urlB mutableRequest.httpMethod = "POST" mutableRequest.setValue("application/json", forHTTPHeaderField: "Accept") mutableRequest.httpBody = postBody let requestCopy1 = mutableRequest // Check that all attributes are copied and that the original ones are // unchanged: XCTAssertEqual(mutableRequest.mainDocumentURL, urlA) XCTAssertEqual(requestCopy1.mainDocumentURL, urlA) XCTAssertEqual(mutableRequest.httpMethod, "POST") XCTAssertEqual(requestCopy1.httpMethod, "POST") XCTAssertEqual(mutableRequest.url, urlB) XCTAssertEqual(requestCopy1.url, urlB) XCTAssertEqual(mutableRequest.allHTTPHeaderFields?["Accept"], "application/json") XCTAssertEqual(requestCopy1.allHTTPHeaderFields?["Accept"], "application/json") XCTAssertEqual(mutableRequest.httpBody, postBody) XCTAssertEqual(requestCopy1.httpBody, postBody) // Change the original, and check that the copy has unchanged // values: let urlC = URL(string: "http://apple.com")! let urlD = URL(string: "http://ibm.com")! mutableRequest.mainDocumentURL = urlC mutableRequest.url = urlD mutableRequest.httpMethod = "HEAD" mutableRequest.addValue("text/html", forHTTPHeaderField: "Accept") XCTAssertEqual(requestCopy1.mainDocumentURL, urlA) XCTAssertEqual(requestCopy1.httpMethod, "POST") XCTAssertEqual(requestCopy1.url, urlB) XCTAssertEqual(requestCopy1.allHTTPHeaderFields?["Accept"], "application/json") XCTAssertEqual(requestCopy1.httpBody, postBody) // Check that we can copy the copy: let requestCopy2 = requestCopy1 XCTAssertEqual(requestCopy2.mainDocumentURL, urlA) XCTAssertEqual(requestCopy2.httpMethod, "POST") XCTAssertEqual(requestCopy2.url, urlB) XCTAssertEqual(requestCopy2.allHTTPHeaderFields?["Accept"], "application/json") XCTAssertEqual(requestCopy2.httpBody, postBody) } func test_mutableCopy_1() { var originalRequest = URLRequest(url: url) let urlA = URL(string: "http://swift.org")! let urlB = URL(string: "http://github.com")! originalRequest.mainDocumentURL = urlA originalRequest.url = urlB originalRequest.httpMethod = "POST" originalRequest.setValue("application/json", forHTTPHeaderField: "Accept") let requestCopy = originalRequest // Change the original, and check that the copy has unchanged values: let urlC = URL(string: "http://apple.com")! let urlD = URL(string: "http://ibm.com")! originalRequest.mainDocumentURL = urlC originalRequest.url = urlD originalRequest.httpMethod = "HEAD" originalRequest.addValue("text/html", forHTTPHeaderField: "Accept") XCTAssertEqual(requestCopy.mainDocumentURL, urlA) XCTAssertEqual(requestCopy.httpMethod, "POST") XCTAssertEqual(requestCopy.url, urlB) XCTAssertEqual(requestCopy.allHTTPHeaderFields?["Accept"], "application/json") } func test_mutableCopy_2() { var originalRequest = URLRequest(url: url) let urlA = URL(string: "http://swift.org")! let urlB = URL(string: "http://github.com")! originalRequest.mainDocumentURL = urlA originalRequest.url = urlB originalRequest.httpMethod = "POST" originalRequest.setValue("application/json", forHTTPHeaderField: "Accept") var requestCopy = originalRequest // Change the copy, and check that the original has unchanged values: let urlC = URL(string: "http://apple.com")! let urlD = URL(string: "http://ibm.com")! requestCopy.mainDocumentURL = urlC requestCopy.url = urlD requestCopy.httpMethod = "HEAD" requestCopy.addValue("text/html", forHTTPHeaderField: "Accept") XCTAssertEqual(originalRequest.mainDocumentURL, urlA) XCTAssertEqual(originalRequest.httpMethod, "POST") XCTAssertEqual(originalRequest.url, urlB) XCTAssertEqual(originalRequest.allHTTPHeaderFields?["Accept"], "application/json") } func test_mutableCopy_3() { let urlA = URL(string: "http://swift.org")! let originalRequest = URLRequest(url: urlA) var requestCopy = originalRequest // Change the copy, and check that the original has unchanged values: let urlC = URL(string: "http://apple.com")! let urlD = URL(string: "http://ibm.com")! requestCopy.mainDocumentURL = urlC requestCopy.url = urlD requestCopy.httpMethod = "HEAD" requestCopy.addValue("text/html", forHTTPHeaderField: "Accept") XCTAssertNil(originalRequest.mainDocumentURL) XCTAssertEqual(originalRequest.httpMethod, "GET") XCTAssertEqual(originalRequest.url, urlA) XCTAssertNil(originalRequest.allHTTPHeaderFields) } func test_hash() { let url = URL(string: "https://swift.org")! let r1 = URLRequest(url: url) let r2 = URLRequest(url: url) XCTAssertEqual(r1, r2) XCTAssertEqual(r1.hashValue, r2.hashValue) checkHashing_ValueType( initialValue: URLRequest(url: url), byMutating: \URLRequest.url, throughValues: (0..<20).map { URL(string: "https://example.org/\($0)")! }) checkHashing_ValueType( initialValue: URLRequest(url: url), byMutating: \URLRequest.mainDocumentURL, throughValues: (0..<20).map { URL(string: "https://example.org/\($0)")! }) checkHashing_ValueType( initialValue: URLRequest(url: url), byMutating: \URLRequest.httpMethod, throughValues: [ "HEAD", "POST", "PUT", "DELETE", "CONNECT", "TWIZZLE", "REFUDIATE", "BUY", "REJECT", "UNDO", "SYNERGIZE", "BUMFUZZLE", "ELUCIDATE"]) let inputStreams: [InputStream] = (0..<100).map { value in InputStream(data: Data("\(value)".utf8)) } checkHashing_ValueType( initialValue: URLRequest(url: url), byMutating: \URLRequest.httpBodyStream, throughValues: inputStreams) // allowsCellularAccess and httpShouldHandleCookies do // not have enough values to test them here. } func test_methodNormalization() { let expectedNormalizations = [ "GET": "GET", "get": "GET", "gEt": "GET", "HEAD": "HEAD", "hEAD": "HEAD", "head": "HEAD", "HEAd": "HEAD", "POST": "POST", "post": "POST", "pOST": "POST", "POSt": "POST", "PUT": "PUT", "put": "PUT", "PUt": "PUT", "DELETE": "DELETE", "delete": "DELETE", "DeleTE": "DELETE", "dELETe": "DELETE", "CONNECT": "CONNECT", "connect": "CONNECT", "Connect": "CONNECT", "cOnNeCt": "CONNECT", "OPTIONS": "OPTIONS", "options": "options", "TRACE": "TRACE", "trace": "trace", "PATCH": "PATCH", "patch": "patch", "foo": "foo", "BAR": "BAR", ] var request = URLRequest(url: url) for n in expectedNormalizations { request.httpMethod = n.key XCTAssertEqual(request.httpMethod, n.value) } } func test_description() { let url = URL(string: "http://swift.org")! var request = URLRequest(url: url) XCTAssertEqual(request.description, "http://swift.org") request.url = nil XCTAssertEqual(request.description, "url: nil") } func test_relativeURL() throws { let baseUrl = URL(string: "http://httpbin.org") let url = try XCTUnwrap(URL(string: "/get", relativeTo: baseUrl)) XCTAssertEqual(url.description, "/get -- http://httpbin.org") XCTAssertEqual(url.baseURL?.description, "http://httpbin.org") XCTAssertEqual(url.relativeString, "/get") XCTAssertEqual(url.absoluteString, "http://httpbin.org/get") var req = URLRequest(url: url) XCTAssertEqual(req.url?.description, "http://httpbin.org/get") XCTAssertNil(req.url?.baseURL) XCTAssertEqual(req.url?.absoluteURL.description, "http://httpbin.org/get") XCTAssertEqual(req.url?.absoluteURL.relativeString, "http://httpbin.org/get") XCTAssertEqual(req.url?.absoluteURL.absoluteString, "http://httpbin.org/get") req.url = url XCTAssertEqual(req.url?.description, "/get -- http://httpbin.org") XCTAssertEqual(req.url?.baseURL?.description, "http://httpbin.org") XCTAssertEqual(req.url?.baseURL?.relativeString, "http://httpbin.org") XCTAssertEqual(req.url?.baseURL?.absoluteString, "http://httpbin.org") XCTAssertEqual(req.url?.absoluteURL.description, "http://httpbin.org/get") XCTAssertEqual(req.url?.absoluteURL.relativeString, "http://httpbin.org/get") XCTAssertEqual(req.url?.absoluteURL.absoluteString, "http://httpbin.org/get") let nsreq = NSURLRequest(url: url) XCTAssertEqual(nsreq.url?.description, "http://httpbin.org/get") XCTAssertNil(nsreq.url?.baseURL) XCTAssertEqual(nsreq.url?.absoluteURL.description, "http://httpbin.org/get") XCTAssertEqual(nsreq.url?.absoluteURL.relativeString, "http://httpbin.org/get") XCTAssertEqual(nsreq.url?.absoluteURL.absoluteString, "http://httpbin.org/get") } }
apache-2.0
93185175e13c81ead421b83d13a07dcb
40.496855
91
0.620794
4.765619
false
true
false
false
jernejstrasner/JSJSON
JSJSONTests/SwiftAssert.swift
1
2599
// // SwiftAssert.swift // JSJSON // // Created by Jernej Strasner on 7/8/15. // Copyright © 2015 Jernej Strasner. All rights reserved. // import XCTest public func AssertThrows<T>(@autoclosure expression: () throws -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) { do { try expression() XCTFail("No error to catch! - \(message)", file: file, line: line) } catch { } } public func AssertThrows<T, E: ErrorType>(expectedError: E, @autoclosure expression: () throws -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) { do { try expression() XCTFail("No error to catch! - \(message)", file: file, line: line) } catch expectedError { } catch { XCTFail("Error caught, but of non-matching type: \(error)") } } public func AssertNoThrow<T>(@autoclosure expression: () throws -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> T? { do { return try expression() } catch let error { XCTFail("Caught error: \(error) - \(message)", file: file, line: line) return nil } } public func AssertNoThrowEqual<T : Equatable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () throws -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) { do { let result1 = expression1() let result2 = try expression2() XCTAssert(result1 == result2, "\"\(result1)\" is not equal to \"\(result2)\" - \(message)") } catch let error { XCTFail("Caught error: \(error) - \(message)", file: file, line: line) } } public func AssertNoThrowValidateValue<T>(@autoclosure expression: () throws -> T, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__, _ validator: (T) -> Bool) { do { let result = try expression() XCTAssert(validator(result), "Value validation failed - \(message)", file: file, line: line) } catch let error { XCTFail("Caught error: \(error) - \(message)", file: file, line: line) } } public func AssertEqual<T: Equatable>(@autoclosure f: () -> T?, @autoclosure _ g: () -> T?, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) { let resultF = f() let resultG = g() XCTAssert(resultF == resultG, "\"\(resultF)\" is not equal to \"\(resultG)\" - \(message)") } // By Marious Rackwitz // https://realm.io/news/testing-swift-error-type/ func ~=(lhs: ErrorType, rhs: ErrorType) -> Bool { return lhs._domain == rhs._domain && rhs._code == rhs._code }
gpl-2.0
835467c1cbcb04e482df321ba1a44e96
37.205882
198
0.592379
3.685106
false
false
false
false
iremarkable/FFActionSheet
FFActionSheet/FFActionSheet/FFActionSheet/FFActionSheet.swift
1
6535
// // FFActionSheet.swift // FFActionSheet // // Created by Liunex on 7/7/15. // Copyright © 2015 liufeifei0914@163.com. All rights reserved. // import Foundation import UIKit extension UIButton { func setBackgroundColor(color: UIColor, forState: UIControlState) { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor) CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, forState: forState) } } class FFAction:UIButton{ init(actionName:String!){ let x:CGFloat = 0.0 let y:CGFloat = 0.0 let w:CGFloat = 0.0 let h:CGFloat = 0.0 super.init(frame: CGRectMake(x,y,w,h)) self.setTitle(actionName, forState: UIControlState.Normal) self.setTitleColor(UIColor.blackColor().colorWithAlphaComponent(0.8), forState: UIControlState.Normal) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class FFActionSheet:UIView { var actions = Array<FFAction!>() let dimmingView = UIView() let actionView = UIView() let cancelButton = UIButton(type: UIButtonType.Custom) var selectBlock : ((Int) -> Void)! class func actionSheet() -> FFActionSheet{ let x:CGFloat = 0.0 let y:CGFloat = 0.0 var w:CGFloat = 0.0 var h:CGFloat = 0.0 w = UIScreen.mainScreen().bounds.size.width h = UIScreen.mainScreen().bounds.size.height let sheet = FFActionSheet(frame: CGRectMake(x,y,w,h)) sheet.hidden = true return sheet } override init(frame: CGRect) { super.init(frame: frame) //dimming view dimmingView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) dimmingView.frame = frame self.addSubview(dimmingView) //action view var x:CGFloat = 0.0 var y:CGFloat = 0.0 var w:CGFloat = 0.0 var h:CGFloat = 0.0 x = 0 y = self.frame.size.height - 44;//initail height w = self.frame.size.width h = 44 actionView.frame = CGRectMake(x,y,w,h) self.addSubview(actionView) actionView.backgroundColor = UIColor.whiteColor() // cancel button cancelButton.titleLabel?.font = UIFont.systemFontOfSize(16) cancelButton .setTitleColor(UIColor.redColor().colorWithAlphaComponent(0.8), forState: UIControlState.Normal) cancelButton.setTitleColor(UIColor.redColor().colorWithAlphaComponent(0.3), forState: UIControlState.Highlighted) cancelButton.setTitle("取消", forState: UIControlState.Normal) cancelButton.setBackgroundColor(UIColor.grayColor().colorWithAlphaComponent(0.2), forState: UIControlState.Highlighted) actionView.addSubview(cancelButton) cancelButton.autoSetDimension(ALDimension.Width, toSize: actionView.frame.size.width) cancelButton.autoSetDimension(ALDimension.Height, toSize: 44) cancelButton.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 0.0) cancelButton.addTarget(self, action: "dismiss", forControlEvents: UIControlEvents.TouchUpInside) } func addActions(actionArray:Array<FFAction>!){ actions = actionArray var x:CGFloat = 0.0 var y:CGFloat = 0.0 var w:CGFloat = 0.0 var h:CGFloat = 0.0 let count = actions.count for var i = 0;i<count;i++ { let action = actions[i] x = 0 y = 0 h = 44 w = actionView.frame.width y = h * CGFloat(i); action.frame = CGRectMake(x,y,w,h) let line = UIView(frame:CGRectMake(20,h-0.5,w-40,0.5)) line.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2) action.addSubview(line) action.setBackgroundColor(UIColor.grayColor().colorWithAlphaComponent(0.2), forState: UIControlState.Highlighted) action.tag = i actionView.addSubview(action) action.addTarget(self, action: "selectAction:", forControlEvents: UIControlEvents.TouchUpInside) } let actionViewH = CGFloat(count) * 44 + 44 let actionY = self.frame.size.height actionView.frame = CGRectMake(x,actionY,w,actionViewH) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(){ self.hidden = false let count = actions.count let actionViewH = CGFloat(count) * 44 + 44 let actionY = self.frame.size.height - actionViewH UIView.animateWithDuration (0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut ,animations: { self.actionView.frame = CGRectMake(0,actionY,self.frame.size.width,actionViewH) }, completion: { _ in }) } func dismiss(){ let actionY = self.frame.size.height UIView.animateWithDuration (0.15, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn ,animations: { self.actionView.frame = CGRectMake(0,actionY,self.frame.size.width,self.actionView.frame.size.height) }, completion: { _ in }) UIView.animateWithDuration (0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear ,animations: { self.dimmingView.alpha = 0 }, completion: { _ in self.hidden = true self.removeFromSuperview() self.dimmingView.removeFromSuperview() }) } func selectAction(sender:FFAction){ self.dismiss() selectBlock(sender.tag) } }
mit
3893b6f7f902ad20ebc1e20239bf4b05
26.32636
127
0.579173
4.891386
false
false
false
false
Raureif/WikipediaKit
Sources/Wikipedia+ArticleSummary.swift
1
3149
// // Wikipedia+ArticleSummary.swift // WikipediaKit // // Created by Frank Rausch on 2018-07-30. // Copyright © 2018 Raureif GmbH / Frank Rausch // // MIT License // // 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 #if canImport(FoundationNetworking) import FoundationNetworking #endif extension Wikipedia { public func requestArticleSummary(language: WikipediaLanguage, title: String, completion: @escaping (WikipediaArticlePreview?, WikipediaError?)->()) -> URLSessionDataTask? { let title = title.wikipediaURLEncodedString(encodeSlashes: true) // We use the REST API here because that’s what the Wikipedia website calls for the link hover previews. // It’s very fast. let urlString = "https://\(language.code).wikipedia.org/api/rest_v1/page/summary/\(title)" guard let url = URL(string: urlString) else { DispatchQueue.main.async { completion(nil, .other(nil)) } return nil } let request = URLRequest(url: url) return WikipediaNetworking.shared.loadJSON(urlRequest: request) { jsonDictionary, error in guard error == nil else { // (also occurs when the request was cancelled programmatically) DispatchQueue.main.async { completion (nil, error) } return } guard let jsonDictionary = jsonDictionary else { DispatchQueue.main.async { completion (nil, .decodingError) } return } let articlePreview = WikipediaArticlePreview(jsonDictionary: jsonDictionary, language: language) DispatchQueue.main.async { completion(articlePreview, error) } } } }
mit
c7fe0948a366919c4495cb78e62d9bd6
37.243902
116
0.613202
5.140984
false
false
false
false
crazypoo/PTools
PooToolsSource/CheckUpdate/PTCheckUpdateFunction.swift
1
8112
// // PTCheckUpdateFunction.swift // PooTools_Example // // Created by jax on 2022/10/3. // Copyright © 2022 crazypoo. All rights reserved. // import UIKit import KakaJSON import SwifterSwift class IpadScreenshotUrls :PTBaseModel { } class AppletvScreenshotUrls :PTBaseModel { } class Features :PTBaseModel { } class Advisories :PTBaseModel { } class Results :PTBaseModel { var primaryGenreName: String = "" var artworkUrl100: String = "" var currency: String = "" var artworkUrl512: String = "" var ipadScreenshotUrls: [IpadScreenshotUrls]? var fileSizeBytes: String = "" var genres: [String]? var languageCodesISO2A: [String]? var artworkUrl60: String = "" var supportedDevices: [String]? var bundleId: String = "" var trackViewUrl: String = "" var version: String = "" var description: String = "" var releaseDate: String = "" var genreIds: [String]? var appletvScreenshotUrls: [AppletvScreenshotUrls]? var wrapperType: String = "" var isGameCenterEnabled: Bool = false var averageUserRatingForCurrentVersion: Int = 0 var artistViewUrl: String = "" var trackId: Int = 0 var userRatingCountForCurrentVersion: Int = 0 var minimumOsVersion: String = "" var formattedPrice: String = "" var primaryGenreId: Int = 0 var currentVersionReleaseDate: String = "" var userRatingCount: Int = 0 var artistId: Int = 0 var trackContentRating: String = "" var artistName: String = "" var price: Int = 0 var trackCensoredName: String = "" var trackName: String = "" var kind: String = "" var contentAdvisoryRating: String! var features: [Features]? var screenshotUrls: [String]? var releaseNotes: String = "" var isVppDeviceBasedLicensingEnabled: Bool = false var sellerName: String = "" var averageUserRating: Int = 0 var advisories: [Advisories]! } class PTCheckUpdateModel:PTBaseModel { var results: [Results]! var resultCount: Int = 0 } @objcMembers public class PTCheckUpdateFunction: NSObject { public static let share = PTCheckUpdateFunction() func compareVesionWithServerVersion(version:String)->Bool { let currentVersion = kAppVersion let versionArray = version.components(separatedBy: ".") let currentVesionArray = currentVersion!.components(separatedBy: ".") let a = (versionArray.count > currentVesionArray.count ) ? currentVesionArray.count : versionArray.count for i in 0...a { let forA = versionArray[i].int! var forB:Int = 0 if i > (currentVesionArray.count - 1) { forB = 0 } else { forB = currentVesionArray[i].int! } if forA > forB { return true } else if forA < forB { return false } } return false } public func checkTheVersionWithappid(appid:String,test:Bool,url:URL?,version:String?,note:String?,force:Bool) { if test { var okBtns = [String]() if force { okBtns = ["更新"] } else { okBtns = ["稍后再说","更新"] } PTUtils.base_alertVC(title:"发现新版本\(version ?? "1.0.0")\n\(note ?? "")",titleFont: .appfont(size: 17,bold: true),msg: "是否更新?",okBtns: okBtns,showIn: PTUtils.getCurrentVC()) { index, title in switch index { case 0: if force { if url != nil { self.jumpToDownloadLink(link: url!) } else { PTLocalConsoleFunction.share.pNSLog("非法url") } } case 1: if url != nil { self.jumpToDownloadLink(link: url!) } else { PTLocalConsoleFunction.share.pNSLog("非法url") } default: break } } } else { if !appid.stringIsEmpty() { Network.requestApi(urlStr: "http://itunes.apple.com/cn/lookup?id=\(appid)",modelType: PTCheckUpdateModel.self) { result, error in guard let responseModel = result!.originalString.kj.model(PTCheckUpdateModel.self) else { return } if responseModel.results.count > 0 { let versionModel = responseModel.results.first! let versionStr = versionModel.version var appStoreVersion = versionStr.replacingOccurrences(of: ".", with: "") if appStoreVersion.nsString.length == 2 { appStoreVersion = appStoreVersion.appending("0") } else if appStoreVersion.nsString.length == 1 { appStoreVersion = appStoreVersion.appending("00") } var currentVersion = kAppVersion?.replacingOccurrences(of: ".", with: "") if currentVersion?.nsString.length == 2 { currentVersion = currentVersion?.appending("0") } else if currentVersion?.nsString.length == 1 { currentVersion = currentVersion?.appending("00") } if self.compareVesionWithServerVersion(version: versionStr) { if appStoreVersion.float()! > currentVersion!.float()! { var okBtns = [String]() if force { okBtns = ["更新"] } else { okBtns = ["稍后再说","更新"] } PTUtils.base_alertVC(title:"发现新版本\(versionStr)\n\(versionModel.releaseNotes)",titleFont: .appfont(size: 17,bold: true),msg: "是否更新?",okBtns: okBtns,showIn: PTUtils.getCurrentVC()) { index, title in switch index { case 0: if force { self.jumpToAppStore(appid: appid) } case 1: self.jumpToAppStore(appid: appid) default: break } } } } } } } else { PTLocalConsoleFunction.share.pNSLog("没有检测到APPID") } } } private func jumpToAppStore(appid:String) { let uriString = String(format: "itms-apps://itunes.apple.com/app/id%@",appid) UIApplication.shared.open(URL(string: uriString)!, options: [:], completionHandler: nil) } private func jumpToDownloadLink(link:URL) { UIApplication.shared.open(link, options: [:], completionHandler: nil) } }
mit
953fe5eb4bbcef086593cb363225c14e
33.004237
228
0.466293
5.238251
false
false
false
false
codefellows/sea-c24-iOS-F2
Dictionaries.playground/section-1.swift
1
229
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var info = ["Year" : 2014] info["Month"] = 11 info["Day"] = 17 var today = info["Day"] var myInfo = [String: AnyObject]()
mit
33784b94f0b7e94fe996126bf3acdb2f
10.45
51
0.628821
3.180556
false
false
false
false
Verchen/Swift-Project
JinRong/JinRong/Classes/Category/String(extension).swift
1
1437
// // String(extension).swift // JinRong // // Created by 乔伟成 on 2017/7/25. // Copyright © 2017年 乔伟成. All rights reserved. // import Foundation extension String{ public var isPhone: Bool { if (characters.count < 11){ return false; }else{ // /// 移动号段 // let CM_NUM = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$" // /// 联通号段 // let CU_NUM = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$" // /// 电信号段 // let CT_NUM = "^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$" let NUM = "^((13[0-9])|(15[^4,\\D]) |(17[0,0-9])|(18[0,0-9]))\\d{8}$" // let pred1 = NSPredicate(format: "SELF MATCHES %@", CM_NUM) // let pred2 = NSPredicate(format: "SELF MATCHES %@", CU_NUM) // let pred3 = NSPredicate(format: "SELF MATCHES %@", CT_NUM) let pred = NSPredicate(format: "SELF MATCHES %@", NUM) // let isMatch1 = pred1.evaluate(with: self) // let isMatch2 = pred2.evaluate(with: self) // let isMatch3 = pred3.evaluate(with: self) let isMatch = pred.evaluate(with: self) if isMatch { return true }else{ return false } } } }
mit
1cdb360b87a37232d6cd163535e0059e
30.066667
101
0.444921
3.228637
false
false
false
false
collegboi/MBaaSKit
MBaaSKit/Classes/TabBarLoad.swift
1
2670
// // TabBarLoad.swift // Pdd // // Created by Timothy Barnard on 08/03/2017. // Copyright © 2017 Timothy Barnard. All rights reserved. // import Foundation public protocol TabBarLoad { } struct RCTabItem: TBJSONSerializable { var title:String! var image:String! var tag:Int! init() { } init(title:String, image:String, tag:Int) { self.title = title self.image = image self.tag = tag } init(jsonObject dict: [String : Any]) { self.title = dict.tryConvert(forKey: "title") self.image = dict.tryConvert(forKey: "image") self.tag = dict.tryConvert(forKey: "tag") } } public extension TabBarLoad where Self: UITabBarController { /** - parameters: - className: put self - name: the name of the object instance */ public func setupTabBar( className: UIViewController, _ name: String = "" ) { self.setup(className: String(describing: type(of: className)), tagValue: name) } /** - parameters: - className: put self - name: the name of the object instance */ private func setup( className: String, tagValue : String ) { let dict = RCConfigManager.getObjectProperties(className: className, objectName: tagValue) for (key, value) in dict { switch key { case "tabBarItems" where dict.tryConvert(forKey: key) != "": self.tabBar.items?.removeAll() guard let tabBarItems = value as? [Any] else { return } for tabBarItemObj in tabBarItems { guard let tabBarDic = tabBarItemObj as? [String:Any] else { return } let rcTabBarItem = RCTabItem(jsonObject: tabBarDic) let tabBarItem = UITabBarItem(title: rcTabBarItem.title, image: UIImage(named:rcTabBarItem.image), tag: rcTabBarItem.tag) self.tabBar.items?.append(tabBarItem) } break case "backgroundColor" where dict.tryConvert(forKey: key) != "": self.view.backgroundColor = RCFileManager.readJSONColor(keyVal: dict.tryConvert(forKey: key) ) break default: break } } } }
mit
c6ea532d7477d04cd321cbc42dc176a7
26.802083
111
0.501686
5.122841
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Core/Extensions/UIStackView.swift
1
896
// // UIStackView.swift // HTWDD // // Created by Mustafa Karademir on 02.10.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation extension HTWNamespace where Base: UIStackView { func addHorizontalSeparators(color: UIColor = UIColor.htw.Badge.secondary) { var i = base.arrangedSubviews.count while i > 1 { let separator = createSeparator(color: color) base.insertArrangedSubview(separator, at: i - 1) separator.widthAnchor.constraint(equalTo: base.widthAnchor, multiplier: 1).isActive = true i = i - 1 } } private func createSeparator(color: UIColor) -> UIView { return UIView().also { $0.heightAnchor.constraint(equalToConstant: 1).isActive = true $0.backgroundColor = color $0.alpha = 0.5 } } }
gpl-2.0
786ba7444b122f5b6d16855c1a90033d
28.833333
102
0.606704
4.408867
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/LinearEquations/Plot/MLinearEquationsPlotRenderCartesian.swift
1
1463
import UIKit import MetalKit class MLinearEquationsPlotRenderCartesian:MetalRenderableProtocol { private let axisX:MTLBuffer private let axisY:MTLBuffer private let color:MTLBuffer private let kAxisWidth:Float = 1 private let kBoundaries:Float = 10000 private let texture:MTLTexture init( device:MTLDevice, texture:MTLTexture) { let vectorStartX:float2 = float2(-kBoundaries, 0) let vectorEndX:float2 = float2(kBoundaries, 0) let vectorStartY:float2 = float2(0, -kBoundaries) let vectorEndY:float2 = float2(0, kBoundaries) self.texture = texture axisX = MetalSpatialLine.vertex( device:device, vectorStart:vectorStartX, vectorEnd:vectorEndX, lineWidth:kAxisWidth) axisY = MetalSpatialLine.vertex( device:device, vectorStart:vectorStartY, vectorEnd:vectorEndY, lineWidth:kAxisWidth) color = MetalColor.color( device:device, originalColor:UIColor.black) } //MARK: renderable Protocol func render(renderEncoder:MTLRenderCommandEncoder) { renderEncoder.render( vertex:axisX, color:color, texture:texture) renderEncoder.render( vertex:axisY, color:color, texture:texture) } }
mit
902382e56286a5fef67e40386a31a7b1
26.092593
65
0.603554
4.8125
false
false
false
false
foretagsplatsen/ios-app
SwiftyJSON/SwiftyJSON.swift
1
36334
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { error.memory = aError } self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var rawArray: [AnyObject] = [] private var rawDictionary: [String : AnyObject] = [:] private var rawString: String = "" private var rawNumber: NSNumber = 0 private var rawNull: NSNull = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? = nil /// Object in JSON public var object: AnyObject { get { switch self.type { case .Array: return self.rawArray case .Dictionary: return self.rawDictionary case .String: return self.rawString case .Number: return self.rawNumber case .Bool: return self.rawNumber default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } self.rawNumber = number case let string as String: _type = .String self.rawString = string case _ as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array self.rawArray = array case let dictionary as [String : AnyObject]: _type = .Dictionary self.rawDictionary = dictionary default: _type = .Unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed="null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } // MARK: - CollectionType, SequenceType, Indexable extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable { public typealias Generator = JSONGenerator public typealias Index = JSONIndex public var startIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.startIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) default: return JSONIndex() } } public var endIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.endIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) default: return JSONIndex() } } public subscript (position: JSON.Index) -> JSON.Generator.Element { switch self.type { case .Array: return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) case .Dictionary: let (key, value) = self.rawDictionary[position.dictionaryIndex!] return (key, JSON(value)) default: return ("", JSON.null) } } /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `true`. public var isEmpty: Bool { get { switch self.type { case .Array: return self.rawArray.isEmpty case .Dictionary: return self.rawDictionary.isEmpty default: return true } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { switch self.type { case .Array: return self.rawArray.count case .Dictionary: return self.rawDictionary.count default: return 0 } } public func underestimateCount() -> Int { switch self.type { case .Array: return self.rawArray.underestimateCount() case .Dictionary: return self.rawDictionary.underestimateCount() default: return 0 } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of JSON. */ public func generate() -> JSON.Generator { return JSON.Generator(self) } } public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable { let arrayIndex: Int? let dictionaryIndex: DictionaryIndex<String, AnyObject>? let type: Type init(){ self.arrayIndex = nil self.dictionaryIndex = nil self.type = .Unknown } init(arrayIndex: Int) { self.arrayIndex = arrayIndex self.dictionaryIndex = nil self.type = .Array } init(dictionaryIndex: DictionaryIndex<String, AnyObject>) { self.arrayIndex = nil self.dictionaryIndex = dictionaryIndex self.type = .Dictionary } public func successor() -> JSONIndex { switch self.type { case .Array: return JSONIndex(arrayIndex: self.arrayIndex!.successor()) case .Dictionary: return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor()) default: return JSONIndex() } } } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex == rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex == rhs.dictionaryIndex default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex < rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex < rhs.dictionaryIndex default: return false } } public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex <= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex <= rhs.dictionaryIndex default: return false } } public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex >= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex >= rhs.dictionaryIndex default: return false } } public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex > rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex > rhs.dictionaryIndex default: return false } } public struct JSONGenerator : GeneratorType { public typealias Element = (String, JSON) private let type: Type private var dictionayGenerate: DictionaryGenerator<String, AnyObject>? private var arrayGenerate: IndexingGenerator<[AnyObject]>? private var arrayIndex: Int = 0 init(_ json: JSON) { self.type = json.type if type == .Array { self.arrayGenerate = json.rawArray.generate() }else { self.dictionayGenerate = json.rawDictionary.generate() } } public mutating func next() -> JSONGenerator.Element? { switch self.type { case .Array: if let o = self.arrayGenerate?.next() { return (String(self.arrayIndex++), JSON(o)) } else { return nil } case .Dictionary: if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() { return (k, JSON(v)) } else { return nil } default: return nil } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case Index(Int) case Key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.Index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.Key(self) } } extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .Array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .Dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .Dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .Index(let index): return self[index: index] case .Key(let key): return self[key: key] } } set { switch sub.jsonKey { case .Index(let index): self[index: index] = newValue case .Key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.removeAtIndex(0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in var d = dictionary d[element.0] = element.1 return d }) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { guard NSJSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return self.rawString case .Number: return self.rawNumber.stringValue case .Bool: return self.rawNumber.boolValue.description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .Dictionary { return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d } } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.rawNumber.boolValue default: return nil } } set { if let newValue = newValue { self.object = NSNumber(bool: newValue) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as? String ?? "" case .Number: return self.object.stringValue case .Bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.rawNumber default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber() { // indicates parse error return NSDecimalNumber.zero() } return decimal case .Number, .Bool: return self.object as? NSNumber ?? NSNumber(int: 0) default: return NSNumber(double: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func isExists() -> Bool{ if let errorValue = error where errorValue.code == ErrorNotExist{ return false } return true } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(double: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(float: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if let newValue = newValue { self.object = NSNumber(integer: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if let newValue = newValue { self.object = NSNumber(unsignedLong: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if let newValue = newValue { self.object = NSNumber(char: newValue) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if let newValue = newValue { self.object = NSNumber(unsignedChar: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if let newValue = newValue { self.object = NSNumber(short: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if let newValue = newValue { self.object = NSNumber(unsignedShort: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(int: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if let newValue = newValue { self.object = NSNumber(unsignedInt: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if let newValue = newValue { self.object = NSNumber(longLong: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if let newValue = newValue { self.object = NSNumber(unsignedLongLong: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber == rhs.rawNumber case (.String, .String): return lhs.rawString == rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber <= rhs.rawNumber case (.String, .String): return lhs.rawString <= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber >= rhs.rawNumber case (.String, .String): return lhs.rawString >= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber > rhs.rawNumber case (.String, .String): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber < rhs.rawNumber case (.String, .String): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } }
mit
7632edfacaea907f94360199990b0198
25.618315
264
0.546898
4.7452
false
false
false
false
jverkoey/swift-midi
LUMI/Internal/MIDIExtensions.swift
1
1074
import CoreMIDI /// Convenience method for retrieving a MIDIEndpointRef's parent MIDIDeviceRef. func MIDIEndpointGetDevice(inEndpoint: MIDIEndpointRef, _ outDevice: UnsafeMutablePointer<MIDIDeviceRef>) -> OSStatus { var entityRef: MIDIEntityRef = 0 var status = MIDIEndpointGetEntity(inEndpoint, &entityRef) guard status == noErr else { return status } var deviceRef: MIDIDeviceRef = 0 status = MIDIEntityGetDevice(entityRef, &deviceRef) guard status == noErr else { return status } outDevice.memory = deviceRef return noErr } extension MIDINotificationMessageID : CustomStringConvertible { public var description: String { switch self { case .MsgIOError: return "MsgIOError" case .MsgObjectAdded: return "MsgObjectAdded" case .MsgObjectRemoved: return "MsgObjectRemoved" case .MsgPropertyChanged: return "MsgPropertyChanged" case .MsgSerialPortOwnerChanged: return "MsgSerialPortOwnerChanged" case .MsgSetupChanged: return "MsgSetupChanged" case .MsgThruConnectionsChanged: return "MsgThruConnectionsChanged" } } }
apache-2.0
6cec63020c9fe9b950906790ff2775e7
38.777778
119
0.774674
4.195313
false
false
false
false
aulas-lab/ads-ios
Optional/Optional/Professor.swift
1
909
// // Professor.swift // Optional // // Created by Mobitec on 24/08/16. // Copyright (c) 2016 Unopar. All rights reserved. // import Cocoa class Professor { var nome : String init(nome: String) { self.nome = nome } } class Disciplina { var nome: String var professor: Professor? init(nome: String) { self.nome = nome } init(nome: String, professor: Professor) { self.nome = nome self.professor = professor } } var p = Professor(nome: "Joao da Silva") var pOG = Disciplina(nome: "POG", professor: p) var aOO = Disciplina(nome: "Analise OO") func imprimir(d: Disciplina) { if let np = aOO.professor?.nome { println("Professor: \(np)") } } func alteraNomeProfessor(p: Disciplina, novoNome: String) { p.professor?.nome = novoNome if let prof = p.professor { prof.nome = novoNome } }
mit
2463238213cbf29dadd9d85eb946d361
17.55102
59
0.60176
3.178322
false
false
false
false
NirvanAcN/JRLoopView
JRLoopView/ViewController.swift
1
3212
// // ViewController.swift // JRLoopView // // Created by 京睿 on 2017/3/30. // Copyright © 2017年 京睿. All rights reserved. // import UIKit class ViewController: UIViewController { // @IBOutlet weak var loopView: JRLoopView! var loopView: JRLoopView! var data: [String] = [ // "http://image.jingruiwangke.com/p/p8e4b9d1f3d5149fa818c89fe83e914f2.png", // "http://image.jingruiwangke.com/p/p9d1ad504e31f4ea382f4827488d04b46.png", // "http://image.jingruiwangke.com/p/pfe5405ba62a94ee8bdefe3f6693eb1a5.png", // "http://image.jingruiwangke.com/p/p8e4b9d1f3d5149fa818c89fe83e914f2.png", // "http://image.jingruiwangke.com/p/p9d1ad504e31f4ea382f4827488d04b46.png", // "http://image.jingruiwangke.com/p/pfe5405ba62a94ee8bdefe3f6693eb1a5.png", // "http://image.jingruiwangke.com/p/p8e4b9d1f3d5149fa818c89fe83e914f2.png", // "http://image.jingruiwangke.com/p/p9d1ad504e31f4ea382f4827488d04b46.png", // "http://image.jingruiwangke.com/p/pfe5405ba62a94ee8bdefe3f6693eb1a5.png" ] var type: JRLoopViewDataSourceType = .urlString override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // let foo = JRLoopView.loopView(frame: CGRect.init(x: 0, y: 0, width: 320, height: 200)) // view.addSubview(foo) // data = ["5.jpeg", "4.jpeg"] loopView = JRLoopView.loopView(frame: CGRect.zero) loopView.delegate = self loopView.dataSource = self view.addSubview(loopView) loopView.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() $0.height.equalTo(200) } } @IBAction func click(_ sender: UIButton) { type = .name data = ["5.jpeg", "4.jpeg", "2.jpg"] loopView.reloadData() } } extension ViewController: JRLoopViewDataSource { func loopView(isAutoLoopFor loopView: JRLoopView) -> Bool { return true } func loopView(imagesSourceType loopView: JRLoopView) -> JRLoopViewDataSourceType { return type } func loopView(imagesURLStringFor loopView: JRLoopView) -> [String] { return data } func loopView(imagesNameFor loopView: JRLoopView) -> [String] { return data } func loopView(placeHolderFor loopView: JRLoopView) -> UIImage! { return UIImage.init(named: "2.jpg") } // func loopView(contentModeFor loopView: JRLoopView) -> UIViewContentMode { // return .scaleAspectFit // } func loopView(autoLoopFor loopView: JRLoopView) -> Bool { return true } func loopView(autoLoopTimeIntervalFor loopView: JRLoopView) -> TimeInterval { return 1.JRSeconds } func loopView(isShowPageControlFor loopView: JRLoopView) -> Bool { return true } func loopView(currentPageFor loopView: JRLoopView) -> Int { return 50 } } extension ViewController: JRLoopViewDelegate { func loopView(_ loopView: JRLoopView, didSelectAt index: Int) { print(index) } }
mit
810e63f6c05fa4403dc292732090b242
30.07767
104
0.642299
3.330905
false
false
false
false
The-iPocalypse/BA-iOS-Application
src/AddBAFormViewController.swift
1
2234
// // AddBAFormViewController.swift // BA-iOS-Application // // Created by Maxime Mongeau on 2016-02-12. // Copyright © 2016 Samuel Bellerose. All rights reserved. // import UIKit import Eureka import MapKit import SwiftyJSON class AddBAFormViewController: FormViewController { let user: String = "Super user" override func viewDidLoad() { super.viewDidLoad() title = "Nouvelle BA" form +++= TextRow("title"){ $0.title = "Titre" $0.placeholder = "Requis" } <<< TextAreaRow("description"){$0.placeholder = "Description"} <<< DateTimeInlineRow("startDate"){$0.title = "Début"} <<< DateTimeInlineRow("endDate"){$0.title = "Fin"} <<< IntRow("nbBenevole"){$0.title = "Nombre de bénévoles"} <<< LocationRow("location"){ $0.title = "Lieu" } } @IBAction func cancelPressed(sender: UIBarButtonItem) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func donePressed(sender: UIBarButtonItem) { var formattedData = [String: AnyObject]() for (tag, value) in form.values() { guard let value = value else { let ac = UIAlertController(title: "Erreur", message: "Le champs \(tag) n'est pas remplie", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) return } if tag == "startDate" || tag == "endDate" { let date = (value as! NSDate).timeIntervalSince1970 formattedData[tag] = date } else if tag == "location" { let coordinate = (value as! CLLocation).coordinate formattedData[tag] = ["longitude": coordinate.longitude, "latitude": coordinate.latitude] } else { formattedData[tag] = (value as! AnyObject) } } let jsonData = try? NSJSONSerialization.dataWithJSONObject(formattedData, options: .PrettyPrinted) } }
mit
7aa0c4f0f280feb3c531f05b8a262124
36.166667
130
0.578027
4.597938
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Settings/CellDescriptors/SettingsCellDescriptorFactory.swift
1
19702
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // 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 Foundation import SafariServices import WireSyncEngine import avs class SettingsCellDescriptorFactory { static let settingsDevicesCellIdentifier: String = "devices" let settingsPropertyFactory: SettingsPropertyFactory let userRightInterfaceType: UserRightInterface.Type init(settingsPropertyFactory: SettingsPropertyFactory, userRightInterfaceType: UserRightInterface.Type = UserRight.self) { self.settingsPropertyFactory = settingsPropertyFactory self.userRightInterfaceType = userRightInterfaceType } func rootGroup(isTeamMember: Bool) -> SettingsControllerGeneratorType & SettingsInternalGroupCellDescriptorType { var rootElements: [SettingsCellDescriptorType] = [] if ZMUser.selfUser().canManageTeam { rootElements.append(self.manageTeamCell()) } rootElements.append(settingsGroup(isTeamMember: isTeamMember)) #if MULTIPLE_ACCOUNTS_DISABLED // We skip "add account" cell #else rootElements.append(self.addAccountOrTeamCell()) #endif let topSection = SettingsSectionDescriptor(cellDescriptors: rootElements) return SettingsGroupCellDescriptor(items: [topSection], title: L10n.Localizable.Self.profile, style: .plain, accessibilityBackButtonText: L10n.Accessibility.Settings.BackButton.description) } func manageTeamCell() -> SettingsCellDescriptorType { return SettingsExternalScreenCellDescriptor(title: "self.settings.manage_team.title".localized, isDestructive: false, presentationStyle: PresentationStyle.modal, identifier: nil, presentationAction: { () -> (UIViewController?) in return BrowserViewController(url: URL.manageTeam(source: .settings)) }, previewGenerator: nil, icon: .team, accessoryViewMode: .alwaysHide) } func addAccountOrTeamCell() -> SettingsCellDescriptorType { let presentationAction: () -> UIViewController? = { if SessionManager.shared?.accountManager.accounts.count < SessionManager.shared?.maxNumberAccounts { SessionManager.shared?.addAccount() } else { if let controller = UIApplication.shared.topmostViewController(onlyFullScreen: false) { let alert = UIAlertController( title: "self.settings.add_account.error.title".localized, message: "self.settings.add_account.error.message".localized, alertAction: .ok(style: .cancel)) controller.present(alert, animated: true, completion: nil) } } return nil } return SettingsExternalScreenCellDescriptor(title: "self.settings.add_team_or_account.title".localized, isDestructive: false, presentationStyle: PresentationStyle.modal, identifier: nil, presentationAction: presentationAction, previewGenerator: nil, icon: .plus, accessoryViewMode: .alwaysHide) } func settingsGroup(isTeamMember: Bool) -> SettingsControllerGeneratorType & SettingsInternalGroupCellDescriptorType { var topLevelElements = [accountGroup(isTeamMember: isTeamMember), devicesCell(), optionsGroup, advancedGroup, helpSection(), aboutSection()] if Bundle.developerModeEnabled { topLevelElements.append(self.developerGroup()) } let topSection = SettingsSectionDescriptor(cellDescriptors: topLevelElements) return SettingsGroupCellDescriptor(items: [topSection], title: L10n.Localizable.Self.settings, style: .plain, previewGenerator: .none, icon: .gear, accessibilityBackButtonText: L10n.Accessibility.Settings.BackButton.description) } func devicesCell() -> SettingsCellDescriptorType { return SettingsExternalScreenCellDescriptor(title: "self.settings.privacy_analytics_menu.devices.title".localized, isDestructive: false, presentationStyle: PresentationStyle.navigation, identifier: type(of: self).settingsDevicesCellIdentifier, presentationAction: { () -> (UIViewController?) in return ClientListViewController(clientsList: .none, credentials: .none, detailedView: true) }, previewGenerator: { _ -> SettingsCellPreview in return SettingsCellPreview.badge(ZMUser.selfUser().clients.count) }, icon: .devices) } func soundGroupForSetting(_ settingsProperty: SettingsProperty, title: String, customSounds: [ZMSound], defaultSound: ZMSound) -> SettingsCellDescriptorType { let items: [ZMSound] = [ZMSound.None, defaultSound] + customSounds let previewPlayer: SoundPreviewPlayer = SoundPreviewPlayer(mediaManager: AVSMediaManager.sharedInstance()) let cells: [SettingsPropertySelectValueCellDescriptor] = items.map { item in let playSoundAction: SettingsPropertySelectValueCellDescriptor.SelectActionType = { _ in switch settingsProperty.propertyName { case .callSoundName: previewPlayer.playPreview(.ringingFromThemSound) case .pingSoundName: previewPlayer.playPreview(.incomingKnockSound) case .messageSoundName: previewPlayer.playPreview(.messageReceivedSound) default: break } } let propertyValue = item == defaultSound ? SettingsPropertyValue.none : SettingsPropertyValue.string(value: item.rawValue) return SettingsPropertySelectValueCellDescriptor(settingsProperty: settingsProperty, value: propertyValue, title: item.descriptionLocalizationKey.localized, identifier: .none, selectAction: playSoundAction) } let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }, header: "self.settings.sound_menu.ringtones.title".localized) let previewGenerator: PreviewGeneratorType = { _ in let value = settingsProperty.value() if let stringValue = value.value() as? String, let enumValue = ZMSound(rawValue: stringValue) { return .text(enumValue.descriptionLocalizationKey.localized) } else { return .text(defaultSound.descriptionLocalizationKey.localized) } } return SettingsGroupCellDescriptor(items: [section], title: title, identifier: .none, previewGenerator: previewGenerator, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description) } func developerGroup() -> SettingsCellDescriptorType { var developerCellDescriptors: [SettingsCellDescriptorType] = [] typealias ExternalScreen = SettingsExternalScreenCellDescriptor typealias Toggle = SettingsPropertyToggleCellDescriptor typealias Button = SettingsButtonCellDescriptor developerCellDescriptors.append( ExternalScreen(title: "Logging") { DeveloperOptionsController() } ) developerCellDescriptors.append( Toggle(settingsProperty: settingsPropertyFactory.property(.enableBatchCollections)) ) developerCellDescriptors.append( Button(title: "Send broken message", isDestructive: true, selectAction: DebugActions.sendBrokenMessage) ) developerCellDescriptors.append( Button(title: "First unread conversation (badge count)", isDestructive: false, selectAction: DebugActions.findUnreadConversationContributingToBadgeCount) ) developerCellDescriptors.append( Button(title: "First unread conversation (back arrow count)", isDestructive: false, selectAction: DebugActions.findUnreadConversationContributingToBackArrowDot) ) developerCellDescriptors.append( Button(title: "Delete invalid conversations", isDestructive: false, selectAction: DebugActions.deleteInvalidConversations) ) developerCellDescriptors.append(SettingsShareDatabaseCellDescriptor()) developerCellDescriptors.append(SettingsShareCryptoboxCellDescriptor()) developerCellDescriptors.append( Button(title: "Reload user interface", isDestructive: false, selectAction: DebugActions.reloadUserInterface) ) developerCellDescriptors.append( Button(title: "Re-calculate badge count", isDestructive: false, selectAction: DebugActions.recalculateBadgeCount) ) developerCellDescriptors.append( Button(title: "Append N messages to the top conv (not sending)", isDestructive: true) { _ in DebugActions.askNumber(title: "Enter count of messages") { count in DebugActions.appendMessagesInBatches(count: count) } } ) developerCellDescriptors.append( Button(title: "Spam the top conv", isDestructive: true) { _ in DebugActions.askNumber(title: "Enter count of messages") { count in DebugActions.spamWithMessages(amount: count) } } ) developerCellDescriptors.append( ExternalScreen(title: "Show database statistics", isDestructive: false, presentationStyle: .navigation, presentationAction: { DatabaseStatisticsController() }) ) if !Analytics.shared.isOptedOut && !TrackingManager.shared.disableAnalyticsSharing { developerCellDescriptors.append( Button(title: "Reset call quality survey", isDestructive: false, selectAction: DebugActions.resetCallQualitySurveyMuteFilter) ) } developerCellDescriptors.append( Button(title: "Generate test crash", isDestructive: false, selectAction: DebugActions.generateTestCrash) ) developerCellDescriptors.append( Button(title: "Trigger slow sync", isDestructive: false, selectAction: DebugActions.triggerSlowSync) ) developerCellDescriptors.append( Button(title: "What's my analytics id?", isDestructive: false, selectAction: DebugActions.showAnalyticsIdentifier) ) developerCellDescriptors.append( Button(title: "What's the api version?", isDestructive: false, selectAction: DebugActions.showAPIVersionInfo) ) return SettingsGroupCellDescriptor(items: [SettingsSectionDescriptor(cellDescriptors: developerCellDescriptors)], title: L10n.Localizable.`Self`.Settings.DeveloperOptions.title, icon: .robot, accessibilityBackButtonText: L10n.Accessibility.DeveloperOptionsSettings.BackButton.description) } func helpSection() -> SettingsCellDescriptorType { let supportButton = SettingsExternalScreenCellDescriptor(title: "self.help_center.support_website".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: URL.wr_support.appendingLocaleParameter) }, previewGenerator: .none) let contactButton = SettingsExternalScreenCellDescriptor(title: "self.help_center.contact_support".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: URL.wr_askSupport.appendingLocaleParameter) }, previewGenerator: .none) let helpSection = SettingsSectionDescriptor(cellDescriptors: [supportButton, contactButton]) let reportButton = SettingsExternalScreenCellDescriptor(title: "self.report_abuse".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: URL.wr_reportAbuse.appendingLocaleParameter) }, previewGenerator: .none) let reportSection = SettingsSectionDescriptor(cellDescriptors: [reportButton]) return SettingsGroupCellDescriptor(items: [helpSection, reportSection], title: L10n.Localizable.Self.helpCenter, style: .grouped, identifier: .none, previewGenerator: .none, icon: .settingsSupport, accessibilityBackButtonText: L10n.Accessibility.SupportSettings.BackButton.description) } func aboutSection() -> SettingsCellDescriptorType { let privacyPolicyButton = SettingsExternalScreenCellDescriptor(title: "about.privacy.title".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: URL.wr_privacyPolicy.appendingLocaleParameter) }, previewGenerator: .none) let tosButton = SettingsExternalScreenCellDescriptor(title: "about.tos.title".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { let url = URL.wr_termsOfServicesURL.appendingLocaleParameter return BrowserViewController(url: url) }, previewGenerator: .none) let shortVersion = Bundle.main.shortVersionString ?? "Unknown" let buildNumber = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "Unknown" var currentYear = NSCalendar.current.component(.year, from: Date()) if currentYear < 2014 { currentYear = 2014 } let version = String(format: "Version %@ (%@)", shortVersion, buildNumber) let copyrightInfo = String(format: "about.copyright.title".localized, currentYear) let linksSection = SettingsSectionDescriptor( cellDescriptors: [tosButton, privacyPolicyButton, licensesSection()], header: nil, footer: "\n" + version + "\n" + copyrightInfo ) let websiteButton = SettingsExternalScreenCellDescriptor(title: "about.website.title".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: URL.wr_website.appendingLocaleParameter) }, previewGenerator: .none) let websiteSection = SettingsSectionDescriptor(cellDescriptors: [websiteButton]) return SettingsGroupCellDescriptor( items: [websiteSection, linksSection], title: L10n.Localizable.Self.about, style: .grouped, identifier: .none, previewGenerator: .none, icon: .about, accessibilityBackButtonText: L10n.Accessibility.AboutSettings.BackButton.description ) } func licensesSection() -> SettingsCellDescriptorType { guard let licenses = LicensesLoader.shared.loadLicenses() else { return webLicensesSection() } let childItems: [SettingsGroupCellDescriptor] = licenses.map { item in let projectCell = SettingsExternalScreenCellDescriptor(title: "about.license.open_project_button".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { return BrowserViewController(url: item.projectURL) }, previewGenerator: .none) let detailsSection = SettingsSectionDescriptor(cellDescriptors: [projectCell], header: "about.license.project_header".localized, footer: nil) let licenseCell = SettingsStaticTextCellDescriptor(text: item.licenseText) let licenseSection = SettingsSectionDescriptor(cellDescriptors: [licenseCell], header: "about.license.license_header".localized, footer: nil) return SettingsGroupCellDescriptor(items: [detailsSection, licenseSection], title: item.name, style: .grouped, accessibilityBackButtonText: L10n.Accessibility.LicenseDetailsSettings.BackButton.description) } let licensesSection = SettingsSectionDescriptor(cellDescriptors: childItems) return SettingsGroupCellDescriptor(items: [licensesSection], title: L10n.Localizable.About.License.title, style: .plain, accessibilityBackButtonText: L10n.Accessibility.LicenseInformationSettings.BackButton.description) } func webLicensesSection() -> SettingsCellDescriptorType { return SettingsExternalScreenCellDescriptor(title: "about.license.title".localized, isDestructive: false, presentationStyle: .modal, presentationAction: { let url = URL.wr_licenseInformation.appendingLocaleParameter return BrowserViewController(url: url) }, previewGenerator: .none) } }
gpl-3.0
33984c230cbc4af8f586caae12bd6ec1
48.502513
218
0.611918
6.045413
false
false
false
false
matfur92/SwiftMongoDB
swiftMongoDB/MongoDocument.swift
1
4201
// // MongoDocument.swift // swiftMongoDB // // Created by Dan Appel on 8/20/15. // Copyright © 2015 Dan Appel. All rights reserved. // import SwiftyJSON public class MongoDocument { let BSONRAW: _bson_ptr_mutable = bson_new() public var JSONString: String? { return JSON(self.data).rawString() } public var JSONValue: JSON { return JSON(self.data) } public var dataWithoutObjectId: DocumentData { var copy = self.data copy["_id"] = nil return copy } public var data: DocumentData { return self.documentData } public var id: String? { return self.data["_id"]?["$oid"] as? String } private var documentData = DocumentData() private func initBSON() { try! MongoBSONEncoder(data: self.data).copyTo(self.BSONRAW) } public init(let data: DocumentData) throws { self.documentData = data self.initBSON() } convenience public init(var data: DocumentData, withObjectId objectId: String) throws { data["_id"] = ["$oid" : objectId] try self.init(data: data) } convenience public init(JSON: String, withObjectId objectId: String) throws { guard let data = JSON.parseJSONDocumentData else { throw MongoError.CorruptDocument } try self.init(data: data, withObjectId: objectId) } convenience public init(JSON: String) throws { guard let data = JSON.parseJSONDocumentData else { throw MongoError.CorruptDocument } try self.init(data: data) } convenience public init(withSchemaObject object: MongoObject, withObjectID objectId: String) throws { let data = object.properties() try self.init(data: data, withObjectId: objectId) } convenience public init(withSchemaObject object: MongoObject) throws { let data = object.properties() try self.init(data: data) } private func generateObjectId() -> String { var oidRAW = bson_oid_t() bson_oid_init(&oidRAW, nil) let oidStrRAW = UnsafeMutablePointer<Int8>.alloc(100) // try to minimize this memory usage while retaining safety, reference: // 4 bytes : The UNIX timestamp in big-endian format. // 3 bytes : The first 3 bytes of MD5(hostname). // 2 bytes : The pid_t of the current process. Alternatively the task-id if configured. // 3 bytes : A 24-bit monotonic counter incrementing from rand() in big-endian. bson_oid_to_string(&oidRAW, oidStrRAW) let oidStr = NSString(UTF8String: oidStrRAW) oidStrRAW.destroy() return oidStr as! String } public func getObjectFromKey(key : String) -> AnyObject? { return self.data[key] } public func getKeys() -> [String]{ var keys = [String]() for (key, _ ) in self.JSONValue { keys.append(key) } keys = keys.sort(<) return keys } deinit { self.BSONRAW.destroy() } } public func == (lhs: MongoDocument, rhs: MongoDocument) -> Bool { return (lhs.data as! [String : NSObject]) == (rhs.data as! [String : NSObject]) } public func != (lhs: MongoDocument, rhs: MongoDocument) -> Bool { return !(lhs == rhs) } public func != (lhs: DocumentData, rhs: DocumentData) -> Bool { return !(lhs == rhs) } public func == (lhs: DocumentData, rhs: DocumentData) -> Bool { // if they're of different sizes if lhs.count != rhs.count { return false } // only need to check from one side because they're the same size - if something doesn't match then they aren't equal. // check that rhs contains all of lhs for (lhkey, lhvalue) in lhs { let lhval = lhvalue as! NSObject // casting into nsobject if let rhval = rhs[lhkey] as? NSObject { // if they're not the same, return false if rhval != lhval { return false } } } return true }
mit
e124f2d19b05576a596bfbac8ab1f4c6
24.149701
122
0.589048
4.191617
false
false
false
false
Marketcloud/marketcloud-swift-application
mCloudSampleApp/Checkout1ViewCtrl.swift
1
4051
import UIKit //Controller for the first part of the checkout class Checkout1ViewCtrl: UIViewController, UITextFieldDelegate { @IBOutlet weak var fullnameLabel: UITextField! @IBOutlet weak var countryLabel: UITextField! @IBOutlet weak var stateLabel: UITextField! @IBOutlet weak var cityLabel: UITextField! @IBOutlet weak var addressLabel: UITextField! @IBOutlet weak var postalcodeLabel: UITextField! override func viewDidLoad() { self.automaticallyAdjustsScrollViewInsets = false } //---------------TEXTFIELD func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func textFieldDidEndEditing(_ textField: UITextField) { /* print(fullnameLabel.text!) print(countryLabel.text!) print(stateLabel.text!) print(cityLabel.text!) print(addressLabel.text!) print(postalcodeLabel.text!) //Do nothing */ } //validates fields, saves the address then goes to the next view @IBAction func nextButton(_ sender: UIButton) { if(validator()) { let fullname = (fullnameLabel.text!) let country = (countryLabel.text!) let state = (stateLabel.text!) let city = (cityLabel.text!) let address = (addressLabel.text!) let postalCode = (postalcodeLabel.text!) let email = UserData.getLastLoggedUserEmail() print("validator is ok. \n email is \(email)") let testAddress:[String:String] = ["email":email,"full_name": fullname,"country" : country, "state": state, "city": city, "address1": address, "postal_code": postalCode] let shippingAddress = MarketcloudMain.getMcloud()!.createAddress(testAddress) print(shippingAddress) guard (shippingAddress["status"] != nil) else { let alertController = UIAlertController(title: "Error", message: "All fields must be filled", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.destructive, handler: nil)) self.present(alertController, animated: true, completion: nil) return } guard (shippingAddress["status"] as! Int != 0) else { let alertController = UIAlertController(title: "Error", message: "Critical error in creating new address", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.destructive, handler: nil)) self.present(alertController, animated: true, completion: nil) return } UserData.lastAddressId = (shippingAddress.value(forKey: "data") as! NSDictionary).value(forKey: "id") as! Int UserData.lastAddressInfos = "\(fullname) \n\(country),\(state) \n\(city), \(address) - \(postalCode)" self.performSegue(withIdentifier: "check2", sender: sender) } } //validates the fields func validator() -> Bool { guard (!fullnameLabel.text!.isEmpty && !countryLabel.text!.isEmpty && !stateLabel.text!.isEmpty && !cityLabel.text!.isEmpty && !addressLabel.text!.isEmpty && !postalcodeLabel.text!.isEmpty) else { let alertController = UIAlertController(title: "Error", message: "All fields must be filled out in order to process the request", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.destructive, handler: nil)) self.present(alertController, animated: true, completion: nil) return false } self.view.endEditing(true) return true } }
apache-2.0
4eb02b4953cb5f66ab5139b5a9c36c37
39.51
205
0.605036
5.213642
false
false
false
false
danpratt/Simply-Zen
Simply Zen/View Controllers/LessonsTableViewCell.swift
1
2531
// // LessonsTableViewCell.swift // Simply Zen // // Created by Daniel Pratt on 10/4/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import UIKit class LessonsTableViewCell: UITableViewCell { @IBOutlet weak var lessonTitle: UILabel! @IBOutlet weak var playButton: UIButton! // Course info var lesson: SZLesson? var course: SZCourse? // View to load var meditationVC: MeditationViewController? var navigation: UINavigationController? // Delegate let delegate = UIApplication.shared.delegate as! AppDelegate override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func playButtonTapped(_ sender: Any) { print("Playing \(String(describing: lesson?.lessonName))") // Create variables for VC and course / lesson to load let selectedCourse = course?.name var addedCourse = false var coreDataCourse: Course! let maxLevel = course?.lessons.count // Check to see if the user already has a history if let courses = self.delegate.user.courses?.array as? [Course] { for course in courses { if course.courseName == selectedCourse { addedCourse = true coreDataCourse = course _ = Int(course.userProgress) break } } } // If the course hasn't been added yet create it and add to the user if !addedCourse { // create course Core Data object and add it to user print("creating course") coreDataCourse = Course(courseName: selectedCourse!, user: delegate.user, insertInto: delegate.stack.context) delegate.user.addToCourses(coreDataCourse) print(delegate.user.courses?.array ?? "No courses") delegate.stack.save() } // Load lesson and attach to meditationVC meditationVC?.lesson = self.lesson meditationVC?.lessonFileName = meditationVC?.lesson.lessonFileName meditationVC?.coreDataCourse = coreDataCourse meditationVC?.maxLevel = maxLevel! navigation?.pushViewController(meditationVC!, animated: true) } }
apache-2.0
8aa9e99af05e343e959c7eba01c59ffe
31.435897
121
0.611858
5.195072
false
false
false
false
Pluto-tv/RxSwift
RxSwift/Observables/Implementations/TakeWhile.swift
1
3573
// // TakeWhile.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TakeWhileSink<ElementType, O: ObserverType where O.E == ElementType> : Sink<O>, ObserverType { typealias Parent = TakeWhile<ElementType> typealias Element = ElementType private let _parent: Parent private var _running = true init(parent: Parent, observer: O, cancel: Disposable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let value): if !_running { return } do { _running = try _parent._predicate(value) } catch let e { observer?.onError(e) dispose() return } if _running { observer?.onNext(value) } else { observer?.onComplete() dispose() } case .Error, .Completed: observer?.on(event) dispose() } } } class TakeWhileSinkWithIndex<ElementType, O: ObserverType where O.E == ElementType> : Sink<O>, ObserverType { typealias Parent = TakeWhile<ElementType> typealias Element = ElementType private let _parent: Parent private var _running = true private var _index = 0 init(parent: Parent, observer: O, cancel: Disposable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let value): if !_running { return } do { _running = try _parent._predicateWithIndex(value, _index) try incrementChecked(&_index) } catch let e { observer?.onError(e) dispose() return } if _running { observer?.onNext(value) } else { observer?.onComplete() dispose() } case .Error, .Completed: observer?.on(event) dispose() } } } class TakeWhile<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool typealias PredicateWithIndex = (Element, Int) throws -> Bool private let _source: Observable<Element> private let _predicate: Predicate! private let _predicateWithIndex: PredicateWithIndex! init(source: Observable<Element>, predicate: Predicate) { _source = source _predicate = predicate _predicateWithIndex = nil } init(source: Observable<Element>, predicate: PredicateWithIndex) { _source = source _predicate = nil _predicateWithIndex = predicate } override func run<O : ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { if let _ = _predicate { let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return _source.subscribeSafe(sink) } else { let sink = TakeWhileSinkWithIndex(parent: self, observer: observer, cancel: cancel) setSink(sink) return _source.subscribeSafe(sink) } } }
mit
bbb5e98f776912aab8abead565aaedef
26.921875
140
0.539882
4.948753
false
false
false
false
vmouta/GitHubSpy
GitHubSpy/ViewController.swift
1
2909
/** * @name ViewController.swift * @partof GitHubSpy * @description * @author Vasco Mouta * @created 17/12/15 * * Copyright (c) 2015 zucred AG All rights reserved. * This material, including documentation and any related * computer programs, is protected by copyright controlled by * zucred AG. All rights are reserved. Copying, * including reproducing, storing, adapting or translating, any * or all of this material requires the prior written consent of * zucred AG. This material also contains confidential * information which may not be disclosed to others without the * prior written consent of zucred AG. */ import UIKit class ViewController: UIViewController { static let BaseUrl = "https://api.github.com/" static let OrgsUrlPath = "orgs/" static let UserUrlPath = "users/" static let ReposUrlPath = "repos/" static let DefaultUser: String = "vmouta" static let DefaultOrganization: String = "zucred" @IBOutlet weak var type: UISegmentedControl! @IBAction func typeChange(sender: AnyObject) { if isUserType { user.placeholder = ViewController.DefaultUser } else { user.placeholder = ViewController.DefaultOrganization } } @IBOutlet weak var user: UITextField! @IBAction func doneUserName(sender: AnyObject) { guard self.url != nil else { // TODO: Show something to the user print("Invalide Name") return } self.user?.endEditing(true) } var url: NSURL? { var url = ViewController.BaseUrl if(self.isUserType) { url += ViewController.UserUrlPath + (user.text?.isEmpty==false ? user.text! : ViewController.DefaultUser) } else { url += ViewController.OrgsUrlPath + (user.text?.isEmpty==false ? user.text! : ViewController.DefaultOrganization) } url += "/repos" return NSURL ( string : url ) } func commitsUrl(repository: String) -> NSURL? { var url = ViewController.BaseUrl + ViewController.ReposUrlPath if(self.isUserType) { url += (user.text?.isEmpty==false ? user.text! : ViewController.DefaultUser) + "/" + repository } else { url += (user.text?.isEmpty==false ? user.text! : ViewController.DefaultOrganization) + "/" + repository } url += "/commits" return NSURL ( string : url ) } var isUserType: Bool { return (type.selectedSegmentIndex == 0) } // MARK: UIViewController 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. } }
mit
255ee4880ea6be001b7808f17ef2cf54
32.436782
125
0.631488
4.46851
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/Linkage.swift
1
11878
#if SWIFT_PACKAGE import cllvm #endif /// `Visibility` enumerates available visibility styles. public enum Visibility { /// On targets that use the ELF object file format, default visibility means /// that the declaration is visible to other modules and, in shared libraries, /// means that the declared entity may be overridden. On Darwin, default /// visibility means that the declaration is visible to other modules. Default /// visibility corresponds to "external linkage" in the language. case `default` /// Two declarations of an object with hidden visibility refer to the same /// object if they are in the same shared object. Usually, hidden visibility /// indicates that the symbol will not be placed into the dynamic symbol /// table, so no other module (executable or shared library) can reference it /// directly. case hidden /// On ELF, protected visibility indicates that the symbol will be placed in /// the dynamic symbol table, but that references within the defining module /// will bind to the local symbol. That is, the symbol cannot be overridden by /// another module. case protected static let visibilityMapping: [Visibility: LLVMVisibility] = [ .default: LLVMDefaultVisibility, .hidden: LLVMHiddenVisibility, .protected: LLVMProtectedVisibility, ] internal init(llvm: LLVMVisibility) { switch llvm { case LLVMDefaultVisibility: self = .default case LLVMHiddenVisibility: self = .hidden case LLVMProtectedVisibility: self = .protected default: fatalError("unknown visibility type \(llvm)") } } /// Retrieves the corresponding `LLVMLinkage`. public var llvm: LLVMVisibility { return Visibility.visibilityMapping[self]! } } /// `Linkage` enumerates the supported kinds of linkage for global values. All /// global variables and functions have a linkage. public enum Linkage { /// Externally visible function. This is the default linkage. /// /// If none of the other linkages are specified, the global is externally /// visible, meaning that it participates in linkage and can be used to /// resolve external symbol references. case external /// Available for inspection, not emission. /// /// Globals with "available_externally" linkage are never emitted into the /// object file corresponding to the LLVM module. From the linker’s /// perspective, an available_externally global is equivalent to an external /// declaration. They exist to allow inlining and other optimizations to take /// place given knowledge of the definition of the global, which is known to /// be somewhere outside the module. Globals with available_externally linkage /// are allowed to be discarded at will, and allow inlining and other /// optimizations. This linkage type is only allowed on definitions, not /// declarations. case availableExternally /// Keep one copy of function when linking. /// /// Globals with "linkonce" linkage are merged with other globals of the same /// name when linkage occurs. This can be used to implement some forms of /// inline functions, templates, or other code which must be generated in each /// translation unit that uses it, but where the body may be overridden with a /// more definitive definition later. Unreferenced linkonce globals are /// allowed to be discarded. Note that linkonce linkage does not actually /// allow the optimizer to inline the body of this function into callers /// because it doesn’t know if this definition of the function is the /// definitive definition within the program or whether it will be overridden /// by a stronger definition. case linkOnceAny /// Keep one copy of function when linking but enable inlining and /// other optimizations. /// /// Some languages allow differing globals to be merged, such as two functions /// with different semantics. Other languages, such as C++, ensure that only /// equivalent globals are ever merged (the "one definition rule" — "ODR"). /// Such languages can use the linkonce_odr and weak_odr linkage types to /// indicate that the global will only be merged with equivalent globals. /// These linkage types are otherwise the same as their non-odr versions. case linkOnceODR /// Keep one copy of function when linking (weak). /// /// "weak" linkage has the same merging semantics as linkonce linkage, except /// that unreferenced globals with weak linkage may not be discarded. This is /// used for globals that are declared "weak" in C source code. case weakAny /// Keep one copy of function when linking but apply "One Definition Rule" /// semantics. /// /// Some languages allow differing globals to be merged, such as two functions /// with different semantics. Other languages, such as C++, ensure that only /// equivalent globals are ever merged (the "one definition rule" — "ODR"). /// Such languages can use the linkonce_odr and weak_odr linkage types to /// indicate that the global will only be merged with equivalent globals. /// These linkage types are otherwise the same as their non-odr versions. case weakODR /// Special purpose, only applies to global arrays. /// /// "appending" linkage may only be applied to global variables of pointer to /// array type. When two global variables with appending linkage are linked /// together, the two global arrays are appended together. This is the LLVM, /// typesafe, equivalent of having the system linker append together /// "sections" with identical names when .o files are linked. /// /// Unfortunately this doesn’t correspond to any feature in .o files, so it /// can only be used for variables like llvm.global_ctors which llvm /// interprets specially. case appending /// Rename collisions when linking (static functions). /// /// Similar to private, but the value shows as a local symbol /// (`STB_LOCAL` in the case of ELF) in the object file. This corresponds to /// the notion of the `static` keyword in C. case `internal` /// Like `.internal`, but omit from symbol table. /// /// Global values with "private" linkage are only directly accessible by /// objects in the current module. In particular, linking code into a module /// with an private global value may cause the private to be renamed as /// necessary to avoid collisions. Because the symbol is private to the /// module, all references can be updated. This doesn’t show up in any symbol /// table in the object file. case `private` /// Keep one copy of the function when linking, but apply ELF semantics. /// /// The semantics of this linkage follow the ELF object file model: the symbol /// is weak until linked, if not linked, the symbol becomes null instead of /// being an undefined reference. case externalWeak /// Tentative definitions. /// /// "common" linkage is most similar to "weak" linkage, but they are used for /// tentative definitions in C, such as "int X;" at global scope. Symbols with /// "common" linkage are merged in the same way as weak symbols, and they may /// not be deleted if unreferenced. common symbols may not have an explicit /// section, must have a zero initializer, and may not be marked ‘constant‘. /// Functions and aliases may not have common linkage. case common private static let linkageMapping: [Linkage: LLVMLinkage] = [ .external: LLVMExternalLinkage, .availableExternally: LLVMAvailableExternallyLinkage, .linkOnceAny: LLVMLinkOnceAnyLinkage, .linkOnceODR: LLVMLinkOnceODRLinkage, .weakAny: LLVMWeakAnyLinkage, .weakODR: LLVMWeakODRLinkage, .appending: LLVMAppendingLinkage, .`internal`: LLVMInternalLinkage, .`private`: LLVMPrivateLinkage, .externalWeak: LLVMExternalWeakLinkage, .common: LLVMCommonLinkage, ] internal init(llvm: LLVMLinkage) { switch llvm { case LLVMExternalLinkage: self = .external case LLVMAvailableExternallyLinkage: self = .availableExternally case LLVMLinkOnceAnyLinkage: self = .linkOnceAny case LLVMLinkOnceODRLinkage: self = .linkOnceODR case LLVMWeakAnyLinkage: self = .weakAny case LLVMWeakODRLinkage: self = .weakODR case LLVMAppendingLinkage: self = .appending case LLVMInternalLinkage: self = .internal case LLVMPrivateLinkage: self = .private case LLVMExternalWeakLinkage: self = .externalWeak case LLVMCommonLinkage: self = .common default: fatalError("unknown linkage type \(llvm)") } } /// Retrieves the corresponding `LLVMLinkage`. public var llvm: LLVMLinkage { return Linkage.linkageMapping[self]! } } /// `StorageClass` enumerates the storage classes for globals in a Portable /// Executable file. public enum StorageClass { /// The default storage class for declarations is neither imported nor /// exported to/from a DLL. case `default` /// The storage class that guarantees the existence of a function in a DLL. /// /// Using this attribute can produce tighter code because the compiler may /// skip emitting a thunk and instead directly jump to a particular address. case dllImport /// The storage class for symbols that should be exposed outside of this DLL. /// /// This storage class augments the use of a `.DEF` file, but cannot /// completely replace them. case dllExport private static let storageMapping: [StorageClass: LLVMDLLStorageClass] = [ .`default`: LLVMDefaultStorageClass, .dllImport: LLVMDLLImportStorageClass, .dllExport: LLVMDLLExportStorageClass, ] internal init(llvm: LLVMDLLStorageClass) { switch llvm { case LLVMDefaultStorageClass: self = .`default` case LLVMDLLImportStorageClass: self = .dllImport case LLVMDLLExportStorageClass: self = .dllExport default: fatalError("unknown DLL storage class \(llvm)") } } /// Retrieves the corresponding `LLVMDLLStorageClass`. public var llvm: LLVMDLLStorageClass { return StorageClass.storageMapping[self]! } } /// Enumerates values representing whether or not this global value's address /// is significant in this module or the program at large. A global value's /// address is considered significant if it is referenced by any module in the /// final program. /// /// This attribute is intended to be used only by the code generator and LTO to /// allow the linker to decide whether the global needs to be in the symbol /// table. Constant global values with unnamed addresses and identical /// initializers may be merged by LLVM. Note that a global value with an /// unnamed address may be merged with a global value with a significant address /// resulting in a global value with a significant address. public enum UnnamedAddressKind { /// Indicates that the address of this global value is significant /// in this module. case none /// Indicates that the address of this global value is not significant to the /// current module but it may or may not be significant to another module; /// only the content of the value is known to be significant within the /// current module. case local /// Indicates that the address of this global value is not significant to the /// current module or any other module; only the content of the value /// is significant globally. case global private static let unnamedAddressMapping: [UnnamedAddressKind: LLVMUnnamedAddr] = [ .none: LLVMNoUnnamedAddr, .local: LLVMLocalUnnamedAddr, .global: LLVMGlobalUnnamedAddr, ] internal init(llvm: LLVMUnnamedAddr) { switch llvm { case LLVMNoUnnamedAddr: self = .none case LLVMLocalUnnamedAddr: self = .local case LLVMGlobalUnnamedAddr: self = .global default: fatalError("unknown unnamed address kind \(llvm)") } } internal var llvm: LLVMUnnamedAddr { return UnnamedAddressKind.unnamedAddressMapping[self]! } }
mit
95806d7e07412035f765197b21d1fcfa
43.762264
85
0.73394
4.553551
false
false
false
false
bennyinc/NarrativeView
Example/ViewController.swift
1
5251
// // ViewController.swift // Example // // Created by Robert Manson on 5/5/15. // Copyright (c) 2015 Benny. All rights reserved. // import UIKit import NarrativeView class TextField: UITextField, NarrativeTextFieldSettableAppearance { private let contentInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) var appearance: NarrativeTextFieldAppearance = .Ready { didSet { setNeedsDisplay() } } override func drawRect(rect: CGRect) { let bottomPath = UIBezierPath(rect: CGRectMake(rect.minX, rect.maxY - 4, rect.maxX , rect.maxY - 2)) switch appearance { case .Invalid: UIColor.redColor().setFill() case .Ready: UIColor.blackColor().setFill() case .Valid: UIColor.greenColor().setFill() } bottomPath.fill() } override func editingRectForBounds(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, contentInsets) } override func textRectForBounds(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, contentInsets) } } class ViewController: UIViewController, NarrativeViewDelegate { @IBOutlet weak var allDoneLabel: UILabel! @IBOutlet weak var narrativeView: NarrativeView! let tagger = NSLinguisticTagger(tagSchemes: NSLinguisticTagger.availableTagSchemesForLanguage("en"), options: Int(NSLinguisticTaggerOptions.OmitWhitespace.rawValue)) private func newField(placeholder: String) -> () -> UITextField { return { let field = TextField() field.placeholder = placeholder field.sizeToFit() return field } } let newLabel: () -> UILabel = { let label = UILabel() label.textColor = UIColor.blackColor() return label } var allDone = false { didSet { allDoneLabel.hidden = !allDone } } override func viewDidLoad() { super.viewDidLoad() narrativeView.label(createLabel: newLabel, text: "One Valentines's") .textField(createTextField: newField("noun")) { field in return self.isNoun(field.text ?? "") } .label(createLabel: newLabel, text: "I was") .textField(createTextField: newField("-ing verb")) { field in return self.isIngVerb(field.text ?? "") } .label(createLabel: newLabel, text: ", when I looked in my") .textField(createTextField: newField("noun")) { field in return self.isNoun(field.text ?? "") } .label(createLabel: newLabel, text: "and saw a") .textField(createTextField: newField("adjective")) { field in return self.isAdjective(field.text ?? "") } .textField(createTextField: newField("noun")) { field in return self.isNoun(field.text ?? "") } .label(createLabel: newLabel, text: "!") .initialLayout() narrativeView.narrativeViewDelegate = self narrativeView.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.5) narrativeView.rowHeight = 40.0 narrativeView.rowVerticalPadding = 4.0 narrativeView.setNeedsDisplay() } //MARK: - Helpers func isNoun(s: String) -> Bool { let sentence = "The \(s)" // tagger only works with more than one word? let options: NSLinguisticTaggerOptions = [NSLinguisticTaggerOptions.OmitWhitespace, NSLinguisticTaggerOptions.OmitOther, NSLinguisticTaggerOptions.OmitPunctuation, NSLinguisticTaggerOptions.JoinNames] tagger.string = sentence var ret = false tagger.enumerateTagsInRange(NSMakeRange(0, sentence.characters.count), scheme: NSLinguisticTagSchemeLexicalClass, options: options) { (tag:String, tokenRange:NSRange, _, _) in if tag == NSLinguisticTagNoun { ret = true } } return ret } func isIngVerb(s: String) -> Bool { if let _ = s.rangeOfString("ing$", options: .RegularExpressionSearch) { return true } return false } func isAdjective(s: String) -> Bool { let sentence = "The \(s)" // tagger only works with more than one word? let options: NSLinguisticTaggerOptions = [NSLinguisticTaggerOptions.OmitWhitespace, NSLinguisticTaggerOptions.OmitOther, NSLinguisticTaggerOptions.OmitPunctuation, NSLinguisticTaggerOptions.JoinNames] tagger.string = sentence var ret = false tagger.enumerateTagsInRange(NSMakeRange(0, sentence.characters.count), scheme: NSLinguisticTagSchemeLexicalClass, options: options) { (tag:String, tokenRange:NSRange, _, _) in if tag == NSLinguisticTagAdjective { ret = true } } return ret } //MARK: - NarrativeViewDelegate func narrativeViewDidValidate(allWereValid: Bool) { allDone = allWereValid } func narrativeViewDoneButtonPressed(allWereValid: Bool) -> Bool { if allWereValid { allDone = true return false } else { return true } } }
mit
befd14e311c8ea72b70befe31e8246cb
38.186567
208
0.624452
4.722122
false
false
false
false
szweier/SZMentionsSwift
SZMentionsSwiftTests/Test Helpers/Helper.swift
1
1361
@testable import SZMentionsSwift import UIKit extension NSRange { var advance: NSRange { return NSRange(location: location + 1, length: length) } } struct ExampleMention: CreateMention { var name = "" } enum TextUpdate { case insert case delete case replace } func type(text: String, at range: NSRange? = nil, on listener: MentionListener) { var newRange = range text.forEach { letter in update(text: String(letter), type: .insert, at: newRange, on: listener) newRange = newRange?.advance } } func update(text: String, type: TextUpdate, at range: NSRange? = nil, on listener: MentionListener) { let textView = listener.mentionsTextView if let range = range { textView.selectedRange = range } if listener.textView(textView, shouldChangeTextIn: textView.selectedRange, replacementText: text) { switch type { case .insert: textView.insertText(text) case .delete: textView.deleteBackward() case .replace: if let range = textView.selectedTextRange { textView.replace(range, withText: text) } } } } @discardableResult func addMention(named name: String, on listener: MentionListener) -> Bool { let mention = ExampleMention(name: name) return listener.addMention(mention) }
mit
a8cc0a20291e0c3c33bbbd00d49eb4eb
27.354167
103
0.658339
4.348243
false
false
false
false
rockgarden/swift_language
Playground/Swift_LocalizedString.playground/Pages/Magic!.xcplaygroundpage/Contents.swift
1
2288
/*: [Previous](@previous) On our previous approach we have an explicit protocol implementation that we should copy to each of our `enum`s, making the code very repetitive */ import Foundation enum Options : String { case Some } enum Login: String { case Name } extension Options: CustomStringConvertible { var description : String { let tableName = "\(type(of:self))" return NSLocalizedString(self.rawValue, tableName: tableName, bundle: Bundle.main, value: "", comment: "") } } extension Login: CustomStringConvertible { var description : String { let tableName = "\(type(of:self))" return NSLocalizedString(self.rawValue, tableName: tableName, bundle: Bundle.main, value: "", comment: "") } } /*: We have here a severe case of code duplication, a very bad code smell. We can do it better by using protocol extensions introduced in **Swift 3.0**. This will allow us to provide a default implementation. First, let define a very simple custom protocol: we only add a phantom幽灵 protocol that is just `CustomStringConvertible` with other hat */ protocol LocalizedEnum : CustomStringConvertible {} /*: With this special case for the `CustomStringConvertible` protocol, we can especialize it. We need to apply it only to `enum`s which has rawValue. And we need to ensure that this RawValue is a `String`. Thankfully _there is a protocol for this_ in the standard library. This protocol is `RawRepresentable`. With this little protocol in hand, we can write our extension to give a default implementation to our phantom protocol: */ class BundleMarker {} extension LocalizedEnum where Self: RawRepresentable, Self.RawValue == String { var description : String { let tableName = "\(type(of:self))" let bundle = Bundle(for: BundleMarker.self) return NSLocalizedString(self.rawValue, tableName: tableName, bundle: bundle, value: "", comment: "") } } /*: That's all!. Now each enum with `String` as rawValue that conforms the `LocalizedEnum` protocol will have *automagical* localization */ enum Swift: String, LocalizedEnum { case Awesome case Magic case Powerful } (Swift.Awesome) (Swift.Awesome.rawValue) (Swift.Magic) (Swift.Magic.rawValue) (Swift.Powerful) (Swift.Powerful.rawValue)
mit
cafb623974eb2a2a28b0c83ee509c93f
38.37931
223
0.730736
4.293233
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/TerrainProvider.swift
1
8640
// // TerrainProvider.swift // CesiumKit // // Created by Ryan Walklin on 12/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation private var regularGridIndexArrays: [Int: [Int: [Int]]] = [:] /** * Provides terrain or other geometry for the surface of an ellipsoid. The surface geometry is * organized into a pyramid of tiles according to a {@link TilingScheme}. This type describes an * interface and is not intended to be instantiated directly. * * @alias TerrainProvider * @constructor * * @see EllipsoidTerrainProvider * @see CesiumTerrainProvider * @see ArcGisImageServerTerrainProvider */ protocol TerrainProvider { /** * Gets an event that is raised when the terrain provider encounters an asynchronous error.. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof TerrainProvider.prototype * @type {Event} */ var errorEvent: Event { get } /** * Gets the credit to display when this terrain provider is active. Typically this is used to credit * the source of the terrain. This function should * not be called before {@link TerrainProvider#ready} returns true. * @memberof TerrainProvider.prototype * @type {Credit} */ var credit : Credit? { get } /** * Gets the tiling scheme used by the provider. This function should * not be called before {@link TerrainProvider#ready} returns true. * @memberof TerrainProvider.prototype * @type {TilingScheme} */ var tilingScheme: TilingScheme { get } /** * Gets the ellipsoid used by the provider. Default is WGS84. */ var ellipsoid: Ellipsoid { get } /** * Gets a value indicating whether or not the provider is ready for use. * @memberof TerrainProvider.prototype * @type {Boolean} */ var ready: Bool { get } /** * Specifies the quality of terrain created from heightmaps. A value of 1.0 will * ensure that adjacent heightmap vertices are separated by no more than * {@link Globe.maximumScreenSpaceError} screen pixels and will probably go very slowly. * A value of 0.5 will cut the estimated level zero geometric error in half, allowing twice the * screen pixels between adjacent heightmap vertices and thus rendering more quickly. */ var heightmapTerrainQuality: Double { get set } /** * Gets a list of indices for a triangle mesh representing a regular grid. Calling * this function multiple times with the same grid width and height returns the * same list of indices. The total number of vertices must be less than or equal * to 65536. * * @param {Number} width The number of vertices in the regular grid in the horizontal direction. * @param {Number} height The number of vertices in the regular grid in the vertical direction. * @returns {Uint16Array} The list of indices. */ static func getRegularGridIndices(width: Int, height: Int) -> [Int] /** * Determines an appropriate geometric error estimate when the geometry comes from a heightmap. * * @param {Ellipsoid} ellipsoid The ellipsoid to which the terrain is attached. * @param {Number} tileImageWidth The width, in pixels, of the heightmap associated with a single tile. * @param {Number} numberOfTilesAtLevelZero The number of tiles in the horizontal direction at tile level zero. * @returns {Number} An estimated geometric error. */ static func estimatedLevelZeroGeometricErrorForAHeightmap(ellipsoid: Ellipsoid, tileImageWidth: Int, numberOfTilesAtLevelZero: Int) -> Double /** * Requests the geometry for a given tile. This function should not be called before * {@link TerrainProvider#ready} returns true. The result must include terrain data and * may optionally include a water mask and an indication of which child tiles are available. * @function * * @param {Number} x The X coordinate of the tile for which to request geometry. * @param {Number} y The Y coordinate of the tile for which to request geometry. * @param {Number} level The level of the tile for which to request geometry. * @param {Boolean} [throttleRequests=true] True if the number of simultaneous requests should be limited, * or false if the request should be initiated regardless of the number of requests * already in progress. * @returns {NetworkOperation?} If the request involves a NetworkOperation, the NetworkOperation is returned * to allow cancellation. */ func requestTileGeometry(x: Int, y: Int, level: Int, throttleRequests: Bool, completionBlock: @escaping (TerrainData?) -> ()) -> NetworkOperation? /** * Gets the maximum geometric error allowed in a tile at a given level. This function should not be * called before {@link TerrainProvider#ready} returns true. * @function * * @param {Number} level The tile level for which to get the maximum geometric error. * @returns {Number} The maximum geometric error. */ func levelMaximumGeometricError(_ level: Int) -> Double /** * Determines whether data for a tile is available to be loaded. * @function * * @param {Number} x The X coordinate of the tile for which to request geometry. * @param {Number} y The Y coordinate of the tile for which to request geometry. * @param {Number} level The level of the tile for which to request geometry. * @returns {Boolean} Undefined if not supported by the terrain provider, otherwise true or false. */ func getTileDataAvailable(x: Int, y: Int, level: Int) -> Bool? /** * Gets a value indicating whether or not the provider includes a water mask. The water mask * indicates which areas of the globe are water rather than land, so they can be rendered * as a reflective surface with animated waves. This function should not be * called before {@link TerrainProvider#ready} returns true. * @function * * @returns {Boolean} True if the provider has a water mask; otherwise, false. */ var hasWaterMask: Bool { get } /** * Gets a value indicating whether or not the requested tiles include vertex normals. * This function should not be called before {@link TerrainProvider#ready} returns true. * @memberof TerrainProvider.prototype * @type {Boolean} */ var hasVertexNormals: Bool { get } } extension TerrainProvider { func getTileDataAvailable(x: Int, y: Int, level: Int) -> Bool? { /*if level > 10 { return false }*/ return nil } static func estimatedLevelZeroGeometricErrorForAHeightmap( ellipsoid: Ellipsoid, tileImageWidth: Int, numberOfTilesAtLevelZero: Int) -> Double { return ellipsoid.maximumRadius * Math.TwoPi * 0.25/*heightmapTerrainQuality*/ / Double(tileImageWidth * numberOfTilesAtLevelZero) } static func getRegularGridIndices(width: Int, height: Int) -> [Int] { assert((width * height <= 64 * 1024), "The total number of vertices (width * height) must be less than or equal to 65536") var byWidth = regularGridIndexArrays[width] if byWidth == nil { byWidth = [:] regularGridIndexArrays[width] = byWidth } var indices = byWidth![height] if indices == nil { indices = [Int]()//ount: (width - 1) * (height - 1) * 6, repeatedValue: 0) var index = 0 //var indicesIndex = 0 for _ in 0..<height-1 { for _ in 0..<width-1 { let upperLeft = index let lowerLeft = upperLeft + width let lowerRight = lowerLeft + 1 let upperRight = upperLeft + 1 indices!.append(upperLeft) indices!.append(lowerLeft) indices!.append(upperRight) indices!.append(upperRight) indices!.append(lowerLeft) indices!.append(lowerRight) index += 1 } index += 1 } var unWrappedByWidth = byWidth! unWrappedByWidth[height] = indices! regularGridIndexArrays[width] = unWrappedByWidth } return indices! } }
apache-2.0
5e408dcc55c2e257eff23e634e61a088
39.754717
150
0.652431
4.688009
false
false
false
false
RoverPlatform/rover-ios-beta
Sources/Models/BlockTapBehavior.swift
2
3428
// // BlockTapBehavior.swift // Rover // // Created by Sean Rucker on 2018-05-14. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import Foundation public enum BlockTapBehavior: Equatable { case goToScreen(screenID: String) case none case openURL(url: URL, dismiss: Bool) case presentWebsite(url: URL) case custom } // MARK: Codable extension BlockTapBehavior: Codable { private enum CodingKeys: String, CodingKey { case typeName = "__typename" } private enum GoToScreenKeys: String, CodingKey { case screenID } private enum OpenURLKeys: String, CodingKey { case url case dismiss } private enum PresentWebsiteKeys: String, CodingKey { case url } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let typeName = try container.decode(String.self, forKey: .typeName) switch typeName { case "GoToScreenBlockTapBehavior": let container = try decoder.container(keyedBy: GoToScreenKeys.self) let screenID = try container.decode(String.self, forKey: .screenID) self = .goToScreen(screenID: screenID) case "NoneBlockTapBehavior": self = .none case "OpenURLBlockTapBehavior": let container = try decoder.container(keyedBy: OpenURLKeys.self) let url = try container.decode(URL.self, forKey: .url) let dismiss = try container.decode(Bool.self, forKey: .dismiss) self = .openURL(url: url, dismiss: dismiss) case "PresentWebsiteBlockTapBehavior": let container = try decoder.container(keyedBy: PresentWebsiteKeys.self) let url = try container.decode(URL.self, forKey: .url) self = .presentWebsite(url: url) case "CustomBlockTapBehavior": self = .custom default: throw DecodingError.dataCorruptedError(forKey: CodingKeys.typeName, in: container, debugDescription: "Expected one of GoToScreenBlockTapBehavior, NoneBlockTapBehavior, OpenURLBlockTapBehavior or PresentWebsiteBlockTapBehavior – found \(typeName)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .goToScreen(let screenID): try container.encode("GoToScreenBlockTapTapBehavior", forKey: .typeName) var container = encoder.container(keyedBy: GoToScreenKeys.self) try container.encode(screenID, forKey: .screenID) case .none: try container.encode("NoneBlockTapBehavior", forKey: .typeName) case let .openURL(url, dismiss): try container.encode("OpenURLBlockTapTapBehavior", forKey: .typeName) var container = encoder.container(keyedBy: OpenURLKeys.self) try container.encode(url, forKey: .url) try container.encode(dismiss, forKey: .dismiss) case .presentWebsite(let url): try container.encode("PresentWebsiteBlockTapBehavior", forKey: .typeName) var container = encoder.container(keyedBy: PresentWebsiteKeys.self) try container.encode(url, forKey: .url) case .custom: try container.encode("CustomBlockTapBehavior", forKey: .typeName) } } }
mit
d8c6fd9887243e5d0cb82eced5968b5a
38.356322
259
0.655666
4.475817
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/Modules/DatePicker/View/Subviews/ByDecadeYearPicker/ByDecadeYearPickerCell.swift
1
2321
import UIKit final class ByDecadeYearPickerCell: UICollectionViewCell { // MARK: Properties var text: String? { get { label.text } set { label.text = newValue } } override var isHighlighted: Bool { didSet { updateFormat() } } override var isSelected: Bool { didSet { updateFormat() } } var isEnabled: Bool = true { didSet { updateFormat() } } private static let cornerRadius: CGFloat = 1.0 private let label: UILabel = { let label = UILabel() label.textAlignment = .center label.font = AMCFont.largeRegular label.textColor = AMCColor.darkGray label.setContentHuggingPriority(.defaultLow, for: .horizontal) return label }() private let insetBackgroundView = UIImageView(image: .imageWithFillColor(.white, cornerRadius: cornerRadius)) func commonInit() { contentView.addSubview(insetBackgroundView) insetBackgroundView.fillSuperview(insets: .all(1.0)) insetBackgroundView.layer.shadowColor = AMCColor.darkGray.cgColor insetBackgroundView.layer.shadowOpacity = 0.3 insetBackgroundView.layer.shadowRadius = 0.5 insetBackgroundView.layer.shadowOffset = .zero contentView.addSubview(label) label.fillSuperview(insets: .zero) updateFormat() } required init?(coder: NSCoder) { super.init(coder: coder) self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } private func updateFormat() { if !isEnabled { insetBackgroundView.image = .imageWithFillColor(.white, cornerRadius: Self.cornerRadius) label.textColor = .lightGray } else if isHighlighted { insetBackgroundView.image = .imageWithFillColor(AMCColor.brightBlue, cornerRadius: Self.cornerRadius) label.textColor = .white } else if isSelected { insetBackgroundView.image = .imageWithFillColor(AMCColor.brightBlue, cornerRadius: Self.cornerRadius) label.textColor = .white } else { insetBackgroundView.image = .imageWithFillColor(.white, cornerRadius: Self.cornerRadius) label.textColor = AMCColor.darkGray } } }
mit
1736547438cf9e47079bb2374d1a35cf
30.794521
113
0.647135
4.896624
false
false
false
false
WXYC/wxyc-ios-64
Shared/Core/Caching/CacheCoordinator.swift
1
2734
import Foundation import Combine let DefaultLifespan: TimeInterval = 30 public final actor CacheCoordinator { public static let WXYCPlaylist = CacheCoordinator(cache: UserDefaults.WXYC) public static let AlbumArt = CacheCoordinator(cache: ImageCache()) // MARK: Private vars private var cache: Cache private static let encoder = JSONEncoder() private static let decoder = JSONDecoder() internal init(cache: Cache) { self.cache = cache } // MARK: Public methods public func value<Value, Key>(for key: Key) async throws -> Value where Value: Codable, Key: RawRepresentable, Key.RawValue == String { try await self.value(for: key.rawValue) } public func value<Value, Key>(for key: Key) async throws -> Value where Value: Codable, Key: Identifiable, Key.ID == Int { try await self.value(for: String(key.id)) } public func value<Value: Codable>(for key: String) async throws -> Value { do { guard let encodedCachedRecord = self.cache[key] else { throw ServiceErrors.noCachedResult } let cachedRecord = try Self.decoder.decode(CachedRecord<Value>.self, from: encodedCachedRecord) // nil out record, if expired guard !cachedRecord.isExpired else { self.set(value: nil as Value?, for: key, lifespan: .distantFuture) // Nil-out expired record throw ServiceErrors.noCachedResult } print(">>> cache hit!", key, cachedRecord.value) return cachedRecord.value } catch { print(error) throw error } } public func set<Value, Key>(value: Value?, for key: Key, lifespan: TimeInterval) where Value: Codable, Key: RawRepresentable, Key.RawValue == String { return self.set(value: value, for: key.rawValue, lifespan: lifespan) } public func set<Value, Key>(value: Value?, for key: Key, lifespan: TimeInterval) where Value: Codable, Key: Identifiable, Key.ID == Int { return self.set(value: value, for: String(key.id), lifespan: lifespan) } public func set<Value: Codable>(value: Value?, for key: String, lifespan: TimeInterval) { if let value = value { let cachedRecord = CachedRecord(value: value, lifespan: lifespan) let encodedCachedRecord = try? Self.encoder.encode(cachedRecord) self.cache[key] = encodedCachedRecord } else { self.cache[key] = nil as Data? } } }
mit
ee005d0e52b945979753b40a880978cf
34.051282
108
0.594367
4.681507
false
false
false
false
ahoppen/swift
stdlib/public/Concurrency/Executor.swift
4
4359
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift /// A service that can execute jobs. @available(SwiftStdlib 5.1, *) public protocol Executor: AnyObject, Sendable { func enqueue(_ job: UnownedJob) } /// A service that executes jobs. @available(SwiftStdlib 5.1, *) public protocol SerialExecutor: Executor { // This requirement is repeated here as a non-override so that we // get a redundant witness-table entry for it. This allows us to // avoid drilling down to the base conformance just for the basic // work-scheduling operation. @_nonoverride func enqueue(_ job: UnownedJob) /// Convert this executor value to the optimized form of borrowed /// executor references. func asUnownedSerialExecutor() -> UnownedSerialExecutor } /// An unowned reference to a serial executor (a `SerialExecutor` /// value). /// /// This is an optimized type used internally by the core scheduling /// operations. It is an unowned reference to avoid unnecessary /// reference-counting work even when working with actors abstractly. /// Generally there are extra constraints imposed on core operations /// in order to allow this. For example, keeping an actor alive must /// also keep the actor's associated executor alive; if they are /// different objects, the executor must be referenced strongly by the /// actor. @available(SwiftStdlib 5.1, *) @frozen public struct UnownedSerialExecutor: Sendable { #if compiler(>=5.5) && $BuiltinExecutor @usableFromInline internal var executor: Builtin.Executor #endif @inlinable internal init(_ executor: Builtin.Executor) { #if compiler(>=5.5) && $BuiltinExecutor self.executor = executor #endif } @inlinable public init<E: SerialExecutor>(ordinary executor: __shared E) { #if compiler(>=5.5) && $BuiltinBuildExecutor self.executor = Builtin.buildOrdinarySerialExecutorRef(executor) #else fatalError("Swift compiler is incompatible with this SDK version") #endif } } // Used by the concurrency runtime @available(SwiftStdlib 5.1, *) @_silgen_name("_swift_task_enqueueOnExecutor") internal func _enqueueOnExecutor<E>(job: UnownedJob, executor: E) where E: SerialExecutor { executor.enqueue(job) } @available(SwiftStdlib 5.1, *) @_transparent public // COMPILER_INTRINSIC func _checkExpectedExecutor(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word, _executor: Builtin.Executor) { if _taskIsCurrentExecutor(_executor) { return } _reportUnexpectedExecutor( _filenameStart, _filenameLength, _filenameIsASCII, _line, _executor) } #if !SWIFT_STDLIB_SINGLE_THREADED_RUNTIME // This must take a DispatchQueueShim, not something like AnyObject, // or else SILGen will emit a retain/release in unoptimized builds, // which won't work because DispatchQueues aren't actually // Swift-retainable. @available(SwiftStdlib 5.1, *) @_silgen_name("swift_task_enqueueOnDispatchQueue") internal func _enqueueOnDispatchQueue(_ job: UnownedJob, queue: DispatchQueueShim) /// Used by the runtime solely for the witness table it produces. /// FIXME: figure out some way to achieve that which doesn't generate /// all the other metadata /// /// Expected to work for any primitive dispatch queue; note that this /// means a dispatch_queue_t, which is not the same as DispatchQueue /// on platforms where that is an instance of a wrapper class. @available(SwiftStdlib 5.1, *) internal final class DispatchQueueShim: @unchecked Sendable, SerialExecutor { func enqueue(_ job: UnownedJob) { _enqueueOnDispatchQueue(job, queue: self) } func asUnownedSerialExecutor() -> UnownedSerialExecutor { return UnownedSerialExecutor(ordinary: self) } } #endif
apache-2.0
20683a1092523336b217e1886c331985
34.439024
80
0.693278
4.489186
false
false
false
false
hirooka/chukasa-ios
chukasa-ios/src/model/database/ChukasaCoreDataOperator.swift
1
8459
import UIKit import CoreData @objc protocol ChukasaCoreDataOperatorDelegate { @objc optional func completeCreatingChukasaServerDestination() @objc optional func completeUpdatingChukasaServerDestination() @objc optional func completeCreatingChukasaPreferences() @objc optional func completeUpdatingChukasaPreferences() } class ChukasaCoreDataOperator: NSObject { var delegate: ChukasaCoreDataOperatorDelegate? func fetch (_ entity: String, key: String, ascending: Bool) -> NSArray { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext let entityDescription = NSEntityDescription.entity(forEntityName: entity, in: managedObjectContext) let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest() fetchRequest.entity = entityDescription let sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: key, ascending: ascending) let sortDescriptorArray: NSArray = [sortDescriptor] fetchRequest.sortDescriptors = sortDescriptorArray as? [NSSortDescriptor] do { let array = try managedObjectContext.fetch(fetchRequest) return array as NSArray } catch { return NSArray() } } func createChukasaServerDestination(_ chukasaServerDestination: ChukasaServerDestination){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) childManagedObjectContext.parent = managedObjectContext childManagedObjectContext.perform { () -> Void in let managedObject = NSEntityDescription.insertNewObject(forEntityName: "ChukasaServerDestination", into: childManagedObjectContext) managedObject.setValue(0, forKey: "id") managedObject.setValue(chukasaServerDestination.scheme.rawValue, forKey: "scheme") managedObject.setValue(chukasaServerDestination.host, forKey: "host") managedObject.setValue(chukasaServerDestination.port, forKey: "port") managedObject.setValue(chukasaServerDestination.username, forKey: "username") managedObject.setValue(chukasaServerDestination.password, forKey: "password") do { try childManagedObjectContext.save() } catch { // } managedObjectContext.perform({ () -> Void in do { try managedObjectContext.save() self.delegate?.completeCreatingChukasaServerDestination!() } catch { // } }) } } func updateChukasaServerDestination(_ id: Int, chukasaServerDestination: ChukasaServerDestination){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext let predicateBoard = NSPredicate(format: "(id == %ld)", id) let fetchRequestBoard: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "ChukasaServerDestination") fetchRequestBoard.predicate = predicateBoard do { let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) childManagedObjectContext.parent = managedObjectContext let chukasaServerDestinationArray = try childManagedObjectContext.fetch(fetchRequestBoard) childManagedObjectContext.perform { () -> Void in let updatedChukasaServerDestination = chukasaServerDestinationArray[0] as! NSManagedObject updatedChukasaServerDestination.setValue(chukasaServerDestination.scheme.rawValue, forKey: "scheme") updatedChukasaServerDestination.setValue(chukasaServerDestination.host, forKey: "host") updatedChukasaServerDestination.setValue(chukasaServerDestination.port, forKey: "port") updatedChukasaServerDestination.setValue(chukasaServerDestination.username, forKey: "username") updatedChukasaServerDestination.setValue(chukasaServerDestination.password, forKey: "password") do { try childManagedObjectContext.save() } catch { // } managedObjectContext.perform({ () -> Void in do { try managedObjectContext.save() self.delegate?.completeUpdatingChukasaServerDestination!() } catch { // } }) } } catch { } } func createChukasaPreferences(_ chukasaPreferences: ChukasaPreferences) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) childManagedObjectContext.parent = managedObjectContext childManagedObjectContext.perform { () -> Void in let managedObject = NSEntityDescription.insertNewObject(forEntityName: "ChukasaPreferences", into: childManagedObjectContext) managedObject.setValue(0, forKey: "id") managedObject.setValue(chukasaPreferences.canEncrypt, forKey: "canEncrypt") managedObject.setValue(chukasaPreferences.transcodingSettings.rawValue, forKey: "transcodingSettings") do { try childManagedObjectContext.save() } catch { // } managedObjectContext.perform({ () -> Void in do { try managedObjectContext.save() self.delegate?.completeCreatingChukasaPreferences!() } catch { // } }) } } func updateChukasaPreferences(_ id: Int, chukasaPreferences: ChukasaPreferences) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContext let predicateBoard = NSPredicate(format: "(id == %ld)", id) let fetchRequestBoard:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "ChukasaPreferences") fetchRequestBoard.predicate = predicateBoard do { let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) childManagedObjectContext.parent = managedObjectContext let chukasaPreferencesArray = try childManagedObjectContext.fetch(fetchRequestBoard) childManagedObjectContext.perform { () -> Void in let updatedChukasaPreferences = chukasaPreferencesArray[0] as! NSManagedObject updatedChukasaPreferences.setValue(chukasaPreferences.canEncrypt, forKey: "canEncrypt") updatedChukasaPreferences.setValue(chukasaPreferences.transcodingSettings.rawValue, forKey: "transcodingSettings") do { try childManagedObjectContext.save() } catch { // } managedObjectContext.perform({ () -> Void in do { try managedObjectContext.save() self.delegate?.completeUpdatingChukasaPreferences!() } catch { // } }) } } catch { } } }
mit
2406a453ef6efdb3846a503312880cef
42.379487
150
0.618513
6.447409
false
false
false
false
darwin/textyourmom
TextYourMom/AirportsProvider.swift
1
2611
import UIKit class AirportsProvider { var airports : [Airport] init() { airports = []; } func lookupAirport(id:Int) -> Airport? { return $.find(airports, { $0.id == id }) } } // MARK: parsing the data file extension AirportsProvider { func parseFromResource(name:String, type:String="txt") -> Bool { let path = NSBundle.mainBundle().pathForResource(name, ofType: type) if path == nil { log("!!! Error forming path for resource \(name) of type \(type)") return false; } return parseFromFile(path!) } func parseFromFile(path:String) -> Bool { let componentSeparator = "," let lineSeparator = "\n" var err: NSError? let content = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: &err) if content == nil { log("!!! \(err)") return false; } func parseAirportLine(line: String) -> Airport? { func readQuotedString(s: String) -> String { // TODO: implement proper unwrapping here return s.substringWithRange(Range<String.Index>(start: advance(s.startIndex, 1), end: advance(s.endIndex, -1))) } func readIntValue(s: String) -> Int { if let result = s.toInt() { return result } else { return 0; } } func readDoubleValue(s: String) -> Double { return (s as NSString).doubleValue } var parts = line.componentsSeparatedByString(componentSeparator) // TODO: better error checking here var airport = Airport() airport.id = readIntValue(parts[0]) airport.name = readQuotedString(parts[1]) airport.city = readQuotedString(parts[2]) airport.country = readQuotedString(parts[3]) airport.latitude = readDoubleValue(parts[6]) airport.longitude = readDoubleValue(parts[7]) return airport; } var counter = 0 var list = content!.componentsSeparatedByString(lineSeparator) for line in list { if line.isEmpty { continue } counter++ if let airport = parseAirportLine(line) { airports.append(airport) } else { log("!!! \(line)") } } return true } }
mit
1aa26c216aee75199119ab410c04a5f1
29.372093
127
0.513596
5.021154
false
false
false
false
elaser/swift-json-mapper
Mapper/JSON/Dictionary+Extensions.swift
1
2118
// // Dictionary+Extensions.swift // Mapper // // Created by Anderthan Hsieh on 10/1/16. // Copyright © 2016 anderthan. All rights reserved. // import Foundation extension Dictionary { /** Note: (Anderthan) This mapping function is different from stock mapping function. Use case here is given JSON init function, you want to iterate through all values of a dictionary and apply the same mapping function to it. You want to return a dictionary with all of the values mapped properly **/ func map<T>(_ f: (Value) -> T) -> [Key: T] { var dict = Dictionary<Key, T>() for (key, value) in self { dict[key] = f(value) } return dict } } /** Note (Anderthan): Dictionaries in Swift don't support getting a value given a key path. In this case, given a keypath, we will call valueForKeyPath. **/ func valueForKeyPath(dictionary: [String: JSON], keyPath: String) -> Any? { let keys = keyPath.components(separatedBy: ".") return valueForKeyPath(dictionary: dictionary, keys: keys) } func valueForKeyPath(json: JSON, keyPath: String) -> Any? { switch json { case .dictionary(let dic): return valueForKeyPath(dictionary: dic, keyPath: keyPath) default: return nil } } /** Note (Anderthan): Given an array of keys, we'll loop through each array and find value for the given keypath. **/ func valueForKeyPath(dictionary: [String: JSON], keys: [String]) -> Any? { var mutableKeys = keys switch keys.count { case 0: return nil case 1: let key = keys[0] return dictionary[key]?.rawValue() case 2..<Int.max: let currentDictionary = dictionary let key = mutableKeys.removeFirst() guard let dict = currentDictionary[key] else { return nil } switch dict { case .dictionary(let dic): return valueForKeyPath(dictionary: dic, keys: mutableKeys) default: return nil } default: return nil } }
mit
fc920af6baf5b22d9317ebd42d0dda3b
25.4625
150
0.613132
4.276768
false
false
false
false
adrfer/swift
validation-test/stdlib/ObjectiveC.swift
2
1375
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import ObjectiveC import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var ObjectiveCTests = TestSuite("ObjectiveC") class NSObjectWithCustomHashable : NSObject { init(value: Int, hashValue: Int) { self._value = value self._hashValue = hashValue } override func isEqual(other: AnyObject?) -> Bool { let other_ = other as! NSObjectWithCustomHashable return self._value == other_._value } override var hashValue: Int { return _hashValue } var _value: Int var _hashValue: Int } ObjectiveCTests.test("NSObject/Hashable") { let objects = [ NSObjectWithCustomHashable(value: 10, hashValue: 100), NSObjectWithCustomHashable(value: 10, hashValue: 100), NSObjectWithCustomHashable(value: 20, hashValue: 100), NSObjectWithCustomHashable(value: 30, hashValue: 300), ] for (i, object1) in objects.enumerate() { for (j, object2) in objects.enumerate() { checkHashable( object1._value == object2._value, object1, object2, "i=\(i), j=\(j)") } } } runAllTests()
apache-2.0
d10df7fec9d8c0626b63978ddb53fa45
23.122807
73
0.694545
4.092262
false
true
false
false
ceicke/HomeControl
HomeControl/AppDelegate.swift
1
6170
// // AppDelegate.swift // HomeControl // // Created by Christoph Eicke on 10.10.15. // Copyright © 2015 Christoph Eicke. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. #if DEBUG NFX.sharedInstance().start() #endif 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:. } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("LoxoneConfiguration", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("LoxoneConfiguration.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() // lazy var managedObjectContext: NSManagedObjectContext? = { // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. // let coordinator = self.persistentStoreCoordinator // if coordinator == nil { // return nil // } // var managedObjectContext = NSManagedObjectContext() // managedObjectContext.persistentStoreCoordinator = coordinator // return managedObjectContext // }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() }
mit
ca0c8e2472dbb9cc20f8d16a4d964717
54.080357
290
0.720862
5.920345
false
false
false
false
SereivoanYong/Charts
Source/Charts/Highlight/PieRadarHighlighter.swift
1
1588
// // PieRadarHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class PieRadarHighlighter: Highlighter { open override func highlight(at pOffset: CGPoint) -> Highlight? { guard let chart = self.chart as? BasePieRadarChartView else { return nil } let touchDistanceToCenter = chart.distanceToCenter(x: pOffset.x, y: pOffset.y) // check if a slice was touched if touchDistanceToCenter > chart.radius { // if no slice was touched, highlight nothing return nil } else { var angle = chart.angleForPoint(x: pOffset.x ,y: pOffset.y) if chart is PieChartView { angle /= chart.animator.phaseY } let index = chart.indexForAngle(angle) // check if the index could be found if index < 0 || index >= chart.data?.maxEntryCountSet?.entries.count ?? 0 { return nil } else { return closestHighlight(index: index, x: pOffset.x, y: pOffset.y) } } } /// - returns: The closest Highlight object of the given objects based on the touch position inside the chart. /// - parameter index: /// - parameter x: /// - parameter y: open func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight? { fatalError("closestHighlight(index, x, y) cannot be called on PieRadarChartHighlighter") } }
apache-2.0
aa12eba766b47e69d669c0d3a83f358b
25.466667
112
0.641058
4.124675
false
false
false
false
tuannme/Up
Up+/Up+/Controller/ContactViewController.swift
1
7111
// // ContactViewController.swift // Up+ // // Created by Nguyen Manh Tuan on 2/7/17. // Copyright © 2017 Dreamup. All rights reserved. // import UIKit import Contacts class ContactViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var spaceToTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerView: UIView! @IBOutlet weak var tbView: UITableView! var arrContacts:[CNContact] = [] var topSpace:CGFloat = 20 override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) headerView.layer.masksToBounds = true let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 60), byRoundingCorners: [.topLeft,.topRight], cornerRadii: CGSize(width: 5, height: 5)).cgPath headerView.layer.mask = maskLayer getContacts() } func rotated(){ drawBoundSearchView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func drawBoundSearchView() { let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: headerView.frame.size.width, height: 60), byRoundingCorners: [.topLeft,.topRight], cornerRadii: CGSize(width: 5, height: 5)).cgPath headerView.layer.mask = maskLayer } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } // Scroll delegate var oldContentOffset = CGPoint(x: 0, y: 0) func scrollViewDidScroll(_ scrollView: UIScrollView) { let delta = scrollView.contentOffset.y - oldContentOffset.y //we compress the top view if delta > 0 && spaceToTopConstraint.constant > topSpace && scrollView.contentOffset.y > 0 { let temp = spaceToTopConstraint.constant - delta spaceToTopConstraint.constant = temp > topSpace ? temp : topSpace } //we expand the top view if delta < 0 && spaceToTopConstraint.constant < 120 && scrollView.contentOffset.y < 0{ let temp = spaceToTopConstraint.constant - delta spaceToTopConstraint.constant = temp > 120 ? 120 : temp } oldContentOffset = scrollView.contentOffset } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if(spaceToTopConstraint.constant > 20){ UIView.animate(withDuration: 0.2, animations: { self.spaceToTopConstraint.constant = 20 self.view.layoutIfNeeded() }) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if(spaceToTopConstraint.constant > 20){ UIView.animate(withDuration: 0.1, animations: { self.spaceToTopConstraint.constant = 20 self.view.layoutIfNeeded() }) } } // Contact func getContacts() { let store = CNContactStore() if(CNContactStore.authorizationStatus(for: .contacts) == .notDetermined){ store.requestAccess(for: .contacts, completionHandler: { (authorized, error) -> Void in if authorized { self.retrieveContactsWithStore(store: store) } }) }else if (CNContactStore.authorizationStatus(for: .contacts) == .authorized) { self.retrieveContactsWithStore(store: store) } } func retrieveContactsWithStore(store: CNContactStore) { do { let keysToFetch = [ CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactImageDataAvailableKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor] let containers = try store.containers(matching: nil) for container in containers{ let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) do{ let containerResults = try store.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch) arrContacts.append(contentsOf: containerResults) }catch{ } } DispatchQueue.main.async(execute: { self.tbView.reloadData() }) } catch let error{ print(error) } } // tableView delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrContacts.count } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 15)) header.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1) return header } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let contact = arrContacts[indexPath.row] let formatter = CNContactFormatter() let cell = tbView.dequeueReusableCell(withIdentifier: "Cell") let nameLb = cell?.contentView.viewWithTag(222) as! UILabel nameLb.text = formatter.string(from: contact) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tbView.deselectRow(at: indexPath, animated: true) let contact = arrContacts[indexPath.row] let labelValue = contact.phoneNumbers.first let phoneNumber = labelValue?.value let phoneStr = phoneNumber?.value(forKey: "digits") as? String print(phoneStr!) // let alertVC = UIAlertController(title: "", message: phoneStr, preferredStyle: .alert) // alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) // self.present(alertVC, animated: true, completion: nil) } }
mit
9c6bb6199d8b7d97fe3e3191519f0464
32.857143
151
0.594093
5.55903
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/Photo/PhotoEditorCropToolView.swift
1
12617
// // PhotoEditorCropToolView.swift // HXPHPicker // // Created by Slience on 2021/4/15. // import UIKit protocol PhotoEditorCropToolViewDelegate: AnyObject { func cropToolView(didRotateButtonClick cropToolView: PhotoEditorCropToolView) func cropToolView(didMirrorHorizontallyButtonClick cropToolView: PhotoEditorCropToolView) func cropToolView(didChangedAspectRatio cropToolView: PhotoEditorCropToolView, at model: PhotoEditorCropToolModel) } public class PhotoEditorCropToolView: UIView { weak var delegate: PhotoEditorCropToolViewDelegate? public lazy var flowLayout: UICollectionViewFlowLayout = { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumInteritemSpacing = 20 flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 10) flowLayout.scrollDirection = .horizontal return flowLayout }() public lazy var collectionView: UICollectionView = { let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowLayout) collectionView.backgroundColor = .clear collectionView.dataSource = self collectionView.delegate = self collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.register( PhotoEditorCropToolViewCell.classForCoder(), forCellWithReuseIdentifier: "PhotoEditorCropToolViewCellID" ) collectionView.register( PhotoEditorCropToolHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "PhotoEditorCropToolHeaderViewID" ) return collectionView }() let ratioModels: [PhotoEditorCropToolModel] var showRatios: Bool var themeColor: UIColor? var currentSelectedModel: PhotoEditorCropToolModel? init( showRatios: Bool, scaleArray: [[Int]] ) { self.showRatios = showRatios var ratioModels: [PhotoEditorCropToolModel] = [] for ratioArray in scaleArray { let model = PhotoEditorCropToolModel.init() model.widthRatio = CGFloat(ratioArray.first!) model.heightRatio = CGFloat(ratioArray.last!) if ratioModels.count == 0 { model.isSelected = true currentSelectedModel = model } ratioModels.append(model) } self.ratioModels = ratioModels super.init(frame: .zero) addSubview(collectionView) } func updateContentInset() { collectionView.contentInset = UIEdgeInsets( top: 0, left: UIDevice.leftMargin, bottom: 0, right: UIDevice.rightMargin ) } func reset(animated: Bool) { currentSelectedModel?.isSelected = false currentSelectedModel = ratioModels.first currentSelectedModel?.isSelected = true collectionView.reloadData() collectionView.setContentOffset(CGPoint(x: -collectionView.contentInset.left, y: 0), animated: animated) } public override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PhotoEditorCropToolView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { showRatios ? ratioModels.count : 0 } public func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "PhotoEditorCropToolViewCellID", for: indexPath ) as! PhotoEditorCropToolViewCell cell.themeColor = themeColor cell.model = ratioModels[indexPath.item] return cell } public func collectionView( _ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath ) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "PhotoEditorCropToolHeaderViewID", for: indexPath ) as! PhotoEditorCropToolHeaderView headerView.delegate = self headerView.showRatios = showRatios return headerView } } extension PhotoEditorCropToolView: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { public func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let model = ratioModels[indexPath.item] if !model.scaleSize.equalTo(.zero) { return model.scaleSize } let scaleWidth: CGFloat = 38 if model.widthRatio == 0 || model.widthRatio == 1 { model.size = .init(width: 28, height: 28) model.scaleSize = .init(width: 28, height: scaleWidth) }else { let scale = scaleWidth / model.widthRatio var itemWidth = model.widthRatio * scale var itemHeight = model.heightRatio * scale if itemHeight > scaleWidth { itemHeight = scaleWidth itemWidth = scaleWidth / model.heightRatio * model.widthRatio } model.size = .init(width: itemWidth, height: itemHeight) if itemHeight < scaleWidth { itemHeight = scaleWidth } let textWidth = model.scaleText.width( ofFont: UIFont.mediumPingFang(ofSize: 12), maxHeight: itemHeight - 3 ) + 5 if itemWidth < textWidth { itemHeight = textWidth / itemWidth * itemHeight itemWidth = textWidth if itemHeight > 45 { itemHeight = 45 } model.size = .init(width: itemWidth, height: itemHeight) } model.scaleSize = .init(width: itemWidth, height: itemHeight) } return model.scaleSize } public func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int ) -> CGSize { CGSize(width: 100, height: 50) } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var selectedIndexPath: IndexPath? if let model = currentSelectedModel { let index = ratioModels.firstIndex(of: model)! if index == indexPath.item { return } selectedIndexPath = IndexPath(item: index, section: 0) } currentSelectedModel?.isSelected = false let model = ratioModels[indexPath.item] model.isSelected = true currentSelectedModel = model var reloadIndexPaths: [IndexPath] = [] reloadIndexPaths.append(indexPath) if selectedIndexPath != nil { reloadIndexPaths.append(selectedIndexPath!) } collectionView.reloadItems(at: reloadIndexPaths) delegate?.cropToolView(didChangedAspectRatio: self, at: model) } } extension PhotoEditorCropToolView: PhotoEditorCropToolHeaderViewDelegate { func headerView(didRotateButtonClick headerView: PhotoEditorCropToolHeaderView) { delegate?.cropToolView(didRotateButtonClick: self) } func headerView(didMirrorHorizontallyButtonClick headerView: PhotoEditorCropToolHeaderView) { delegate?.cropToolView(didMirrorHorizontallyButtonClick: self) } } protocol PhotoEditorCropToolHeaderViewDelegate: AnyObject { func headerView(didRotateButtonClick headerView: PhotoEditorCropToolHeaderView) func headerView(didMirrorHorizontallyButtonClick headerView: PhotoEditorCropToolHeaderView) } class PhotoEditorCropToolHeaderView: UICollectionReusableView { weak var delegate: PhotoEditorCropToolHeaderViewDelegate? lazy var rotateButton: UIButton = { let button = UIButton.init(type: .system) button.setImage("hx_editor_photo_rotate".image, for: .normal) button.size = button.currentImage?.size ?? .zero button.tintColor = .white button.addTarget(self, action: #selector(didRotateButtonClick(button:)), for: .touchUpInside) return button }() @objc func didRotateButtonClick(button: UIButton) { delegate?.headerView(didRotateButtonClick: self) } lazy var mirrorHorizontallyButton: UIButton = { let button = UIButton.init(type: .system) button.setImage("hx_editor_photo_mirror_horizontally".image, for: .normal) button.size = button.currentImage?.size ?? .zero button.tintColor = .white button.addTarget(self, action: #selector(didMirrorHorizontallyButtonClick(button:)), for: .touchUpInside) return button }() @objc func didMirrorHorizontallyButtonClick(button: UIButton) { delegate?.headerView(didMirrorHorizontallyButtonClick: self) } lazy var lineView: UIView = { let view = UIView.init(frame: .init(x: 0, y: 0, width: 2, height: 20)) view.backgroundColor = .white return view }() var showRatios: Bool = true { didSet { lineView.isHidden = !showRatios } } override init(frame: CGRect) { super.init(frame: frame) addSubview(rotateButton) addSubview(mirrorHorizontallyButton) addSubview(lineView) } override func layoutSubviews() { super.layoutSubviews() rotateButton.centerY = height * 0.5 rotateButton.x = 20 mirrorHorizontallyButton.x = rotateButton.frame.maxX + 10 mirrorHorizontallyButton.centerY = rotateButton.centerY lineView.x = width - 2 lineView.centerY = mirrorHorizontallyButton.centerY } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class PhotoEditorCropToolViewCell: UICollectionViewCell { lazy var scaleView: UIView = { let view = UIView.init() view.layer.cornerRadius = 2 view.addSubview(scaleImageView) view.addSubview(scaleLabel) return view }() lazy var scaleImageView: UIImageView = { let imageView = UIImageView.init(image: "hx_editor_photo_crop_free".image?.withRenderingMode(.alwaysTemplate)) return imageView }() lazy var scaleLabel: UILabel = { let label = UILabel.init() label.textColor = .white label.textAlignment = .center label.font = UIFont.mediumPingFang(ofSize: 12) label.adjustsFontSizeToFitWidth = true return label }() var themeColor: UIColor? var model: PhotoEditorCropToolModel! { didSet { updateViewFrame() scaleLabel.text = model.scaleText if model.widthRatio == 0 { scaleView.layer.borderWidth = 0 scaleImageView.isHidden = false }else { scaleView.layer.borderWidth = 1.25 scaleImageView.isHidden = true } if model.isSelected { scaleImageView.tintColor = themeColor scaleView.layer.borderColor = themeColor?.cgColor scaleLabel.textColor = themeColor }else { scaleImageView.tintColor = .white scaleView.layer.borderColor = UIColor.white.cgColor scaleLabel.textColor = .white } } } override init(frame: CGRect) { super.init(frame: frame) addSubview(scaleView) } func updateViewFrame() { scaleView.size = model.size scaleView.centerX = model.scaleSize.width * 0.5 scaleView.centerY = model.scaleSize.height * 0.5 scaleLabel.frame = CGRect(x: 1.5, y: 1.5, width: scaleView.width - 3, height: scaleView.height - 3) scaleImageView.frame = scaleView.bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
5acca474937d4399818a9803f1e18473
36.218289
118
0.648332
5.389577
false
false
false
false
aijaz/icw1502
playgrounds/Week05Homework.playground/Pages/Untitled Page 2.xcplaygroundpage/Contents.swift
1
1489
//: [Previous](@previous) [Next](@next) enum Planet:Int { case Mercury = 1 case Venus case Earth case Mars case Jupiter case Saturn case Uranus case Neptune case Pluto } var planet:Planet = .Mercury planet enum DistantObject:Int { case Mercury = 36 case Venus = 67 case Earth = 93 case Mars = 228 case Jupiter = 778 case Saturn = 1427 case Uranus = 2871 case Neptune = 4497 case Pluto = 5913 } enum ObjectInSpace:String { case Mercury case Venus case Earth case Mars case Jupiter case Saturn case Uranus case Neptune case Pluto func periodOfRevolution()->Double { switch self { case .Mercury : return Double(87.96) case .Venus: return 224.68 case .Earth: return 365.26 case .Mars: return 686.98 case .Jupiter: return 11.862 * ObjectInSpace.Earth.periodOfRevolution() case .Saturn: return 29.456 * ObjectInSpace.Earth.periodOfRevolution() case .Uranus: return 84.07 * ObjectInSpace.Earth.periodOfRevolution() case .Neptune: return 164.81 * ObjectInSpace.Earth.periodOfRevolution() case .Pluto: return 247.7 * ObjectInSpace.Earth.periodOfRevolution() } } } let mercury:ObjectInSpace = .Mercury mercury.periodOfRevolution() //: [Previous](@previous) [Next](@next)
mit
d9cb94521b696e79c6c55a4778fa3131
19.39726
68
0.596373
4.101928
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/DynamicProgramming/63_UniquePaths.swift
1
1245
// // 63_UniquePaths.swift // LeetcodeSwift // // Created by yansong li on 2016-09-12. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:63 Unique Paths II URL: https://leetcode.com/problems/unique-paths-ii/ Space: O(mn) Time: O(mn) */ class UniquePathsII_Solution { func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int { let m = obstacleGrid.count let n = obstacleGrid[0].count guard m > 1 || n > 1 else { if obstacleGrid[m - 1][n - 1] == 1 { return 0 } else { return 1 } } var pathsMatrix = Array(repeating: Array(repeating: 0, count: n), count: m) for i in 0..<m { for j in 0..<n { if i == 0 || j == 0 { if i > 0 && pathsMatrix[i - 1][j] == 0 || obstacleGrid[i][j] == 1 || (j > 0 && pathsMatrix[i][j - 1] == 0) { pathsMatrix[i][j] = 0 } else { pathsMatrix[i][j] = 1 } } else { if obstacleGrid[i][j] == 1 { pathsMatrix[i][j] = 0 } else { pathsMatrix[i][j] = pathsMatrix[i][j - 1] + pathsMatrix[i - 1][j] } } } } return pathsMatrix[m - 1][n - 1] } }
mit
d910ede8d648c2b9a486db6e8576ea11
23.392157
79
0.494373
3.173469
false
false
false
false
Estimote/iOS-SDK
Examples/swift/Loyalty/Loyalty/Views/OfferCell/OfferCell.swift
1
1735
// // Please report any problems with this app template to contact@estimote.com // import UIKit class OfferCell: UITableViewCell { @IBOutlet weak var backgroundRectangleView : UIView! @IBOutlet weak var offerImageView : UIImageView! @IBOutlet weak var offerNameLabel : UILabel! @IBOutlet weak var offerDescriptionTextView : UITextView! @IBOutlet weak var offerStarsCountLabel : UILabel! @IBOutlet weak var offerExtraInfoLabel : UILabel! override func awakeFromNib() { super.awakeFromNib() // stylize cell self.stylizeCell() } @objc func stylizeCell() { let clearColor = UIColor.clear // set default selection style to None selectionStyle = .none // set background colors contentView.backgroundColor = clearColor backgroundView?.backgroundColor = clearColor backgroundColor = clearColor // set corner radius, shadow, background color self.backgroundRectangleView.layer.cornerRadius = 4.0 self.backgroundRectangleView.layer.shadowRadius = 2.0 self.backgroundRectangleView.layer.shadowOpacity = 0.7 self.backgroundRectangleView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0) self.backgroundRectangleView.layer.shadowColor = UIColor.gray.withAlphaComponent(0.5).cgColor self.backgroundRectangleView.backgroundColor = UIColor.white } override func layoutIfNeeded() { super.layoutIfNeeded() offerImageView.layer.cornerRadius = offerImageView.frame.size.width/2 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
365c57f46c60110e553af608eb84e08a
31.735849
99
0.711239
4.714674
false
false
false
false
forwk1990/PropertyExchange
PropertyExchange/YPNothingView.swift
1
2644
// // YPNothingView.swift // PropertyExchange // // Created by 尹攀 on 16/10/16. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit class YPNothingView: UIView { fileprivate lazy var imageView:UIImageView = { let _imageView = UIImageView() return _imageView }() fileprivate lazy var titleLabel:UILabel = { let _titleLabel = UILabel() _titleLabel.textColor = UIColor.colorWithHex(hex: 0x999999) _titleLabel.font = UIFont.boldSystemFont(ofSize: 16) return _titleLabel }() fileprivate lazy var operationButton:UIButton = { let _operationButton = UIButton(type: .custom) _operationButton.setTitleColor(UIColor.colorWithHex(hex: 0xFFFFFF), for: .normal) _operationButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) _operationButton.backgroundColor = UIColor.colorWithHex(hex: 0xCBA064) _operationButton.addTarget(self, action: #selector(operationButtonTouched(sender:)), for: .touchUpInside) return _operationButton }() func operationButtonTouched(sender:UIButton){ guard let _model = self.model else { return } let viewController = _model.controller.init() self.viewController?.navigationController?.pushViewController(viewController, animated: true) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.imageView) self.addSubview(self.titleLabel) self.addSubview(self.operationButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var model:(title:String,image:UIImage,operationTitle:String,controller:UIViewController.Type)?{ didSet{ guard let _model = self.model else { return } self.titleLabel.text = _model.title self.imageView.image = _model.image self.operationButton.setTitle(_model.operationTitle, for: .normal) if _model.title.contains("暂无债权转让项目") { self.operationButton.isHidden = true } } } override func layoutSubviews() { super.layoutSubviews() self.imageView.snp.makeConstraints { (make) in make.width.height.equalTo(160) make.center.equalTo(self) } self.titleLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.bottom.equalTo(self.imageView.snp.top).offset(-20) } self.operationButton.snp.makeConstraints { (make) in make.left.equalTo(self).offset(18) make.right.equalTo(self).offset(-18) make.bottom.equalTo(self).offset(-18) make.height.equalTo(50) } } }
mit
5be5c99b0fdd4019dd1ed720fbbade33
27.48913
109
0.682564
4.069876
false
false
false
false
TalkingBibles/Talking-Bible-iOS
TalkingBible/BookTableViewController.swift
1
9987
// // Copyright 2015 Talking Bibles International // // 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 MDMCoreData final class BookTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { var defaultUser = DefaultUser.sharedManager var language: Language? { didSet { if let language = language { let languageName = language.englishName ∆ "Language name" self.navigationItem.title = languageName self.navigationItem.backBarButtonItem = UIBarButtonItem(title: languageName, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } } } private lazy var persistenceController: MDMPersistenceController = { return ExternalDataStore.sharedManager.persistentStoreCoordinator }() private lazy var managedObjectContext: NSManagedObjectContext = { [unowned self] in return self.persistenceController.managedObjectContext }() private lazy var fetchedResultsController: NSFetchedResultsController = { [unowned self] in guard let languageId = self.language?.languageId else { log.error("Can't find languageId from default user. (Shouldn't happen!)") fatalError() } let fetchRequest = NSFetchRequest(entityName: Book.entityName()) fetchRequest.predicate = NSPredicate(format: "collection.language.languageId == %@", languageId) fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "collection.englishName", ascending: false), NSSortDescriptor(key: "position", ascending: true) ] let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "collection.englishName", cacheName: nil) do { try controller.performFetch() } catch let error as NSError { log.error("Can't fetch books: \(error.localizedDescription)") self.navigationController?.popToRootViewControllerAnimated(true) } return controller }() override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) UIApplication.sharedApplication().statusBarStyle = .LightContent setNeedsStatusBarAppearanceUpdate() // !!!? } // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // // trackScreenView("Book Table View", languageId: defaultUser.languageId!) // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return fetchedResultsController.sections!.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let info = fetchedResultsController.sections![section] return info.numberOfObjects } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let info = fetchedResultsController.sections![section] return info.name ∆ "Collection title" } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { let info = fetchedResultsController.sections![section] var footerTitle: String? if let version = (info.objects?.first as? Book)?.collection?.version { let trimmedVersion = version.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if trimmedVersion.isEmpty == false { footerTitle = "Text: \(version)" } } if let copyright = (info.objects?.first as? Book)?.collection?.copyright { let trimmedCopyright = copyright.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if trimmedCopyright.isEmpty == false { if let existingTitle = footerTitle { footerTitle = "\(existingTitle) - \(copyright)" } else { footerTitle = "Text: \(copyright)" } } } return footerTitle } // override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // if let view = view as? UITableViewHeaderFooterView { // view.textLabel?.substituteFontName = "AvenirNext-Medium" // } // } // // override func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { // if let view = view as? UITableViewHeaderFooterView { // view.textLabel?.substituteFontName = "AvenirNext-Medium" // } // } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BookCellIdentifier", forIndexPath: indexPath) as! UniversalTableViewCell configureCell(cell, atIndexPath: indexPath) return cell } // MARK: - Helper functions func configureCell(cell: UniversalTableViewCell, atIndexPath indexPath: NSIndexPath) { let book = fetchedResultsController.objectAtIndexPath(indexPath) as! Book // cell.textLabel?.text = NSLocalizedString(book.englishName, comment: "Bible book name") cell.label.text = book.englishName ∆ "Bible book name" cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() } // 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. if segue.identifier == "ShowBookIdentifier" { if let indexPath = tableView.indexPathForSelectedRow { let destinationController = segue.destinationViewController as! BookDetailViewController let book = fetchedResultsController.objectAtIndexPath(indexPath) as! Book destinationController.book = book /// save default user let bookmark = Bookmark(languageId: defaultUser.languageId, bookId: book.bookId, chapterId: nil) defaultUser.set(bookmark) } } } // MARK: - Fetched Results Controller Delegate var storedSteps: [() -> Void] = [] /* called first begins update to `UITableView` ensures all updates are animated simultaneously */ func controllerWillChangeContent(controller: NSFetchedResultsController) {} /* called last tells `UITableView` updates are complete */ func controllerDidChangeContent(controller: NSFetchedResultsController) { if view.window == nil { tableView.reloadData() return } tableView.beginUpdates() for step in storedSteps { step() } storedSteps = [] tableView.endUpdates() } /* called: - when a new model is created - when an existing model is updated - when an existing model is deleted */ func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: storedSteps.append({ [unowned self] in self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) return }) case .Update: storedSteps.append({ [unowned self] in let cell = self.tableView.dequeueReusableCellWithIdentifier("BookCellIdentifier", forIndexPath: indexPath!) as! UniversalTableViewCell self.configureCell(cell, atIndexPath: indexPath!) self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) return }) case .Move: storedSteps.append({ [unowned self] in self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) return }) case .Delete: storedSteps.append({ [unowned self] in self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) return }) } } /* called: - when a new model is created - when an existing model is updated - when an existing model is deleted */ func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: storedSteps.append({ [unowned self] in self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) }) case .Delete: storedSteps.append({ [unowned self] in self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) }) default: return } } }
apache-2.0
66bbf59de7dc81b89e97e0a1a156f282
35.966667
209
0.71075
5.348875
false
false
false
false
karllessard/tensorflow
tensorflow/lite/swift/Sources/SignatureRunner.swift
11
11102
// Copyright 2022 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 Foundation import TensorFlowLiteC #if os(Linux) import SwiftGlibc #else import Darwin #endif /// A TensorFlow Lite model signature runner. You can get a `SignatureRunner` instance for a /// signature from an `Interpreter` and then use the SignatureRunner APIs. /// /// - Note: `SignatureRunner` instances are *not* thread-safe. /// - Note: Each `SignatureRunner` instance is associated with an `Interpreter` instance. As long /// as a `SignatureRunner` instance is still in use, its associated `Interpreter` instance /// will not be deallocated. public final class SignatureRunner { /// The signature key. public let signatureKey: String /// The SignatureDefs input names. public var inputs: [String] { guard let inputs = _inputs else { let inputCount = Int(TfLiteSignatureRunnerGetInputCount(self.cSignatureRunner)) let ins: [String] = (0..<inputCount).map { guard let inputNameCString = TfLiteSignatureRunnerGetInputName( self.cSignatureRunner, Int32($0)) else { return "" } return String(cString: inputNameCString) } _inputs = ins return ins } return inputs } /// The SignatureDefs output names. public var outputs: [String] { guard let outputs = _outputs else { let outputCount = Int(TfLiteSignatureRunnerGetOutputCount(self.cSignatureRunner)) let outs: [String] = (0..<outputCount).map { guard let outputNameCString = TfLiteSignatureRunnerGetOutputName( self.cSignatureRunner, Int32($0)) else { return "" } return String(cString: outputNameCString) } _outputs = outs return outs } return outputs } /// The backing interpreter. It's a strong reference to ensure that the interpreter is never /// released before this signature runner is released. /// /// - Warning: Never let the interpreter hold a strong reference to the signature runner to avoid /// retain cycles. private var interpreter: Interpreter /// The `TfLiteSignatureRunner` C pointer type represented as an /// `UnsafePointer<TfLiteSignatureRunner>`. private typealias CSignatureRunner = OpaquePointer /// The `TfLiteTensor` C pointer type represented as an /// `UnsafePointer<TfLiteTensor>`. private typealias CTensor = UnsafePointer<TfLiteTensor>? /// The underlying `TfLiteSignatureRunner` C pointer. private var cSignatureRunner: CSignatureRunner /// Whether we need to allocate tensors memory. private var isTensorsAllocationNeeded: Bool = true /// The SignatureDefs input names. private var _inputs: [String]? /// The SignatureDefs output names. private var _outputs: [String]? // MARK: Initializers /// Initializes a new TensorFlow Lite signature runner instance with the given interpreter and /// signature key. /// /// - Parameters: /// - interpreter: The TensorFlow Lite model interpreter. /// - signatureKey: The signature key. /// - Throws: An error if fail to create the signature runner with given key. internal init(interpreter: Interpreter, signatureKey: String) throws { guard let signatureKeyCString = signatureKey.cString(using: String.Encoding.utf8), let cSignatureRunner = TfLiteInterpreterGetSignatureRunner( interpreter.cInterpreter, signatureKeyCString) else { throw SignatureRunnerError.failedToCreateSignatureRunner(signatureKey: signatureKey) } self.cSignatureRunner = cSignatureRunner self.signatureKey = signatureKey self.interpreter = interpreter try allocateTensors() } deinit { TfLiteSignatureRunnerDelete(cSignatureRunner) } // MARK: Public /// Invokes the signature with given input data. /// /// - Parameters: /// - inputs: A map from input name to the input data. The input data will be copied into the /// input tensor. /// - Throws: `SignatureRunnerError` if input data copying or signature invocation fails. public func invoke(with inputs: [String: Data]) throws { try allocateTensors() for (inputName, inputData) in inputs { try copy(inputData, toInputNamed: inputName) } guard TfLiteSignatureRunnerInvoke(self.cSignatureRunner) == kTfLiteOk else { throw SignatureRunnerError.failedToInvokeSignature(signatureKey: signatureKey) } } /// Returns the input tensor with the given input name in the signature. /// /// - Parameters: /// - name: The input name in the signature. /// - Throws: An error if fail to get the input `Tensor` or the `Tensor` is invalid. /// - Returns: The input `Tensor` with the given input name. public func input(named name: String) throws -> Tensor { return try tensor(named: name, withType: TensorType.input) } /// Returns the output tensor with the given output name in the signature. /// /// - Parameters: /// - name: The output name in the signature. /// - Throws: An error if fail to get the output `Tensor` or the `Tensor` is invalid. /// - Returns: The output `Tensor` with the given output name. public func output(named name: String) throws -> Tensor { return try tensor(named: name, withType: TensorType.output) } /// Resizes the input `Tensor` with the given input name to the specified `Tensor.Shape`. /// /// - Note: After resizing an input tensor, the client **must** explicitly call /// `allocateTensors()` before attempting to access the resized tensor data. /// - Parameters: /// - name: The input name of the `Tensor`. /// - shape: The shape to resize the input `Tensor` to. /// - Throws: An error if the input tensor with given input name could not be resized. public func resizeInput(named name: String, toShape shape: Tensor.Shape) throws { guard let inputNameCString = name.cString(using: String.Encoding.utf8), TfLiteSignatureRunnerResizeInputTensor( self.cSignatureRunner, inputNameCString, shape.int32Dimensions, Int32(shape.rank) ) == kTfLiteOk else { throw SignatureRunnerError.failedToResizeInputTensor(inputName: name) } isTensorsAllocationNeeded = true } /// Copies the given data to the input `Tensor` with the given input name. /// /// - Parameters: /// - data: The data to be copied to the input `Tensor`'s data buffer. /// - name: The input name of the `Tensor`. /// - Throws: An error if fail to get the input `Tensor` or if the `data.count` does not match the /// input tensor's `data.count`. /// - Returns: The input `Tensor` with the copied data. public func copy(_ data: Data, toInputNamed name: String) throws { guard let inputNameCString = name.cString(using: String.Encoding.utf8), let cTensor = TfLiteSignatureRunnerGetInputTensor(self.cSignatureRunner, inputNameCString) else { throw SignatureRunnerError.failedToGetTensor(tensorType: "input", nameInSignature: name) } let byteCount = TfLiteTensorByteSize(cTensor) guard data.count == byteCount else { throw SignatureRunnerError.invalidTensorDataCount(provided: data.count, required: byteCount) } #if swift(>=5.0) let status = data.withUnsafeBytes { TfLiteTensorCopyFromBuffer(cTensor, $0.baseAddress, data.count) } #else let status = data.withUnsafeBytes { TfLiteTensorCopyFromBuffer(cTensor, $0, data.count) } #endif // swift(>=5.0) guard status == kTfLiteOk else { throw SignatureRunnerError.failedToCopyDataToInputTensor } } /// Allocates memory for tensors. /// - Note: This is a relatively expensive operation and this call is *purely optional*. /// Tensor allocation will occur automatically during execution. /// - Throws: An error if memory could not be allocated for the tensors. public func allocateTensors() throws { if !isTensorsAllocationNeeded { return } guard TfLiteSignatureRunnerAllocateTensors(self.cSignatureRunner) == kTfLiteOk else { throw SignatureRunnerError.failedToAllocateTensors } isTensorsAllocationNeeded = false } // MARK: - Private /// Returns the I/O tensor with the given name in the signature. /// /// - Parameters: /// - nameInSignature: The input or output name in the signature. /// - type: The tensor type. /// - Throws: An error if fail to get the `Tensor` or the `Tensor` is invalid. /// - Returns: The `Tensor` with the given name in the signature. private func tensor(named nameInSignature: String, withType type: TensorType) throws -> Tensor { guard let nameInSignatureCString = nameInSignature.cString(using: String.Encoding.utf8) else { throw SignatureRunnerError.failedToGetTensor( tensorType: type.rawValue, nameInSignature: nameInSignature) } var cTensorPointer: CTensor switch type { case .input: cTensorPointer = UnsafePointer( TfLiteSignatureRunnerGetInputTensor(self.cSignatureRunner, nameInSignatureCString)) case .output: cTensorPointer = TfLiteSignatureRunnerGetOutputTensor( self.cSignatureRunner, nameInSignatureCString) } guard let cTensor = cTensorPointer else { throw SignatureRunnerError.failedToGetTensor( tensorType: type.rawValue, nameInSignature: nameInSignature) } guard let bytes = TfLiteTensorData(cTensor) else { throw SignatureRunnerError.allocateTensorsRequired } guard let dataType = Tensor.DataType(type: TfLiteTensorType(cTensor)) else { throw SignatureRunnerError.invalidTensorDataType } let nameCString = TfLiteTensorName(cTensor) let name = nameCString == nil ? "" : String(cString: nameCString!) let byteCount = TfLiteTensorByteSize(cTensor) let data = Data(bytes: bytes, count: byteCount) let rank = TfLiteTensorNumDims(cTensor) let dimensions = (0..<rank).map { Int(TfLiteTensorDim(cTensor, $0)) } let shape = Tensor.Shape(dimensions) let cQuantizationParams = TfLiteTensorQuantizationParams(cTensor) let scale = cQuantizationParams.scale let zeroPoint = Int(cQuantizationParams.zero_point) var quantizationParameters: QuantizationParameters? = nil if scale != 0.0 { quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint) } let tensor = Tensor( name: name, dataType: dataType, shape: shape, data: data, quantizationParameters: quantizationParameters ) return tensor } }
apache-2.0
3bf373a734a97aef4d59ed380960f4f4
38.091549
100
0.704107
4.299768
false
false
false
false
Vadim-Yelagin/DataSource
DataSourceTests/QuickSpecWithDataSets.swift
1
1515
// // QuickSpecWithDataSets.swift // DataSourceTests // // Created by Aleksei Bobrov on 04/02/2019. // Copyright © 2019 Fueled. All rights reserved. // import Quick class QuickSpecWithDataSets: QuickSpec { let testDataSet = Array(1...7) let testDataSet2 = Array(33...43) let testDataSet3 = Array(50...55) let newElement = Int.random(in: 100..<500) var testDataSetWithNewElement: [Int] { return [newElement] + testDataSet } var testDataSetWithoutFirstElement: [Int] { return Array(testDataSet.dropFirst()) } var testDataSetWithReplacedFirstElement: [Int] { return Array([newElement] + testDataSet.dropFirst()) } var testDataSetWithReplacedFirstWithSecondElement: [Int] { var testDataSetCopy = testDataSet testDataSetCopy.replaceSubrange(0...1, with: [testDataSet[testDataSet.index(after: testDataSet.startIndex)], testDataSet[testDataSet.startIndex]]) return testDataSetCopy } let supplementaryItemOfKind = ["item1": Int.random(in: 500..<1000), "item2": Int.random(in: 1000..<1100)] let supplementaryItemOfKind2 = ["item1": Int.random(in: 5000..<10000), "item2": Int.random(in: 10000..<11000), "item3": Int.random(in: 55..<66)] let dataSetWithTestCellModels = [TestCellModel(), TestCellModel(), TestCellModel()] let dataSetWithTestCellModels2 = [TestCellModel()] var coreDataManager: CoreDataManager! func initCoreDataManagerWithTestData(testData: [Int]) { self.coreDataManager = CoreDataManager() self.coreDataManager?.fillItemsWithDataSet(dataSet: testData) } }
mit
4ad76a4ace88fc38dab79af2a5839377
29.897959
148
0.746367
3.496536
false
true
false
false
smac89/UVA_OJ
fun-projects/Numbers/FastExponent.swift
2
719
func fast_exponent(value value :Int, topower exp :Int) -> Int { guard exp >= 0 else { return -1 } if exp == 0 { return 1 } if value == 2 { return 1 << exp } if value == 1 { return value } var p2: Int = 1, power: Int = value while (p2 << 1) <= exp { power *= power p2 <<= 1 } if p2 < exp { power *= fast_exponent(value: value, topower: exp - p2) } return power } print("Enter two numbers a and b seperated by space: ", terminator:"") let inputs = readLine()!.characters.split(){$0==" "}.map{Int(String($0))} print(fast_exponent(value: inputs[0]!, topower:inputs[1]!))
mit
66f6984c216b5f00f0dad4f53314be70
19.205882
73
0.497914
3.631313
false
false
false
false
EZ-NET/CodePiece
ESTwitter/Data/Color.swift
1
1999
// // Color.swift // CodePiece // // Created by Tomohiro Kumagai on H27/10/04. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import AppKit public struct Color : RawRepresentable { public var rawValue: NSColor public enum InitializeError : Error { case InvalidFormat(String) } public init(rawValue: NSColor) { self.rawValue = rawValue } } extension Color.InitializeError : CustomStringConvertible { public var description: String { switch self { case let .InvalidFormat(string): return "Color Initialization Error : Invalid Format (\(string))" } } } extension Color { public init(twitterColorString string: String) throws { guard string.count == 6 else { throw InitializeError.InvalidFormat(string) } enum ColorPartLocation : Int { case Red = 0 case Green = 2 case Blue = 4 } let getColorPart = { (part:ColorPartLocation) -> String in let location = part.rawValue let start = string.index(string.startIndex, offsetBy: location) let end = string.index(string.startIndex, offsetBy: location + 2) return String(string[start ..< end]) } let toColorElement = { (part:String) throws -> CGFloat in guard part.count == 2, let value = Int(part, radix: 16) else { throw InitializeError.InvalidFormat(string) } return CGFloat(value) / 255.0 } let red = try toColorElement(getColorPart(.Red)) let green = try toColorElement(getColorPart(.Green)) let blue = try toColorElement(getColorPart(.Blue)) rawValue = NSColor(red: red, green: green, blue: blue, alpha: 1.0) } } extension Color : Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let string = try container.decode(String.self) do { self = try Color(twitterColorString: string) } catch { throw DecodingError.dataCorruptedError(in: container, debugDescription: error.localizedDescription) } } }
gpl-3.0
d89d35749d715f9e2b938771e369d9c4
19.536082
102
0.685743
3.709497
false
false
false
false
victorchee/SettingsBundle
SettingsBundle/SettingsBundle/AppDelegate.swift
1
3824
// // AppDelegate.swift // SettingsBundle // // Created by qihaijun on 12/22/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if let settingsBundleURL = NSBundle.mainBundle().URLForResource("Settings", withExtension: "bundle"), let appDefaults = loadDefaultsFromSettingPage("Root.plist", inSettingsBundleAtURL: settingsBundleURL) { NSUserDefaults.standardUserDefaults().registerDefaults(appDefaults) NSUserDefaults.standardUserDefaults().synchronize() } 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:. } private func loadDefaultsFromSettingPage(plistName: String, inSettingsBundleAtURL settingsBundleURL: NSURL) -> [String : AnyObject]? { let url = settingsBundleURL.URLByAppendingPathComponent(plistName) guard let settings = NSDictionary(contentsOfURL: url) else { return nil } guard let specifiers = settings["PreferenceSpecifiers"] as? [[String : AnyObject]] else { return nil } let keyValuePairs = NSMutableDictionary() for item in specifiers { let itemType = item["Type"] as? String let itemKey = item["Key"] as? String let itemDefaultValue = item["DefaultValue"] if let type = itemType where type == "PSChildPaneSpecifier" { if let itemFile = item["File"] as? String, let childPageKeyValuePairs = loadDefaultsFromSettingPage(itemFile, inSettingsBundleAtURL: settingsBundleURL) { keyValuePairs.addEntriesFromDictionary(childPageKeyValuePairs) } } else if itemKey != nil && itemDefaultValue != nil { keyValuePairs[itemKey!] = itemDefaultValue } } return keyValuePairs as [NSObject : AnyObject] as? [String : AnyObject] } }
mit
1989d67356aac8aa1ad5dfd3bf35e61d
48.649351
285
0.705205
5.556686
false
false
false
false
xdliu002/TAC_communication
LocationDemo/LocationDemo/WeatherModel.swift
1
2347
// // WeatherModel.swift // LocationDemo // // Created by Teng on 3/29/16. // Copyright © 2016 huoteng. All rights reserved. // import Foundation import SwiftyJSON import Alamofire class WeatherModel { func getWeather(_ lat:Double, lon:Double, resultHandler:@escaping (String, String) -> Void) { // let location = "\(lat):\(lon)" // Alamofire.request(.GET, "https://api.thinkpage.cn/v3/weather/now.json", parameters: ["key": "z81dtslpgnokdun3", "location": location], encoding: .URL, headers: nil) // .responseJSON { (response) -> Void in // if let data = response.result.value { // print("data:\(data)") // let jsonData = JSON(data) // print(jsonData) // } // } // Alamofire 4 let parameters: Parameters = ["lat": lat, "lon": lon, "appid": "168b476d6c0e2ad2fc8d16b81ec86018"] Alamofire.request("http://api.openweathermap.org/data/2.5/weather", method: .get, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in if let data = response.result.value { print("data:\(data)") let jsonData = JSON(data) let cityName = jsonData["name"].stringValue let weatherDescription = jsonData["weather"][0]["description"].stringValue resultHandler(cityName, weatherDescription) } else { print("Can't get data") } } // Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/weather", parameters: ["lat": lat, "lon": lon, "appid": "168b476d6c0e2ad2fc8d16b81ec86018"], encoding: .URL, headers: nil) // .responseJSON { (response) -> Void in // if let data = response.result.value { // print("data:\(data)") // let jsonData = JSON(data) // let cityName = jsonData["name"].stringValue // let weatherDescription = jsonData["weather"][0]["description"].stringValue // resultHandler(cityName, weatherDescription) // } else { // print("Can't get data") // } // } } }
mit
f940195b190653c87c0ddd39270aa5ae
41.654545
196
0.534527
4.19678
false
false
false
false
narner/AudioKit
Examples/iOS/SongProcessor/SongProcessor/SongProcessor.swift
1
9669
// // SongProcessor.swift // SongProcessor // // Created by Aurelius Prochazka on 6/22/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit import AudioKit import MediaPlayer class SongProcessor: NSObject, UIDocumentInteractionControllerDelegate { static let sharedInstance = SongProcessor() var iTunesFilePlayer: AKAudioPlayer? var variableDelay = AKDelay() //Was AKVariableDelay, but it wasn't offline render friendly! var delayMixer = AKDryWetMixer() var moogLadder = AKMoogLadder() var filterMixer = AKDryWetMixer() var reverb = AKCostelloReverb() var reverbMixer = AKDryWetMixer() var pitchShifter = AKPitchShifter() var pitchMixer = AKDryWetMixer() var bitCrusher = AKBitCrusher() var bitCrushMixer = AKDryWetMixer() var playerBooster = AKBooster() var offlineRender = AKOfflineRenderNode() var players = [String: AKAudioPlayer]() var playerMixer = AKMixer() fileprivate var docController: UIDocumentInteractionController? var iTunesPlaying: Bool { set { if newValue { guard let iTunesFilePlayer = iTunesFilePlayer else { return } if !iTunesFilePlayer.isPlaying { iTunesFilePlayer.play() } } else { iTunesFilePlayer?.stop() } } get { return iTunesFilePlayer?.isPlaying ?? false } } var loopsPlaying: Bool { set { if newValue { guard let firtPlayer = players.values.first else { return } if !firtPlayer.isPlaying { playLoops() } } else { stopLoops() } } get { return players.values.first?.isPlaying ?? false } } override init() { super.init() for name in ["bass", "drum", "guitar", "lead"] { do { let audioFile = try AKAudioFile(readFileName: name+"loop.wav", baseDir: .resources) players[name] = try AKAudioPlayer(file: audioFile, looping: true) players[name]?.connect(to: playerMixer) } catch { fatalError(String(describing: error)) } } playerMixer >>> delayMixer >>> filterMixer >>> reverbMixer >>> pitchMixer >>> bitCrushMixer >>> playerBooster >>> offlineRender AudioKit.output = offlineRender playerMixer >>> variableDelay >>> delayMixer.wetInput delayMixer >>> moogLadder >>> filterMixer.wetInput filterMixer >>> reverb >>> reverbMixer.wetInput reverbMixer >>> pitchShifter >>> pitchMixer.wetInput pitchMixer >>> bitCrusher >>> bitCrushMixer.wetInput // Allow the app to play in the background do { try AKSettings.setSession(category: .playback, with: .mixWithOthers) } catch { print("error") } AKSettings.playbackWhileMuted = true AudioKit.output = offlineRender initParameters() AudioKit.start() } func initParameters() { delayMixer.balance = 0 filterMixer.balance = 0 reverbMixer.balance = 0 pitchMixer.balance = 0 bitCrushMixer.balance = 0 bitCrusher.bitDepth = 16 bitCrusher.sampleRate = 3_333 //Booster for Volume playerBooster.gain = 0.5 } func rewindLoops() { playersDo { $0.schedule(from: 0, to: $0.duration, avTime: nil)} } func playLoops(at when: AVAudioTime? = nil) { let startTime = when ?? SongProcessor.twoRendersFromNow() playersDo { $0.play(at: startTime) } } func stopLoops() { playersDo { $0.stop() } } func playersDo(_ action: @escaping (AKAudioPlayer) -> Void) { for player in players.values { action(player) } } private class func twoRendersFromNow() -> AVAudioTime { let twoRenders = AVAudioTime.hostTime(forSeconds: AKSettings.bufferLength.duration * 2) return AVAudioTime(hostTime: mach_absolute_time() + twoRenders) } enum ShareTarget { case iTunes case loops } fileprivate func mixDownItunes(url: URL) throws { offlineRender.internalRenderEnabled = false guard let player = iTunesFilePlayer else { offlineRender.internalRenderEnabled = true throw NSError(domain: "SongProcessor", code: 1, userInfo: [NSLocalizedDescriptionKey: "Target itunes but no player exists"]) } let duration = player.duration player.schedule(from: 0, to: duration, avTime: nil) let timeZero = AVAudioTime(sampleTime: 0, atRate: offlineRender.avAudioNode.inputFormat(forBus: 0).sampleRate) player.play(at:timeZero) try offlineRender.renderToURL(url, seconds: duration) player.stop() offlineRender.internalRenderEnabled = true } fileprivate func mixDownLoops(url: URL, loops: Int) throws { offlineRender.internalRenderEnabled = false guard let player = players.values.first else { offlineRender.internalRenderEnabled = true throw NSError(domain: "SongProcessor", code: 1, userInfo: [NSLocalizedDescriptionKey: "No loop players!"]) } let duration = player.duration * Double(loops) let timeZero = AVAudioTime(sampleTime: 0, atRate: offlineRender.avAudioNode.inputFormat(forBus: 0).sampleRate) rewindLoops() playLoops(at: timeZero) try offlineRender.renderToURL(url, seconds: duration) rewindLoops() stopLoops() offlineRender.internalRenderEnabled = true } func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) { docController = nil guard let url = controller.url else { return } if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(at: url) } catch { print(error) } } } var mixDownURL: URL = { let tempDir = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true) return tempDir.appendingPathComponent("mixDown.m4a") }() } extension UIViewController { func renderAndShare(completion: @escaping (UIDocumentInteractionController?) -> Void) { let songProcessor = SongProcessor.sharedInstance let url = songProcessor.mixDownURL let cleanup: (Error) -> Void = { error in if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(at: url) } catch { print(error) } } let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) self.present(alert, animated: true, completion: {completion(nil)}) } let success = { let docController = UIDocumentInteractionController(url: url) docController.delegate = songProcessor songProcessor.docController = docController completion(docController) } let shareLoops = { let alert = UIAlertController(title: "How many loops?", message: nil, preferredStyle: .alert) alert.addTextField { (textField) in textField.keyboardType = .decimalPad textField.text = String(1) } alert.addAction(.init(title: "OK", style: .default, handler: { (_) in let text = alert.textFields?.first?.text guard let countText = text, let count = Int(countText), count > 0 else { let message = text == nil ? "Need a count" : text! + " isn't a vaild loop count!" cleanup(NSError(domain: "SongProcessor", code: 1, userInfo: [NSLocalizedDescriptionKey: message])) return } do { try songProcessor.mixDownLoops(url: url, loops: count) success() } catch { cleanup(error) } })) alert.addAction(.init(title: "Cancel", style: .cancel, handler:nil)) self.present(alert, animated: true, completion: nil) } if songProcessor.iTunesFilePlayer != nil { let alert = UIAlertController(title: "Export Song or Loops?", message: nil, preferredStyle: .alert) alert.addAction(.init(title: "Song", style: .default, handler: { (_) in do { try songProcessor.mixDownItunes(url: url) success() } catch { cleanup(error) } })) alert.addAction(.init(title: "Loops", style: .default, handler: { (_) in shareLoops() })) alert.addAction(.init(title: "Cancel", style: .cancel, handler:nil)) present(alert, animated: true, completion: nil) } else { shareLoops() } } func alertForShareFail() -> UIAlertController { let message = TARGET_OS_SIMULATOR == 0 ? nil : "Try using a device instead of the simulator :)" let alert = UIAlertController(title: "No Applications to share with", message: message, preferredStyle: .alert) alert.addAction(.init(title: "OK", style: .default, handler: nil)) return alert } }
mit
84ffa970fdff722102eb56863e42c09b
34.544118
136
0.59216
4.824351
false
false
false
false
zyhndesign/SDX_DG
sdxdg/sdxdg/FeedbackListViewController.swift
1
5084
// // FeedbackListViewController.swift // sdxdg // // Created by lotusprize on 16/12/26. // Copyright © 2016年 geekTeam. All rights reserved. // import UIKit import Alamofire import ObjectMapper class FeedbackListViewController: UITableViewController { var sBoard:UIStoryboard? var naviController:UINavigationController? let screenWidth = UIScreen.main.bounds.width let refresh = UIRefreshControl.init() let pageLimit:Int = 10 var pageNum:Int = 0 var matchList:[Match] = [] let userId = LocalDataStorageUtil.getUserIdFromUserDefaults() var vipName:String = "" var vipId:Int = 0 init(sBoard:UIStoryboard, naviController:UINavigationController, vipName:String, vipId:Int){ super.init(nibName: nil, bundle: nil) self.sBoard = sBoard self.naviController = naviController self.vipName = vipName self.vipId = vipId } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.tableView.register(FeedbackListCell.self, forCellReuseIdentifier: "feedbackCell") //self.tableView.dataSource = self refresh.backgroundColor = UIColor.white refresh.tintColor = UIColor.lightGray refresh.attributedTitle = NSAttributedString(string:"下拉刷新") refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged) self.tableView.addSubview(refresh) loadData(limit: pageLimit,offset: 0) self.tableView.tableFooterView = UIView.init(frame: CGRect.zero) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return matchList.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return (screenWidth - 50) / 4 + 60 } func refreshLoadingData(){ loadData(limit: pageLimit,offset: pageLimit * pageNum) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController:FeedbackDetailViewController = sBoard?.instantiateViewController(withIdentifier: "FeedbackDetailView") as! FeedbackDetailViewController let match:Match = matchList[indexPath.row] let matchLists:[Matchlist] = match.matchlists! viewController.initData(matchLists: matchLists) viewController.vipId = vipId naviController?.pushViewController(viewController, animated: true) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identify:String = "feedbackCell" let cell:FeedbackListCell = tableView.dequeueReusableCell(withIdentifier: identify, for: indexPath) as! FeedbackListCell; let match:Match = matchList[indexPath.row] let matchLists:[Matchlist] = match.matchlists! cell.initDataForCell(name:match.seriesname! , fbIcon1: matchLists[0].modelurl!, fbIcon2: matchLists[1].modelurl!, fbIcon3: matchLists[2].modelurl!, fbIcon4: matchLists[3].modelurl!,time:match.createtime! ,storyBoard: sBoard!, navigationController:naviController!) return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadData(limit:Int, offset:Int){ let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.label.text = "正在加载中..." let parameters:Parameters = ["userId":userId, "vipName":vipName, "limit":limit,"offset":offset] Alamofire.request(ConstantsUtil.APP_SHARE_HISTORY_URL,method:.post, parameters:parameters).responseObject { (response: DataResponse<MatchServerModel>) in let matchServerModel = response.result.value if (matchServerModel?.resultCode == 200){ if let matchServerModelList = matchServerModel?.object { for matchModel in matchServerModelList{ self.matchList.insert(matchModel, at: 0) self.pageNum = self.pageNum + 1 } self.tableView.reloadData() self.refresh.endRefreshing() hud.label.text = "加载成功" hud.hide(animated: true, afterDelay: 0.5) } else{ hud.label.text = "无推送历史数据" hud.hide(animated: true, afterDelay: 0.5) } } else{ hud.label.text = "加载失败" hud.hide(animated: true, afterDelay: 0.5) } } } }
apache-2.0
eb627a74f4cc1f0a0776b132fc322840
36.007353
178
0.625273
4.915039
false
false
false
false
neilsardesai/chrono-swift
Sample Apps/ChronoSample/Chrono iOS/ViewController.swift
1
1142
// // ViewController.swift // Chrono iOS // // Created by Neil Sardesai on 2016-11-17. // Copyright © 2016 Neil Sardesai. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: IBOutlets @IBOutlet weak var discoveredDateLabel: UILabel! @IBOutlet weak var inputField: UITextField! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() discoveredDateLabel.text = "" inputField.addTarget(self, action: #selector(updateDiscoveredDateLabel), for: .editingChanged) } @objc func updateDiscoveredDateLabel() { let chrono = Chrono.shared let date = chrono.dateFrom(naturalLanguageString: inputField.text!) // Make the date pretty let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .long guard let discoveredDate = date else { discoveredDateLabel.text = "" return } discoveredDateLabel.text = dateFormatter.string(from: discoveredDate) } }
mit
68986fbe03831090ed8c90be654fec60
24.355556
102
0.629273
5.026432
false
false
false
false
iThinkersTeam/Reports
Whats-new-in-Swift-4.playground/Pages/Integer protocols.xcplaygroundpage/Contents.swift
1
2921
/*: [Table of contents](Table%20of%20contents) • [Previous page](@previous) • [Next page](@next) ## New integer protocols [SE-0104][SE-0104] was originally accepted for Swift 3, but didnʼt make the cut. Now a slightly revised version is coming in Swift 4. “This proposal cleans up Swifts integer APIs and makes them more useful for generic programming.” [SE-0104]: https://github.com/apple/swift-evolution/blob/master/proposals/0104-improved-integers.md "Swift Evolution Proposal SE-0104: Protocol-oriented integers" The protocol hierarchy looks like this: ![](integer-protocols.png) This might look a little intimidating, but the most important thing to take away from this is that you don’t have to care about all the protocols. Just use the integer types you’re familiar with, such as `Int` and `UInt8`, as you always have and you’ll be absolutely fine. The new protocols only come into play once you want to write generic algorithms that work on multiple numeric types. For a library that takes advantage of the new protocols, check out [NumericAnnex](https://github.com/xwu/NumericAnnex) by Xiaodi Wu. ### Heterogeneous comparison operators You can now compare an `Int` to an `UInt` without explicit conversion, thanks to new generic overloads for these functions in the standard library. */ let a: Int = 5 let b: UInt = 5 let c: Int8 = -10 a == b // doesn't compile in Swift 3 a > c // doesn't compile in Swift 3 /*: Note that mixed-type _arithmetic_ doesn’t work because Swift doesn’t have a concept of _promoting_ one type to another yet. (The implicit promotion of `T` to `Optional<T>` is an exception, hardcoded into the compiler.) This is a desirable feature for a future version. */ //a + b // doesn't compile in either Swift 3 or 4 /*: There’s a lot more to the new protocols. Here are a few examples of new properties and methods: */ // Get information about the bit pattern 0xFFFF.words 0b11001000.trailingZeroBitCount (0b00001100 as UInt8).leadingZeroBitCount 0b110001.nonzeroBitCount // Artihmetic with overflow reporting let (partialValue, overflow) = Int32.max.addingReportingOverflow(1) partialValue overflow // Calculate the full result of a multiplication that would otherwise overflow let x: UInt8 = 100 let y: UInt8 = 20 let result = x.multipliedFullWidth(by: y) result.high result.low /*: I left out some more additions, such as new bit shifting operators and semantics. Read the proposal to get the full picture. */ /*: ### `DoubleWidth` The new `DoubleWidth<T>` type is supposed to make it possible to create wider fixed-width integer types from the ones available in the standard library. It didn't work in my tests yet, however. */ //var veryBigNumber = DoubleWidth<Int64>(Int64.max) // EXC_BAD_INSTRUCTION //veryBigNumber + 1 /*: [Table of contents](Table%20of%20contents) • [Previous page](@previous) • [Next page](@next) */
apache-2.0
81343d2c2c93fc1c33c9818ea7f4d32c
41.588235
390
0.753108
3.861333
false
false
false
false
I-SYST/iOS
SensorTagDemo/SensorTagDemo/ViewController.swift
1
5972
// // ViewController.swift // SensorTagDemo // // Created by Nguyen Hoan Hoang on 2017-10-08. // Copyright © 2017 I-SYST inc. All rights reserved. // import UIKit import CoreBluetooth import simd class ViewController: UIViewController, CBCentralManagerDelegate { var bleCentral : CBCentralManager! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. bleCentral = CBCentralManager(delegate: self, queue: DispatchQueue.main) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var graphView : GraphView! @IBOutlet weak var tempLabel: UILabel! @IBOutlet weak var humiLabel : UILabel! @IBOutlet weak var pressLabel : UILabel! @IBOutlet weak var rssiLabel : UILabel! @IBOutlet weak var aqiLabel : UILabel! @IBOutlet weak var batLevelLabel : UILabel! @IBOutlet weak var batVoltLabel : UILabel! // MARK: BLE Central func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData : [String : Any], rssi RSSI: NSNumber) { print("PERIPHERAL NAME: \(String(describing: peripheral.name))\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n") print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n") print("IDENTIFIER: \(peripheral.identifier)\n") if advertisementData[CBAdvertisementDataManufacturerDataKey] == nil { return } //sensorData.text = sensorData.text + "FOUND PERIPHERALS: \(peripheral) AdvertisementData: \(advertisementData) RSSI: \(RSSI)\n" var manId = UInt16(0) let manData = advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData if manData.length < 3 { return } //(advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&manId, range: NSMakeRange(0, 2)) manData.getBytes(&manId, range: NSMakeRange(0, 2)) if manId != 0x177 { return } var type = UInt8(0) //(advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&type, range: NSMakeRange(2, 1)) manData.getBytes(&type, range: NSMakeRange(2, 1)) switch (type) { case 1: var press = Int32(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&press, range: NSMakeRange(3, 4)) pressLabel.text = String(format:"%.2f KPa", Float(press) / 1000.0) var temp = Int16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&temp, range: NSMakeRange(7, 2)) tempLabel.text = String(format:"%.2f C", Float(temp) / 100.0) var humi = UInt16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&humi, range: NSMakeRange(9, 2)) humiLabel.text = String(format:"%d%%", humi / 100) graphView.add(double3(Double(temp) / 100.0, Double(press) / 1000.0, Double(humi) / 100.0)) break case 2: var aqi = UInt16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&aqi, range: NSMakeRange(3, 2)) break case 16: var batLevel = UInt8(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&batLevel, range: NSMakeRange(3, 1)) batLevelLabel.text = String(format:"%d%%", batLevel) var batVolt = Int32(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&batVolt, range: NSMakeRange(4, 4)) batVoltLabel.text = String(format:"%.2fV", Float(batVolt) / 1000.0) break default: break } rssiLabel.text = String( describing: RSSI) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { peripheral.discoverServices(nil) print("Connected to peripheral") } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { print("disconnected from peripheral") } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { } func scanPeripheral(_ sender: CBCentralManager) { print("Scan for peripherals") bleCentral.scanForPeripherals(withServices: nil, options: nil) } func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOff: print("CoreBluetooth BLE hardware is powered off") break case .poweredOn: print("CoreBluetooth BLE hardware is powered on and ready") bleCentral.scanForPeripherals(withServices: nil, options: nil) break case .resetting: print("CoreBluetooth BLE hardware is resetting") break case .unauthorized: print("CoreBluetooth BLE state is unauthorized") break case .unknown: print("CoreBluetooth BLE state is unknown") break case .unsupported: print("CoreBluetooth BLE hardware is unsupported on this platform") break } } }
bsd-2-clause
4f80e3615fc85a1a5d4f18b09eaa2068
36.086957
136
0.600904
5.073067
false
false
false
false
SteveRohrlack/CitySimCore
src/Model/Locateable.swift
1
2991
// // Locateable.swift // CitySimCore // // Created by Steve Rohrlack on 13.05.16. // Copyright © 2016 Steve Rohrlack. All rights reserved. // import Foundation import GameplayKit /** the Locateable protocol describes a location on a 2D map it provides several helpers for getting and calculating often needed values - y = height - x = width */ public protocol Locateable { /// origin of the location /// this is relative to the used coordinate system var origin: (Int, Int) { get } /// height of the location, absolute value var height: Int { get } /// width of the location, absolute value var width: Int { get } /// relative maximum Y value var maxY: Int { get } /// relative maximum X value var maxX: Int { get } /// origin's Y value var originY: Int { get } /// origin's X value var originX: Int { get } /// helper to iterate over each cell var forEachCell: ((((Int, Int) -> Void)) -> Void) { get } /// representation as GKGridGraphNodes var nodes: [GKGridGraphNode] { get } } extension Locateable { /// since "origin" is a tuple, accessing the tuple's /// content is more convenient and readable using .originY instead of /// .origin.0 public var originY: Int { return origin.0 } /// since "origin" is a tuple, accessing the tuple's /// content is more convenient and readable using .originX instead of /// .origin.1 public var originX: Int { return origin.1 } /// calculates Y coordinate based on the location's origin and it's height public var maxY: Int { return origin.0 - 1 + height } /// calculates X coordinate based on the location's origin and it's width public var maxX: Int { return origin.1 - 1 + width } /** return a function to call with another function as parameter to recieve y, x coordinates for each cell in the location - returns: function */ public var forEachCell: ((((Int, Int) -> Void)) -> Void) { func forEach(callback: ((y: Int, x: Int) -> Void)) -> Void { for y in (originY...maxY) { for x in (originX...maxX) { callback(y: y, x: x) } } } return forEach } /// representation as GKGridGraphNodes public var nodes: [GKGridGraphNode] { var nodes: [GKGridGraphNode] = [] forEachCell { (y: Int, x: Int) in nodes.append(GKGridGraphNode(gridPosition: vector_int2(Int32(x), Int32(y)))) } return nodes } } /** operator "==" to allow comparing Locations - parameter lhs: Locateable - parameter rhs: Locateable - returns: Bool */ public func == (lhs: Locateable, rhs: Locateable) -> Bool { return lhs.origin == rhs.origin && lhs.height == rhs.height && lhs.width == rhs.width }
mit
d3b18be9f8c24ea215e52c27bd55476e
24.347458
89
0.588629
4.235127
false
false
false
false
mactive/rw-courses-note
RWBlueLibrary-Part1-Starter/RWBlueLibrary/AlbumView.swift
1
3238
/** * Copyright (c) 2017 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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 class AlbumView: UIView { private var coverImageView: UIImageView! private var indicatorView: UIActivityIndicatorView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } init(frame: CGRect, coverUrl: String) { super.init(frame: frame) commonInit() } private func commonInit() { // Setup the background backgroundColor = .black // Create the cover image view coverImageView = UIImageView() coverImageView.translatesAutoresizingMaskIntoConstraints = false addSubview(coverImageView) // Create the indicator view indicatorView = UIActivityIndicatorView() indicatorView.translatesAutoresizingMaskIntoConstraints = false indicatorView.activityIndicatorViewStyle = .whiteLarge indicatorView.startAnimating() addSubview(indicatorView) NSLayoutConstraint.activate([ coverImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5), coverImageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -5), coverImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5), coverImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5), indicatorView.centerXAnchor.constraint(equalTo: self.centerXAnchor), indicatorView.centerYAnchor.constraint(equalTo: self.centerYAnchor) ]) } func highlightAlbum(_ didHighlightView: Bool) { if didHighlightView == true { backgroundColor = .white } else { backgroundColor = .black } } }
mit
13aaa06deb53e3e5a17b118391e43915
38.975309
91
0.748301
5.03577
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/results/TKUICompactAlertCell.swift
1
2390
// // TKUICompactAlertCell.swift // TripKitUI-iOS // // Created by Adrian Schönig on 21.04.20. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // import UIKit import TripKit class TKUICompactAlertCell: UITableViewCell { static let reuseIdentifier = "TKUICompactAlertCell" @IBOutlet weak var alertIcon: UIImageView! @IBOutlet weak var alertLabel: UILabel! override convenience init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { self.init() } init() { super.init(style: .default, reuseIdentifier: Self.reuseIdentifier) didInit() } required init?(coder: NSCoder) { super.init(coder: coder) didInit() } func configure(_ alert: TKAPI.Alert) { contentView.backgroundColor = alert.severity.backgroundColor alertIcon?.tintColor = alert.severity.textColor alertLabel?.text = alert.title alertLabel?.textColor = alert.severity.textColor } private func didInit() { // WARNING: Important to do this first, otherwise it'll crash on 12.4 contentView.constraintsAffectingLayout(for: .vertical).forEach { $0.priority = UILayoutPriority(999) } let icon = UIImageView() icon.image = .iconAlert icon.contentMode = .scaleAspectFit icon.widthAnchor.constraint(equalToConstant: 16).isActive = true icon.heightAnchor.constraint(equalToConstant: 16).isActive = true icon.translatesAutoresizingMaskIntoConstraints = false self.alertIcon = icon let label = UILabel() label.numberOfLines = 1 label.text = nil label.font = TKStyleManager.customFont(forTextStyle: .subheadline) label.translatesAutoresizingMaskIntoConstraints = false self.alertLabel = label let stack = UIStackView(arrangedSubviews: [icon, label]) stack.axis = .horizontal stack.alignment = .center stack.distribution = .fill stack.spacing = 8 stack.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(stack) NSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), stack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12), contentView.bottomAnchor.constraint(equalTo: stack.bottomAnchor, constant: 12), contentView.trailingAnchor.constraint(equalTo: stack.trailingAnchor, constant: 16) ] ) } }
apache-2.0
98acc8a5f8f97c0fe78862da34c46471
30.421053
106
0.721106
4.710059
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Routing/Weather List Flow/WeatherListStepper.swift
1
3219
// // ListStepper.swift // NearbyWeather // // Created by Erik Maximilian Martens on 19.04.20. // Copyright © 2020 Erik Maximilian Martens. All rights reserved. // import RxSwift import RxCocoa import RxFlow import Swinject enum WeatherListStep: Step { case list case emptyList case loadingList case weatherDetails(identity: PersistencyModelIdentity) case changeListTypeAlert(selectionDelegate: ListTypeSelectionAlertDelegate) case changeListTypeAlertAdapted(selectionDelegate: ListTypeSelectionAlertDelegate, currentSelectedOptionValue: ListTypeOptionValue) case changeAmountOfResultsAlert(selectionDelegate: AmountOfResultsSelectionAlertDelegate) case changeAmountOfResultsAlertAdapted(selectionDelegate: AmountOfResultsSelectionAlertDelegate, currentSelectedOptionValue: AmountOfResultsOptionValue) case changeSortingOrientationAlert(selectionDelegate: SortingOrientationSelectionAlertDelegate) case changeSortingOrientationAlertAdapted(selectionDelegate: SortingOrientationSelectionAlertDelegate, currentSelectedOptionValue: SortingOrientationOptionValue) case dismiss case pop } extension WeatherListStep: Equatable { static func == (lhs: Self, rhs: Self) -> Bool { switch (lhs, rhs) { case (let .weatherDetails(lhsIdentity), let .weatherDetails(rhsIdentity)): return lhsIdentity.identifier == rhsIdentity.identifier case (.list, .list), (.emptyList, .emptyList), (.loadingList, .loadingList), (.dismiss, .dismiss), (.pop, .pop): return true case (.changeListTypeAlert, .changeListTypeAlert), (.changeAmountOfResultsAlert, .changeAmountOfResultsAlert), (.changeSortingOrientationAlert, .changeSortingOrientationAlert): return false case (let .changeListTypeAlertAdapted(_, lhsOption), let .changeListTypeAlertAdapted(_, rhsOption)): return lhsOption.rawValue == rhsOption.rawValue case (let .changeAmountOfResultsAlertAdapted(_, lhsOption), let .changeAmountOfResultsAlertAdapted(_, rhsOption)): return lhsOption.rawValue == rhsOption.rawValue case (let .changeSortingOrientationAlertAdapted(_, lhsOption), let .changeSortingOrientationAlertAdapted(_, rhsOption)): return lhsOption.rawValue == rhsOption.rawValue default: return false } } } final class WeatherListStepper: Stepper { // MARK: - Assets private let disposeBag = DisposeBag() let steps = PublishRelay<Step>() // MARK: - Properties let dependencyContainer: Container // MARK: - Initialization init(dependencyContainer: Container) { self.dependencyContainer = dependencyContainer } func readyToEmitSteps() { dependencyContainer .resolve(WeatherInformationService.self)? .createDidUpdateWeatherInformationObservable() .map { informationAvailable in (informationAvailable == .available) ? WeatherListStep.list : WeatherListStep.emptyList } .distinctUntilChanged { lhsStep, rhsStep in guard let lhsWeatherListStep = lhsStep as? WeatherListStep, let rhsWeatherListStep = rhsStep as? WeatherListStep else { return true } return lhsWeatherListStep == rhsWeatherListStep } .bind(to: steps) .disposed(by: disposeBag) } }
mit
cb3c1cdb19b297c9c76835e38c230770
38.728395
180
0.766004
4.725404
false
false
false
false
Bunn/firefox-ios
Client/Frontend/Widgets/FirefoxHomeHighlightCell.swift
1
8490
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage private struct FirefoxHomeHighlightCellUX { static let BorderWidth: CGFloat = 0.5 static let CellSideOffset = 20 static let TitleLabelOffset = 2 static let CellTopBottomOffset = 12 static let SiteImageViewSize = CGSize(width: 99, height: UIDevice.current.userInterfaceIdiom == .pad ? 120 : 90) static let StatusIconSize = 12 static let FaviconSize = CGSize(width: 45, height: 45) static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25) static let CornerRadius: CGFloat = 3 static let BorderColor = UIColor.Photon.Grey30 } class FirefoxHomeHighlightCell: UICollectionViewCell { fileprivate lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeHeavyWeightAS titleLabel.textColor = UIColor.theme.homePanel.activityStreamCellTitle titleLabel.textAlignment = .left titleLabel.numberOfLines = 3 return titleLabel }() fileprivate lazy var descriptionLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS descriptionLabel.textColor = UIColor.theme.homePanel.activityStreamCellDescription descriptionLabel.textAlignment = .left descriptionLabel.numberOfLines = 1 return descriptionLabel }() fileprivate lazy var domainLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS descriptionLabel.textColor = UIColor.theme.homePanel.activityStreamCellDescription descriptionLabel.textAlignment = .left descriptionLabel.numberOfLines = 1 descriptionLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .vertical) return descriptionLabel }() lazy var siteImageView: UIImageView = { let siteImageView = UIImageView() siteImageView.contentMode = .scaleAspectFit siteImageView.clipsToBounds = true siteImageView.contentMode = .center siteImageView.layer.cornerRadius = FirefoxHomeHighlightCellUX.CornerRadius siteImageView.layer.borderColor = FirefoxHomeHighlightCellUX.BorderColor.cgColor siteImageView.layer.borderWidth = FirefoxHomeHighlightCellUX.BorderWidth siteImageView.layer.masksToBounds = true return siteImageView }() fileprivate lazy var statusIcon: UIImageView = { let statusIcon = UIImageView() statusIcon.contentMode = .scaleAspectFit statusIcon.clipsToBounds = true statusIcon.layer.cornerRadius = FirefoxHomeHighlightCellUX.CornerRadius return statusIcon }() fileprivate lazy var selectedOverlay: UIView = { let selectedOverlay = UIView() selectedOverlay.backgroundColor = FirefoxHomeHighlightCellUX.SelectedOverlayColor selectedOverlay.isHidden = true return selectedOverlay }() fileprivate lazy var playLabel: UIImageView = { let view = UIImageView() view.image = UIImage.templateImageNamed("play") view.tintColor = .white view.alpha = 0.97 view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.3 view.layer.shadowRadius = 2 view.isHidden = true return view }() fileprivate lazy var pocketTrendingIconNormal = UIImage(named: "context_pocket")?.tinted(withColor: UIColor.Photon.Grey90) fileprivate lazy var pocketTrendingIconDark = UIImage(named: "context_pocket")?.tinted(withColor: UIColor.Photon.Grey10) override var isSelected: Bool { didSet { self.selectedOverlay.isHidden = !isSelected } } override init(frame: CGRect) { super.init(frame: frame) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale isAccessibilityElement = true contentView.addSubview(siteImageView) contentView.addSubview(descriptionLabel) contentView.addSubview(selectedOverlay) contentView.addSubview(titleLabel) contentView.addSubview(statusIcon) contentView.addSubview(domainLabel) contentView.addSubview(playLabel) siteImageView.snp.makeConstraints { make in make.top.equalTo(contentView) make.leading.equalTo(contentView.safeArea.leading) make.trailing.equalTo(contentView.safeArea.trailing) make.centerX.equalTo(contentView) make.height.equalTo(FirefoxHomeHighlightCellUX.SiteImageViewSize) } selectedOverlay.snp.makeConstraints { make in make.edges.equalTo(contentView.safeArea.edges) } domainLabel.snp.makeConstraints { make in make.leading.equalTo(siteImageView) make.trailing.equalTo(contentView.safeArea.trailing) make.top.equalTo(siteImageView.snp.bottom).offset(5) } titleLabel.snp.makeConstraints { make in make.leading.equalTo(siteImageView) make.trailing.equalTo(contentView.safeArea.trailing) make.top.equalTo(domainLabel.snp.bottom).offset(5) } descriptionLabel.snp.makeConstraints { make in make.leading.equalTo(statusIcon.snp.trailing).offset(FirefoxHomeHighlightCellUX.TitleLabelOffset) make.bottom.equalTo(contentView) } statusIcon.snp.makeConstraints { make in make.size.equalTo(FirefoxHomeHighlightCellUX.StatusIconSize) make.centerY.equalTo(descriptionLabel.snp.centerY) make.leading.equalTo(siteImageView) } playLabel.snp.makeConstraints { make in make.center.equalTo(siteImageView.snp.center) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() self.siteImageView.image = nil contentView.backgroundColor = UIColor.clear siteImageView.backgroundColor = UIColor.clear playLabel.isHidden = true descriptionLabel.textColor = UIColor.theme.homePanel.activityStreamCellDescription } func configureWithSite(_ site: Site) { if let mediaURLStr = site.metadata?.mediaURL, let mediaURL = URL(string: mediaURLStr) { self.siteImageView.sd_setImage(with: mediaURL) self.siteImageView.contentMode = .scaleAspectFill } else { let itemURL = site.tileURL self.siteImageView.setFavicon(forSite: site, onCompletion: { [weak self] (color, url) in if itemURL == url { self?.siteImageView.image = self?.siteImageView.image?.createScaled(FirefoxHomeHighlightCellUX.FaviconSize) self?.siteImageView.backgroundColor = color } }) self.siteImageView.contentMode = .center } self.domainLabel.text = site.tileURL.shortDisplayString self.titleLabel.text = site.title.isEmpty ? site.url : site.title if let bookmarked = site.bookmarked, bookmarked { self.descriptionLabel.text = Strings.HighlightBookmarkText self.statusIcon.image = UIImage(named: "context_bookmark") } else { self.descriptionLabel.text = Strings.HighlightVistedText self.statusIcon.image = UIImage(named: "context_viewed") } } func configureWithPocketStory(_ pocketStory: PocketStory) { self.siteImageView.sd_setImage(with: pocketStory.imageURL) self.siteImageView.contentMode = .scaleAspectFill self.domainLabel.text = pocketStory.domain self.titleLabel.text = pocketStory.title self.descriptionLabel.text = Strings.PocketTrendingText self.statusIcon.image = ThemeManager.instance.currentName == .dark ? pocketTrendingIconDark : pocketTrendingIconNormal } func configureWithPocketVideoStory(_ pocketStory: PocketStory) { playLabel.isHidden = false self.configureWithPocketStory(pocketStory) } }
mpl-2.0
a1e7e186f06e4053dcc252948f847bd1
38.859155
127
0.690577
5.08079
false
false
false
false
mxclove/compass
毕业设计_指南针最新3.2/毕业设计_指南针/setTableViewController.swift
1
4851
// // setTableViewController.swift // 毕业设计_指南针 // // Created by MC on 15/12/9. // Copyright © 2015年 马超. All rights reserved. // import UIKit class setTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let nibtextCell = UINib(nibName: "switchSetCell", bundle: nil) tableView.registerNib(nibtextCell, forCellReuseIdentifier: "switchcell") let nibsetCell = UINib(nibName: "setCell", bundle: nil) tableView.registerNib(nibsetCell, forCellReuseIdentifier: "settingCell") let nibdetailCell = UINib(nibName: "detailCell", bundle: nil) tableView.registerNib(nibdetailCell, forCellReuseIdentifier: "detailcell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 6 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCellWithIdentifier("switchcell") as! switchSetCell cell.nameLabel?.text = "流量保护" cell.mySwitch.on = trafficProtection if cell.delegate == nil { cell.delegate = leftViewController cell.delegateMap = mainViewController } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier("switchcell") as! switchSetCell cell.nameLabel?.text = "屏幕常亮" cell.mySwitch.on = UIApplication.sharedApplication().idleTimerDisabled return cell case 2: let cell = tableView.dequeueReusableCellWithIdentifier("switchcell") as! switchSetCell cell.nameLabel?.text = "显示位置信息" cell.mySwitch.on = compassViewShouldShowLocation if cell.delegate == nil { cell.delegate = leftViewController cell.delegateMap = mainViewController } return cell case 3: let cell = tableView.dequeueReusableCellWithIdentifier("switchcell") as! switchSetCell cell.nameLabel?.text = "边界滑动效果" cell.mySwitch.on = borderAnimationEnable return cell // case 4: let cell = tableView.dequeueReusableCellWithIdentifier("detailcell") as! detailCell cell.nameLabel?.text = "指南针使用帮助" return cell case 5: let cell = tableView.dequeueReusableCellWithIdentifier("settingCell") as! setCell cell.rightLabel?.text = "986455470@qq.com" cell.nameLabel?.text = "联系我们" return cell default: let cell = tableView.dequeueReusableCellWithIdentifier("settingCell") as! setCell cell.nameLabel?.text = "test" return cell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 2 { let alert = UIAlertController(title: "指南针使用帮助", message: "请尽量远离磁场干扰,指南针方向更准确。“附近可能有磁场干扰”需要校准时,会自动激活校准界面,请按照提示操作。\r\r获取详细位置信息需要网络连接。", preferredStyle: UIAlertControllerStyle.Alert) let Action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(Action) presentViewController(alert, animated: true, completion: nil) tableView.deselectRowAtIndexPath(indexPath, animated: true) } } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch section { case 0: return "移动数据联网情况下,不加载地图" case 1: return "开启此开关,则屏幕常亮" case 2: return "在指南针界面显示位置和经纬度信息" case 3: return "允许边界被滑动" default: return "" } } }
apache-2.0
5c133512c86eb51820376dc32187e9df
33.746154
187
0.615589
4.990055
false
false
false
false
joemcbride/outlander-osx
src/OutlanderTests/TriggersLoaderTester.swift
1
3573
// // TriggersLoaderTester.swift // Outlander // // Created by Joseph McBride on 6/5/15. // Copyright (c) 2015 Joe McBride. All rights reserved. // import Foundation import Nimble import Quick class TriggersLoaderTester : QuickSpec { override func spec() { let fileSystem = StubFileSystem() let context = GameContext() let loader = TriggersLoader(context: context, fileSystem: fileSystem) describe("triggers") { beforeEach { context.triggers.removeAll() } it("loads trigger") { fileSystem.fileContents = "#trigger {^hi} {say hello}" loader.load() expect(context.triggers.count()).to(equal(1)) let trigger = context.triggers.objectAtIndex(0) as! Trigger expect(trigger.trigger).to(equal("^hi")) expect(trigger.action).to(equal("say hello")) expect(trigger.actionClass).to(equal("")) } it("loads trigger with class") { fileSystem.fileContents = "#trigger {^hi} {say hello} {people}" loader.load() expect(context.triggers.count()).to(equal(1)) let trigger = context.triggers.objectAtIndex(0) as! Trigger expect(trigger.trigger).to(equal("^hi")) expect(trigger.action).to(equal("say hello")) expect(trigger.actionClass).to(equal("people")) } it("loads multiple triggers") { fileSystem.fileContents = "#trigger {^hi} {say hello}\n#trigger {^something} {another}" loader.load() expect(context.triggers.count()).to(equal(2)) var trigger = context.triggers.objectAtIndex(0) as! Trigger expect(trigger.trigger).to(equal("^hi")) expect(trigger.action).to(equal("say hello")) trigger = context.triggers.objectAtIndex(1) as! Trigger expect(trigger.trigger).to(equal("^something")) expect(trigger.action).to(equal("another")) } it("saves trigger") { let trigger = Trigger("^hi", "say hello", "people") context.triggers.addObject(trigger) loader.save() expect(fileSystem.fileContents).to(equal("#trigger {^hi} {say hello} {people}\n")) } it("saves trigger without class") { let trigger = Trigger("^hi", "say hello", "") context.triggers.addObject(trigger) loader.save() expect(fileSystem.fileContents).to(equal("#trigger {^hi} {say hello}\n")) } it("saves multiple triggers") { var trigger = Trigger("^hi", "say hello", "people") context.triggers.addObject(trigger) trigger = Trigger("^oh", "say I heard ...", "") context.triggers.addObject(trigger) loader.save() expect(fileSystem.fileContents).to(equal("#trigger {^hi} {say hello} {people}\n#trigger {^oh} {say I heard ...}\n")) } } } }
mit
694146e9d6d6a282fec8943958927e62
35.469388
132
0.483067
5.082504
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Toolbox/Gacha/Controller/GachaCardTableViewController.swift
1
3541
// // GachaCardTableViewController.swift // DereGuide // // Created by zzk on 2016/9/16. // Copyright © 2016年 zzk. All rights reserved. // import UIKit class GachaCardTableViewController: BaseCardTableViewController { var _filter: CGSSCardFilter = CGSSSorterFilterManager.DefaultFilter.gacha var _sorter: CGSSSorter = CGSSSorterFilterManager.DefaultSorter.gacha override var filter: CGSSCardFilter { get { return _filter } set { _filter = newValue } } override var sorter: CGSSSorter { get { return _sorter } set { _sorter = newValue } } override var filterVC: CardFilterSortController { set { _filterVC = newValue as! GachaCardFilterSortController } get { return _filterVC } } lazy var _filterVC: GachaCardFilterSortController = { let vc = GachaCardFilterSortController() vc.filter = self.filter vc.sorter = self.sorter vc.delegate = self return vc }() override func viewDidLoad() { super.viewDidLoad() let leftItem = UIBarButtonItem.init(image: UIImage.init(named: "765-arrow-left-toolbar"), style: .plain, target: self, action: #selector(backAction)) leftItem.width = 44 navigationItem.leftBarButtonItem = leftItem self.tableView.register(GachaCardTableViewCell.self, forCellReuseIdentifier: GachaCardTableViewCell.description()) } @objc func backAction() { navigationController?.popViewController(animated: true) } var defaultCardList : [CGSSCard]! var rewardTable: [Int: Reward]! func setup(with pool: CGSSGacha) { defaultCardList = pool.cardList.map { $0.odds = pool.rewardTable[$0.id!]?.relativeOdds ?? 0 return $0 } rewardTable = pool.rewardTable } // 根据设定的筛选和排序方法重新展现数据 override func updateUI() { filter.searchText = searchBar.text ?? "" self.cardList = filter.filter(defaultCardList) sorter.sortList(&self.cardList) tableView.reloadData() // 滑至tableView的顶部 暂时不需要 // tableView.scrollToRowAtIndexPath(IndexPath.init(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { searchBar.resignFirstResponder() let cardDetailVC = CardDetailViewController() cardDetailVC.card = cardList[indexPath.row] cardDetailVC.hidesBottomBarWhenPushed = true navigationController?.pushViewController(cardDetailVC, animated: true) } override func doneAndReturn(filter: CGSSCardFilter, sorter: CGSSSorter) { self.filter = filter self.sorter = sorter updateUI() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: GachaCardTableViewCell.description(), for: indexPath) as! GachaCardTableViewCell let row = indexPath.row let card = cardList[row] if let odds = rewardTable[card.id]?.relativeOdds { cell.setupWith(card, odds) } else { cell.setup(with: card) } return cell } }
mit
69c5e79cc09e4c5b8d723b2f88d6b640
30.369369
157
0.633831
4.776406
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Band Reject Butterworth Filter.xcplaygroundpage/Contents.swift
2
1499
//: ## Band Reject Butterworth Filter import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var filter = AKBandRejectButterworthFilter(player) filter.centerFrequency = 5000 // Hz filter.bandwidth = 600 // Cents AudioKit.output = filter AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Band Reject Butterworth Filter") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: filter)) addSubview(AKPropertySlider( property: "Center Frequency", format: "%0.1f Hz", value: filter.centerFrequency, minimum: 20, maximum: 22050, color: AKColor.greenColor() ) { sliderValue in filter.centerFrequency = sliderValue }) addSubview(AKPropertySlider( property: "Bandwidth", format: "%0.1f Hz", value: filter.bandwidth, minimum: 100, maximum: 12000, color: AKColor.redColor() ) { sliderValue in filter.bandwidth = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
ffd9120d41fdf8159d8f77e0e2d1ee97
27.283019
71
0.649099
5.081356
false
false
false
false
NextLevel/NextLevel
Sources/NextLevelClip.swift
1
8547
// // NextLevelClip.swift // NextLevel (http://github.com/NextLevel) // // Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.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 import Foundation import AVFoundation // NextLevelClip dictionary representation keys public let NextLevelClipFilenameKey = "NextLevelClipFilenameKey" public let NextLevelClipInfoDictKey = "NextLevelClipInfoDictKey" /// NextLevelClip, an object for managing a single media clip public class NextLevelClip { /// Unique identifier for a clip public var uuid: UUID { get { self._uuid } } /// URL of the clip public var url: URL? { didSet { self._asset = nil } } /// True, if the clip's file exists public var fileExists: Bool { get { if let url = self.url { return FileManager.default.fileExists(atPath: url.path) } return false } } /// `AVAsset` of the clip public var asset: AVAsset? { get { if let url = self.url { if self._asset == nil { self._asset = AVAsset(url: url) } } return self._asset } } /// Duration of the clip, otherwise invalid. public var duration: CMTime { get { self.asset?.duration ?? CMTime.zero } } /// Set to true if the clip's audio should be muted in the merged file public var isMutedOnMerge = false /// If it doesn't already exist, generates a thumbnail image of the clip. public var thumbnailImage: UIImage? { get { guard self._thumbnailImage == nil else { return self._thumbnailImage } if let asset = self.asset { let imageGenerator: AVAssetImageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true do { let cgimage: CGImage = try imageGenerator.copyCGImage(at: CMTime.zero, actualTime: nil) let uiimage: UIImage = UIImage(cgImage: cgimage) self._thumbnailImage = uiimage } catch { print("NextLevel, unable to generate lastFrameImage for \(String(describing: self.url?.absoluteString)))") self._thumbnailImage = nil } } return self._thumbnailImage } } /// If it doesn't already exist, generates an image for the last frame of the clip. public var lastFrameImage: UIImage? { get { guard self._lastFrameImage == nil, let asset = self.asset else { return self._lastFrameImage } let imageGenerator: AVAssetImageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true do { let cgimage: CGImage = try imageGenerator.copyCGImage(at: self.duration, actualTime: nil) let uiimage: UIImage = UIImage(cgImage: cgimage) self._lastFrameImage = uiimage } catch { print("NextLevel, unable to generate lastFrameImage for \(String(describing: self.url?.absoluteString))") self._lastFrameImage = nil } return self._lastFrameImage } } /// Frame rate at which the asset was recorded. public var frameRate: Float { get { if let tracks = self.asset?.tracks(withMediaType: AVMediaType.video), tracks.isEmpty == false { if let videoTrack = tracks.first { return videoTrack.nominalFrameRate } } return 0 } } /// Dictionary containing metadata about the clip. public var infoDict: [String: Any]? { get { self._infoDict } } /// Dictionary containing data for re-initialization of the clip. public var representationDict: [String: Any]? { get { if let infoDict = self.infoDict, let url = self.url { return [NextLevelClipFilenameKey: url.lastPathComponent, NextLevelClipInfoDictKey: infoDict] } else if let url = self.url { return [NextLevelClipFilenameKey: url.lastPathComponent] } else { return nil } } } // MARK: - class functions /// Class method initializer for a clip URL /// /// - Parameters: /// - filename: Filename for the media asset /// - directoryPath: Directory path for the media asset /// - Returns: Returns a URL for the designated clip, otherwise nil public class func clipURL(withFilename filename: String, directoryPath: String) -> URL? { var clipURL = URL(fileURLWithPath: directoryPath) clipURL.appendPathComponent(filename) return clipURL } /// Class method initializer for a NextLevelClip /// /// - Parameters: /// - url: URL of the media asset /// - infoDict: Dictionary containing metadata about the clip /// - Returns: Returns a NextLevelClip public class func clip(withUrl url: URL?, infoDict: [String: Any]?) -> NextLevelClip { NextLevelClip(url: url, infoDict: infoDict) } // MARK: - private instance vars internal var _uuid: UUID = UUID() internal var _asset: AVAsset? internal var _infoDict: [String: Any]? internal var _thumbnailImage: UIImage? internal var _lastFrameImage: UIImage? // MARK: - object lifecycle /// Initialize a clip from a URL and dictionary. /// /// - Parameters: /// - url: URL and filename of the specified media asset /// - infoDict: Dictionary with NextLevelClip metadata information public convenience init(url: URL?, infoDict: [String: Any]?) { self.init() self.url = url self._infoDict = infoDict } /// Initialize a clip from a dictionary representation and directory name /// /// - Parameters: /// - directoryPath: Directory where the media asset is located /// - representationDict: Dictionary containing defining metadata about the clip public convenience init(directoryPath: String, representationDict: [String: Any]?) { if let clipDict = representationDict, let filename = clipDict[NextLevelClipFilenameKey] as? String, let url: URL = NextLevelClip.clipURL(withFilename: filename, directoryPath: directoryPath) { let infoDict = clipDict[NextLevelClipInfoDictKey] as? [String: Any] self.init(url: url, infoDict: infoDict) } else { self.init() } } deinit { self._asset = nil self._infoDict = nil self._thumbnailImage = nil self._lastFrameImage = nil } // MARK: - functions /// Removes the associated file representation on disk. public func removeFile() { do { if let url = self.url { try FileManager.default.removeItem(at: url) self.url = nil } } catch { print("NextLevel, error deleting a clip's file \(String(describing: self.url?.absoluteString))") } } }
mit
49d826262b12e1e0c3b32572ad842eef
33.188
126
0.603604
4.897994
false
false
false
false
cornerAnt/PilesSugar
PilesSugar/PilesSugar/Module/Me/MeMain/Model/MeItemModel.swift
1
1287
// // MeItemModel.swift // PilesSugar // // Created by SoloKM on 16/1/11. // Copyright © 2016年 SoloKM. All rights reserved. // import UIKit enum ItemType{ case Switch case Defult } class MeItemModel: NSObject { typealias itemTargetClosure = (indexPath: NSIndexPath) -> () typealias targetViewControllerClosure = () -> UIViewController var image: UIImage? var title: String? var subtitle: String? var type : ItemType = ItemType.Defult // cell对应的功能 var itemTarget : itemTargetClosure? // 跳转对应的控制器 var targetViewController : targetViewControllerClosure? convenience init(image: UIImage,title: String, subtitle: String) { self.init() self.image = image; self.title = title; self.subtitle = subtitle; } convenience init(image: UIImage?,title: String) { self.init() self.image = image; self.title = title; } func setTarget(targetClosure : itemTargetClosure){ self.itemTarget = targetClosure } func setTargetVc(targetVcClosure : targetViewControllerClosure){ self.targetViewController = targetVcClosure } }
apache-2.0
0b408564ea16ba927a76bd166df5a102
19.306452
70
0.612083
4.541516
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Controllers/Chat/ChatDataController.swift
1
6792
// // ChatDataController.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 09/12/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation enum ChatDataType { case daySeparator case message case loader case header } struct ChatData { var identifier = String.random(10) var type: ChatDataType = .message var timestamp: Date var indexPath: IndexPath! // This is only used for messages var message: Message? // Initializers init?(type: ChatDataType, timestamp: Date) { self.type = type self.timestamp = timestamp } } final class ChatDataController { var data: [ChatData] = [] var loadedAllMessages = false func clear() -> [IndexPath] { var indexPaths: [IndexPath] = [] for item in data { indexPaths.append(item.indexPath) } data = [] return indexPaths } func itemAt(_ indexPath: IndexPath) -> ChatData? { return data.filter { item in return item.indexPath?.row == indexPath.row && item.indexPath?.section == indexPath.section }.first } func indexPathOf(_ identifier: String) -> IndexPath? { return data.filter { item in return item.identifier == identifier }.flatMap { item in item.indexPath }.first } // swiftlint:disable function_body_length cyclomatic_complexity @discardableResult func insert(_ items: [ChatData]) -> ([IndexPath], [IndexPath]) { var indexPaths: [IndexPath] = [] var removedIndexPaths: [IndexPath] = [] var newItems: [ChatData] = [] var lastObj = data.last var identifiers: [String] = items.map { $0.identifier } func insertDaySeparator(from obj: ChatData) { guard let calendar = NSCalendar(calendarIdentifier: .gregorian) else { return } let date = obj.timestamp let components = calendar.components([.day, .month, .year], from: date) guard let newDate = calendar.date(from: components) else { return } guard let separator = ChatData(type: .daySeparator, timestamp: newDate) else { return } identifiers.append(separator.identifier) newItems.append(separator) } if loadedAllMessages { if data.filter({ $0.type == .header }).count == 0 { if let obj = ChatData(type: .header, timestamp: Date(timeIntervalSince1970: 0)) { newItems.append(obj) identifiers.append(obj.identifier) } } let messages = data.filter({ $0.type == .message }) let firstMessage = messages.sorted(by: { $0.timestamp < $1.timestamp }).first if let firstMessage = firstMessage { // Check if already contains some separator with this data var insert = true for obj in data.filter({ $0.type == .daySeparator }) where firstMessage.timestamp.day == obj.timestamp.day && firstMessage.timestamp.month == obj.timestamp.month && firstMessage.timestamp.year == obj.timestamp.year { insert = false } if insert { insertDaySeparator(from: firstMessage) } } } // Has loader? let loaders = data.filter({ $0.type == .loader }) if loadedAllMessages { for (idx, obj) in loaders.enumerated() { data.remove(at: idx) removedIndexPaths.append(obj.indexPath) } } else { if loaders.count == 0 { if let obj = ChatData(type: .loader, timestamp: Date(timeIntervalSince1970: 0)) { newItems.append(obj) identifiers.append(obj.identifier) } } } for newObj in items { if let lastObj = lastObj { if lastObj.type == .message && ( lastObj.timestamp.day != newObj.timestamp.day || lastObj.timestamp.month != newObj.timestamp.month || lastObj.timestamp.year != newObj.timestamp.year) { // Check if already contains some separator with this data var insert = true for obj in data.filter({ $0.type == .daySeparator }) where lastObj.timestamp.day == obj.timestamp.day && lastObj.timestamp.month == obj.timestamp.month && lastObj.timestamp.year == obj.timestamp.year { insert = false } if insert { insertDaySeparator(from: lastObj) } } } newItems.append(newObj) lastObj = newObj } data.append(contentsOf: newItems) data.sort(by: { $0.timestamp < $1.timestamp }) var normalizeds: [ChatData] = [] for (idx, item) in data.enumerated() { var customItem = item let indexPath = IndexPath(item: idx, section: 0) customItem.indexPath = indexPath normalizeds.append(customItem) for identifier in identifiers where identifier == item.identifier { indexPaths.append(indexPath) break } } data = normalizeds return (indexPaths, removedIndexPaths) } func update(_ message: Message) -> Int { for (idx, obj) in data.enumerated() where obj.message?.identifier == message.identifier { data[idx].message = message return obj.indexPath.row } return -1 } func shouldShowDate(atIndexPath indexPath: IndexPath) -> Bool { // if indexPath is last of the data or overflowed guard indexPath.row + 1 < data.count else { return true } let recentOne = data[indexPath.row + 1] let current = data[indexPath.row] // if two messages are sent by different user if current.message?.user != recentOne.message?.user { return true } // if indexPath is 10 minutes earlier than a recent one if abs(current.timestamp.seconds(to: recentOne.timestamp)) > (10 * 60) { return true } return false } func oldestMessage() -> Message? { for obj in data where obj.type == .message { return obj.message } return nil } }
mit
50525eb8928b2ead9cb9a6a166329a4d
31.492823
103
0.538801
4.864613
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Localization/Sources/Localization/LocalizationConstants+AnnouncementCards.swift
1
12115
// Copyright © Blockchain Luxembourg S.A. All rights reserved. // swiftlint:disable all import Foundation extension LocalizationConstants { public enum AnnouncementCards { // MARK: - Persistent public enum Welcome { public static let title = NSLocalizedString( "Welcome to Blockchain.com!", comment: "Welcome announcement card title" ) public static let description = NSLocalizedString( "Here are a few tips to get your account up and running, we’ll also help you make sure everything is secure.", comment: "Welcome announcement card description" ) public static let ctaButton = NSLocalizedString( "Tell Me More", comment: "Welcome announcement card CTA button title" ) public static let skipButton = NSLocalizedString( "Maybe Later", comment: "Welcome announcement card skip button title" ) } public enum VerifyEmail { public static let title = NSLocalizedString( "Verify Your Email Address", comment: "Verify email announcement card title" ) public static let description = NSLocalizedString( "You need to confirm your email address so that we can keep you informed about your wallet.", comment: "Verify email announcement card description" ) public static let ctaButton = NSLocalizedString( "Verify Email Address", comment: "Verify email announcement card CTA button title" ) } public enum BackupFunds { public static let title = NSLocalizedString( "Wallet Recovery Phrase", comment: "Backup funds announcement card title" ) public static let description = NSLocalizedString( "You control your crypto. Write down your recovery phrase to restore all your funds in case you lose your password.", comment: "Backup funds announcement card description" ) public static let ctaButton = NSLocalizedString( "Backup Phrase", comment: "Backup funds announcement card CTA button title" ) } public enum SimpleBuyFinishSignup { public static let title = NSLocalizedString( "Finish Signing Up. Buy Crypto.", comment: "Simple Buy KYC Incomplete announcement card title" ) public static let description = NSLocalizedString( "You’re almost done signing up for your Blockchain.com Wallet. Once you finish and get approved, start buying crypto.", comment: "Simple Buy KYC Incomplete announcement card description" ) public static let ctaButton = NSLocalizedString( "Continue", comment: "Simple Buy KYC Incomplete announcement card CTA button title" ) } // MARK: - One time public enum ViewNFT { public static let title = NSLocalizedString( "View NFTs In Your Wallet", comment: "View NFTs In Your Wallet" ) public static let description = NSLocalizedString( "Soon you will be able to view your NFTs right from the comfort of your wallet.", comment: "Soon you will be able to view your NFTs right from the comfort of your wallet." ) public static let buttonTitle = NSLocalizedString( "Join Waitlist", comment: "Join Waitlist" ) } public enum IdentityVerification { public static let title = NSLocalizedString( "Finish Verifying Your Account", comment: "Finish identity verification announcement card title" ) public static let description = NSLocalizedString( "Pick up where you left off and complete your identity verification.", comment: "Finish identity verification announcement card description" ) public static let ctaButton = NSLocalizedString( "Continue Verification", comment: "Finish identity verification announcement card CTA button title" ) } public enum NewAsset { public static let title = NSLocalizedString( "%@ (%@) is Now Trading", comment: "New asset announcement card title." ) public static let description = NSLocalizedString( "Buy, sell, swap, send, receive and store %@ in your Blockchain.com Wallet.", comment: "New asset announcement card description." ) public static let ctaButton = NSLocalizedString( "Buy %@", comment: "New asset card CTA button title." ) } public enum AssetRename { public static let title = NSLocalizedString( "%@ has a new name", comment: "Asset Rename announcement card title." ) public static let description = NSLocalizedString( "Heads up: %@ has renamed to %@. All balances are unaffected.", comment: "Asset Rename announcement card description." ) public static let ctaButton = NSLocalizedString( "Trade %@", comment: "Asset Rename card CTA button title." ) } public enum MajorProductBlocked { public static let title = NSLocalizedString( "Trading Restricted", comment: "EU_5_SANCTION card title." ) public static let ctaButtonLearnMore = NSLocalizedString( "Learn More", comment: "EU_5_SANCTION card CTA button title." ) public static let defaultMessage = NSLocalizedString( "Default message for inelibility", comment: "This operation cannot be performed at this time. Please try again later." ) } public enum WalletConnect { public static let title = NSLocalizedString( "WalletConnect is Now Available!", comment: "WalletConnect announcement card title" ) public static let description = NSLocalizedString( "Securely connect your wallet to any web 3.0 application. ", comment: "WalletConnect announcement card description" ) public static let ctaButton = NSLocalizedString( "Learn more", comment: "WalletConnect announcement card CTA button title" ) } public enum ApplePay { public static let title = NSLocalizedString( "New: Apple Pay", comment: "Apple Pay announcement card title" ) public static let description = NSLocalizedString( "Enjoy frictionless crypto purchases with Apple Pay.", comment: "Apple Pay announcement card description" ) public static let ctaButton = NSLocalizedString( "Buy Crypto", comment: "Apple Pay announcement card CTA button title" ) } // MARK: - Periodic public enum BuyBitcoin { public static let title = NSLocalizedString( "Buy Crypto", comment: "Buy BTC announcement card title" ) public static let description = NSLocalizedString( "We can help you buy in just a few simple steps.", comment: "Buy BTC announcement card description" ) public static let ctaButton = NSLocalizedString( "Buy Crypto Now", comment: "Buy BTC announcement card CTA button title" ) } public enum TransferInCrypto { public static let title = NSLocalizedString( "Transfer In Crypto", comment: "Transfer crypto announcement card title" ) public static let description = NSLocalizedString( "Deposit crypto in your wallet to get started. It's the best way to store your crypto while keeping control of your keys.", comment: "Transfer crypto announcement card description" ) public static let ctaButton = NSLocalizedString( "Get Started", comment: "Transfer crypto announcement card CTA button title" ) } public enum ResubmitDocuments { public static let title = NSLocalizedString( "Documents Needed", comment: "The title of the action on the announcement card for when a user needs to submit documents to verify their identity." ) public static let description = NSLocalizedString( "We had some issues with the documents you’ve supplied. Please try uploading the documents again to continue with your verification.", comment: "The description on the announcement card for when a user needs to submit documents to verify their identity." ) public static let ctaButton = NSLocalizedString( "Upload Documents", comment: "The title of the action on the announcement card for when a user needs to submit documents to verify their identity." ) } public enum ResubmitDocumentsAfterRecovery { public static let title = NSLocalizedString( "Documents Needed", comment: "The title of the action on the announcement card for when a user needs to submit documents to re-verify their identity." ) public static let description = NSLocalizedString( "Please re-verify your identity to complete account recovery. Some features may not be available until you do.", comment: "The description on the announcement card for when a user needs to submit documents to re-verify their identity." ) public static let ctaButton = NSLocalizedString( "Re-verify Now", comment: "The title of the action on the announcement card for when a user needs to submit documents to re-verify their identity." ) } public enum TwoFA { public static let title = NSLocalizedString( "Enable 2-Step Verification", comment: "2FA announcement card title" ) public static let description = NSLocalizedString( "Protect your wallet from unauthorized access by enabling 2-Step Verification.", comment: "2FA announcement card description" ) public static let ctaButton = NSLocalizedString( "Enable 2-Step Verification", comment: "2FA announcement card CTA button title" ) } public enum ClaimFreeDomain { public static let title = NSLocalizedString( "Claim Your Free Domain!", comment: "Claim free domain annoucement card title" ) public static let description = NSLocalizedString( "Get a free .blockchain domain through Unstoppable Domains. Use your domain to receive crypto and much more.", comment: "Claim free domain annoucement card description" ) public static let button = NSLocalizedString( "Claim Domain", comment: "Claim free domain annoucement card button" ) } } }
lgpl-3.0
a5dca347acb59f27b00c89d3f83cfd6f
42.553957
150
0.576396
6.130633
false
false
false
false
Lweek/Formulary
Formulary/Forms/FormViewController.swift
1
5492
// // FormViewController.swift // Formulary // // Created by Fabian Canas on 1/16/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import UIKit public class FormViewController: UIViewController, UITableViewDelegate { var dataSource: FormDataSource? public var form :Form { didSet { form.editingEnabled = editingEnabled dataSource = FormDataSource(form: form, tableView: tableView) tableView?.dataSource = dataSource } } public var tableView: UITableView! public var tableViewStyle: UITableViewStyle = .Grouped public var editingEnabled :Bool = true { didSet { self.form.editingEnabled = editingEnabled if editing == false { self.tableView?.firstResponder()?.resignFirstResponder() } self.tableView?.reloadData() } } public init(form: Form) { self.form = form super.init(nibName: nil, bundle: nil) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { form = Form(sections: []) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init(coder aDecoder: NSCoder) { form = Form(sections: []) super.init(coder: aDecoder) } func link(form: Form, table: UITableView) { dataSource = FormDataSource(form: form, tableView: tableView) tableView.dataSource = dataSource } override public func viewDidLoad() { super.viewDidLoad() if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight } if tableView.superview == nil { view.addSubview(tableView) } tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60 tableView.rowHeight = 60 tableView.delegate = self dataSource = FormDataSource(form: form, tableView: tableView) tableView.dataSource = dataSource } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { if let cell = tableView.firstResponder()?.containingCell(), let selectedIndexPath = tableView.indexPathForCell(cell) { let keyboardInfo = KeyboardNotification(notification) var keyboardEndFrame = keyboardInfo.screenFrameEnd keyboardEndFrame = view.window!.convertRect(keyboardEndFrame, toView: view) var contentInset = tableView.contentInset var scrollIndicatorInsets = tableView.scrollIndicatorInsets contentInset.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y scrollIndicatorInsets.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y UIView.beginAnimations("keyboardAnimation", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .EaseInOut) UIView.setAnimationDuration(keyboardInfo.animationDuration) tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets tableView.scrollToRowAtIndexPath(selectedIndexPath, atScrollPosition: .None, animated: true) UIView.commitAnimations() } } func keyboardWillHide(notification: NSNotification) { let keyboardInfo = KeyboardNotification(notification) var contentInset = tableView.contentInset var scrollIndicatorInsets = tableView.scrollIndicatorInsets contentInset.bottom = 0 scrollIndicatorInsets.bottom = 0 UIView.beginAnimations("keyboardAnimation", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .EaseInOut) UIView.setAnimationDuration(keyboardInfo.animationDuration) tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { tableView.firstResponder()?.resignFirstResponder() } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? FormTableViewCell { cell.formRow?.action?(nil) cell.action?(nil) } } }
mit
2730b15e24f2cc8856795583a4738b85
37.950355
154
0.652768
6.129464
false
false
false
false
wxxsw/GSPhotos
GSPhotos/GSPhotoLibrary.swift
1
4193
// // GSPhotoLibrary.swift // GSPhotosExample // // Created by Gesen on 15/10/20. // Copyright © 2015年 Gesen. All rights reserved. // import UIKit public enum GSPhotoAuthorizationStatus: Int { case NotDetermined // 用户还没决定是否授权应用访问照片. case Restricted // 用户无法改变应用状态,可能由于主动限制.(例如家长控制) case Denied // 用户明确拒绝应用访问照片数据. case Authorized // 用户已经授权应用访问照片数据. } public typealias AssetsCompletionHandler = ([GSAsset]?, NSError?) -> Void public typealias AlbumsCompletionHandler = ([GSAlbum]?, NSError?) -> Void public class GSPhotoLibrary { // MARK: Properties static let sharedInstance = GSPhotoLibrary() // MARK: Functions class var canUsePhotos: Bool { get { let status = authorizationStatus() return status == .Authorized || status == .NotDetermined } } /** 获取当前访问权限 - returns: 权限状态 */ class func authorizationStatus() -> GSPhotoAuthorizationStatus { if #available(iOS 8.0, *) { return PHPhotoLibraryGSHelper.authorizationStatus() } else { return ALAssetsLibraryGSHelper.authorizationStatus() } } /** 获取全部资源集合 - parameter mediaType: 资源类型 - parameter handler: 完成回调 */ public func fetchAllAssets(mediaType: GSAssetMediaType, handler: AssetsCompletionHandler) { gs_dispatch_async { if #available(iOS 8.0, *) { self.phLibraryHelper.fetchAllAssets(mediaType, handler: self.safe_assets_handler(handler)) } else { self.alLibraryHelper.fetchAllAssets(mediaType, handler: self.safe_assets_handler(handler)) } } } /** 获取指定相册中的资源 - parameter album: 相册实例 - parameter mediaType: 资源类型 - parameter handler: 完成回调 */ public func fetchAssetsInAlbum(album: GSAlbum, mediaType: GSAssetMediaType, handler: AssetsCompletionHandler) { gs_dispatch_async { if #available(iOS 8.0, *) { self.phLibraryHelper.fetchAssetsInAlbum(album, mediaType: mediaType, handler: self.safe_assets_handler(handler)) } else { self.alLibraryHelper.fetchAssetsInAlbum(album, mediaType: mediaType, handler: self.safe_assets_handler(handler)) } } } /** 获取相册集合 - parameter handler: 完成回调 */ public func fetchAlbums(handler: AlbumsCompletionHandler) { gs_dispatch_async { if #available(iOS 8.0, *) { self.phLibraryHelper.fetchAlbums(self.safe_albums_handler(handler)) } else { self.alLibraryHelper.fetchAlbums(self.safe_albums_handler(handler)) } } } // MARK: - Private @available(iOS 8.0, *) private lazy var phLibraryHelper: PHPhotoLibraryGSHelper = { return PHPhotoLibraryGSHelper() }() private lazy var alLibraryHelper: ALAssetsLibraryGSHelper = { return ALAssetsLibraryGSHelper() }() private func safe_assets_handler(handler: AssetsCompletionHandler) -> AssetsCompletionHandler { return { (assets, error) in gs_dispatch_main_async_safe { handler(assets, error) } } } private func safe_albums_handler(handler: AlbumsCompletionHandler) -> AlbumsCompletionHandler { return { (albums, error) in gs_dispatch_main_async_safe { handler(albums, error) } } } } func gs_dispatch_async(closure: () -> Void) { dispatch_async(dispatch_get_global_queue(0, 0)) { closure() } } func gs_dispatch_main_async_safe(closure: () -> Void) { if NSThread.isMainThread() { closure() } else { dispatch_async(dispatch_get_main_queue()) { closure() } } }
mit
eb7a3cca9f8fc3f8414ea963f5e812a9
27.057143
128
0.595214
4.364444
false
false
false
false
CocoaFlow/WebSocketTransport
WebSocketTransportTests/WebSocketTransportSpec.swift
1
7078
// // WebSocketTransportSpec.swift // WebSocketTransportSpec // // Created by Paul Young on 28/08/2014. // Copyright (c) 2014 CocoaFlow. All rights reserved. // import Quick import Nimble import WebSocketTransport import JSONLib class WebSocketTransportSpec: QuickSpec { override func spec() { describe("WebSocket transport") { describe("receiving a message") { context("without a payload") { it("should receive a message in the message receiver") { let transportChannel = "channel" let transportTopic = "topic" let transportPayload = "null" let transportData = "{\"protocol\":\"\(transportChannel)\",\"command\":\"\(transportTopic)\",\"payload\":\(transportPayload)}" var receiverChannel: String! var receiverTopic: String! var receiverPayload: JSON? let fakeMessageReceiver = FakeMessageReceiver() { (channel, topic, payload) in receiverChannel = channel receiverTopic = topic receiverPayload = payload } let port: Int32 = 3569 let protocolName = "CocoaFlow" let transport = WebSocketTransport(port, protocolName, fakeMessageReceiver) let fakeWebSocketClient = FakeWebSocketClient(port, protocolName) { webSocket in webSocket.send(transportData) } expect(receiverChannel).toEventually(equal(transportChannel)) expect(receiverTopic).toEventually(equal(transportTopic)) expect(receiverPayload).toEventually(beNil()) } } context("with a payload") { it("should receive a message in the message receiver") { let transportChannel = "channel" let transportTopic = "topic" let transportPayload = "{\"key\":\"value\"}" let transportData = "{\"protocol\":\"\(transportChannel)\",\"command\":\"\(transportTopic)\",\"payload\":\(transportPayload)}" var receiverChannel: String! var receiverTopic: String! var receiverPayload: JSON? let fakeMessageReceiver = FakeMessageReceiver() { (channel, topic, payload) in receiverChannel = channel receiverTopic = topic receiverPayload = payload } let port: Int32 = 3569 let protocolName = "CocoaFlow" let transport = WebSocketTransport(port, protocolName, fakeMessageReceiver) let fakeWebSocketClient = FakeWebSocketClient(port, protocolName) { webSocket in webSocket.send(transportData) } expect(receiverChannel).toEventually(equal(transportChannel)) expect(receiverTopic).toEventually(equal(transportTopic)) expect(receiverPayload).toEventually(equal(JSON.parse(transportPayload).value)) } } } describe("sent a message") { context("without a payload") { it("should send a message") { let receiverChannel = "channel" let receiverTopic = "topic" let receiverPayload = "null" let expectedMessage = "{\"protocol\":\"\(receiverChannel)\",\"command\":\"\(receiverTopic)\",\"payload\":\(receiverPayload)}" var jsonExpectedMessage = JSON.parse(expectedMessage).value var jsonTransportMessage: JSON! let fakeMessageReceiver = FakeMessageReceiver() let port: Int32 = 3569 let protocolName = "CocoaFlow" let transport = WebSocketTransport(port, protocolName, fakeMessageReceiver) let fakeWebSocketClient = FakeWebSocketClient(port, protocolName, { webSocket in fakeMessageReceiver.messageSender = transport fakeMessageReceiver.send(receiverChannel, receiverTopic, nil) }, { message in jsonTransportMessage = JSON.parse(message).value }) expect(jsonTransportMessage).toEventually(equal(jsonExpectedMessage)) } } context("with a payload") { it("should send a message") { let receiverChannel = "channel" let receiverTopic = "topic" let receiverPayload = "{\"key\":\"value\"}" let expectedMessage = "{\"protocol\":\"\(receiverChannel)\",\"command\":\"\(receiverTopic)\",\"payload\":\(receiverPayload)}" var jsonExpectedMessage = JSON.parse(expectedMessage).value var jsonTransportMessage: JSON! let fakeMessageReceiver = FakeMessageReceiver() let port: Int32 = 3569 let protocolName = "CocoaFlow" let transport = WebSocketTransport(port, protocolName, fakeMessageReceiver) let fakeWebSocketClient = FakeWebSocketClient(port, protocolName, { webSocket in fakeMessageReceiver.messageSender = transport fakeMessageReceiver.send(receiverChannel, receiverTopic, JSON.parse(receiverPayload).value!) }, { message in jsonTransportMessage = JSON.parse(message).value }) expect(jsonTransportMessage).toEventually(equal(jsonExpectedMessage)) } } } } } }
apache-2.0
9d6855305b755dd8d7fc7efceb992218
47.14966
150
0.458887
7.281893
false
false
false
false
ZulwiyozaPutra/Alien-Adventure-Tutorial
Alien Adventure/AlienAdventure1.swift
4
9353
// // AlienAdventure1.swift // Alien Adventure // // Created by Jarrod Parkes on 10/5/15. // Copyright © 2015 Udacity. All rights reserved. // // MARK: - RequestTester (Alien Adventure 1 Tests) extension UDRequestTester { // MARK: ReverseLongString func testReverseLongestName() -> Bool { // check 1 if delegate.handleReverseLongestName([UDItem]()) != "" { print("ReverseLongestName FAILED: If the inventory is empty, then the method should return \"\".") return false } // check 2 if delegate.handleReverseLongestName(allItems()) != "akoozaBresaL" { print("ReverseLongestName FAILED: The reverse longest string was not returned.") return false } // check 3 if delegate.handleReverseLongestName(delegate.inventory) != "nonnaCresaL" { print("ReverseLongestName FAILED: The reverse longest string was not returned.") return false } return true } // MARK: MatchMoonRocks func testMatchMoonRocks() -> Bool { // check 1 let itemsFromCheck1 = delegate.handleMatchMoonRocks([UDItem]()) if itemsFromCheck1.count != 0 { print("MatchMoonRocks FAILED: If the inventory is empty, then no MoonRocks should be returned.") return false } // check 2 let itemsFromCheck2 = delegate.handleMatchMoonRocks(allItems()) var moonRocksCount2 = 0 for item in itemsFromCheck2 { if item == UDItemIndex.items["MoonRock"]! { moonRocksCount2 += 1 } } if moonRocksCount2 != 1 { print("MatchMoonRocks FAILED: An incorrect number of MoonRocks was returned.") return false } // check 3 let itemsFromCheck3 = delegate.handleMatchMoonRocks(delegate.inventory) var moonRocksCount3 = 0 for item in itemsFromCheck3 { if item == UDItemIndex.items["MoonRock"]! { moonRocksCount3 += 1 } } if moonRocksCount3 != 2 || itemsFromCheck3.count != 2 { print("MatchMoonRocks FAILED: An incorrect number of MoonRocks was returned.") return false } return true } // MARK: InscriptionEternalStar func testInscriptionEternalStar() -> Bool { // check 1 if delegate.handleInscriptionEternalStar([UDItem]()) != nil { print("InscriptionEternalStar FAILED: If the inventory is empty, then nil should be returned.") return false } // check 2 let item = delegate.handleInscriptionEternalStar(delegate.inventory) if item != UDItemIndex.items["GlowSphere"]! { print("InscriptionEternalStar FAILED: The correct item was not returned.") return false } return true } // MARK: LeastValuableItem func testLeastValuableItem() -> Bool { // check 1 if delegate.handleLeastValuableItem([UDItem]()) != nil { print("LeastValuableItem FAILED: If the inventory is empty, then nil should be returned.") return false } // check 2 let result2 = delegate.handleLeastValuableItem(allItems()) if result2 != UDItemIndex.items["Dust"]! { print("LeastValuableItem FAILED: The least valuable item was not returned.") return false } // check 3 let result3 = delegate.handleLeastValuableItem(delegate.inventory) if result3 != UDItemIndex.items["MoonRubble"]! { print("LeastValuableItem FAILED: The least valuable item was not returned.") return false } return true } // MARK: ShuffleStrings func testShuffleStrings() -> Bool { // check 1 if !delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "acbd") { print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"acbd\") is valid, but false was returned.") return false } // check 2 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "badc") { print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"badc\") is invalid, but true was returned.") return false } // check 3 if !delegate.handleShuffleStrings("", s2: "", shuffle: "") { print("ShuffleStrings FAILED: The shuffle for the input (\"\", \"\", \"\") is valid, but false was returned.") return false } // check 4 if delegate.handleShuffleStrings("", s2: "", shuffle: "sdf") { print("ShuffleStrings FAILED: The shuffle for the input (\"\", \"\", \"sdf\") is invalid, but true was returned.") return false } // check 5 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "abef") { print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"abef\") is invalid, but true was returned.") return false } // check 6 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "abdc") { print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"abdc\") is invalid, but true was returned.") return false } return true } } // MARK: - RequestTester (Alien Adventure 1 Process Requests) extension UDRequestTester { // MARK: ReverseLongString func processReverseLongestName(_ failed: Bool) -> String { if !failed { let reverseLongestName = delegate.handleReverseLongestName(delegate.inventory) return "Hero: \"How about \(reverseLongestName)?\"" } else { return "Hero: \"Uhh... Udacity?\"" } } // MARK: MatchMoonRocks func processMatchMoonRocks(_ failed: Bool) -> String { if(!failed) { let moonRocks = delegate.handleMatchMoonRocks(delegate.inventory) delegate.inventory = delegate.inventory.filter({$0.name != "MoonRock"}) return "Hero: [Hands over \(moonRocks.count) MoonRocks]" } else { return "Hero: [Hands over some items (they might be MoonRocks...)]" } } // MARK: InscriptionEternalStar func processInscriptionEternalStar(_ failed: Bool) -> String { var processingString = "Hero: [Hands over " if let eternalStarItem = delegate.handleInscriptionEternalStar(delegate.inventory) { processingString += "the \(eternalStarItem.name)]" if(!failed) { delegate.inventory = delegate.inventory.filter({$0.inscription == nil || $0 != eternalStarItem}) } } else { processingString += "NOTHING!]" } return processingString } // MARK: LeastValuableItem func processLeastValuableItem(_ failed: Bool) -> String { var processingString = "Hero: [Hands over " if let leastValuableItem = delegate.handleLeastValuableItem(delegate.inventory) { processingString += "the \(leastValuableItem.name)]" if(!failed) { for (idx, item) in delegate.inventory.enumerated() { if item == leastValuableItem { delegate.inventory.remove(at: idx) break } } } } else { processingString += "NOTHING!]" } return processingString } // MARK: ShuffleStrings func processShuffleStrings(_ failed: Bool) -> String { // check 1 if !delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "acbd") { return "Hero: \"So is (\"ab\", \"cd\", \"acbd\") a valid shuffle? Umm... no?\"" } // check 2 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "badc") { return "Hero: \"So is (\"ab\", \"cd\", \"badc\") a valid shuffle? Umm... yes?\"" } // check 3 if !delegate.handleShuffleStrings("", s2: "", shuffle: "") { return "Hero: \"So is (\"\", \"\", \"\") a valid shuffle? Umm... no?\"" } // check 4 if delegate.handleShuffleStrings("", s2: "", shuffle: "sdf") { return "Hero: \"So is (\"\", \"\", \"sdf\") a valid shuffle? Umm... yes?\"" } // check 5 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "abef") { return "Hero: \"So is (\"ab\", \"cd\", \"abef\") a valid shuffle? Umm... yes?\"" } // check 6 if delegate.handleShuffleStrings("ab", s2: "cd", shuffle: "abdc") { return "Hero: \"So is (\"ab\", \"cd\", \"abdc\") a valid shuffle? Umm... yes?\"" } return "Hero: \"So is (\"ab\", \"cd\", \"badc\") a valid shuffle? No it isn't!\"" } }
mit
91ccd45ec538e4826abf6c45acab9101
33.131387
131
0.540847
4.602362
false
false
false
false
mrchenhao/VPNOn
VPNOn/LTVPNDownloader.swift
2
1227
// // LTVPNDownloader.swift // VPNOn // // Created by Lex Tang on 1/27/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit class LTVPNDownloader: NSObject { var queue: NSOperationQueue? func download(URL: NSURL, callback: (NSURLResponse!, NSData!, NSError!) -> Void) { let request = NSMutableURLRequest(URL: URL) var agent = "VPN On" if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as String? { agent = "\(agent) \(version)" } request.HTTPShouldHandleCookies = false request.HTTPShouldUsePipelining = true request.cachePolicy = NSURLRequestCachePolicy.ReloadRevalidatingCacheData request.addValue(agent, forHTTPHeaderField: "User-Agent") request.timeoutInterval = 20 if let q = queue { q.suspended = true queue = nil } queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: callback) } func cancel() { if let q = queue { q.suspended = true queue = nil } } }
mit
6cb5448b8ea10445b4e6358747cff865
27.534884
116
0.611247
4.908
false
false
false
false
kNeerajPro/PlayPauseAnimation
PlayPauseAnimation/PlayPauseAnimation/VIews/Layers/TriangleShapeLayer.swift
1
1666
// // TriangleShapeLayer.swift // SignatureAnimation // // Created by Neeraj Kumar on 22/02/15. // Copyright (c) 2015 Neeraj Kumar. All rights reserved. // import UIKit class TriangleShapeLayer: CAShapeLayer { override var bounds : CGRect { didSet { path = self.shapeForBounds(bounds).CGPath } } func shapeForBounds(rect: CGRect) -> UIBezierPath { // Triangle side length let length = rect.size.height let point1 = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)) let point2 = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)) let point3 = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect)) let trianglePath = UIBezierPath() trianglePath.moveToPoint(point1) trianglePath.addLineToPoint(point2) trianglePath.addLineToPoint(point3) trianglePath.closePath() return trianglePath } override func addAnimation(anim: CAAnimation!, forKey key: String!) { super.addAnimation(anim, forKey: key) if (anim.isKindOfClass(CABasicAnimation.self)) { let basicAnimation = anim as CABasicAnimation if (basicAnimation.keyPath == "bounds.size") { var pathAnimation = basicAnimation.mutableCopy() as CABasicAnimation pathAnimation.keyPath = "path" pathAnimation.fromValue = self.path pathAnimation.toValue = self.shapeForBounds(self.bounds).CGPath self.removeAnimationForKey("path") self.addAnimation(pathAnimation,forKey: "path") } } } }
mit
06ef0e2d37455ff47e49d22277220c50
32.32
83
0.631453
5.173913
false
false
false
false
IvoPaunov/selfie-apocalypse
Selfie apocalypse/Frameworks/DCKit/UIButtons/DCRoundedButton.swift
1
2023
// // DCRoundedButton.swift // DCKitSample // // Created by Andrey Gordeev on 5/10/15. // Copyright (c) 2015 Andrey Gordeev. All rights reserved. // import UIKit @IBDesignable public class DCRoundedButton: DCBorderedButton { /// cornerRadius doesn't work for this control. It's strictly set to frame.size.height*0.5 override public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { } } // MARK: - Initializers // IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out. // http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Life cycle public override func layoutSubviews() { super.layoutSubviews() setCornerRadius() } // MARK: - Build control override public func customInit() { super.customInit() addBorder() } override public func addBorder() { layer.borderColor = normalBorderColor.CGColor layer.borderWidth = 1.0 / UIScreen.mainScreen().scale setCornerRadius() clipsToBounds = true // http://stackoverflow.com/questions/4735623/uilabel-layer-cornerradius-negatively-impacting-performance layer.masksToBounds = true layer.rasterizationScale = UIScreen.mainScreen().scale layer.shouldRasterize = true } private func setCornerRadius() { layer.cornerRadius = frame.size.height*0.5 } // MARK: - Misc override public func updateColor() { super.updateColor() layer.borderColor = enabled ? (selected ? selectedBorderColor.CGColor : normalBorderColor.CGColor) : disabledBorderColor.CGColor } }
mit
e604a1f7fa347814469ecf7392174396
25.973333
136
0.631735
4.726636
false
false
false
false
ECP-CANDLE/Supervisor
workflows/common/ext/EQ-Py/EQPy.swift
1
1369
/* EMEWS EQPy.swift */ import location; pragma worktypedef resident_work; @dispatch=resident_work (void v) _void_py(string code, string expr="\"\"") "turbine" "0.1.0" [ "turbine::python 1 1 <<code>> <<expr>> "]; @dispatch=resident_work (string output) _string_py(string code, string expr) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 1 1 <<code>> <<expr>> ]" ]; string init_package_string = "import eqpy\neqpy.init('%s')"; (void v) EQPy_init_package(location loc, string packageName){ //printf("EQPy_init_package(%s) ...", packageName); string code = init_package_string % (packageName); //,packageName); //printf("Code is: \n%s", code); @location=loc _void_py(code) => v = propagate(); } EQPy_stop(location loc){ // do nothing } string get_string = "result = eqpy.output_q_get()"; (string result) EQPy_get(location loc){ //printf("EQPy_get called"); string code = get_string; //printf("Code is: \n%s", code); result = @location=loc _string_py(code, "result"); } string put_string = """ eqpy.input_q.put("%s")\n"" """; (void v) EQPy_put(location loc, string data){ // printf("EQPy_put called with: \n%s", data); string code = put_string % data; // printf("EQPy_put code: \n%s", code); @location=loc _void_py(code) => v = propagate(); } // Local Variables: // c-basic-offset: 4 // End:
mit
aa950276fb69bb9d97e49eb19a0484e7
25.326923
71
0.61943
2.944086
false
false
false
false
ekreative/testbuild-rocks-ios
AppsV2/CoreData/Human/AVProject.swift
1
1185
private var map: RKEntityMapping? private var onceToken: dispatch_once_t = 0 @objc(AVProject) class AVProject: _AVProject { class func mappingInStore(managedObjectStore: RKManagedObjectStore) -> RKEntityMapping { dispatch_once(&onceToken, { map = RKEntityMapping(forEntityForName: self.entityName(), inManagedObjectStore: managedObjectStore) map?.addAttributeMappingsFromArray(["id", "name", "identifier"]) map?.addAttributeMappingsFromDictionary(["created_on":"created"]) map?.identificationAttributes = ["id"] }) return map! } class func removeAllProjects(){ let context = RKObjectManager.sharedManager().managedObjectStore.mainQueueManagedObjectContext var request = NSFetchRequest(entityName: self.entityName()) request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] var error:NSError? var projects = context.executeFetchRequest(request, error: &error) as! [AVProject] for project in projects{ context.deleteObject(project) } } }
mit
4f812da014f65ff743978bb7998bd78f
33.882353
112
0.64135
5.243363
false
false
false
false
ello/ello-ios
Sources/Views/ClearTextField.swift
1
3779
//// /// ClearTextField.swift // class ClearTextField: UITextField { struct Size { static let lineMargin: CGFloat = 5 } let onePasswordButton = OnePasswordButton() var lineColor: UIColor? = .grey6 { didSet { if !isFirstResponder { line.backgroundColor = lineColor } } } var selectedLineColor: UIColor? = .white { didSet { if isFirstResponder { line.backgroundColor = selectedLineColor } } } private var line = Line() var hasOnePassword = false { didSet { onePasswordButton.isVisible = hasOnePassword setNeedsLayout() } } var validationState: ValidationState = .none { didSet { rightView = UIImageView(image: validationState.imageRepresentation) // This nonsense below is to prevent the rightView // from animating into position from 0,0 and passing specs rightView?.frame = rightViewRect(forBounds: self.bounds) setNeedsLayout() layoutIfNeeded() } } required override init(frame: CGRect) { super.init(frame: frame) sharedSetup() } required init?(coder: NSCoder) { super.init(coder: coder) sharedSetup() } func sharedSetup() { backgroundColor = .clear font = .defaultFont(18) textColor = .white rightViewMode = .always addSubview(onePasswordButton) addSubview(line) onePasswordButton.isVisible = hasOnePassword onePasswordButton.snp.makeConstraints { make in make.centerY.equalTo(self).offset(-Size.lineMargin / 2) make.trailing.equalTo(self) make.size.equalTo(CGSize.minButton) } line.backgroundColor = lineColor line.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(self) } } override var intrinsicContentSize: CGSize { var size = super.intrinsicContentSize if size.height != UIView.noIntrinsicMetric { size.height += Size.lineMargin } return size } override func drawPlaceholder(in rect: CGRect) { placeholder?.draw( in: rect, withAttributes: [ .font: UIFont.defaultFont(18), .foregroundColor: UIColor.white, ] ) } override func becomeFirstResponder() -> Bool { line.backgroundColor = selectedLineColor return super.becomeFirstResponder() } override func resignFirstResponder() -> Bool { line.backgroundColor = lineColor return super.resignFirstResponder() } // MARK: Layout rects override func textRect(forBounds bounds: CGRect) -> CGRect { return rectForBounds(bounds) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return rectForBounds(bounds) } override func clearButtonRect(forBounds bounds: CGRect) -> CGRect { var rect = super.clearButtonRect(forBounds: bounds) rect.origin.x -= 10 if hasOnePassword { rect.origin.x -= 44 } return rect } override func rightViewRect(forBounds bounds: CGRect) -> CGRect { var rect = super.rightViewRect(forBounds: bounds) rect.origin.x -= 10 if hasOnePassword { rect.origin.x -= 20 } return rect } private func rectForBounds(_ bounds: CGRect) -> CGRect { var rect = bounds.shrink(left: 15) if validationState.imageRepresentation != nil { rect = rect.shrink(left: 20) } return rect } }
mit
c2480b80e79d910cb8cc2220a1f5dece
26.18705
79
0.585605
5.120596
false
false
false
false
ello/ello-ios
Sources/Views/CommentsIcon.swift
1
1661
//// /// CommentsIcon.swift // class CommentsIcon: BasicIcon { private let commentTailView: UIView init(isDark: Bool) { let tailStyle: InterfaceImage.Style let selectedStyle: InterfaceImage.Style if isDark { tailStyle = .white selectedStyle = .white } else { tailStyle = .normal selectedStyle = .selected } let icon = UIImageView(image: InterfaceImage.bubbleBody.normalImage) let iconSelected = UIImageView(image: InterfaceImage.bubbleBody.image(selectedStyle)) commentTailView = UIImageView(image: InterfaceImage.bubbleTail.image(tailStyle)) super.init(normalIconView: icon, selectedIconView: iconSelected) addSubview(commentTailView) commentTailView.isHidden = true } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateIcon(selected: Bool, enabled: Bool) { super.updateIcon(selected: selected, enabled: enabled) commentTailView.isVisible = selected } } extension CommentsIcon { func animate() { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 8.9, 9.9, 9.9, 0.1, 0, 0] animation.keyTimes = [0, 0.25, 0.45, 0.55, 0.75, 0.95, 0] animation.duration = 0.6 animation.repeatCount = Float.infinity animation.isAdditive = true commentTailView.layer.add(animation, forKey: "comments") } func finishAnimation() { commentTailView.layer.removeAnimation(forKey: "comments") } }
mit
21118e3299916bc1c46c31a046763457
29.759259
93
0.640578
4.269923
false
false
false
false
AliSoftware/Dip
SampleApp/DipSampleApp/Providers/SWAPIStarshipProvider.swift
1
2548
// // SWAPIStarshipProvider.swift // Dip // // Created by Olivier Halligon on 10/10/2015. // Copyright © 2015 AliSoftware. All rights reserved. // import Foundation ///Provides Starship entities fetching them using web service struct SWAPIStarshipProvider : StarshipProviderAPI { let ws: NetworkLayer //Here we inject dependency using _constructor injection_ pattern. //The alternative way is a _property injection_ //but it should be used only for optional dependencies //where there is a good local default implementation init(webService: NetworkLayer) { self.ws = webService } func fetchIDs(completion: @escaping ([Int]) -> Void) { ws.request(path: "starships") { response in do { let dict = try response.json() as NSDictionary guard let results = dict["results"] as? [NSDictionary] else { throw SWAPIError.InvalidJSON } // Extract URLs (flatten to ignore invalid ones) let urlStrings = results.compactMap({ $0["url"] as? String }) let ids = urlStrings.compactMap(idFromURLString) completion(ids) } catch { completion([]) } } } func fetch(id: Int, completion: @escaping (Starship?) -> Void) { ws.request(path: "starships/\(id)") { response in do { let json = try response.json() as NSDictionary guard let name = json["name"] as? String, let model = json["model"] as? String, let manufacturer = json["manufacturer"] as? String, let crewStr = json["crew"] as? String, let crew = Int(crewStr), let passengersStr = json["passengers"] as? String, let passengers = Int(passengersStr), let pilotIDStrings = json["pilots"] as? [String] else { throw SWAPIError.InvalidJSON } let ship = Starship( name: name, model: model, manufacturer: manufacturer, crew: crew, passengers: passengers, pilotIDs: pilotIDStrings.compactMap(idFromURLString) ) completion(ship) } catch { completion(nil) } } } }
mit
fb3572ea544a15239643cfb5c821d429
34.873239
108
0.520612
5.187373
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Exporters/OpenTelemetryProtocol/trace/OtlpTraceJsonExporter.swift
1
1463
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk public class OtlpTraceJsonExporter: SpanExporter { // MARK: - Variables declaration private var exportedSpans = [OtlpSpan]() private var isRunning: Bool = true // MARK: - Json Exporter helper methods func getExportedSpans() -> [OtlpSpan] { exportedSpans } public func export(spans: [SpanData]) -> SpanExporterResultCode { guard isRunning else { return .failure } let exportRequest = Opentelemetry_Proto_Collector_Trace_V1_ExportTraceServiceRequest.with { $0.resourceSpans = SpanAdapter.toProtoResourceSpans(spanDataList: spans) } do { let jsonData = try exportRequest.jsonUTF8Data() do { let span = try JSONDecoder().decode(OtlpSpan.self, from: jsonData) exportedSpans.append(span) } catch { print("Decode Error: \(error)") } return .success } catch { return .failure } } public func flush() -> SpanExporterResultCode { guard isRunning else { return .failure } return .success } public func reset() { exportedSpans.removeAll() } public func shutdown() { exportedSpans.removeAll() isRunning = false } }
apache-2.0
126bc9a84437eae7fd36ac75af5e0647
26.092593
99
0.590567
4.892977
false
false
false
false
kouky/ORSSerialPort
Examples/RequestResponseDemo/Swift/Sources/MainViewController.swift
1
2235
// // MainViewController.swift // RequestResponseDemo // // Created by Andrew Madsen on 3/14/15. // Copyright (c) 2015 Open Reel Software. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Cocoa import ORSSerial class MainViewController: NSViewController { @IBOutlet weak var temperaturePlotView: TemperaturePlotView! let serialPortManager = ORSSerialPortManager.sharedSerialPortManager() let boardController = SerialBoardController() override func viewDidLoad() { self.boardController.addObserver(self, forKeyPath: "temperature", options: NSKeyValueObservingOptions(), context: MainViewControllerKVOContext) } // MARK: KVO let MainViewControllerKVOContext = UnsafeMutablePointer<()>() override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context != MainViewControllerKVOContext { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } if object as! NSObject == self.boardController && keyPath == "temperature" { self.temperaturePlotView.addTemperature(self.boardController.temperature) } } }
mit
f604981d56309c87791ef625b8243c12
40.388889
154
0.77047
4.425743
false
false
false
false
keyacid/keyacid-iOS
keyacid/EncryptViewController.swift
1
6906
// // EncryptViewController.swift // keyacid // // Created by Yuan Zhou on 6/24/17. // Copyright © 2017 yvbbrjdr. All rights reserved. // import UIKit class EncryptViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var signedAnonymous: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() textView.inputAccessoryView = DoneView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 40), textBox: textView) } func getSelectedRemoteProfile() -> RemoteProfile? { if ProfilesTableViewController.selectedRemoteProfileIndex == -1 { let remoteProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a remote profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) remoteProfileNotSelected.addAction(OKAction) self.present(remoteProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.remoteProfiles[ProfilesTableViewController.selectedRemoteProfileIndex] } func getSelectedLocalProfile() -> LocalProfile? { if ProfilesTableViewController.selectedLocalProfileIndex == -1 { let localProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a local profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) localProfileNotSelected.addAction(OKAction) self.present(localProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.localProfiles[ProfilesTableViewController.selectedLocalProfileIndex] } @IBAction func encryptClicked() { let plainText: String = textView.text var cipherText: String = "" if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "You have to encrypt something!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.textView.becomeFirstResponder() }) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } if signedAnonymous.selectedSegmentIndex == 0 { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } cipherText = Crypto.encrypt(data: plainText.data(using: String.Encoding.utf8)!, from: localProfile!, to: remoteProfile!).base64EncodedString() if cipherText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = cipherText } else { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } cipherText = Crypto.sealedEncrypt(data: plainText.data(using: String.Encoding.utf8)!, to: remoteProfile!).base64EncodedString() if cipherText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = cipherText } UIPasteboard.general.string = cipherText } @IBAction func decryptClicked() { let cipher: Data? = Data.init(base64Encoded: textView.text) if cipher == nil { let notBase64: UIAlertController = UIAlertController.init(title: "Error", message: "Invalid cipher!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) notBase64.addAction(OKAction) self.present(notBase64, animated: true, completion: nil) return } if signedAnonymous.selectedSegmentIndex == 0 { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } let plainText: String = String.init(data: Crypto.decrypt(data: cipher!, from: remoteProfile!, to: localProfile!), encoding: String.Encoding.utf8)! if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = plainText } else { let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } let plainText: String = String.init(data: Crypto.sealedDecrypt(data: cipher!, to: localProfile!), encoding: String.Encoding.utf8)! if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = plainText } } }
bsd-3-clause
36d32a38173612b497fe16b84c85d380
49.036232
173
0.623896
5.025473
false
false
false
false
vchuo/Photoasis
Photoasis/Classes/Models/Data/PersistentStorage/POPhoto.swift
1
848
// // POPhoto.swift // Realm用のフォトモデル。 // // Created by Vernon Chuo Chian Khye on 2017/02/25. // Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved. // import Foundation import RealmSwift class POPhoto: Object { dynamic var id = "" dynamic var photoAspectRatio: Double = 1 dynamic var photoURL = "" dynamic var authorName = "" dynamic var dateAdded = NSDate() dynamic var isSaved = false // MARK: - Realm Object Config /** 主キーの指定 - returns: 主キー名 */ override static func primaryKey() -> String? { return "id" } /** 保存しないプロパティ指定 - returns: プロパティ名配列 */ override static func ignoredProperties() -> [String] { return [] } }
mit
b865e4a23cdd410671d37c585485d9d1
17.756098
65
0.579974
4.005208
false
false
false
false
sachin004/firefox-ios
Client/Frontend/Browser/SessionRestoreHelper.swift
7
1270
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol SessionRestoreHelperDelegate: class { func sessionRestoreHelper(helper: SessionRestoreHelper, didRestoreSessionForBrowser browser: Browser) } class SessionRestoreHelper: BrowserHelper { weak var delegate: SessionRestoreHelperDelegate? private weak var browser: Browser? required init(browser: Browser) { self.browser = browser } func scriptMessageHandlerName() -> String? { return "sessionRestoreHelper" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let browser = browser, params = message.body as? [String: AnyObject] { if params["name"] as! String == "didRestoreSession" { dispatch_async(dispatch_get_main_queue()) { self.delegate?.sessionRestoreHelper(self, didRestoreSessionForBrowser: browser) } } } } class func name() -> String { return "SessionRestoreHelper" } }
mpl-2.0
edaddd9c65c02a050d4de43a5c8a8e98
33.324324
130
0.685039
5.019763
false
false
false
false
hanhailong/practice-swift
Apps/Calculator/Calculator/ViewController.swift
3
5574
// // ViewController.swift // Calculator // // Created by Domenico Solazzo on 7/12/14. // Copyright (c) 2014 Domenico Solazzo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var resultTextView: UITextView = UITextView() @IBOutlet var operationTextView: UITextView @IBOutlet var memoryTextView: UITextView var operation: String = "" var accumulator:Double? = nil var isResult = false var firstOperand:Double? var secondOperand:Double? var memoryResult:Double = 0 var result:Double? = nil 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. } /// Reset the calculator @IBAction func resetResult(sender: UIButton?) { isResult = false firstOperand = nil secondOperand = nil resultTextView.text = "" } // Memory operations @IBAction func MemoryOperationPressed(sender: UIButton) { var memoryOp = sender.titleLabel.text as String switch(memoryOp){ case "MR": showMemory() case "M+": addToMemory() case "M-": removeFromMemory() case "MC": cleanMemory() default: showError() } } func cleanMemory(){ memoryResult = 0 memoryTextView.text = "" } func addToMemory(){ var res:Double = 0 if(!resultTextView.text.isEmpty){ res = (resultTextView.text as NSString).doubleValue }else{ return; } memoryResult = (memoryResult + res) memoryTextView.text = "M" } func removeFromMemory(){ var res:Double = 0 if(!resultTextView.text.isEmpty){ res = (resultTextView.text as NSString).doubleValue }else{ return; } memoryResult = (memoryResult - res) memoryTextView.text = "M" } func showMemory(){ resultTextView.text = "\(memoryResult)" } // Prefix pressed @IBAction func prefixPressed(sender: UIButton) { if resultTextView.text.isEmpty || resultTextView.text == "0" || resultTextView.text == "ERROR!"{ resultTextView.text = "0" return } var result = resultTextView.text as NSString if(result.containsString("-") ){ resultTextView.text = result.substringFromIndex(1) }else{ resultTextView.text = "-" + resultTextView.text } } // The operation has been pressed @IBAction func pressedOperation(sender: UIButton) { var op = sender.titleLabel.text operation = op operationTextView.text = operation var temp:Double = 0 if(!resultTextView.text.isEmpty){ temp = (resultTextView.text as NSString).doubleValue }else{ return; } if(firstOperand){ secondOperand = temp }else{ firstOperand = temp } resultTextView.text = "" } // Calculate the result @IBAction func calculateResult(sender: UIButton?) { if(secondOperand || !resultTextView.text.isEmpty){ secondOperand = (resultTextView.text as NSString).doubleValue } if(firstOperand && secondOperand){ var temp = firstOperand! var temp2 = secondOperand! println("First:\(temp), second: \(temp2)") var res:Double = 0 switch(operation){ case "+": res = temp + temp2 case "-": res = temp - temp2 case "x": res = temp * temp2 case "/": if temp2 == 0{ showError() return } res = temp/temp2 default: showError() } println("Res:\(res)") firstOperand = res result = res showResult(res) }else{ resultTextView.text = "" } } // The dot button has been pressed @IBAction func dotPressed(sender: UIButton) { var dot = "." if resultTextView.text.isEmpty || resultTextView.text == "ERROR!"{ resultTextView.text = "0" } var result = resultTextView.text as NSString if(!result.containsString(dot) ){ resultTextView.text = resultTextView.text + dot } } // The number has been pressed @IBAction func numberPressed(sender: UIButton) { if(resultTextView.text == "0" || resultTextView.text == "ERROR!" || isResult){ resultTextView.text = sender.titleLabel.text }else{ resultTextView.text = resultTextView.text + sender.titleLabel.text } } func showResult(result: Double){ resultTextView.text = "\(result)" isResult = true } func showError(){ resetResult(nil) resultTextView.text = "ERROR!" } }
mit
3ccb4e25d430d3372bfec4a0ac8d53e4
26.594059
104
0.524578
5.06267
false
false
false
false
sachin004/firefox-ios
Providers/Profile.swift
1
36322
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import ReadingList import Shared import Storage import Sync import XCGLogger private let log = Logger.syncLogger public let ProfileDidStartSyncingNotification = "ProfileDidStartSyncingNotification" public let ProfileDidFinishSyncingNotification = "ProfileDidFinishSyncingNotification" public let ProfileRemoteTabsSyncDelay: NSTimeInterval = 0.1 public protocol SyncManager { var isSyncing: Bool { get } func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult func syncEverything() -> Success // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func applicationDidEnterBackground() func applicationDidBecomeActive() func onNewProfile() func onRemovedAccount(account: FirefoxAccount?) -> Success func onAddedAccount() -> Success } typealias EngineIdentifier = String typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult class ProfileFileAccessor: FileAccessor { convenience init(profile: Profile) { self.init(localName: profile.localName()) } init(localName: String) { let profileDirName = "profile.\(localName)" // Bug 1147262: First option is for device, second is for simulator. var rootPath: NSString if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path { rootPath = path as NSString } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString } super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName)) } } class CommandStoringSyncDelegate: SyncDelegate { let profile: Profile init() { profile = BrowserProfile(localName: "profile", app: nil) } func displaySentTabForURL(URL: NSURL, title: String) { let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil) self.profile.queue.addToQueue(item) } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } class BrowserProfileSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } // SyncDelegate func displaySentTabForURL(URL: NSURL, title: String) { // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them if let currentSettings = app.currentUserNotificationSettings() { if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 { if Logger.logPII { log.info("Displaying notification for URL \(URL.absoluteString)") } let notification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString) notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title] notification.alertAction = nil notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> { get } func shutdown() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } // Do we have an account at all? func hasAccount() -> Bool // Do we have an account that (as far as we know) is in a syncable state? func hasSyncableAccount() -> Bool func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(account: FirefoxAccount) func getClients() -> Deferred<Maybe<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) var syncManager: SyncManager { get } } public class BrowserProfile: Profile { private let name: String internal let files: FileAccessor weak private var app: UIApplication? /** * N.B., BrowserProfile is used from our extensions, often via a pattern like * * BrowserProfile(…).foo.saveSomething(…) * * This can break if BrowserProfile's initializer does async work that * subsequently — and asynchronously — expects the profile to stick around: * see Bug 1218833. Be sure to only perform synchronous actions here. */ init(localName: String, app: UIApplication?) { log.debug("Initing profile \(localName) on thread \(NSThread.currentThread()).") self.name = localName self.files = ProfileFileAccessor(localName: localName) self.app = app let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil) notificationCenter.addObserver(self, selector: Selector("onProfileDidFinishSyncing:"), name: ProfileDidFinishSyncingNotification, object: nil) notificationCenter.addObserver(self, selector: Selector("onPrivateDataClearedHistory:"), name: NotificationPrivateDataClearedHistory, object: nil) if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() { KeychainWrapper.serviceName = baseBundleIdentifier } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") } // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account metadata.") self.removeAccountMetadata() self.syncManager.onNewProfile() prefs.clearAll() } // Always start by needing invalidation. // This is the same as self.history.setTopSitesNeedsInvalidation, but without the // side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread. prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func shutdown() { if self.dbCreated { db.close() } if self.loginsDBCreated { loginsDB.close() } } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url), let title = notification.userInfo!["title"] as? NSString { // Only record local vists if the change notification originated from a non-private tab if !(notification.userInfo!["isPrivate"] as? Bool ?? false) { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString, title: title as String) let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType) history.addLocalVisit(visit) } history.setTopSitesNeedsInvalidation() } else { log.debug("Ignoring navigation.") } } // These selectors run on which ever thread sent the notifications (not the main thread) @objc func onProfileDidFinishSyncing(notification: NSNotification) { history.setTopSitesNeedsInvalidation() } @objc func onPrivateDataClearedHistory(notification: NSNotification) { // Immediately invalidate the top sites cache history.refreshTopSitesCache() } deinit { log.debug("Deiniting profile \(self.localName).") self.syncManager.endTimedSyncs() NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationOnLocationChange, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil) } func localName() -> String { return name } lazy var queue: TabQueue = { withExtendedLifetime(self.history) { return SQLiteQueue(db: self.db) } }() private var dbCreated = false var db: BrowserDB { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "browser.db", files: self.files) self.dbCreated = true } return Singleton.instance } /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. * * Any other class that needs to access any one of these should ensure * that this is initialized first. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = { return SQLiteHistory(db: self.db, prefs: self.prefs)! }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { return self.places } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. withExtendedLifetime(self.places) { return MergedSQLiteBookmarks(db: self.db) } }() lazy var mirrorBookmarks: BookmarkMirrorStorage = { // Yeah, this is lazy. Sorry. return self.bookmarks as! MergedSQLiteBookmarks }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() lazy var remoteClientsAndTabs: protocol<RemoteClientsAndTabs, ResettableSyncStorage, AccountRemovalDelegate> = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var syncManager: SyncManager = { return BrowserSyncManager(profile: self) }() private func getSyncDelegate() -> SyncDelegate { if let app = self.app { return BrowserProfileSyncDelegate(app: app) } return CommandStoringSyncDelegate() } public func getClients() -> Deferred<Maybe<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { let commands = items.map { item in SyncCommand.fromShareItem(item, withAction: "displayURI") } self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() } } lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = { return SQLiteLogins(db: self.loginsDB) }() private lazy var loginsKey: String? = { let key = "sqlcipher.key.logins.db" if KeychainWrapper.hasValueForKey(key) { return KeychainWrapper.stringForKey(key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString KeychainWrapper.setString(secret, forKey: key) return secret }() private var loginsDBCreated = false private lazy var loginsDB: BrowserDB = { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) self.loginsDBCreated = true } return Singleton.instance }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() private lazy var account: FirefoxAccount? = { if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] { return FirefoxAccount.fromDictionary(dictionary) } return nil }() func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.None } func getAccount() -> FirefoxAccount? { return account } func removeAccountMetadata() { self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) KeychainWrapper.removeObjectForKey(self.name + ".account") } func removeAccount() { let old = self.account removeAccountMetadata() self.account = nil // Tell any observers that our account has changed. NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) // Deregister for remote notifications. app?.unregisterForRemoteNotifications() } func setAccount(account: FirefoxAccount) { KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account") self.account = account // register for notifications for the account registerForNotifications() // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) self.syncManager.onAddedAccount() } func registerForNotifications() { let viewAction = UIMutableUserNotificationAction() viewAction.identifier = SentTabAction.View.rawValue viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") viewAction.activationMode = UIUserNotificationActivationMode.Foreground viewAction.destructive = false viewAction.authenticationRequired = false let bookmarkAction = UIMutableUserNotificationAction() bookmarkAction.identifier = SentTabAction.Bookmark.rawValue bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground bookmarkAction.destructive = false bookmarkAction.authenticationRequired = false let readingListAction = UIMutableUserNotificationAction() readingListAction.identifier = SentTabAction.ReadingList.rawValue readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") readingListAction.activationMode = UIUserNotificationActivationMode.Foreground readingListAction.destructive = false readingListAction.authenticationRequired = false let sentTabsCategory = UIMutableUserNotificationCategory() sentTabsCategory.identifier = TabSendCategory sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default) sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal) app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory])) app?.registerForRemoteNotifications() } // Extends NSObject so we can use timers. class BrowserSyncManager: NSObject, SyncManager { // We shouldn't live beyond our containing BrowserProfile, either in the main app or in // an extension. // But it's possible that we'll finish a side-effect sync after we've ditched the profile // as a whole, so we hold on to our Prefs, potentially for a little while longer. This is // safe as a strong reference, because there's no cycle. unowned private let profile: BrowserProfile private let prefs: Prefs let FifteenMinutes = NSTimeInterval(60 * 15) let OneMinute = NSTimeInterval(60) private var syncTimer: NSTimer? = nil private var backgrounded: Bool = true func applicationDidEnterBackground() { self.backgrounded = true self.endTimedSyncs() } func applicationDidBecomeActive() { self.backgrounded = false self.beginTimedSyncs() } /** * Locking is managed by withSyncInputs. Make sure you take and release these * whenever you do anything Sync-ey. */ var syncLock = OSSpinLock() { didSet { let notification = syncLock == 0 ? ProfileDidFinishSyncingNotification : ProfileDidStartSyncingNotification NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil)) } } // According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value // and a locked lock is a non-zero value var isSyncing: Bool { return syncLock != 0 } private func beginSyncing() -> Bool { return OSSpinLockTry(&syncLock) } private func endSyncing() { OSSpinLockUnlock(&syncLock) } init(profile: BrowserProfile) { self.profile = profile self.prefs = profile.prefs super.init() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil) center.addObserver(self, selector: "onFinishSyncing:", name: ProfileDidFinishSyncingNotification, object: nil) } deinit { // Remove 'em all. let center = NSNotificationCenter.defaultCenter() center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil) center.removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil) } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(notification: NSNotification) { log.debug("Login did change.") if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = NSDate.now() // Give it a few seconds. let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered) // Trigger on the main queue. The bulk of the sync work runs in the background. let greenLight = self.greenLight() dispatch_after(when, dispatch_get_main_queue()) { if greenLight() { self.syncLogins() } } } } @objc func onFinishSyncing(notification: NSNotification) { self.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastSyncFinishTime) } var prefsForSync: Prefs { return self.prefs.branch("sync") } func onAddedAccount() -> Success { return self.syncEverything() } func locallyResetCollection(collection: String) -> Success { switch collection { case "bookmarks": return MirroringBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks") case "clients": fallthrough case "tabs": // Because clients and tabs share storage, and thus we wipe data for both if we reset either, // we reset the prefs for both at the same time. return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync) case "history": return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history") case "passwords": return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords") case "forms": log.debug("Requested reset for forms, but this client doesn't sync them yet.") return succeed() case "addons": log.debug("Requested reset for addons, but this client doesn't sync them.") return succeed() case "prefs": log.debug("Requested reset for prefs, but this client doesn't sync them.") return succeed() default: log.warning("Asked to reset collection \(collection), which we don't know about.") return succeed() } } func onNewProfile() { SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } func onRemovedAccount(account: FirefoxAccount?) -> Success { let profile = self.profile // Run these in order, because they might write to the same DB! let remove = [ profile.history.onRemovedAccount, profile.remoteClientsAndTabs.onRemovedAccount, profile.logins.onRemovedAccount, profile.bookmarks.onRemovedAccount, ] let clearPrefs: () -> Success = { withExtendedLifetime(self) { // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } return succeed() } return accumulate(remove) >>> clearPrefs } private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true) } func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = Selector("syncOnTimer") log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping sync timer.") self.syncTimer = nil t.invalidate() } } private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info) } private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) } private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Mirroring server bookmarks to storage.") let bookmarksMirrorer = ready.synchronizer(MirroringBookmarksSynchronizer.self, delegate: delegate, prefs: prefs) return bookmarksMirrorer.mirrorBookmarksToStorage(self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) } func takeActionsOnEngineStateChanges<T: EngineStateChanges>(changes: T) -> Deferred<Maybe<T>> { var needReset = Set<String>(changes.collectionsThatNeedLocalReset()) needReset.unionInPlace(changes.enginesDisabled()) needReset.unionInPlace(changes.enginesEnabled()) if needReset.isEmpty { log.debug("No collections need reset. Moving on.") return deferMaybe(changes) } // needReset needs at most one of clients and tabs, because we reset them // both if either needs reset. This is strictly an optimization to avoid // doing duplicate work. if needReset.contains("clients") { if needReset.remove("tabs") != nil { log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.") } } return walk(Array(needReset), f: self.locallyResetCollection) >>> effect(changes.clearLocalCommands) >>> always(changes) } /** * Returns nil if there's no account. */ private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? { if let account = profile.account { if !beginSyncing() { log.info("Not syncing \(label); already syncing something.") return deferMaybe(AlreadySyncingError()) } if let label = label { log.info("Syncing \(label).") } let authState = account.syncAuthState let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState) let delegate = profile.getSyncDelegate() let go = readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in function(delegate, self.prefsForSync, ready) } // Always unlock when we're done. go.upon({ res in self.endSyncing() }) return go } log.warning("No account; can't sync.") return nil } /** * Runs the single provided synchronization function and returns its status. */ private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult { return self.withSyncInputs(label, function: function) ?? deferMaybe(.NotStarted(.NoAccount)) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses the same length as the input. */ private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { typealias Pair = (EngineIdentifier, SyncStatus) let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Maybe<Pair>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) } } } return accumulate(thunks) } return self.withSyncInputs(nil, function: combined) ?? deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) }) } func syncEverything() -> Success { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("logins", self.syncLoginsWithDelegate), ("bookmarks", self.mirrorBookmarksWithDelegate), ("history", self.syncHistoryWithDelegate) ) >>> succeed } @objc func syncOnTimer() { log.debug("Running timed logins sync.") // Note that we use .upon here rather than chaining with >>> precisely // to allow us to sync subsequent engines regardless of earlier failures. // We don't fork them in parallel because we want to limit perf impact // due to background syncs, and because we're cautious about correctness. self.syncLogins().upon { result in if let success = result.successValue { log.debug("Timed logins sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed logins sync failed. Reason: \(reason).") } log.debug("Running timed history sync.") self.syncHistory().upon { result in if let success = result.successValue { log.debug("Timed history sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed history sync failed. Reason: \(reason).") } } } } func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate) ) >>== { statuses in let tabsStatus = statuses[1].1 return deferMaybe(tabsStatus) } } func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } func mirrorBookmarks() -> SyncResult { return self.sync("bookmarks", function: mirrorBookmarksWithDelegate) } /** * Return a thunk that continues to return true so long as an ongoing sync * should continue. */ func greenLight() -> () -> Bool { let start = NSDate.now() // Give it one minute to run before we stop. let stopBy = start + OneMinuteInMilliseconds log.debug("Checking green light. Backgrounded: \(self.backgrounded).") return { !self.backgrounded && NSDate.now() < stopBy && self.profile.hasSyncableAccount() } } } } class AlreadySyncingError: MaybeErrorType { var description: String { return "Already syncing." } }
mpl-2.0
d5ae511f0940f11f6689ddeda60646b9
39.61745
238
0.641413
5.394741
false
false
false
false
magnetsystems/max-ios
Tests/Tests/MMAttachmentServiceSpec.swift
1
3492
/* * Copyright (c) 2015 Magnet Systems, 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 Foundation import Quick import Nimble import MagnetMax class MMAttachmentServiceSpec : QuickSpec { override func spec() { describe("MMAttachmentService") { let user = MMUser() user.firstName = "Jane" user.lastName = "Doe" user.email = "richmessageuser_\(NSDate.timeIntervalSinceReferenceDate())@magnet.com" user.userName = user.email user.password = "magnet" beforeSuite { let credential = NSURLCredential(user: user.userName, password: user.password, persistence: .None) var loggedInUser: MMUser? user.register({ user in MMUser.login(credential, rememberMe: false, success: { loggedInUser = MMUser.currentUser() }) { error in } }) { error in } expect(loggedInUser).toEventuallyNot(beNil(), timeout: 10) } afterSuite { var loggedInUser: MMUser? = MMUser() MMUser.logout({ loggedInUser = MMUser.currentUser() }, failure: { error in }) expect(loggedInUser).toEventually(beNil(), timeout: 10) } let attachment = MMAttachment(fileURL: NSURL(fileURLWithPath: NSBundle(forClass: MMAttachmentServiceSpec.self).pathForResource("GoldenGateBridge1", ofType: "jpg")!), mimeType: "image/jpeg") let attachment2 = MMAttachment(fileURL: NSURL(fileURLWithPath: NSBundle(forClass: MMAttachmentServiceSpec.self).pathForResource("GoldenGateBridge2", ofType: "jpg")!), mimeType: "image/jpeg", name: "Golden Gate Bridge", description: nil) it("should be able to upload attachments") { MMAttachmentService.upload([attachment, attachment2], metaData:nil, success: { // }, failure: { error in // }) expect(attachment.attachmentID).toEventuallyNot(beNil(), timeout: 10) expect(attachment2.attachmentID).toEventuallyNot(beNil(), timeout: 10) } it("should be able to download attachments") { var localFilePath: NSURL? MMAttachmentService.download(attachment.attachmentID!, userID: MMUser.currentUser()?.userID, success: { filePath in localFilePath = filePath }, failure: { error in // }) expect(localFilePath).toEventuallyNot(beNil(), timeout: 10) } } } }
apache-2.0
617ecedeb1547a180ae505cde741a7cc
38.681818
248
0.558133
5.45625
false
false
false
false
macteo/bezier
Bézier.playgroundbook/Contents/Chapters/Bezier.playgroundchapter/Sources/GraphicsView.swift
2
3329
import UIKit public class GraphicsView : UIView { var interpolationPoints = [CGPoint]() public var closed = false public var interpolationAlpha : CGFloat = 0.35 public var showHandles = true public var showCurve = true var lineWidth : CGFloat = 6 var lineColor : UIColor = UIColor.orange.withAlphaComponent(0.7) public override func draw(_ rect: CGRect) { guard interpolationPoints.count > 0 else { return } // Dashed line drawing let dashedConnectors = UIBezierPath() var ii = 0 while ii < interpolationPoints.count { let point = interpolationPoints[ii] if interpolationPoints.count > 1 { if ii == 0 { dashedConnectors.move(to: point) } else { dashedConnectors.addLine(to: point) } } ii = ii + 1 } if closed { dashedConnectors.addLine(to: interpolationPoints[0]) dashedConnectors.close() } let dashedPattern : [CGFloat] = [3, 3, 3, 3] dashedConnectors.setLineDash(dashedPattern, count: 4, phase: 0.0) dashedConnectors.lineWidth = 1 UIColor(colorLiteralRed: 0.4, green: 0.4, blue: 0.4, alpha: 1).setStroke() dashedConnectors.stroke() // Interpolation points drawing for point in interpolationPoints { let pointPath = UIBezierPath(ovalIn: CGRect(x:point.x - 4, y:point.y - 4, width: 8, height: 8)) UIColor.red.setFill() pointPath.fill() } guard showCurve == true else { return } // Curve drawing let path = UIBezierPath() let controlPoints = path.interpolatePointsWithHermite(interpolationPoints: interpolationPoints, alpha: interpolationAlpha, closed: closed) lineColor.setStroke() path.lineWidth = lineWidth path.stroke() guard showHandles == true else { return } // Drawing control points for controlPoint in controlPoints { let pointPath = UIBezierPath(ovalIn: CGRect(x:controlPoint.x - 2, y: controlPoint.y - 2, width: 4, height: 4)) UIColor.blue.setFill() pointPath.fill() } // Drawing handles to connect control points // To iterate on controlPoints var jj = 0 while jj < controlPoints.count { // To iterate on interpolationPoints let ii = jj / 2 let handle = UIBezierPath() if jj % 2 == 0 { handle.move(to: interpolationPoints[ii]) handle.addLine(to: controlPoints[jj]) } else { handle.move(to: controlPoints[jj]) if interpolationPoints.count > ii + 1 { handle.addLine(to: interpolationPoints[ii + 1]) } else { handle.addLine(to: interpolationPoints[0]) } } handle.lineWidth = 1 / UIScreen.main.scale UIColor(colorLiteralRed: 0.4, green: 0.4, blue: 0.4, alpha: 1).setStroke() handle.stroke() jj = jj + 1 } } }
mit
a3b2b3fda2e38d4b57a6e1096e7264ef
34.042105
146
0.543406
4.874085
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/FeedBack/View/WaitFeedBackTableViewCell.swift
1
2184
// // WaitFeedBackTableViewCell.swift // OMS-WH // // Created by xuech on 2017/11/21. // Copyright © 2017年 medlog. All rights reserved. // import UIKit protocol WaitFeedBackTableViewCellDelegate { func editUseReqTableViewCell(cell:UITableViewCell,modifiedModel:FeedBackMedModel,currentTableView:UITableView) } class WaitFeedBackTableViewCell: UITableViewCell { @IBOutlet weak var choiceKitImg: UIImageView! @IBOutlet weak var metailType: UILabel! @IBOutlet weak var metailRule: UILabel! @IBOutlet weak var metailName: UILabel! @IBOutlet weak var metailCode: UILabel! @IBOutlet weak var prolnName: UILabel! @IBOutlet weak var brandName: UILabel! @IBOutlet weak var stepperView: StepperSwift! fileprivate var tableView: UITableView? fileprivate var modifiedModel : FeedBackMedModel? var delegate : WaitFeedBackTableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configMetailData(medMaterialList:FeedBackMedModel?,currentTableView:UITableView) { guard let model = medMaterialList else { return } tableView = currentTableView modifiedModel = model prolnName.text = "产品线:\(model.medProdLnName)" brandName.text = "品牌:\(model.medBrandName)" metailName.text = "物料名称:\(model.medMIName)" metailCode.text = "物料编码:\(model.medMICode)" metailRule.text = "规格:\(model.specification)" metailType.text = "类型:\(model.categoryByPlatformName)" stepperView.value = Double(model.useQty) stepperView.addTarget(self, action: #selector(stepperValueChanged), for: .valueChanged) } @objc func stepperValueChanged(stepper: StepperSwift) { modifiedModel?.useQty = Int(stepper.value) delegate?.editUseReqTableViewCell(cell: self, modifiedModel: modifiedModel!, currentTableView: tableView!) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
960520ca8102ecf6e07f87737aafa298
33.435484
114
0.70445
4.278557
false
false
false
false
itsbriany/Sudoku
Sudoku/HomeViewController.swift
1
1724
// // ViewController.swift // Sudoku // // Created by Brian Yip on 2016-01-14. // Copyright © 2016 Brian Yip. All rights reserved. // import UIKit class HomeViewController: UIViewController { var sudokuManager: SudokuManager? let format = SudokuFormat(rows: 9, columns: 9) let selectLevelSegue = "SelectLevelSegue" let startSudokuSegue = "StartSudokuSegue" override func viewDidLoad() { super.viewDidLoad() // The sudoku manager is passed around different view controllers // This maintains the state of the sudoku manager via the app's lifetime if sudokuManager == nil { sudokuManager = SudokuManager(format: self.format) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Navigation // Pass data to the destination view controller override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == self.selectLevelSegue { if let navigationController = segue.destinationViewController as? UINavigationController { if let destination = navigationController.topViewController as? LevelViewController { destination.sudokuManager = self.sudokuManager } } } else if segue.identifier == self.startSudokuSegue { if let navigationController = segue.destinationViewController as? UINavigationController { if let destination = navigationController.topViewController as? SudokuViewController { destination.sudokuManager = self.sudokuManager } } } } }
apache-2.0
5204b332df18670df0642d1e3eec0776
34.183673
102
0.655252
5.558065
false
false
false
false
fiveagency/ios-five-utils
Sources/FiveTimeInterval.swift
1
2751
// // FiveTimeInterval.swift // FiveUtils // // Created by Denis Mendica on 5/27/16. // Copyright © 2016 Five Agency. All rights reserved. // import Foundation public class FiveTimeInterval { fileprivate let timeInterval: TimeInterval /** Total number of seconds in this time interval. */ public var totalSeconds: Double { return timeInterval } /** Total number of minutes in this time interval. */ public var totalMinutes: Double { return totalSeconds / 60 } /** Total number of hours in this time interval. */ public var totalHours: Double { return totalMinutes / 60 } /** Total number of days in this time interval. */ public var totalDays: Double { return totalHours / 24 } /** Total number of weeks in this time interval. */ public var totalWeeks: Double { return totalDays / 7 } /** Current second in a minute, from 0 to 59. */ public var second: Int { return Int(totalSeconds) - Int(totalMinutes) * 60 } /** Current minute in an hour, from 0 to 59. */ public var minute: Int { return Int(totalMinutes) - Int(totalHours) * 60 } /** Current hour in a day, from 0 to 23. */ public var hour: Int { return Int(totalHours) - Int(totalDays) * 24 } /** Current day in a week, from 0 to 6. */ public var day: Int { return Int(totalDays) - Int(totalWeeks) * 7 } /** Current week. */ public var week: Int { return Int(totalWeeks) } /** Creates an FiveTimeInterval object that represents a given TimeInterval value. - parameter timeInterval: TimeInterval value to create the FiveTimeInterval instance from. */ public init(timeInterval: TimeInterval) { self.timeInterval = timeInterval } /** Creates an FiveTimeInterval object by summing up amounts of different time units. - parameter weeks: number of weeks to add to the interval. - parameter days: number of days to add to the interval. - parameter hours: number of hours to add to the interval. - parameter minutes: number of minutes to add to the interval. - parameter seconds: number of seconds to add to the interval. */ public init(weeks: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Double = 0) { timeInterval = Double(weeks * 7 * 24 * 60 * 60) + Double(days * 24 * 60 * 60) + Double(hours * 60 * 60) + Double(minutes * 60) + seconds } }
mit
c67592d89e7aec3c87d755e327e754bf
23.774775
103
0.580727
4.486134
false
false
false
false