repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Donny8028/Swift-TinyFeatures
SpotlightSearch/SpotlightSearch/ViewController.swift
1
4874
// // ViewController.swift // SpotlightSearch // // Created by 賢瑭 何 on 2016/5/29. // Copyright © 2016年 Donny. All rights reserved. // import UIKit import CoreSpotlight import MobileCoreServices class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var movies = [] var selectRow: Int? override func viewDidLoad() { super.viewDidLoad() configuration() setSpotlight() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Constants.cellId, forIndexPath: indexPath) as? MovieSummaryCell let info = movies[indexPath.row] as? [String:String] cell?.imgMovieImage.image = UIImage(named: info!["Image"]!) cell?.lblTitle.text = info!["Title"] cell?.lblDescription.text = info!["Description"] cell?.lblRating.text = info!["Rating"] return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectRow = indexPath.row performSegueWithIdentifier(Constants.segueId, sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let dataInfo = movies[selectRow!] as? [String:String] { if segue.identifier == Constants.segueId { if let dv = segue.destinationViewController as? MovieDetailsViewController { dv.movie = dataInfo } } } } func configuration() { tableView.delegate = self tableView.dataSource = self let nib = UINib(nibName: Constants.nibName, bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: Constants.cellId) tableView.rowHeight = 120 let sourceURL = NSBundle.mainBundle().URLForResource(Constants.dataFile, withExtension: Constants.fileExtention) let data = NSArray(contentsOfURL: sourceURL!) movies = data! } func setSpotlight() { var searchableItems = [CSSearchableItem]() for i in 0...movies.count-1 { let movie = movies[i] as! [String:String] let searchableAttribute = CSSearchableItemAttributeSet(itemContentType: kUTTypeImage as String) let ary = movie["Image"]?.componentsSeparatedByString(".") let url = NSBundle.mainBundle().URLForResource(ary![0], withExtension: ary![1]) var keywords = [String]() searchableAttribute.title = movie["Title"] searchableAttribute.thumbnailURL = url searchableAttribute.contentDescription = movie["Description"] let stars = movie["Stars"]?.componentsSeparatedByString(",") let category = movie["Category"]?.componentsSeparatedByString(",") keywords = stars! + category! if !keywords.isEmpty { searchableAttribute.keywords = keywords } let searchableItem = CSSearchableItem(uniqueIdentifier: "movie.number.at.\(i)", domainIdentifier: "movies", attributeSet: searchableAttribute) searchableItems.append(searchableItem) } if searchableItems.count == movies.count { CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems, completionHandler: { error in if error != nil { print("\(error?.localizedDescription)") } }) } } override func restoreUserActivityState(activity: NSUserActivity) { if activity.activityType == CSSearchableItemActionType{ if let userInfo = activity.userInfo { let activityId = userInfo[CSSearchableItemActivityIdentifier] let index = activityId?.componentsSeparatedByString(".") selectRow = Int(index!.last!) ?? nil if let _ = selectRow { performSegueWithIdentifier(Constants.segueId, sender: self) } } } } struct Constants { static let nibName = "MovieSummaryCell" static let cellId = "MainCell" static let dataFile = "MoviesData" static let fileExtention = ".plist" static let segueId = "idSegueShowMovieDetails" } }
mit
a1ea07d54d3f69a96fa6ec3b28008002
37.007813
154
0.628983
5.541002
false
false
false
false
annecruz/MDCSwipeToChoose
Examples/SwiftLikedOrNope/SwiftLikedOrNope/ImageLabelView.swift
3
2444
// // ImageLabelView.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 class ImagelabelView: UIView{ var imageView: UIImageView! var label: UILabel! override init(frame: CGRect){ super.init(frame: frame) imageView = UIImageView() label = UILabel() } init(frame: CGRect, image: UIImage, text: String) { super.init(frame: frame) constructImageView(image) constructLabel(text) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } func constructImageView(image:UIImage) -> Void{ let topPadding:CGFloat = 10.0 let framex = CGRectMake(floor((CGRectGetWidth(self.bounds) - image.size.width)/2), topPadding, image.size.width, image.size.height) imageView = UIImageView(frame: framex) imageView.image = image addSubview(self.imageView) } func constructLabel(text:String) -> Void{ let height:CGFloat = 18.0 let frame2 = CGRectMake(0, CGRectGetMaxY(self.imageView.frame), CGRectGetWidth(self.bounds), height); self.label = UILabel(frame: frame2) label.text = text addSubview(label) } }
mit
32d96af3a1aa5b314cbcf682de61ef3f
32.493151
90
0.66653
4.509225
false
false
false
false
6ag/BaoKanIOS
BaoKanIOS/Classes/Module/News/View/Column/JFColumnReusableView.swift
1
2454
// // JFColumnReusableView.swift // BaoKanIOS // // Created by zhoujianfeng on 16/5/31. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit enum ButtonState { case stateComplish case stateSortDelete } class JFColumnReusableView: UICollectionReusableView { typealias ClickBlock = (_ state: ButtonState) -> () var clickBlock: ClickBlock? var buttonHidden: Bool? { didSet { clickButton.isHidden = buttonHidden! } } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func clickWithBlock(_ clickBlock: @escaping ClickBlock) -> Void { self.clickBlock = clickBlock } fileprivate func prepareUI() { addSubview(titleLabel) addSubview(clickButton) } func didTappedClickButton(_ button: UIButton) -> Void { button.isSelected = !button.isSelected if button.isSelected { clickBlock!(ButtonState.stateSortDelete) } else { clickBlock!(ButtonState.stateComplish) } } // MARK: - 懒加载 lazy var titleLabel: UILabel = { let titleLabel = UILabel(frame: CGRect(x: 10, y: 0, width: 200, height: self.bounds.size.height)) titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.textColor = UIColor.colorWithRGB(51, g: 51, b: 51) return titleLabel }() lazy var clickButton: UIButton = { let clickButton = UIButton(frame: CGRect(x: SCREEN_WIDTH - 100, y: 10, width: 60, height: 20)) clickButton.backgroundColor = UIColor.white clickButton.layer.masksToBounds = true clickButton.layer.cornerRadius = 10 clickButton.layer.borderColor = UIColor.colorWithRGB(214, g: 39, b: 48) .cgColor; clickButton.layer.borderWidth = 0.7; clickButton.setTitle("排序删除", for: UIControlState()) clickButton.setTitle("完成", for: UIControlState.selected) clickButton.titleLabel!.font = UIFont.systemFont(ofSize: 13) clickButton.setTitleColor(UIColor.colorWithRGB(214, g: 39, b: 48), for: UIControlState()) clickButton.addTarget(self, action: #selector(didTappedClickButton(_:)), for: UIControlEvents.touchUpInside) return clickButton }() }
apache-2.0
2e259537c0623102a552c593d51f2e37
30.115385
116
0.636176
4.380866
false
false
false
false
sswierczek/Helix-Movie-Guide-iOS
Helix Movie GuideTests/UIActivityIndicatorView+ShowTest.swift
1
789
// // UIActivityIndicatorView+ShowTest.swift // Helix Movie Guide // // Created by Sebastian Swierczek on 08/03/2017. // Copyright © 2017 user. All rights reserved. // @testable import Helix_Movie_Guide import XCTest class UIActivityIndicatorViewsExtensionsTest: XCTestCase { var loadingIndicator: UIActivityIndicatorView? override func setUp() { loadingIndicator = UIActivityIndicatorView() } func test_WHEN_startAnimationTrue_THEN_startAnimating() { loadingIndicator?.startAnimating(start: true) XCTAssert(loadingIndicator?.isAnimating == true) } func test_WHEN_startAnimationFalse_THEN_stopAnimating() { loadingIndicator?.startAnimating(start: false) XCTAssert(loadingIndicator?.isAnimating == false) } }
apache-2.0
3062c7f98bb523c27e8d0a07e35c0c44
24.419355
61
0.72335
4.804878
false
true
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
PerchReadyApp/apps/Perch/iphone/native/Perch/ExternalLibraries/JsonObject/JsonObject+Serialization.swift
2
1148
// // JsonObject+Serialization.swift // JsonObject // // Created by Bradley Hilton on 3/17/15. // // import Foundation // MARK: JsonObject+Serialization extension JsonObject { func serializedDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() for (name, mirrorType) in properties() { if let mapper = mapperForType(mirrorType.valueType), let value: AnyObject = valueForProperty(name, mirrorType: mirrorType) { if let jsonValue = mapper.jsonValueFromPropertyValue(value) { dictionary.setObject(jsonValue.value(), forKey: dictionaryKeyForPropertyKey(name)) } } } return dictionary } private func valueForProperty(name: String, mirrorType: _MirrorType) -> AnyObject? { if let value: AnyObject = mirrorType.value as? AnyObject { return value } else if respondsToSelector(NSSelectorFromString(name)) { if let value: AnyObject = valueForKey(name) { return value } } return nil } }
epl-1.0
02a6824e2d25613884e941ecfb36442f
28.461538
106
0.598432
5.125
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/EnumGenerator.swift
1
5982
// Sources/protoc-gen-swift/EnumGenerator.swift - Enum logic // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This file handles the generation of a Swift enum for each .proto enum. /// // ----------------------------------------------------------------------------- import Foundation import SwiftProtobufPluginLibrary import SwiftProtobuf /// The name of the case used to represent unrecognized values in proto3. /// This case has an associated value containing the raw integer value. private let unrecognizedCaseName = "UNRECOGNIZED" /// Generates a Swift enum from a protobuf enum descriptor. class EnumGenerator { private let enumDescriptor: EnumDescriptor private let generatorOptions: GeneratorOptions private let namer: SwiftProtobufNamer /// The values that aren't aliases, sorted by number. private let mainEnumValueDescriptorsSorted: [EnumValueDescriptor] private let swiftRelativeName: String private let swiftFullName: String init(descriptor: EnumDescriptor, generatorOptions: GeneratorOptions, namer: SwiftProtobufNamer ) { self.enumDescriptor = descriptor self.generatorOptions = generatorOptions self.namer = namer mainEnumValueDescriptorsSorted = descriptor.values.filter({ return $0.aliasOf == nil }).sorted(by: { return $0.number < $1.number }) swiftRelativeName = namer.relativeName(enum: descriptor) swiftFullName = namer.fullName(enum: descriptor) } func generateMainEnum(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\n") p.print(enumDescriptor.protoSourceComments()) p.print("\(visibility)enum \(swiftRelativeName): SwiftProtobuf.Enum {\n") p.indent() p.print("\(visibility)typealias RawValue = Int\n") // Cases/aliases generateCasesOrAliases(printer: &p) // Generate the default initializer. p.print("\n") p.print("\(visibility)init() {\n") p.indent() let dottedDefault = namer.dottedRelativeName(enumValue: enumDescriptor.defaultValue) p.print("self = \(dottedDefault)\n") p.outdent() p.print("}\n") p.print("\n") generateInitRawValue(printer: &p) p.print("\n") generateRawValueProperty(printer: &p) p.outdent() p.print("\n") p.print("}\n") } func generateRuntimeSupport(printer p: inout CodePrinter) { p.print("\n") p.print("extension \(swiftFullName): SwiftProtobuf._ProtoNameProviding {\n") p.indent() generateProtoNameProviding(printer: &p) p.outdent() p.print("}\n") } /// Generates the cases or statics (for alias) for the values. /// /// - Parameter p: The code printer. private func generateCasesOrAliases(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet for enumValueDescriptor in namer.uniquelyNamedValues(enum: enumDescriptor) { let comments = enumValueDescriptor.protoSourceComments() if !comments.isEmpty { p.print("\n", comments) } let relativeName = namer.relativeName(enumValue: enumValueDescriptor) if let aliasOf = enumValueDescriptor.aliasOf { let aliasOfName = namer.relativeName(enumValue: aliasOf) p.print("\(visibility)static let \(relativeName) = \(aliasOfName)\n") } else { p.print("case \(relativeName) // = \(enumValueDescriptor.number)\n") } } if enumDescriptor.hasUnknownPreservingSemantics { p.print("case \(unrecognizedCaseName)(Int)\n") } } /// Generates the mapping from case numbers to their text/JSON names. /// /// - Parameter p: The code printer. private func generateProtoNameProviding(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n") p.indent() for v in mainEnumValueDescriptorsSorted { if v.aliases.isEmpty { p.print("\(v.number): .same(proto: \"\(v.name)\"),\n") } else { let aliasNames = v.aliases.map({ "\"\($0.name)\"" }).joined(separator: ", ") p.print("\(v.number): .aliased(proto: \"\(v.name)\", aliases: [\(aliasNames)]),\n") } } p.outdent() p.print("]\n") } /// Generates `init?(rawValue:)` for the enum. /// /// - Parameter p: The code printer. private func generateInitRawValue(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)init?(rawValue: Int) {\n") p.indent() p.print("switch rawValue {\n") for v in mainEnumValueDescriptorsSorted { let dottedName = namer.dottedRelativeName(enumValue: v) p.print("case \(v.number): self = \(dottedName)\n") } if enumDescriptor.hasUnknownPreservingSemantics { p.print("default: self = .\(unrecognizedCaseName)(rawValue)\n") } else { p.print("default: return nil\n") } p.print("}\n") p.outdent() p.print("}\n") } /// Generates the `rawValue` property of the enum. /// /// - Parameter p: The code printer. private func generateRawValueProperty(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\(visibility)var rawValue: Int {\n") p.indent() p.print("switch self {\n") for v in mainEnumValueDescriptorsSorted { let dottedName = namer.dottedRelativeName(enumValue: v) p.print("case \(dottedName): return \(v.number)\n") } if enumDescriptor.hasUnknownPreservingSemantics { p.print("case .\(unrecognizedCaseName)(let i): return i\n") } p.print("}\n") p.outdent() p.print("}\n") } }
gpl-3.0
7286132a3c67a669f8c7d3cb6bc045c4
32.233333
91
0.661317
4.245564
false
false
false
false
alexking124/Picture-Map
Picture Map/RootTabBarController.swift
1
836
// // RootTabBarController.swift // Picture Map // // Created by Alex King on 11/17/16. // Copyright © 2016 Alex King. All rights reserved. // import UIKit import FirebaseAuth class RootTabBarController: UITabBarController { var authStateListenerToken: FIRAuthStateDidChangeListenerHandle? override func viewDidLoad() { super.viewDidLoad() self.tabBar.isHidden = true self.viewControllers = [MapViewController(), WelcomeViewController()] // Do any additional setup after loading the view. self.authStateListenerToken = FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in if user != nil { self.selectedIndex = 0 } else { self.selectedIndex = 1 } }) } }
mit
2fb80616bc16d26fcfed7c5e92421ee3
22.194444
97
0.608383
5.091463
false
false
false
false
jtbandes/swift
benchmark/single-source/LinkedList.swift
11
1233
//===--- LinkedList.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of linked lists. It is based on LinkedList from // utils/benchmark, with modifications for performance measuring. import TestsUtils final class Node { var next: Node? var data: Int init(n: Node?, d: Int) { next = n data = d } } @inline(never) public func run_LinkedList(_ N: Int) { let size = 100 var head = Node(n:nil, d:0) for i in 0..<size { head = Node(n:head, d:i) } var sum = 0 let ref_result = size*(size-1)/2 var ptr = head for _ in 1...5000*N { ptr = head sum = 0 while let nxt = ptr.next { sum += ptr.data ptr = nxt } if sum != ref_result { break } } CheckResults(sum == ref_result) }
apache-2.0
3026c7b685de62f554bb45e534d5c480
23.66
80
0.568532
3.865204
false
false
false
false
mali1488/Bluefruit_LE_Connect
Pods/Moscapsule/Moscapsule/Moscapsule.swift
1
17997
// // Moscapsule.swift // Moscapsule // // Created by flightonary on 2014/11/23. // // The MIT License (MIT) // // Copyright (c) 2014 tonary <[email protected]>. 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 Foundation public enum ReturnCode: Int { case Success = 0 case Unacceptable_Protocol_Version = 1 case Identifier_Rejected = 2 case Broker_Unavailable = 3 case NoConnection = 4 // Added by [email protected] case Connection_Refused = 5 // Added by [email protected] case Unknown = 256 public var description: String { switch self { case .Success: return "Success" case .Unacceptable_Protocol_Version: return "Unacceptable_Protocol_Version" case .Identifier_Rejected: return "Identifier_Rejected" case .Broker_Unavailable: return "Broker_Unavailable" case .NoConnection: // Added by [email protected] return "Connection Refused. Bad username or password" case .Connection_Refused: // Added by [email protected] return "Connection Refused. Not Authorized" case .Unknown: return "Unknown" } } } public enum ReasonCode: Int { case Disconnect_Requested = 0 case Unexpected = 1 public var description: String { switch self { case .Disconnect_Requested: return "Disconnect_Requested" case .Unexpected: return "Unexpected" } } } public enum MosqResult: Int { case MOSQ_CONN_PENDING = -1 case MOSQ_SUCCESS = 0 case MOSQ_NOMEM = 1 case MOSQ_PROTOCOL = 2 case MOSQ_INVAL = 3 case MOSQ_NO_CONN = 4 case MOSQ_CONN_REFUSED = 5 case MOSQ_NOT_FOUND = 6 case MOSQ_CONN_LOST = 7 case MOSQ_TLS = 8 case MOSQ_PAYLOAD_SIZE = 9 case MOSQ_NOT_SUPPORTED = 10 case MOSQ_AUTH = 11 case MOSQ_ACL_DENIED = 12 case MOSQ_UNKNOWN = 13 case MOSQ_ERRNO = 14 case MOSQ_EAI = 15 } public struct Qos { public static let At_Most_Once: Int32 = 0 // Fire and Forget, i.e. <=1 public static let At_Least_Once: Int32 = 1 // Acknowledged delivery, i.e. >=1 public static let Exactly_Once: Int32 = 2 // Assured delivery, i.e. =1 } public func moscapsule_init() { mosquitto_lib_init() } public func moscapsule_cleanup() { mosquitto_lib_cleanup() } public struct MQTTReconnOpts { public let reconnect_delay_s: UInt32 public let reconnect_delay_max_s: UInt32 public let reconnect_exponential_backoff: Bool public init() { self.reconnect_delay_s = 5 //5sec self.reconnect_delay_max_s = 60 * 30 //30min self.reconnect_exponential_backoff = true } public init(reconnect_delay_s: UInt32, reconnect_delay_max_s: UInt32, reconnect_exponential_backoff: Bool) { self.reconnect_delay_s = reconnect_delay_s self.reconnect_delay_max_s = reconnect_delay_max_s self.reconnect_exponential_backoff = reconnect_exponential_backoff } } public struct MQTTWillOpts { public let topic: String public let payload: NSData public let qos: Int32 public let retain: Bool public init(topic: String, payload: NSData, qos: Int32, retain: Bool) { self.topic = topic self.payload = payload self.qos = qos self.retain = retain } public init(topic: String, payload: String, qos: Int32, retain: Bool) { let rawPayload = payload.dataUsingEncoding(NSUTF8StringEncoding)! self.init(topic: topic, payload: rawPayload, qos: qos, retain: retain) } } public struct MQTTAuthOpts { public let username: String public let password: String public init(username: String, password: String) { self.username = username self.password = password } } public struct MQTTPublishOpts { public let max_inflight_messages: UInt32 public let message_retry: UInt32 public init(max_inflight_messages: UInt32, message_retry: UInt32) { self.max_inflight_messages = max_inflight_messages self.message_retry = message_retry } } public struct MQTTServerCert { public let cafile: String? public let capath: String? public init(cafile: String?, capath: String?) { self.cafile = cafile self.capath = capath } } public struct MQTTClientCert { public let certfile: String public let keyfile: String public let keyfile_passwd: String? public init(certfile: String, keyfile: String, keyfile_passwd: String?) { self.certfile = certfile self.keyfile = keyfile self.keyfile_passwd = keyfile_passwd } } public enum CertReqs: Int32 { case SSL_VERIFY_NONE = 0 case SSL_VERIFY_PEER = 1 } public struct MQTTTlsOpts { public let tls_insecure: Bool public let cert_reqs: CertReqs public let tls_version: String? public let ciphers: String? public init(tls_insecure: Bool, cert_reqs: CertReqs, tls_version: String?, ciphers: String?) { self.tls_insecure = tls_insecure self.cert_reqs = cert_reqs self.tls_version = tls_version self.ciphers = ciphers } } public struct MQTTPsk { public let psk: String public let identity: String public let ciphers: String? public init(psk: String, identity: String, ciphers: String?) { self.psk = psk self.identity = identity self.ciphers = ciphers } } public class MQTTConfig { public let clientId: String public let host: String public let port: Int32 public let keepAlive: Int32 public var cleanSession: Bool public var mqttReconnOpts: MQTTReconnOpts public var mqttWillOpts: MQTTWillOpts? public var mqttAuthOpts: MQTTAuthOpts? public var mqttPublishOpts: MQTTPublishOpts? public var mqttServerCert: MQTTServerCert? public var mqttClientCert: MQTTClientCert? public var mqttTlsOpts: MQTTTlsOpts? public var mqttPsk: MQTTPsk? public var onConnectCallback: ((returnCode: ReturnCode) -> ())! public var onDisconnectCallback: ((reasonCode: ReasonCode) -> ())! public var onPublishCallback: ((messageId: Int) -> ())! public var onMessageCallback: ((mqttMessage: MQTTMessage) -> ())! public var onSubscribeCallback: ((messageId: Int, grantedQos: Array<Int32>) -> ())! public var onUnsubscribeCallback: ((messageId: Int) -> ())! public init(clientId: String, host: String, port: Int32, keepAlive: Int32) { // MQTT client ID is restricted to 23 characters in the MQTT v3.1 spec self.clientId = { max in (clientId as NSString).length <= max ? clientId : clientId.substringToIndex(advance(clientId.startIndex, max)) }(Int(MOSQ_MQTT_ID_MAX_LENGTH)) self.host = host self.port = port self.keepAlive = keepAlive cleanSession = true mqttReconnOpts = MQTTReconnOpts() } } @objc(__MosquittoContext) public final class __MosquittoContext { public var mosquittoHandler: COpaquePointer = nil public var isConnected: Bool = false public var onConnectCallback: ((returnCode: Int) -> ())! public var onDisconnectCallback: ((reasonCode: Int) -> ())! public var onPublishCallback: ((messageId: Int) -> ())! public var onMessageCallback: ((message: UnsafePointer<mosquitto_message>) -> ())! public var onSubscribeCallback: ((messageId: Int, qosCount: Int, grantedQos: UnsafePointer<Int32>) -> ())! public var onUnsubscribeCallback: ((messageId: Int) -> ())! public var keyfile_passwd: String = "" internal init(){} } public final class MQTTMessage { public let messageId: Int public let topic: String public let payload: NSData public let qos: Int32 public let retain: Bool public var payloadString: String? { return NSString(data: payload, encoding: NSUTF8StringEncoding) as? String } internal init(messageId: Int, topic: String, payload: NSData, qos: Int32, retain: Bool) { self.messageId = messageId self.topic = topic self.payload = payload self.qos = qos self.retain = retain } } public final class MQTT { public class func newConnection(mqttConfig: MQTTConfig) -> MQTTClient { let mosquittoContext = __MosquittoContext() mosquittoContext.onConnectCallback = onConnectAdapter(mqttConfig.onConnectCallback) mosquittoContext.onDisconnectCallback = onDisconnectAdapter(mqttConfig.onDisconnectCallback) mosquittoContext.onPublishCallback = mqttConfig.onPublishCallback mosquittoContext.onMessageCallback = onMessageAdapter(mqttConfig.onMessageCallback) mosquittoContext.onSubscribeCallback = onSubscribeAdapter(mqttConfig.onSubscribeCallback) mosquittoContext.onUnsubscribeCallback = mqttConfig.onUnsubscribeCallback // setup mosquittoHandler mosquitto_context_setup(mqttConfig.clientId.cCharArray, mqttConfig.cleanSession, mosquittoContext) // set MQTT Reconnection Options mosquitto_reconnect_delay_set(mosquittoContext.mosquittoHandler, mqttConfig.mqttReconnOpts.reconnect_delay_s, mqttConfig.mqttReconnOpts.reconnect_delay_max_s, mqttConfig.mqttReconnOpts.reconnect_exponential_backoff) // set MQTT Will Options if let mqttWillOpts = mqttConfig.mqttWillOpts { mosquitto_will_set(mosquittoContext.mosquittoHandler, mqttWillOpts.topic.cCharArray, Int32(mqttWillOpts.payload.length), mqttWillOpts.payload.bytes, mqttWillOpts.qos, mqttWillOpts.retain) } // set MQTT Authentication Options if let mqttAuthOpts = mqttConfig.mqttAuthOpts { mosquitto_username_pw_set(mosquittoContext.mosquittoHandler, mqttAuthOpts.username.cCharArray, mqttAuthOpts.password.cCharArray) } // set MQTT Publish Options if let mqttPublishOpts = mqttConfig.mqttPublishOpts { mosquitto_max_inflight_messages_set(mosquittoContext.mosquittoHandler, mqttPublishOpts.max_inflight_messages) mosquitto_message_retry_set(mosquittoContext.mosquittoHandler, mqttPublishOpts.message_retry) } // set Server/Client Certificate if mqttConfig.mqttServerCert != nil || mqttConfig.mqttClientCert != nil { let sc = mqttConfig.mqttServerCert let cc = mqttConfig.mqttClientCert mosquittoContext.keyfile_passwd = cc?.keyfile_passwd ?? "" mosquitto_tls_set_bridge(sc?.cafile, sc?.capath, cc?.certfile, cc?.keyfile, mosquittoContext) } // set TLS Options if let mqttTlsOpts = mqttConfig.mqttTlsOpts { mosquitto_tls_insecure_set(mosquittoContext.mosquittoHandler, mqttTlsOpts.tls_insecure) mosquitto_tls_opts_set_bridge(mqttTlsOpts.cert_reqs.rawValue, mqttTlsOpts.tls_version, mqttTlsOpts.ciphers, mosquittoContext) } // set PSK if let mqttPsk = mqttConfig.mqttPsk { mosquitto_tls_psk_set_bridge(mqttPsk.psk, mqttPsk.identity, mqttPsk.ciphers, mosquittoContext) } // start MQTTClient let mqttClient = MQTTClient(mosquittoContext: mosquittoContext) let host = mqttConfig.host let port = mqttConfig.port let keepAlive = mqttConfig.keepAlive mqttClient.serialQueue.addOperationWithBlock { mosquitto_connect(mosquittoContext.mosquittoHandler, host.cCharArray, port, keepAlive) mosquitto_loop_start(mosquittoContext.mosquittoHandler) } return mqttClient } private class func onConnectAdapter(callback: ((ReturnCode) -> ())!) -> ((returnCode: Int) -> ())! { return callback == nil ? nil : { (rawReturnCode: Int) in callback(ReturnCode(rawValue: rawReturnCode) ?? ReturnCode.Unknown) } } private class func onDisconnectAdapter(callback: ((ReasonCode) -> ())!) -> ((reasonCode: Int) -> ())! { return callback == nil ? nil : { (rawReasonCode: Int) in callback(ReasonCode(rawValue: rawReasonCode) ?? ReasonCode.Unexpected) } } private class func onMessageAdapter(callback: ((MQTTMessage) -> ())!) -> ((UnsafePointer<mosquitto_message>) -> ())! { return callback == nil ? nil : { (rawMessage: UnsafePointer<mosquitto_message>) in let message = rawMessage.memory let topic = String.fromCString(message.topic)! let payload = NSData(bytes: message.payload, length: Int(message.payloadlen)) let mqttMessage = MQTTMessage(messageId: Int(message.mid), topic: topic, payload: payload, qos: message.qos, retain: message.retain) callback(mqttMessage) } } private class func onSubscribeAdapter(callback: ((Int, Array<Int32>) -> ())!) -> ((Int, Int, UnsafePointer<Int32>) -> ())! { return callback == nil ? nil : { (messageId: Int, qosCount: Int, grantedQos: UnsafePointer<Int32>) in var grantedQosList = [Int32](count: qosCount, repeatedValue: Qos.At_Least_Once) Array(0..<qosCount).reduce(grantedQos) { (qosPointer, index) in grantedQosList[index] = qosPointer.memory return qosPointer.successor() } callback(messageId, grantedQosList) } } } public final class MQTTClient { private let mosquittoContext: __MosquittoContext public private(set) var isFinished: Bool = false internal let serialQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "MQTT Client Operation Queue" queue.maxConcurrentOperationCount = 1 return queue }() public var isConnected: Bool { return mosquittoContext.isConnected } internal init(mosquittoContext: __MosquittoContext) { self.mosquittoContext = mosquittoContext } deinit { disconnect() } public func publish(payload: NSData, topic: String, qos: Int32, retain: Bool, requestCompletion: ((MosqResult, Int) -> ())? = nil) { serialQueue.addOperationWithBlock { if (!self.isFinished) { var messageId: Int32 = 0 let mosqReturn = mosquitto_publish(self.mosquittoContext.mosquittoHandler, &messageId, topic.cCharArray, Int32(payload.length), payload.bytes, qos, retain) requestCompletion?(MosqResult(rawValue: Int(mosqReturn)) ?? MosqResult.MOSQ_UNKNOWN, Int(messageId)) } } } public func publishString(payload: String, topic: String, qos: Int32, retain: Bool, requestCompletion: ((MosqResult, Int) -> ())? = nil) { if let payloadData = (payload as NSString).dataUsingEncoding(NSUTF8StringEncoding) { publish(payloadData, topic: topic, qos: qos, retain: retain, requestCompletion: requestCompletion) } } public func subscribe(topic: String, qos: Int32, requestCompletion: ((MosqResult, Int) -> ())? = nil) { serialQueue.addOperationWithBlock { if (!self.isFinished) { var messageId: Int32 = 0 let mosqReturn = mosquitto_subscribe(self.mosquittoContext.mosquittoHandler, &messageId, topic.cCharArray, qos) requestCompletion?(MosqResult(rawValue: Int(mosqReturn)) ?? MosqResult.MOSQ_UNKNOWN, Int(messageId)) } } } public func unsubscribe(topic: String, requestCompletion: ((MosqResult, Int) -> ())? = nil) { serialQueue.addOperationWithBlock { if (!self.isFinished) { var messageId: Int32 = 0 let mosqReturn = mosquitto_unsubscribe(self.mosquittoContext.mosquittoHandler, &messageId, topic.cCharArray) requestCompletion?(MosqResult(rawValue: Int(mosqReturn)) ?? MosqResult.MOSQ_UNKNOWN, Int(messageId)) } } } public func disconnect() { if (!isFinished) { isFinished = true let context = mosquittoContext serialQueue.addOperationWithBlock { mosquitto_disconnect(context.mosquittoHandler) mosquitto_loop_stop(context.mosquittoHandler, false) mosquitto_context_cleanup(context) } } } public func awaitRequestCompletion() { serialQueue.waitUntilAllOperationsAreFinished() } public var socket: Int32? { let sock = mosquitto_socket(mosquittoContext.mosquittoHandler) return (sock == -1 ? nil : sock) } } private extension String { var cCharArray: [CChar] { return self.cStringUsingEncoding(NSUTF8StringEncoding)! } }
bsd-3-clause
6ef3b504b7bf557b18109d5e8eac3ed6
36.890526
144
0.657276
4.115481
false
true
false
false
haawa799/WaniPersistance
WaniPersistance/SRSLevelInfo.swift
1
1039
// // SRSLevelInfo.swift // WaniKani // // Created by Andriy K. on 3/31/17. // Copyright © 2017 haawa. All rights reserved. // import Foundation import WaniModel import RealmSwift class SRSLevelInfo: Object { dynamic var radicals: Int = 0 dynamic var kanji: Int = 0 dynamic var vocabulary: Int = 0 dynamic var total: Int = 0 dynamic var label: String = "" override static func primaryKey() -> String? { return "label" } convenience init(srs: WaniModel.SRSLevelInfo, label: String) { self.init() self.label = label self.radicals = srs.radicals self.kanji = srs.kanji self.vocabulary = srs.vocabulary self.total = srs.total } var waniModelStruct: WaniModel.SRSLevelInfo { return WaniModel.SRSLevelInfo(realmObject: self) } } extension WaniModel.SRSLevelInfo { init(realmObject: WaniPersistance.SRSLevelInfo) { self.radicals = realmObject.radicals self.kanji = realmObject.kanji self.vocabulary = realmObject.vocabulary self.total = realmObject.total } }
mit
3338a2ed1378540ed024261b2b1a1790
21.085106
64
0.701349
3.56701
false
false
false
false
HarwordLiu/Ing.
Ing/Ing/Operations/CKSubscriptionOperations/FetchAllSubscriptionsOperation.swift
1
1356
// // FetchAllSubscriptionsOperation.swift // CloudKitSyncPOC // // Created by Nick Harris on 1/18/16. // Copyright © 2016 Nick Harris. All rights reserved. // import CloudKit class FetchAllSubscriptionsOperation: CKFetchSubscriptionsOperation { var fetchedSubscriptions: [String : CKSubscription] override init() { fetchedSubscriptions = [:] super.init() } override func main() { print("FetchAllSubscriptionsOperation.main()") setOperationBlocks() super.main() } func setOperationBlocks() { fetchSubscriptionCompletionBlock = { [unowned self] (subscriptions: [String : CKSubscription]?, error: NSError?) -> Void in print("FetchAllSubscriptionsOperation.fetchRecordZonesCompletionBlock") if let error = error { print("FetchAllRecordZonesOperation error: \(error)") } if let subscriptions = subscriptions { self.fetchedSubscriptions = subscriptions for subscriptionID in subscriptions.keys { print("Fetched CKSubscription: \(subscriptionID)") } } } as? ([String : CKSubscription]?, Error?) -> Void } }
mit
8aedb42a2b5e09c0958503282c884c73
26.653061
83
0.571956
5.530612
false
false
false
false
benlangmuir/swift
stdlib/public/core/BuiltinMath.swift
25
4006
//===--- BuiltinMath.swift --------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // Each of the following functions is ordered to match math.h // These functions have a corresponding LLVM intrinsic. // Note, keep this up to date with Darwin/tgmath.swift.gyb // Order of intrinsics: cos, sin, exp, exp2, log, log10, log2, nearbyint, rint // Float Intrinsics (32 bits) @_transparent public func _cos(_ x: Float) -> Float { return Float(Builtin.int_cos_FPIEEE32(x._value)) } @_transparent public func _sin(_ x: Float) -> Float { return Float(Builtin.int_sin_FPIEEE32(x._value)) } @_transparent public func _exp(_ x: Float) -> Float { return Float(Builtin.int_exp_FPIEEE32(x._value)) } @_transparent public func _exp2(_ x: Float) -> Float { return Float(Builtin.int_exp2_FPIEEE32(x._value)) } @_transparent public func _log(_ x: Float) -> Float { return Float(Builtin.int_log_FPIEEE32(x._value)) } @_transparent public func _log10(_ x: Float) -> Float { return Float(Builtin.int_log10_FPIEEE32(x._value)) } @_transparent public func _log2(_ x: Float) -> Float { return Float(Builtin.int_log2_FPIEEE32(x._value)) } @_transparent public func _nearbyint(_ x: Float) -> Float { return Float(Builtin.int_nearbyint_FPIEEE32(x._value)) } @_transparent public func _rint(_ x: Float) -> Float { return Float(Builtin.int_rint_FPIEEE32(x._value)) } // Double Intrinsics (64 bits) @_transparent public func _cos(_ x: Double) -> Double { return Double(Builtin.int_cos_FPIEEE64(x._value)) } @_transparent public func _sin(_ x: Double) -> Double { return Double(Builtin.int_sin_FPIEEE64(x._value)) } @_transparent public func _exp(_ x: Double) -> Double { return Double(Builtin.int_exp_FPIEEE64(x._value)) } @_transparent public func _exp2(_ x: Double) -> Double { return Double(Builtin.int_exp2_FPIEEE64(x._value)) } @_transparent public func _log(_ x: Double) -> Double { return Double(Builtin.int_log_FPIEEE64(x._value)) } @_transparent public func _log10(_ x: Double) -> Double { return Double(Builtin.int_log10_FPIEEE64(x._value)) } @_transparent public func _log2(_ x: Double) -> Double { return Double(Builtin.int_log2_FPIEEE64(x._value)) } @_transparent public func _nearbyint(_ x: Double) -> Double { return Double(Builtin.int_nearbyint_FPIEEE64(x._value)) } @_transparent public func _rint(_ x: Double) -> Double { return Double(Builtin.int_rint_FPIEEE64(x._value)) } // Float80 Intrinsics (80 bits) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) @_transparent public func _cos(_ x: Float80) -> Float80 { return Float80(Builtin.int_cos_FPIEEE80(x._value)) } @_transparent public func _sin(_ x: Float80) -> Float80 { return Float80(Builtin.int_sin_FPIEEE80(x._value)) } @_transparent public func _exp(_ x: Float80) -> Float80 { return Float80(Builtin.int_exp_FPIEEE80(x._value)) } @_transparent public func _exp2(_ x: Float80) -> Float80 { return Float80(Builtin.int_exp2_FPIEEE80(x._value)) } @_transparent public func _log(_ x: Float80) -> Float80 { return Float80(Builtin.int_log_FPIEEE80(x._value)) } @_transparent public func _log10(_ x: Float80) -> Float80 { return Float80(Builtin.int_log10_FPIEEE80(x._value)) } @_transparent public func _log2(_ x: Float80) -> Float80 { return Float80(Builtin.int_log2_FPIEEE80(x._value)) } @_transparent public func _nearbyint(_ x: Float80) -> Float80 { return Float80(Builtin.int_nearbyint_FPIEEE80(x._value)) } @_transparent public func _rint(_ x: Float80) -> Float80 { return Float80(Builtin.int_rint_FPIEEE80(x._value)) } #endif
apache-2.0
d7e2d83222634025efa5f88d83ab7afd
23.881988
80
0.675237
3.166798
false
false
false
false
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Data/ChartData.swift
3
24895
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(start start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis let firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis let firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += fabs(_dataSets[i].yValueSum) } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// - returns: the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// - returns: the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// - returns: the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// - returns: the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// - returns: the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// - returns: the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// - returns: the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// - returns: the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// /// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.** /// /// - parameter dataSets: the DataSet array to search /// - parameter type: /// - parameter ignorecase: if true, the search is not case-sensitive /// - returns: the index of the DataSet Object with the given label. Sensitive or not. internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// - returns: the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// - returns: the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// - parameter highlight: /// - returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.** /// /// - parameter label: /// - parameter ignorecase: /// - returns: the DataSet Object with the given label. Sensitive or not. public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { let index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } let d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { let val = e.value let set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { let val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. /// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { let set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// - returns: all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { let clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. /// - returns: true if so, false if not. public func contains(entry entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. /// - returns: true if so, false if not. public func contains(dataSet dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// - returns: the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
mit
3d954be34858f5b93b317ebd6879f223
25.597222
138
0.472866
5.196201
false
false
false
false
malaonline/iOS
mala-ios/Model/StudyReport/SingleAbilityData.swift
1
1559
// // SingleAbilityData.swift // mala-ios // // Created by 王新宇 on 16/5/31. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit class SingleAbilityData: NSObject { // MARK: - Property /// 能力名称(简略) var key: String = "" /// 数值 var val: Int = 0 { didSet { if val == 0 { val = 1 } } } /// 能力 var ability: MalaStudyReportAbility { get { return MalaStudyReportAbility(rawValue: key) ?? .unkown } } /// 能力字符串 var abilityString: String { get { switch ability { case .abstract: return "抽象概括" case .reason: return "推理论证" case .appl: return "实际应用" case .spatial: return "空间想象" case .calc: return "运算求解" case .data: return "数据分析" case .unkown: return "" } } } // MARK: - Constructed override init() { super.init() } init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } convenience init(key: String, value: Int) { self.init() self.key = key self.val = value } }
mit
2201e4d17b1f1dc5d9a81fc3ec02a8c7
18.573333
67
0.405995
4.448485
false
false
false
false
hardikdevios/HKKit
Pod/Classes/HKExtras/HKNibView.swift
1
1161
// // HKNibView.swift // Genemedics // // Created by Praxinfo on 10/08/16. // Copyright © 2016 Praxinfo. All rights reserved. // import Foundation import UIKit #if canImport(Cartography) import Cartography open class HKNibView: UIView { weak var view: UIView! open var nibName: String? { return String(describing: type(of: self)) } override public init(frame: CGRect) { super.init(frame: frame) nibSetup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) nibSetup() } fileprivate func nibSetup() { view = loadViewFromNib() addSubview(view) constrain(view) { (view) in view.edges == inset(view.superview!.edges, 0, 0, 0, 0) } } fileprivate func loadViewFromNib() -> UIView { guard let nibName = nibName else { return UIView() } let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView return nibView } } #endif
mit
9965dc5f76e500d054422f98ad0725b1
19
85
0.601724
4.027778
false
false
false
false
mtransitapps/mtransit-for-ios
MonTransit/Source/SQL/SQLHelper/ServiceDateDataProvider.swift
1
3964
// // ServiceDateDataProvider.swift // MonTransit // // Created by Thibault on 16-01-07. // Copyright © 2016 Thibault. All rights reserved. // import UIKit import SQLite class ServiceDateDataProvider { private let service_dates = Table("service_dates") private let service_id = Expression<String>("service_id") private let date = Expression<Int>("date") init() { } func createServiceDate(iAgency:Agency, iSqlCOnnection:Connection) -> Bool { do { let wServiceRawType = iAgency.getMainFilePath() let wFileText = iAgency.getZipData().getDataFileFromZip(iAgency.mGtfsServiceDate, iDocumentName: wServiceRawType) if wFileText != "" { let wServices = wFileText.stringByReplacingOccurrencesOfString("'", withString: "").componentsSeparatedByString("\n") let docsTrans = try! iSqlCOnnection.prepare("INSERT INTO service_dates (service_id, date) VALUES (?,?)") try iSqlCOnnection.transaction { for wService in wServices { let wServiceFormated = wService.componentsSeparatedByString(",") if wServiceFormated.count == 2{ try docsTrans.run(wServiceFormated[0], Int(wServiceFormated[1])!) } } } } return true } catch { print("insertion failed: \(error)") return false } } func retrieveCurrentService(iId:Int) -> [String] { // get the user's calendar let userCalendar = NSCalendar.currentCalendar() // choose which date and time components are needed let requestedComponents: NSCalendarUnit = [ NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day ] // get the components let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: NSDate()) let wYear = dateTimeComponents.year let wMonth = dateTimeComponents.month let wDay = dateTimeComponents.day //Verify if the current date is in DB let wDate = getDatesLimit(iId) let wTimeString = String(format: "%04d", wYear) + String(format: "%02d", wMonth) + String(format: "%02d", wDay) var wTimeInt = Int(wTimeString)! if wDate.max.getNSDate().getDateToInt() < wTimeInt{ wTimeInt = wDate.max.getNSDate().getDateToInt() } let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == wTimeInt)) var wCurrentService = [String]() for wService in wServices { wCurrentService.append(wService.get(service_id)) } return wCurrentService } func retrieveCurrentServiceByDate(iDate:Int, iId:Int) -> [String] { let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == iDate)) var wCurrentServices = [String]() for wService in wServices { wCurrentServices.append(wService.get(service_id)) } return wCurrentServices } func getDatesLimit(iId:Int) ->(min:GTFSTimeObject, max:GTFSTimeObject){ var min:GTFSTimeObject! var max:GTFSTimeObject! var wGtfsList:[GTFSTimeObject] = [] let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates) for wService in wServices{ wGtfsList.append(GTFSTimeObject(iGtfsDate: wService[date])) } min = wGtfsList.first max = wGtfsList.last return (min,max) } }
apache-2.0
d46e83bdb9485babb019872db8a3f7dc
31.491803
133
0.575322
4.565668
false
false
false
false
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwift/Classes/Send/Controller/YBSendViewController.swift
1
11369
// // YBSendViewController.swift // weiBoSwift // // Created by MAC on 15/12/9. // Copyright © 2015年 MAC. All rights reserved. // import UIKit import SVProgressHUD class YBSendViewController: UIViewController { // MARK: - 属性 /// toolBar底边约束 var toolBarConstant: NSLayoutConstraint? /// 点击图片的索引(如果是直接添加图片索引为100) private var imageIndex = 100 // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() // 准备UI prepareUI() // 通知 setterNotification() } // MARK: - 通知 private func setterNotification(){ // weak var weakSelf = self // // textView文字改变通知 // NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: nil, queue: nil) {[unowned self] (_) -> Void in // weakSelf?.navigationItem.rightBarButtonItem?.enabled = self.textView.text.characters.count != 0 // } // // // 监听键盘代理 // NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) {[unowned self] (notification) -> Void in // // 获取时间 // let time = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval // // 获取变化后的位置 // let kayboardY = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue.origin.y // // weakSelf?.toolBarConstant?.constant = -(UIScreen.height() - kayboardY) // // 动画 // UIView.animateWithDuration(time, animations: {[unowned self] () -> Void in // self.toolBar.layoutIfNeeded() // }) // } NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChangeNotification", name: UITextViewTextDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrameNotification:", name: UIKeyboardWillChangeFrameNotification, object: nil) // 相册展现通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "popImageLib:", name: "YBSendImageViewPresentNotification", object: nil) } func textViewTextDidChangeNotification (){ navigationItem.rightBarButtonItem?.enabled = self.textView.text.characters.count != 0 } func keyboardWillChangeFrameNotification (notification: NSNotification){ // 获取时间 let time = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval // 获取变化后的位置 let kayboardY = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue.origin.y self.toolBarConstant?.constant = -(UIScreen.height() - kayboardY) // 动画 UIView.animateWithDuration(time, animations: {[unowned self] () -> Void in self.toolBar.layoutIfNeeded() }) } // MARK: - 准备UI private func prepareUI(){ // 设置导航栏 setNavBar() // textView view.addSubview(textView); textView.ff_Fill(view) // toolBar view.addSubview(toolBar) let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44), offset: CGPoint(x: 0, y: 0)) // 获取底边约束 toolBarConstant = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom) } /// 设置导航栏 private func setNavBar(){ // 设置左边按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "leftBarButtonItemClick") // 设置右边导航栏 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "rightBarButtonItemClick") navigationItem.rightBarButtonItem?.enabled = false // 设置中间 navigationItem.titleView = navCenterView } // MARK: - 按钮点击事件 /// 导航栏左边按钮点击 @objc private func leftBarButtonItemClick(){ textView.resignFirstResponder() dismissViewControllerAnimated(true, completion: nil) } /// 导航栏右边按钮点击 @objc private func rightBarButtonItemClick(){ var text: String = "" textView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: textView.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) {[unowned self] (dic, range, _) -> Void in if dic["NSAttachment"] != nil { // 附件 text += (dic["NSAttachment"] as! YBTextAttachment).emotionName! } else { // 普通通文字或者emoji // 获取属性字符串 text += (self.textView.attributedText.string as NSString).substringWithRange(range) } } // 发微薄(判断是否有图片) if textView.imageCollectionView.dataArr.count > 1 { // 有图片 YBNetworking.sharedInstance.sendWeiBo(text, image: textView.imageCollectionView.dataArr[0], finish: { (isSeccess) -> () in if isSeccess { SVProgressHUD.showSuccessWithStatus("发送成功") } else{ SVProgressHUD.showErrorWithStatus("发送失败") } }) } else { // 没有图片 YBNetworking.sharedInstance.sendWeiBo(text) { (isSeccess) -> () in if isSeccess { SVProgressHUD.showSuccessWithStatus("发送成功") } else{ SVProgressHUD.showErrorWithStatus("发送失败") } } } } // MARK: - 弹出图片库 @objc private func popImageLib(notification: NSNotification){ // 判断是否有数据 if notification.userInfo != nil { imageIndex = Int(notification.userInfo!["index"] as! NSNumber) }else{ imageIndex = 100 } // 判断图片相册是否可用 if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { SVProgressHUD.showErrorWithStatus("相册不可用") return } // 创建图片控制器 let imagePicker = UIImagePickerController() // 设置代理 imagePicker.delegate = self // 展现 presentViewController(imagePicker, animated: true, completion: nil) } // MARK: - 懒加载 /// 导航栏中间 private lazy var navCenterView: UILabel = { let lable = UILabel() let text = "xxx" let attStr = NSMutableAttributedString(string: text) attStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(14), NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSRange(location: 0, length:3)) attStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(12), NSForegroundColorAttributeName:UIColor.grayColor()], range: NSRange(location: 3, length: text.characters.count - 3)) lable.attributedText = attStr lable.numberOfLines = 0 lable.textAlignment = .Center lable.sizeToFit() return lable }() /// textView private lazy var textView: YBSendTextView = { let textView = YBSendTextView() return textView; }() /// 工具条 private lazy var toolBar: YBSendToolBar = { let toolBar = YBSendToolBar() toolBar.ybDelegate = self return toolBar }() /// 对象销毁 deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } /// 代理 extension YBSendViewController: YBSendToolBarDelegate, YBEmotionKeyboardViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { /// 工具条点击代理 func sendToolBar(toolBar: YBSendToolBar, clickStatus: YBSendToolBarStatus) { // 判断当前状态 if clickStatus == YBSendToolBarStatus.Emotion { // 表情 textView.resignFirstResponder() let inputView = YBEmotionKeyboardView.sharedInstance inputView.ybDelegate = self textView.inputView = inputView // 通知textView复位 inputView.reset() textView.becomeFirstResponder() } else if clickStatus == .Keyboard { // 键盘 textView.resignFirstResponder() textView.inputView = nil textView.becomeFirstResponder() } else if clickStatus == .Picture { // 图片 // 图片点击通知 NSNotificationCenter.defaultCenter().postNotificationName("YBSendToolBarImageClickNotification", object: nil) } } /// 点击表情调用 func emotionKeyboardView(keyboardView: YBEmotionKeyboardView, emotionModel: YBEmotionModel) { // 判断删除按钮 if emotionModel.deleteStr != nil { textView.deleteBackward() return } // emoji 表情 if emotionModel.code != nil { textView.insertText(emotionModel.code!) return } //------- 普通表情 ---------// // 创建附件 let textAttachment = YBTextAttachment() // 设置文字 textAttachment.emotionName = emotionModel.chs // 添加图片 textAttachment.image = UIImage(named: emotionModel.png!) // 获取字体高度 let textHeight = textView.font!.lineHeight // 设置附件大小 textAttachment.bounds = CGRect(x: 0, y: -5, width: textHeight, height: textHeight) // 创建属性字符串 let newAttStr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textAttachment)) // 设置属性字符串大小 newAttStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSRange(location: 0, length: 1)) // 获取文本属性字符串 let oldAttStr = NSMutableAttributedString(attributedString: textView.attributedText) // 插入数据 oldAttStr.replaceCharactersInRange(textView.selectedRange, withAttributedString: newAttStr) // 赋值 textView.attributedText = oldAttStr // 手动发送通知(占位符) textView.textViewDidChange(textView) NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil) } // MARK: - 图片展现代理 func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { // 宽度 let minImage = image.image(300, maxHeight: 300) // 通知讲图片发送过去 NSNotificationCenter.defaultCenter().postNotificationName("UIImagePickerControllerGetImageNotification", object: nil, userInfo: ["image" : minImage, "index": imageIndex]) // 退出 picker.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
5e4eaf012ee13a263f5a07713cccdd22
38.570896
223
0.634795
5.173171
false
false
false
false
Maslor/swift-cannon
swift-cannon/GameScene.swift
1
3320
// // GameScene.swift // swift-cannon // // Created by Gabriel Freire on 11/02/16. // Copyright (c) 2016 maslor. All rights reserved. // import SpriteKit let wallMask:UInt32 = 0x1 << 0 // 1 let ballMask:UInt32 = 0x1 << 1 // 1 let pegMask:UInt32 = 0x1 << 2 // 4 let squareMask:UInt32 = 0x1 << 3 // 8 let orangePegMask:UInt32 = 0x1 << 4 //16 class GameScene: SKScene, SKPhysicsContactDelegate { var cannon: SKSpriteNode! var touchLocation: CGPoint = CGPointZero override func didMoveToView(view: SKView) { /* Setup your scene here */ cannon = self.childNodeWithName("cannon") as? SKSpriteNode self.physicsWorld.contactDelegate = self } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ touchLocation = touches.first!.locationInNode(self) } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ touchLocation = touches.first!.locationInNode(self) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { let ball: SKSpriteNode = SKScene(fileNamed: "Ball")?.childNodeWithName("ball")! as! SKSpriteNode ball.removeFromParent() self.addChild(ball) ball.position = cannon.position ball.zPosition = 0 let angleInRadians = Float(cannon.zRotation) let speed = CGFloat(75.0) let vx: CGFloat = CGFloat(cosf(angleInRadians)) * speed let vy: CGFloat = CGFloat(sinf(angleInRadians)) * speed ball.physicsBody?.applyImpulse(CGVectorMake(vx, vy), atPoint: ball.position) ball.physicsBody?.collisionBitMask = wallMask | ballMask | pegMask | orangePegMask ball.physicsBody?.contactTestBitMask = ball.physicsBody!.collisionBitMask | squareMask } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ let percent = touchLocation.x / size.width let newAngle = percent * 180 - 180 cannon?.zRotation = CGFloat(newAngle) * CGFloat(M_PI) / 180.0 } func didBeginContact(contact: SKPhysicsContact) { let ball = (contact.bodyA.categoryBitMask == ballMask) ? contact.bodyA : contact.bodyB let other = (ball == contact.bodyA) ? contact.bodyB : contact.bodyA if other.categoryBitMask == pegMask || other.categoryBitMask == orangePegMask{ self.didHitPeg(other) } else if other.categoryBitMask == squareMask { print("hit square!") } else if other.categoryBitMask == wallMask { print("hit wall!") } else if other.categoryBitMask == ballMask { print("hit ball!") } } func didHitPeg(peg:SKPhysicsBody) { let blue = UIColor(red: 0.16, green: 0.73, blue: 0.78, alpha: 1.0) let orange = UIColor(red: 1.0, green: 0.45, blue: 0.0, alpha: 1.0) let flame:SKEmitterNode = SKEmitterNode(fileNamed: "Fire")! flame.position = peg.node!.position flame.particleColor = (peg.categoryBitMask == orangePegMask) ? orange : blue self.addChild(flame) peg.node?.removeFromParent() } }
unlicense
bc32fc5e3d0bc5d481551f98c44f947e
36.303371
104
0.634639
4.234694
false
false
false
false
CraigZheng/KomicaViewer
KomicaViewer/KomicaViewer/View/UIViewController+ProgressBar.swift
1
2142
// // UIViewController+ProgressBar.swift // Exellency // // Created by Craig Zheng on 5/04/2016. // Copyright © 2016 cz. All rights reserved. // import Foundation extension UIViewController { func showLoading() { hideLoading() DLog("showLoading()") let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicator.startAnimating() let indicatorBarButtonItem = UIBarButtonItem(customView: activityIndicator) if var rightBarButtonItems = navigationItem.rightBarButtonItems { rightBarButtonItems.append(indicatorBarButtonItem) navigationItem.rightBarButtonItems = rightBarButtonItems } else { navigationItem.rightBarButtonItem = indicatorBarButtonItem } } func hideLoading() { DLog("hideLoading()") if let rightBarButtonItems = navigationItem.rightBarButtonItems { var BarButtonItemsWithoutActivityIndicator = rightBarButtonItems for button in rightBarButtonItems { if let customView = button.customView { if customView.isKind(of: UIActivityIndicatorView.self) { // Remove the bar button with an activity indicator as the custom view. BarButtonItemsWithoutActivityIndicator.removeObject(button) } } } // At the end, if the count of the array without activity indicator is different than the original array, // then assign the modified array to the menu bar. if BarButtonItemsWithoutActivityIndicator.count != rightBarButtonItems.count { navigationItem.rightBarButtonItems = BarButtonItemsWithoutActivityIndicator } } } } extension RangeReplaceableCollection where Iterator.Element : Equatable { // Remove first collection element that is equal to the given `object`: mutating func removeObject(_ object : Iterator.Element) { if let index = self.index(of: object) { self.remove(at: index) } } }
mit
30afe5f357ebeb4c4b978cf38f81dab8
37.927273
117
0.654367
6.082386
false
false
false
false
dsxNiubility/SXSwiftWeibo
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/String+Hash.swift
1
877
/// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入 /// #import <CommonCrypto/CommonCrypto.h> /// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入 import Foundation extension String { /// 返回字符串的 MD5 散列结果 var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.dealloc(digestLen) return hash.copy() as! String } }
mit
68a99cf631a673bd864187d65660f83c
29.52
83
0.623853
4.015789
false
false
false
false
bradwoo8621/Swift-Study
Instagram/Instagram/SignUpViewController.swift
1
10653
// // SignUpViewController.swift // Instagram // // Created by brad.wu on 2017/4/7. // Copyright © 2017年 bradwoo8621. All rights reserved. // import UIKit import AVOSCloud class SignUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // Image View, 头像 @IBOutlet weak var avaImg: UIImageView! // Text Fields @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var passwordTxt: UITextField! @IBOutlet weak var repeatPasswordTxt: UITextField! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var fullnameTxt: UITextField! @IBOutlet weak var bioTxt: UITextField! @IBOutlet weak var webTxt: UITextField! // Scroll View @IBOutlet weak var scrollView: UIScrollView! // 根据需要, 设置Scroll的高度 var scrollViewHeight: CGFloat = 0 var keyboard: CGRect = CGRect() // Buttons @IBOutlet weak var signupBtn: UIButton! @IBOutlet weak var cancelBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // scroll view 的窗口尺寸 scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) // or as below, 设置成为主屏幕的尺寸 // scrollView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) scrollView.contentSize.height = self.view.frame.height scrollViewHeight = self.view.frame.height // 检测键盘出现或者消失状态 NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard), name: Notification.Name.UIKeyboardWillHide, object: nil) // 定义隐藏虚拟键盘操作 let hideTap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardTap)) // 只需要点击一次 hideTap.numberOfTapsRequired = 1 // 将当前视图开放用户操作 self.view.isUserInteractionEnabled = true // 添加事件监听 self.view.addGestureRecognizer(hideTap) // 定义头像点击事件 let imgTap = UITapGestureRecognizer(target: self, action: #selector(loadImg)) imgTap.numberOfTapsRequired = 1 avaImg.isUserInteractionEnabled = true avaImg.addGestureRecognizer(imgTap) // 让头像变成圆形 avaImg.layer.cornerRadius = avaImg.frame.width / 2 avaImg.clipsToBounds = true // 布局 avaImg.frame = CGRect(x: self.view.frame.width / 2 - 40, y: 40, width: 80, height: 80) let viewWidth = self.view.frame.width; usernameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y + 90, width: viewWidth - 20, height: 30) passwordTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30) repeatPasswordTxt.frame = CGRect(x: 10, y: passwordTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30) emailTxt.frame = CGRect(x: 10, y: repeatPasswordTxt.frame.origin.y + 60, width: viewWidth - 20, height: 30) fullnameTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30) bioTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30) webTxt.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 40, width: viewWidth - 20, height: 30) signupBtn.frame = CGRect(x: 20, y: webTxt.frame.origin.y + 50, width: viewWidth / 4, height: 30) cancelBtn.frame = CGRect(x: viewWidth - viewWidth / 4 - 20, y: signupBtn.frame.origin.y, width: viewWidth / 4, height: 30) let bg = UIImageView(frame: CGRect(x:0, y:0, width: self.view.frame.width, height: self.view.frame.height)) bg.image = UIImage(named: "bg.jpg") bg.layer.zPosition = -1 self.view.addSubview(bg) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signupButton_clicked(_ sender: UIButton) { // 隐藏虚拟键盘 self.view.endEditing(true) if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || repeatPasswordTxt.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty || bioTxt.text!.isEmpty || webTxt.text!.isEmpty { let alert = UIAlertController(title: "Alert", message: "Fill all fields", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) return } if passwordTxt.text != repeatPasswordTxt.text { let alert = UIAlertController(title: "Alert", message: "Password mismatch", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) return } // AVUser是LeanCloud的对象 let user = AVUser() user.username = usernameTxt.text?.lowercased() user.email = emailTxt.text?.lowercased() user.password = passwordTxt.text // 以下属性不是AVUser的标准属性, 只能通过[]来添加, 不能直接dot user["fullname"] = fullnameTxt.text?.lowercased() user["bio"] = bioTxt.text?.lowercased() user["web"] = webTxt.text?.lowercased() user["gender"] = "" // 头像数据 let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5) let avaFile = AVFile(name: "ava.jpg", data: avaData!) user["ava"] = avaFile // 提交数据 user.signUpInBackground { (success: Bool, error: Error?) in if success { print("用户注册成功") AVUser.logInWithUsername(inBackground: user.username!, password: user.password!, block: { (user: AVUser?, error: Error?) in if let user = user { // 记录用户名 UserDefaults.standard.set(user.username, forKey: "username") // 立刻同步到磁盘上, 如果不调用, 则系统自行决定什么写入到磁盘 UserDefaults.standard.synchronize() let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.login() } }) } else { print(error?.localizedDescription as Any) } } } @IBAction func cancelButton_clicked(_ sender: UIButton) { // 动画方式去除通过modally方式添加的控制器 self.view.endEditing(true) self.dismiss(animated: true, completion: nil) } func showKeyboard(notification: Notification) { // 定义keyboard尺寸 let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue keyboard = rect.cgRectValue // 虚拟键盘出现以后, 将视图实际高度缩小为屏幕高度减去键盘的高度 UIView.animate(withDuration: 0.4) { print(self.scrollViewHeight) print(self.keyboard.size.height) self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.size.height print(self.scrollView.frame.size.height) } } func hideKeyboard(notification: Notification) { // 虚拟键盘消失后, 将视图实际高度修改为屏幕高度 UIView.animate(withDuration: 0.4) { self.scrollView.frame.size.height = self.view.frame.height } } // 响应当前视图点击事件, 隐藏虚拟键盘 func hideKeyboardTap(recognizer: UITapGestureRecognizer) { self.view.endEditing(true) } // 响应头像点击事件, 打开相册 // 需要在Info.plist中增加关于使用照片库的声明 func loadImg(recognizer: UITapGestureRecognizer) { let picker = UIImagePickerController() picker.delegate = self // 指定来源为照片库 picker.sourceType = .photoLibrary // 指可以编辑 picker.allowsEditing = true present(picker, animated: true, completion: nil) } // 响应选取照片库 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 选择经过裁剪的图像 avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage // UIImagePickerControllerOriginalImage // 选择的原始图像, 未经裁剪 // UIImagePickerContollerMediaURL // 文件系统中影片的URL // UIImagePickerControllerCropRect // 应用到原始图像当中裁剪的矩形 // UIImagePikcerControllerMediaType // 用户选择的图像的类型, 包括kUTTypeImage和kUTTypeMovie self.dismiss(animated: true, completion: nil) } // 响应取消选取照片 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
e9f703a52e6a35ebef7ca2ed64f8ea8c
35.477941
120
0.588591
4.223925
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXResult/New UI/PixCode/Views/InstructionActionView.swift
1
3282
import UIKit final class InstructionActionView: UIView { // MARK: - Private properties private weak var delegate: ActionViewDelegate? private let mainStack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.alignment = .leading stack.spacing = 8 return stack }() private let instructionLabel: UILabel = { let label = UILabel() label.font = UIFont.ml_regularSystemFont(ofSize: 16) label.numberOfLines = 0 return label }() private let codeBorderView: UIView = { let view = UIView() view.backgroundColor = .clear view.layer.borderColor = UIColor.black.withAlphaComponent(0.05).cgColor view.layer.borderWidth = 1 view.layer.cornerRadius = 6 return view }() private let codeLabel: UILabel = { let label = UILabel() label.font = UIFont.ml_semiboldSystemFont(ofSize: 16) label.textColor = UIColor.black.withAlphaComponent(0.45) label.textAlignment = .left return label }() private let actionButton: ActionView // MARK: - Initialization init(instruction: PXInstructionInteraction, delegate: ActionViewDelegate?) { self.actionButton = ActionView(action: instruction.action, delegate: delegate) self.delegate = delegate super.init(frame: .zero) setupInfos(with: instruction) setupViewConfiguration() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private methods private func setupInfos(with instruction: PXInstructionInteraction) { instructionLabel.attributedText = instruction.title?.htmlToAttributedString?.with(font: instructionLabel.font) codeBorderView.isHidden = instruction.content == nil || instruction.content == "" codeLabel.numberOfLines = instruction.showMultiLine ? 0 : 1 codeLabel.text = instruction.content } } extension InstructionActionView: ViewConfiguration { func buildHierarchy() { addSubviews(views: [mainStack]) codeBorderView.addSubviews(views: [codeLabel]) mainStack.addArrangedSubviews(views: [instructionLabel, codeBorderView, actionButton]) } func setupConstraints() { NSLayoutConstraint.activate([ mainStack.topAnchor.constraint(equalTo: topAnchor), mainStack.leadingAnchor.constraint(equalTo: leadingAnchor), mainStack.trailingAnchor.constraint(equalTo: trailingAnchor), mainStack.bottomAnchor.constraint(equalTo: bottomAnchor), codeBorderView.leadingAnchor.constraint(equalTo: leadingAnchor), codeBorderView.trailingAnchor.constraint(equalTo: trailingAnchor), codeLabel.topAnchor.constraint(equalTo: codeBorderView.topAnchor, constant: 8), codeLabel.leadingAnchor.constraint(equalTo: codeBorderView.leadingAnchor, constant: 16), codeLabel.trailingAnchor.constraint(equalTo: codeBorderView.trailingAnchor, constant: -16), codeLabel.bottomAnchor.constraint(equalTo: codeBorderView.bottomAnchor, constant: -8) ]) } func viewConfigure() { backgroundColor = .white } }
mit
7ae2c05e49cf033ca0ea993cb68c6c94
35.466667
118
0.677636
5.128125
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallRotateChase.swift
8
2418
// // NVActivityIndicatorAnimationBallRotateChase.swift // NVActivityIndicatorViewDemo // // Created by ChildhoodAndy on 15/12/7. // Copyright © 2015年 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallRotateChase: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize = size.width / 5; // Draw circles for i in 0 ..< 5 { let factor = Float(i) * 1.0 / 5 let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let animation = rotateAnimation(factor, x: layer.bounds.size.width / 2, y: layer.bounds.size.height / 2, size: CGSize(width: size.width - circleSize, height: size.height - circleSize)) circle.frame = CGRect(x: 0, y: 0, width: circleSize, height: circleSize) circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } func rotateAnimation(_ rate: Float, x: CGFloat, y: CGFloat, size: CGSize) -> CAAnimationGroup { let duration: CFTimeInterval = 1.5 let fromScale = 1 - rate let toScale = 0.2 + rate let timeFunc = CAMediaTimingFunction(controlPoints: 0.5, 0.15 + rate, 0.25, 1.0) // Scale animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.repeatCount = HUGE scaleAnimation.fromValue = fromScale scaleAnimation.toValue = toScale // Position animation let positionAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = duration positionAnimation.repeatCount = HUGE positionAnimation.path = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: size.width / 2, startAngle: 3 * CGFloat(M_PI) * 0.5, endAngle: 3 * CGFloat(M_PI) * 0.5 + 2 * CGFloat(M_PI), clockwise: true).cgPath // Aniamtion let animation = CAAnimationGroup() animation.animations = [scaleAnimation, positionAnimation] animation.timingFunction = timeFunc animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } }
apache-2.0
1f410ad024feed3f8744f4f52b1cfd43
40.637931
217
0.650104
4.801193
false
false
false
false
zhihuitang/LeLey
Pods/Kingfisher/Kingfisher/ImageCache.swift
1
27685
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification" /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" private let defaultCacheName = "default" private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache." private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue." private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue." private let defaultCacheInstance = ImageCache(name: defaultCacheName) private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = dispatch_block_t /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case None, Memory, Disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher. public class ImageCache { //Memory private let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory. public var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk private let ioQueue: dispatch_queue_t private var fileManager: NSFileManager! ///The disk cache location. public let diskCachePath: String /// The longest time duration of the cache being stored in disk. Default is 1 week. public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond /// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit. public var maxDiskCacheSize: UInt = 0 private let processQueue: dispatch_queue_t /// The default cache. public class var defaultCache: ImageCache { return defaultCacheInstance } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string. - parameter path: Optional - Location of cache path on disk. If `nil` is passed (the default value), the cache folder in of your app will be used. If you want to cache some user generating images, you could pass the Documentation path here. - returns: The cache object. */ public init(name: String, path: String? = nil) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = cacheReverseDNS + name memoryCache.name = cacheName let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! diskCachePath = (dstPath as NSString).stringByAppendingPathComponent(cacheName) ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL) processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT) dispatch_sync(ioQueue, { () -> Void in self.fileManager = NSFileManager() }) NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } // MARK: - Store & Remove public extension ImageCache { /** Store an image to cache. It will be saved to both memory and disk. It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:` instead. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. */ public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) { storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil) } /** Store an image to cache. It is an async operation. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when stroe operation completes. */ public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) { memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if toDisk { dispatch_async(ioQueue, { () -> Void in let imageFormat: ImageFormat if let originalData = originalData { imageFormat = originalData.kf_imageFormat } else { imageFormat = .Unknown } let data: NSData? switch imageFormat { case .PNG: data = UIImagePNGRepresentation(image) case .JPEG: data = UIImageJPEGRepresentation(image, 1.0) case .GIF: data = UIImageGIFRepresentation(image) case .Unknown: data = originalData ?? UIImagePNGRepresentation(image.kf_normalizedImage()) } if let data = data { if !self.fileManager.fileExistsAtPath(self.diskCachePath) { do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil) callHandlerInMainQueue() } else { callHandlerInMainQueue() } }) } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:` instead. - parameter key: Key for the image. */ public func removeImageForKey(key: String) { removeImageForKey(key, fromDisk: true, completionHandler: nil) } /** Remove the image for key for the cache. It is an async operation. - parameter key: Key for the image. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) { memoryCache.removeObjectForKey(key) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if fromDisk { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.cachePathForKey(key)) } catch _ {} callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } } // MARK: - Get data from cache extension ImageCache { /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ public func retrieveImageForKey(key: String, options: KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? if let image = self.retrieveImageInMemoryCacheForKey(key) { //Found image in memory cache. if options.shouldDecode { dispatch_async(self.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scale) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) }) }) } else { completionHandler(image, .Memory) } } else { var sSelf: ImageCache! = self block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) { // Begin to load image from disk dispatch_async(sSelf.ioQueue, { () -> Void in if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scale) { if options.shouldDecode { dispatch_async(sSelf.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scale) sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) sSelf = nil }) }) } else { sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(image, .Disk) sSelf = nil }) } } else { // No image found from either memory or disk dispatch_async(options.queue, { () -> Void in completionHandler(nil, nil) sSelf = nil }) } }) } dispatch_async(dispatch_get_main_queue(), block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? { return memoryCache.objectForKey(key) as? UIImage } /** Get an image for a key from disk. - parameter key: Key for the image. - param scale: The scale factor to assume when interpreting the image data. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? { return diskImageForKey(key, scale: scale) } } // MARK: - Clear & Clean extension ImageCache { /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is an async operation. */ public func clearDiskCache() { clearDiskCacheWithCompletionHandler(nil) } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.diskCachePath) } catch _ { } do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let completionHander = completionHander { dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHander() }) } }) } /** Clean expired disk cache. This is an async operation. */ @objc public func cleanExpiredDiskCache() { cleanExpiredDiskCacheWithCompletionHander(nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) { // Do things in cocurrent io queue dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond) var cachedFiles = [NSURL: [NSObject: AnyObject]]() var URLsToDelete = [NSURL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber { if isDirectory.boolValue { continue } } // If this file is expired, add it to URLsToDelete if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expiredDate) == expiredDate { URLsToDelete.append(fileURL) continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue cachedFiles[fileURL] = resourceValues } } catch _ { } } } for fileURL in URLsToDelete { do { try self.fileManager.removeItemAtURL(fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate { if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate { return date1.compare(date2) == .OrderedAscending } } // Not valid date information. This should not happen. Just in case. return true }) for fileURL in sortedFiles { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize -= fileSize.unsignedLongValue } if diskCacheSize < targetSize { break } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map({ (url) -> String in return url.lastPathComponent! }) NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } if let completionHandler = completionHandler { completionHandler() } }) }) } /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCacheWithCompletionHander { () -> () in endBackgroundTask(&backgroundTask!) } } } // MARK: - Check cache status public extension ImageCache { /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ public func isImageCachedForKey(key: String) -> CacheCheckResult { if memoryCache.objectForKey(key) != nil { return CacheCheckResult(cached: true, cacheType: .Memory) } let filePath = cachePathForKey(key) if fileManager.fileExistsAtPath(filePath) { return CacheCheckResult(cached: true, cacheType: .Disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - returns: Corresponding hash. */ public func hashForKey(key: String) -> String { return cacheFileNameForKey(key) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) { dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue { if isDirectory { continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue } } catch _ { } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if let completionHandler = completionHandler { completionHandler(size: diskCacheSize) } }) }) } } // MARK: - Internal Helper extension ImageCache { func diskImageForKey(key: String, scale: CGFloat) -> UIImage? { if let data = diskImageDataForKey(key) { return UIImage.kf_imageWithData(data, scale: scale) } else { return nil } } func diskImageDataForKey(key: String) -> NSData? { let filePath = cachePathForKey(key) return NSData(contentsOfFile: filePath) } func cachePathForKey(key: String) -> String { let fileName = cacheFileNameForKey(key) return (diskCachePath as NSString).stringByAppendingPathComponent(fileName) } func cacheFileNameForKey(key: String) -> String { return key.kf_MD5() } } extension UIImage { var kf_imageCost: Int { return images == nil ? Int(size.height * size.width * scale * scale) : Int(size.height * size.width * scale * scale) * images!.count } } extension Dictionary { func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] { var array = Array(self) array.sortInPlace { let (_, lv) = $0 let (_, rv) = $1 return isOrderedBefore(lv, rv) } return array.map { let (k, _) = $0 return k } } }
apache-2.0
eb4e3a071d73f269640e602422437cba
40.694277
337
0.583096
5.690647
false
false
false
false
OlivierVoyer/FirebaseHelpers
Example/Tests/Tests.swift
1
1186
// https://github.com/Quick/Quick import Quick import Nimble import FirebaseHelpers class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { /*it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) }*/ context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
0d97e079340189bfc16e9f744ba8708c
22.6
63
0.365254
5.488372
false
false
false
false
rudkx/swift
validation-test/compiler_crashers_2_fixed/0142-rdar36549499.swift
1
294
// RUN: %target-swift-frontend %s -emit-ir -o /dev/null -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify protocol S { associatedtype I: IteratorProtocol typealias E = I.Element } func foo<T: S>(_ s: T) -> Int where T.E == Int { return 42 }
apache-2.0
580924f955ce25f32cb98da6a454641c
31.666667
151
0.717687
3.37931
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Optional.swift
10
2023
// // Optional.swift // RxSwift // // Created by tarunon on 2016/12/13. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation class ObservableOptionalScheduledSink<O: ObserverType> : Sink<O> { typealias E = O.E typealias Parent = ObservableOptionalScheduled<E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.schedule(_parent._optional) { (optional: E?) -> Disposable in if let next = optional { self.forwardOn(.next(next)) return self._parent._scheduler.schedule(()) { _ in self.forwardOn(.completed) return Disposables.create() } } else { self.forwardOn(.completed) return Disposables.create() } } } } class ObservableOptionalScheduled<E> : Producer<E> { fileprivate let _optional: E? fileprivate let _scheduler: ImmediateSchedulerType init(optional: E?, scheduler: ImmediateSchedulerType) { _optional = optional _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } class ObservableOptional<E>: Producer<E> { private let _optional: E? init(optional: E?) { _optional = optional } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = _optional { observer.on(.next(element)) } observer.on(.completed) return Disposables.create() } }
apache-2.0
5bf2da8d1f3bcc5c66f2ee4e24aebb79
28.735294
139
0.603858
4.503341
false
false
false
false
adolfrank/Swift_practise
18-day/18-day/MenuTransitionManager.swift
1
2909
// // MenuTransitionManager.swift // SlideMenu // // Created by Allen on 16/1/22. // Copyright © 2016年 AppCoda. All rights reserved. // import UIKit @objc protocol MenuTransitionManagerDelegate { func dismiss() } class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { var duration = 0.5 var isPresenting = false var snapshot:UIView? { didSet { if let _delegate = delegate { let tapGestureRecognizer = UITapGestureRecognizer(target: _delegate, action: #selector(MenuTransitionManagerDelegate.dismiss)) snapshot?.addGestureRecognizer(tapGestureRecognizer) } } } var delegate:MenuTransitionManagerDelegate? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let container = transitionContext.containerView() let moveDown = CGAffineTransformMakeTranslation(0, container!.frame.height - 150) let moveUp = CGAffineTransformMakeTranslation(0, -50) if isPresenting { toView.transform = moveUp snapshot = fromView.snapshotViewAfterScreenUpdates(true) container!.addSubview(toView) container!.addSubview(snapshot!) } UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .CurveEaseInOut, animations: { if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransformIdentity } else { self.snapshot?.transform = CGAffineTransformIdentity fromView.transform = moveUp } }, completion: { finished in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } }) } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } }
mit
cd6d7da2c5e51aeae62f5bcc5ae7721a
31.288889
217
0.645217
6.75814
false
false
false
false
withcopper/CopperKit
Example/CopperKit/ViewController.swift
1
5246
// // ViewController.swift // CopperKit-Example // // Created by Doug Williams on 3/15/16. // Copyright © 2016 Copper Technologies, Inc. All rights reserved. // import UIKit import CopperKit @available(iOS 9.0, *) class ViewController: UIViewController { // Signed Out view IB Variables @IBOutlet weak var signedOutView: UIView! @IBOutlet weak var signinButton: UIButton! @IBOutlet weak var optionsButton: UIButton! @IBOutlet weak var versionLabel: UILabel! // Signed In view IB Variables @IBOutlet weak var signedInView: UIView! @IBOutlet weak var signoutButton: UIButton! @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var userIdLabel: UILabel! static let DefaultScopes: [C29Scope] = [.Name, .Picture, .Email, .Phone] // note: C29Scope.DefaultScopes = [C29Scope.Name, C29Scope.Picture, C29Scope.Phone] // Reference to our CopperKit singleton var copper: C29Application? // Instance variable holding our desired scopes to allow changes, see showOptionsMenu() var desiredScopes: [C29Scope]? = ViewController.DefaultScopes override func viewDidLoad() { super.viewDidLoad() self.signedInView.setNeedsLayout() // reset our UI elements to the Signed Out state resetView() } @IBAction func signinButtonPressed(sender: AnyObject) { // get a reference to our CopperKit application instance copper = C29Application.sharedInstance // Required: configure it with our app's token copper!.configureForApplication("573F837FD248FF72EF554F3093D9C1D396F8AA43") // Optionally, decide what information we want from the user copper!.scopes = desiredScopes // OK, let's make our call // An example with an optional phoneNumber varable (to skip entry) //copper!.login(withViewController: self, emailAddress: "[email protected]", completion: { (result: C29UserInfoResult) in //copper!.login(withViewController: self, phoneNumber: "17165550000", completion: { (result: C29UserInfoResult) in copper!.login(withViewController: self, completion: { (result: C29UserInfoResult) in switch result { case let .Success(userInfo): self.setupViewWithUserInfo(userInfo) case .UserCancelled: print("The user cancelled.") case let .Failure(error): print("Bummer: \(error)") } }) } func setupViewWithUserInfo(userInfo: C29UserInfo) { self.avatarImageView.image = userInfo.picture // userInfo.pictureURL is available, too self.nameLabel.text = userInfo.fullName self.emailLabel.text = userInfo.emailAddress self.phoneLabel.text = userInfo.phoneNumber self.userIdLabel.text = userInfo.userId // flip our signout state self.signedInView.hidden = false self.signedOutView.hidden = true } func resetView() { // set our version string self.versionLabel.text = "CopperKit Version \(CopperKitVersion)" // reset our signed in state self.avatarImageView.image = nil self.nameLabel.text = "" self.emailLabel.text = "" self.phoneLabel.text = "" self.userIdLabel.text = "" // flip our state to the signed out state self.signedInView.hidden = true self.signedOutView.hidden = false } @IBAction func signoutButtonPressed(sender: AnyObject) { copper?.closeSession() resetView() } @IBAction func showOptionsMenu() { let alertController = UIAlertController(title: "CopperKit Settings", message: nil, preferredStyle: .ActionSheet) let defaultScopesAction = UIAlertAction(title: "Default scopes", style: .Default) { (action) in self.desiredScopes = ViewController.DefaultScopes } alertController.addAction(defaultScopesAction) let verificationOnlyAction = UIAlertAction(title: "Verification only, no scopes? \(self.desiredScopes == nil)", style: .Default) { (action) in // toggle between defualt and verification only self.desiredScopes = self.desiredScopes == nil ? ViewController.DefaultScopes : nil } alertController.addAction(verificationOnlyAction) let sfSafariViewController = UIAlertAction(title: "Use SFSafariViewController? (\(self.copper?.safariViewIfAvailable ?? true))", style: .Default) { (action) in guard let current = self.copper?.safariViewIfAvailable else { self.copper?.safariViewIfAvailable = true return } self.copper?.safariViewIfAvailable = !current } alertController.addAction(sfSafariViewController) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // no op } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true) { // no op } } }
mit
c2608b0e3d124df86bbf7d7c6a787eca
40.96
167
0.661964
4.653949
false
false
false
false
jay18001/brickkit-ios
Example/Source/Examples/Layout/PopoverBrickViewController.swift
1
1196
// // PopoverBrickViewController.swift // BrickKit // // Created by Ruben Cagnie on 9/28/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import BrickKit class PopoverBrickViewController: UIViewController { override class var brickTitle: String { return "Popover" } override class var subTitle: String { return "Example for size classes" } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .brickBackground // Do any additional setup after loading the view. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Popover", style: .plain, target: self, action: #selector(PopoverBrickViewController.showPopover)) } func showPopover(sender: UIBarButtonItem) { let brickController = SimpleRepeatBrickViewController() brickController.modalPresentationStyle = .popover self.present(brickController, animated: true, completion: nil) let popoverController = brickController.popoverPresentationController popoverController?.permittedArrowDirections = .any popoverController?.barButtonItem = sender } }
apache-2.0
def76f7879943b80f699fbe3b20606d0
27.452381
170
0.705439
5.241228
false
false
false
false
diesmal/thisorthat
ThisOrThat/Code/Services/TOTAPI/Operations/TOTFinalOperation.swift
1
1919
// // TOTErrorHandlerOperation.swift // ThisOrThat // // Created by Ilya Nikolaenko on 27/01/2017. // Copyright © 2017 Ilya Nikolaenko. All rights reserved. // import UIKit enum TOTFinalOperationError : Error { case authorizationError case wrongInputDataFormat(data: Any) } class TOTFinalOperation<InputType, OutputType>: Operation { let inputSocket : DIOperationSocket<InputType> let successfullyBlock: (_ data: OutputType) -> () let errorBlock: (_ errorText: String) -> () init(input: DIOperationSocket<InputType>, successfully: @escaping (_ data: OutputType) -> (), error: @escaping (_ errorText: String) -> ()) { self.inputSocket = input self.successfullyBlock = successfully self.errorBlock = error } override func main() { guard let inputBlock = inputSocket.block else { if let param = Void() as? OutputType { successfullyBlock(param) } return } do { let data = try inputBlock() if let data = data as? OutputType { self.successfullyBlock(data) } else { logError(error: TOTFinalOperationError.wrongInputDataFormat(data: data)) self.errorBlock("Не удалось обработать данные") } } catch TOTNetworkOperationError.incorrectAuthorization { TOTAuthorizationData.token = nil TOTAuthorizationData.userId = nil logError(error: TOTFinalOperationError.authorizationError) errorBlock("Не удалось авторизироваться") } catch let error { logError(error: error) errorBlock("Ошибка: \(error)") } } }
apache-2.0
0ae1109e88d0d9b5cbc99ff39ec9fe75
27.212121
88
0.572503
5.005376
false
false
false
false
007HelloWorld/DouYuZhiBo
DYZB/DYZB/Main/Model/AnchorGroup.swift
1
1164
// // AnchorGroup.swift // DYZB // // Created by MacMini on 2017/8/7. // Copyright © 2017年 MacMini. All rights reserved. // import UIKit class AnchorGroup: NSObject { //定义主播的模型对象数组 public lazy var anchors : [AnchorModel] = [AnchorModel]() //该组中对应的房间信息 var room_list : [[String : NSObject]]? { //属性监听器 didSet { guard let room_list = room_list else { return } for dict in room_list { anchors.append(AnchorModel(dict : dict)) } } } //组显示的标题 var tag_name : String = "" //组显示的图标 var icon_name : String = "home_header_normal" //游戏对应的图标 var icon_url : String = "" init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} // MARK: - 构造函数 override init() { } }
mit
4fd91d8ec85326fcaf1a92ee692eb3f8
15.353846
73
0.476011
4.429167
false
false
false
false
aipeople/SimplyLayout
SimplyLayout/Anchor/CenterAnchor.swift
1
1568
// // CenterAnchor.swift // SimplyLayout // // Created by Sean, Su on 2019/1/1. // Copyright © 2019 aipeople. All rights reserved. // import UIKit public struct CenterAnchor { let xAnchor: NSLayoutXAxisAnchor let yAnchor: NSLayoutYAxisAnchor let constant: CGPoint fileprivate init(xAnchor: NSLayoutXAxisAnchor, yAnchor: NSLayoutYAxisAnchor, constant: CGPoint) { self.xAnchor = xAnchor self.yAnchor = yAnchor self.constant = constant } } extension CenterAnchor { @discardableResult public static func ==(lhs: CenterAnchor, rhs: CenterAnchor) -> [NSLayoutConstraint] { return [ lhs.xAnchor == rhs.xAnchor + (rhs.constant.x - lhs.constant.x), lhs.yAnchor == rhs.yAnchor + (rhs.constant.y - lhs.constant.y) ] } @discardableResult public static func +(lhs: CenterAnchor, constant: CGPoint) -> CenterAnchor { return CenterAnchor( xAnchor: lhs.xAnchor, yAnchor: lhs.yAnchor, constant: CGPoint( x: lhs.constant.x + constant.x, y: lhs.constant.y + constant.y )) } } extension UIView { public var centerAnchor: CenterAnchor { return CenterAnchor(xAnchor: centerXAnchor, yAnchor: centerYAnchor, constant: .zero) } } @available(iOS 9.0, *) extension UILayoutGuide { public var centerAnchor: CenterAnchor { return CenterAnchor(xAnchor: centerXAnchor, yAnchor: centerYAnchor, constant: .zero) } }
mit
62460515f0d7716b50e4515e93d170b0
23.484375
101
0.624123
4.18984
false
false
false
false
mumuda/Swift_Weibo
weibo/weibo/AppDelegate.swift
1
3205
// // AppDelegate.swift // weibo // // Created by ldj on 16/5/26. // Copyright © 2016年 ldj. All rights reserved. // import UIKit // 切换控制器通知 let SwitchRootViewController = "SwitchRootViewController" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // 注册一个通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.switchRootViewController(_:)), name: SwitchRootViewController, object: nil) // 设置导航栏和工具栏的外观 // 因为外观一旦设置全局有效,所以在程序一进入就设置 UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() // 1.创建widnow window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() // 2.创建根视图控制器 window?.rootViewController = defaultController() window?.makeKeyAndVisible() return true } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func switchRootViewController(notify:NSNotification){ if notify.object as! Bool { window?.rootViewController = MainViewController() }else { window?.rootViewController = WelcomeViewController() } } /** 用于获取默认界面 */ private func defaultController()-> UIViewController{ // 1.检查用户是否登录 if UserAccount.userLogin() { // 判断是否有新版本 return isNewUpdate() ? NewFeatureCollectionViewController(): WelcomeViewController() } return MainViewController() } private func isNewUpdate() -> Bool{ // 1.获取当前版本号 ->info.plist let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String // 2.获取以前的版本号 ->从本地文件中读取(以前自己存储的) // 如果前面是空,就取后面的值 let sandboxVersion = NSUserDefaults.standardUserDefaults().valueForKey("CFBundleShortVersionString") as? String ?? "" print("currentVersion = \(currentVersion) sandboxVersion = \(sandboxVersion)") // 3.比较当前版本号和以前版本号 // 3.1如果当前版本大于以前版本 有新版本 // ios 7以后就不用调用同步方法了 if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending { // 3.1.1存储当前最新的版本号 NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString") return true } // 3.2如果当前< == 没有新版本 return false } }
mit
792e2eeeebc44676b6caaf46caa9c902
29.06383
170
0.637297
5.082734
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Model/PhotoAsset+Network.swift
1
3073
// // PhotoAsset+Network.swift // HXPHPicker // // Created by Slience on 2021/5/24. // import UIKit #if canImport(Kingfisher) import Kingfisher #endif public extension PhotoAsset { #if canImport(Kingfisher) /// 获取网络图片的地址,编辑过就是本地地址,未编辑就是网络地址 /// - Parameter resultHandler: 图片地址、是否为网络地址 func getNetworkImageURL(resultHandler: AssetURLCompletion) { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit { resultHandler(.success(.init(url: photoEdit.editedImageURL, urlType: .local, mediaType: .photo))) return } #endif if let url = networkImageAsset?.originalURL { resultHandler(.success(.init(url: url, urlType: .network, mediaType: .photo))) }else { resultHandler(.failure(.networkURLIsEmpty)) } } /// 获取网络图片 /// - Parameters: /// - filterEditor: 过滤编辑的数据 /// - resultHandler: 获取结果 func getNetworkImage(urlType: DonwloadURLType = .original, filterEditor: Bool = false, progressBlock: DownloadProgressBlock? = nil, resultHandler: @escaping (UIImage?) -> Void) { #if HXPICKER_ENABLE_EDITOR if let photoEdit = photoEdit, !filterEditor { if urlType == .thumbnail { resultHandler(photoEdit.editedImage) }else { let image = UIImage.init(contentsOfFile: photoEdit.editedImageURL.path) resultHandler(image) } return } #endif let isThumbnail = urlType == .thumbnail let url = isThumbnail ? networkImageAsset!.thumbnailURL : networkImageAsset!.originalURL let options: KingfisherOptionsInfo = isThumbnail ? .init( [.onlyLoadFirstFrame, .cacheOriginalImage] ) : .init( [.backgroundDecode] ) PhotoTools.downloadNetworkImage(with: url, options: options, progressBlock: progressBlock) { (image) in if let image = image { resultHandler(image) }else { resultHandler(nil) } } } #endif /// 获取网络视频的地址,编辑过就是本地地址,未编辑就是网络地址 /// - Parameter resultHandler: 视频地址、是否为网络地址 func getNetworkVideoURL(resultHandler: AssetURLCompletion) { #if HXPICKER_ENABLE_EDITOR if let videoEdit = videoEdit { resultHandler(.success(.init(url: videoEdit.editedURL, urlType: .local, mediaType: .video))) return } #endif if let url = networkVideoAsset?.videoURL { resultHandler(.success(.init(url: url, urlType: .network, mediaType: .video))) }else { resultHandler(.failure(.networkURLIsEmpty)) } } }
mit
6dfedb77f3653e49f68b71b72c09a6a2
31.670455
111
0.573217
4.759934
false
false
false
false
juanm95/Soundwich
Quaggify/SeeAllCell.swift
2
851
// // SeeAllCell.swift // Quaggify // // Created by Jonathan Bijos on 02/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class SeeAllCell: CollectionViewCell { var title: String? { didSet { if let title = title { titleLabel.text = title } } } private let titleLabel: UILabel = { let label = UILabel() label.backgroundColor = .clear label.textColor = ColorPalette.white label.textAlignment = .left label.font = Font.montSerratRegular(size: 16) return label }() override func setupViews() { super.setupViews() addSubview(titleLabel) titleLabel.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 0) } }
mit
c7acc493acba7482aa67414bd4096eb8
22.611111
199
0.668235
4.146341
false
false
false
false
beninho85/BBOrm
BBOrm/BBManager.swift
1
741
// // BBManager.swift // BBOrm // // Created by Benjamin Bourasseau on 30/01/2016. // Copyright © 2016 Benjamin. All rights reserved. // import Foundation public class BBManager { public static var apiKey: String? public static var apiUrl: String? /* Set debug mode */ public static var isDebug = false /* Object identifier default property */ public static var objIdDefault = "id" /* Initialize all setup datas. Here: Api Key and apiUrl */ public static func initialize(apiUrl:String,apiKey:String?){ BBManager.apiUrl = apiUrl BBManager.apiKey = apiKey } public static func initialize(apiUrl:String){ BBManager.apiUrl = apiUrl } }
apache-2.0
2ae8707a02be970082f7059e46fa0218
21.454545
64
0.643243
4.228571
false
false
false
false
DrabWeb/Booru-chan
Booru-chan/Booru-chan/BooruUtilities.swift
1
14140
// // BooruUtilities.swift // Booru-chan // // Created by Ushio on 2018-01-14. // import Alamofire import SwiftyJSON import SWXMLHash class BooruUtilities { private(set) weak var representedBooru: BooruHost! var lastSearch = ""; var lastSearchLimit = -1; var lastSearchPage = -1; // search parameter supports wildcards func getTagsFromSearch(_ search: String, completionHandler: @escaping ([String]) -> ()) -> Request? { print("BooruUtilities: Searching for tags matching \"\(search)\" on \(representedBooru.url)"); var request: Request! var results: [String] = []; if representedBooru.type == .moebooru { // /tag.json?name=[search]&limit=[limit] let url = sanitizeUrl("\(representedBooru.url)/tag.json?name=\(search)&limit=0"); print("BooruUtilities: Using \(url) to search for tags"); request = jsonRequest(url: url, completionHandler: { json in for (_, t) in json.enumerated() { results.append(t.1["name"].stringValue); } completionHandler(results); }); } else if representedBooru.type == .danbooru || representedBooru.type == .danbooruLegacy { // /tags.json?search[name_matches]=[search]&limit=[limit] // note: danbooru does not support getting all tags from a search, and has an upper limit of 1000 and a lower limit of 0 let url = sanitizeUrl("\(representedBooru.url)/tags.json?search[name_matches]=\(search)&limit=1000"); print("BooruUtilities: Using \(url) to search for tags"); request = jsonRequest(url: url, completionHandler: { json in for (_, t) in json.enumerated() { results.append(t.1["name"].stringValue); } completionHandler(results); }); } else if representedBooru.type == .gelbooru { // gelbooru does not support tag searching } return request; } func getPostsFromSearch(_ search: String, limit: Int, page: Int, completionHandler: @escaping ([BooruPost]) -> ()) -> Request? { print("BooruUtilities: Searching for \"\(search)\", limit: \(limit), page: \(page) on \(representedBooru.name)"); var results: [BooruPost] = []; var request: Request? = nil; var ratingLimitString: String = ""; switch representedBooru.maximumRating { case .safe: ratingLimitString = " rating:safe"; break; case .questionable: ratingLimitString = " -rating:explicit"; break; default: break; } func handlePost(_ post: BooruPost) { if !self.postIsBlacklisted(post) { results.append(post); } } if representedBooru.type == .moebooru { // /post.json?tags=[search]&page=[page]&limit=[limit] let url = "\(representedBooru.url)/post.json?tags=\(search + ratingLimitString)&page=\(page)&limit=\(limit)"; print("BooruUtilities: Using \(url) to search"); request = jsonRequest(url: url, completionHandler: { json in for (_, currentResult) in json.enumerated() { handlePost(self.getPostFromData(json: currentResult.1)); } completionHandler(results); }); } else if representedBooru.type == .danbooruLegacy { // /post/index.xml?page=[page]&limit=[limit]&tags=[tags] let url = sanitizeUrl("\(representedBooru.url)/post/index.xml?page=\(page)&limit=\(limit)&tags=\(search + ratingLimitString)"); print("BooruUtilities: Using \(url) to search"); request = xmlRequest(url: url, completionHandler: { xml in for (_, currentResult) in xml["posts"].children.enumerated() { handlePost(self.getPostFromData(xml: currentResult)); } completionHandler(results); }); } else if representedBooru.type == .danbooru { // /posts.json?tags=[tags]&page=[page]&limit=[limit] let url = sanitizeUrl("\(representedBooru.url)/posts.json?tags=\(search + ratingLimitString)&page=\(page)&limit=\(limit)"); print("BooruUtilities: Using \(url) to search"); request = jsonRequest(url: url, completionHandler: { json in for (_, currentResult) in json.enumerated() { handlePost(self.getPostFromData(json: currentResult.1)); } completionHandler(results); }); } else if representedBooru.type == .gelbooru { // /index.php?page=dapi&s=post&q=index&tags=[tags]&pid=[page - 1]&limit=[limit] let url = sanitizeUrl("\(representedBooru.url)/index.php?page=dapi&s=post&q=index&tags=\(search + ratingLimitString)&pid=\(page - 1)&limit=\(limit)"); print("BooruUtilities: Using \(url) to search"); request = xmlRequest(url: url, completionHandler: { xml in for (_, currentResult) in xml["posts"].children.enumerated() { handlePost(self.getPostFromData(xml: currentResult)); } completionHandler(results); }); } lastSearch = search; lastSearchLimit = limit; lastSearchPage = page; return request; } func getPostFromId(_ id: Int, completionHandler: @escaping (BooruPost?) -> Void) -> Request? { return getPostsFromSearch("id:\(id)", limit: 1, page: 1, completionHandler: { posts in completionHandler(posts.first); }); } func getPostFromData(json: JSON? = nil, xml: XMLIndexer? = nil) -> BooruPost { let post: BooruPost = BooruPost(); if representedBooru.type == .moebooru { post.id = json!["id"].intValue; post.url = "\(representedBooru.url)/post/show/\(post.id)"; post.tags = json!["tags"].stringValue.components(separatedBy: " ").filter { !$0.isEmpty }; post.thumbnailUrl = sanitizeUrl(json!["preview_url"].stringValue); post.thumbnailSize = NSSize(width: json!["actual_preview_width"].intValue, height: json!["actual_preview_height"].intValue); post.imageUrl = sanitizeUrl(json!["file_url"].stringValue); post.imageSize = NSSize(width: json!["width"].intValue, height: json!["height"].intValue); let r = json!["rating"]; switch r { case "s": post.rating = .safe; break; case "q": post.rating = .questionable; break; case "e": post.rating = .explicit; break; default: print("BooruUtilities: Rating \(r) for post \(post.id) is invalid"); break; } } else if representedBooru.type == .danbooruLegacy { post.id = NSString(string: xml!.element!.allAttributes["id"]!.text).integerValue; post.url = "\(representedBooru.url)/posts/\(post.id)"; post.tags = xml!.element!.allAttributes["tags"]!.text.components(separatedBy: " ").filter { !$0.isEmpty }; // danbooru legacy doesnt have thumbnail resolution in the api post.thumbnailUrl = sanitizeUrl("\(representedBooru.url)/\(xml?.element?.allAttributes["preview_url"]?.text ?? "")"); post.thumbnailSize = NSSize.zero; post.imageUrl = sanitizeUrl("\(representedBooru.url)/\(xml?.element?.allAttributes["file_url"]?.text ?? "")"); post.imageSize = NSSize(width: NSString(string: xml!.element!.allAttributes["width"]!.text).integerValue, height: NSString(string: xml!.element!.allAttributes["height"]!.text).integerValue); let r = xml!.element!.allAttributes["rating"]!.text; switch r { case "s": post.rating = .safe; break; case "q": post.rating = .questionable; break; case "e": post.rating = .explicit; break; default: print("BooruUtilities: Rating \(r) for post \(post.id) is invalid"); break; } } else if representedBooru.type == .danbooru { post.id = json!["id"].intValue; post.url = "\(representedBooru.url)/posts/\(post.id)"; func addTags(key: String) { post.tags = json![key].stringValue.components(separatedBy: " "); } //todo: properly handle tag types addTags(key: "tag_string_artist"); addTags(key: "tag_string_character"); addTags(key: "tag_string_copyright"); addTags(key: "tag_string_general"); post.tags = post.tags.filter { !$0.isEmpty }; // danbooru doesnt have thumbnail resolution in the api post.thumbnailUrl = sanitizeUrl("\(representedBooru.url)/\(json!["preview_file_url"].stringValue)"); post.thumbnailSize = NSSize.zero; post.imageUrl = sanitizeUrl("\(representedBooru.url)/\(json!["file_url"].stringValue)"); post.imageSize = NSSize(width: json!["image_width"].intValue, height: json!["image_height"].intValue); let r = json!["rating"]; switch r { case "s": post.rating = .safe; break; case "q": post.rating = .questionable; break; case "e": post.rating = .explicit; break; default: print("BooruUtilities: Rating \(r) for post \(post.id) is invalid"); break; } } else if representedBooru.type == .gelbooru { post.id = NSString(string: xml!.element!.allAttributes["id"]!.text).integerValue; post.url = "\(representedBooru.url)/index.php?page=post&s=view&id=\(post.id)"; post.tags = xml!.element!.allAttributes["tags"]!.text.components(separatedBy: " ").filter { !$0.isEmpty }; post.thumbnailUrl = sanitizeUrl(xml!.element!.allAttributes["preview_url"]!.text); post.thumbnailSize = NSSize(width: NSString(string: xml!.element!.allAttributes["preview_width"]!.text).integerValue, height: NSString(string: xml!.element!.allAttributes["preview_height"]!.text).integerValue); post.imageUrl = sanitizeUrl(xml!.element!.allAttributes["file_url"]!.text); post.imageSize = NSSize(width: NSString(string: xml!.element!.allAttributes["width"]!.text).integerValue, height: NSString(string: xml!.element!.allAttributes["height"]!.text).integerValue); let r = xml!.element!.allAttributes["rating"]!.text; switch r { case "s": post.rating = .safe; break; case "q": post.rating = .questionable; break; case "e": post.rating = .explicit; break; default: print("BooruUtilities: Rating \(r) for post \(post.id) is invalid"); break; } } let booruUrlProtocol = String(self.representedBooru!.url[..<self.representedBooru!.url.range(of: "//")!.lowerBound]); if post.imageUrl.hasPrefix("//") { post.imageUrl = booruUrlProtocol + post.imageUrl; } if post.thumbnailUrl.hasPrefix("//") { post.thumbnailUrl = booruUrlProtocol + post.thumbnailUrl; } return post; } private func jsonRequest(url: String, completionHandler: @escaping (JSON) -> Void) -> Request { return Alamofire.request(url).responseJSON { responseData in let jsonString = NSString(data: responseData.data!, encoding: String.Encoding.utf8.rawValue)!; if let jsonData = jsonString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) { completionHandler(try! JSON(data: jsonData)); } } } private func xmlRequest(url: String, completionHandler: @escaping (XMLIndexer) -> Void) -> Request { return Alamofire.request(url).responseJSON { responseData in let xmlString = NSString(data: responseData.data!, encoding: String.Encoding.utf8.rawValue)!; if let xmlData = xmlString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) { completionHandler(SWXMLHash.parse(xmlData)); } } } private func sanitizeUrl(_ url: String) -> String { return url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!; } private func postIsBlacklisted(_ post: BooruPost) -> Bool { var containsTagInBlacklist = false; if self.representedBooru.tagBlacklist.count > 0 { for (_, t) in post.tags.enumerated() { if self.representedBooru!.tagBlacklist.contains(t) { print("BooruUtilities: Blacklisted post \(post.id) from \(self.representedBooru!.name) for tag \"\(t)\""); containsTagInBlacklist = true; break; } } } return containsTagInBlacklist; } convenience init(booru: BooruHost) { self.init(); self.representedBooru = booru; } }
gpl-3.0
833183342f63a6130a201c877a183a46
41.083333
162
0.546393
4.642154
false
false
false
false
xwu/swift
test/IRGen/protocol_conformance_records_objc.swift
1
1811
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir -num-threads 8 | %FileCheck %s // REQUIRES: objc_interop import gizmo public protocol Runcible { func runce() } // CHECK-LABEL: @"$sSo6NSRectV33protocol_conformance_records_objc8RuncibleACMc" = constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE:@"\$s33protocol_conformance_records_objc8RuncibleMp"]] // -- nominal type descriptor // CHECK-SAME: @"$sSo6NSRectVMn" // -- witness table // CHECK-SAME: @"$sSo6NSRectV33protocol_conformance_records_objc8RuncibleACWP" // -- flags // CHECK-SAME: i32 0 // CHECK-SAME: }, extension NSRect: Runcible { public func runce() {} } // CHECK-LABEL: @"$sSo5GizmoC33protocol_conformance_records_objc8RuncibleACMc" = constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- class name reference // CHECK-SAME: @[[GIZMO_NAME:[0-9]+]] // -- witness table // CHECK-SAME: @"$sSo5GizmoC33protocol_conformance_records_objc8RuncibleACWP" // -- flags // CHECK-SAME: i32 16 // CHECK-SAME: } extension Gizmo: Runcible { public func runce() {} } // CHECK: @[[GIZMO_NAME]] = private constant [6 x i8] c"Gizmo\00" // CHECK-LABEL: @"$sSo6NSRectV33protocol_conformance_records_objc8RuncibleACHc" = private constant // CHECK-LABEL: @"$sSo5GizmoC33protocol_conformance_records_objc8RuncibleACHc" = private constant
apache-2.0
f63648adccfc50c9f8ff8a98d5ec688c
38.369565
138
0.672557
3.378731
false
false
false
false
JanGorman/Agrume
Example/Agrume Example/MultipleURLsCollectionViewController.swift
1
2420
// // Copyright © 2016 Schnaub. All rights reserved. // import Agrume import UIKit final class MultipleURLsCollectionViewController: UICollectionViewController { private let identifier = "Cell" private struct ImageWithURL { let image: UIImage let url: URL } private let images = [ ImageWithURL(image: UIImage(named: "MapleBacon")!, url: URL(string: "https://www.dropbox.com/s/mlquw9k6ogvspox/MapleBacon.png?raw=1")!), ImageWithURL(image: UIImage(named: "EvilBacon")!, url: URL(string: "https://www.dropbox.com/s/fwjbsuonhv1wrqu/EvilBacon.png?raw=1")!) ] override func viewDidLoad() { super.viewDidLoad() let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: view.bounds.width, height: view.bounds.height) } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { images.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! DemoCell cell.imageView.image = images[indexPath.item].image return cell } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let urls = images.map { $0.url } let agrume = Agrume(urls: urls, startIndex: indexPath.item, background: .blurred(.extraLight)) agrume.didScroll = { [unowned self] index in self.collectionView?.scrollToItem(at: IndexPath(item: index, section: 0), at: [], animated: false) } let helper = makeHelper() agrume.onLongPress = helper.makeSaveToLibraryLongPressGesture agrume.show(from: self) } private func makeHelper() -> AgrumePhotoLibraryHelper { let saveButtonTitle = NSLocalizedString("Save Photo", comment: "Save Photo") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel") let helper = AgrumePhotoLibraryHelper(saveButtonTitle: saveButtonTitle, cancelButtonTitle: cancelButtonTitle) { error in guard error == nil else { print("Could not save your photo") return } print("Photo has been saved to your library") } return helper } }
mit
a13912765d303b5c89dcb5d371874d1e
35.651515
140
0.722199
4.496283
false
false
false
false
Evgeniy-Odesskiy/Bond
Bond/Bond+Foundation.swift
1
5901
// // Bond+Foundation.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 private var XXContext = 0 @objc private class DynamicKVOHelper: NSObject { let listener: AnyObject -> Void weak var object: NSObject? let keyPath: String init(keyPath: String, object: NSObject, listener: AnyObject -> Void) { self.keyPath = keyPath self.object = object self.listener = listener super.init() self.object?.addObserver(self, forKeyPath: keyPath, options: .New, context: &XXContext) } deinit { object?.removeObserver(self, forKeyPath: keyPath) } //?? override dynamic func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &XXContext { if let newValue: AnyObject = change?[NSKeyValueChangeNewKey] { listener(newValue) } } } } @objc private class DynamicNotificationCenterHelper: NSObject { let listener: NSNotification -> Void init(notificationName: String, object: AnyObject?, listener: NSNotification -> Void) { self.listener = listener super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNotification:", name: notificationName, object: object) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } dynamic func didReceiveNotification(notification: NSNotification) { listener(notification) } } public func dynamicObservableFor<T>(object: NSObject, keyPath: String, defaultValue: T) -> Dynamic<T> { let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath) let value: T = (keyPathValue != nil) ? (keyPathValue as? T)! : defaultValue let dynamic = InternalDynamic(value) let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) { [unowned dynamic] (v: AnyObject) -> Void in dynamic.updatingFromSelf = true if v is NSNull { dynamic.value = defaultValue } else { dynamic.value = (v as? T)! } dynamic.updatingFromSelf = false } dynamic.retain(helper) return dynamic } public func dynamicOptionalObservableFor<T>(object: NSObject, keyPath: String, defaultValue: T? = nil) -> Dynamic<T?> { return dynamicObservableFor(object, keyPath: keyPath, from: { (value: AnyObject?) -> T? in return value as? T }, to: { (value: T?) -> AnyObject? in return value as? AnyObject }) } public func dynamicObservableFor<T>(object: NSObject, keyPath: String, from: AnyObject? -> T, to: T -> AnyObject?) -> Dynamic<T> { let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath) let dynamic = InternalDynamic(from(keyPathValue)) let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) { [unowned dynamic] (v: AnyObject?) -> Void in dynamic.updatingFromSelf = true dynamic.value = from(v) dynamic.updatingFromSelf = false } let feedbackBond = Bond<T>() { [weak object] value in if let object = object { //дописать Int bool NSObject let currentValue = from(object.valueForKey(keyPath)) if let eCurrentValue = currentValue as? String, let eValue = value as? String { if eCurrentValue != eValue { object.setValue(to(value), forKey: keyPath) } } else if let eCurrentValue = currentValue as? Int, let eValue = value as? Int { if eCurrentValue != eValue { object.setValue(to(value), forKey: keyPath) } } else { object.setValue(to(value), forKey: keyPath) } } } dynamic.bindTo(feedbackBond, fire: false, strongly: false) dynamic.retain(feedbackBond) dynamic.retain(helper) return dynamic } public func dynamicObservableFor<T>(notificationName: String, object: AnyObject?, parser: NSNotification -> T) -> InternalDynamic<T> { let dynamic: InternalDynamic<T> = InternalDynamic() let helper = DynamicNotificationCenterHelper(notificationName: notificationName, object: object) { [unowned dynamic] notification in dynamic.updatingFromSelf = true dynamic.value = parser(notification) dynamic.updatingFromSelf = false } dynamic.retain(helper) return dynamic } public extension Dynamic { public class func asObservableFor(object: NSObject, keyPath: String, defaultValue: T) -> Dynamic<T> { let dynamic: Dynamic<T> = dynamicObservableFor(object, keyPath: keyPath, defaultValue: defaultValue) return dynamic } public class func asObservableFor(notificationName: String, object: AnyObject?, parser: NSNotification -> T) -> Dynamic<T> { let dynamic: InternalDynamic<T> = dynamicObservableFor(notificationName, object: object, parser: parser) return dynamic } }
mit
16d6a98fd31cb43c2af37aef196b72ef
34.077381
163
0.706771
4.34587
false
false
false
false
jhugman/turo-react-native
ios/Turo/AppDelegate.swift
1
1113
// // AppDelegate.swift // Turo // // Created by James Hugman on 4/10/16. // Copyright © 2016 Turo. All rights reserved. // import Foundation class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? = nil //- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let jsCodeLocation = isSimulator ? NSURL(string: "http://localhost:8081/index.ios.bundle?platform=ios&dev=true") : NSBundle.mainBundle().URLForResource("main", withExtension: "jsbundle") let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "Turo", initialProperties: nil, launchOptions: launchOptions) let window = UIWindow(frame:UIScreen.mainScreen().bounds) let vc = UIViewController() vc.view = rootView window.rootViewController = vc self.window = window window.makeKeyAndVisible() return true } var isSimulator: Bool { return TARGET_OS_SIMULATOR > 0 } }
mit
4c8b7b230f6809504c12b1a8799d7402
29.081081
131
0.726619
4.633333
false
false
false
false
bugsnag/bugsnag-cocoa
features/fixtures/shared/scenarios/UnhandledErrorChangeValidReleaseStageScenario.swift
1
539
class UnhandledErrorChangeValidReleaseStageScenario : Scenario { override func startBugsnag() { self.config.autoTrackSessions = false; if (self.eventMode == "noevent") { // The event is evaluated whether to be sent self.config.releaseStage = "test" } else { // A crash will occur self.config.releaseStage = "prod" } self.config.enabledReleaseStages = ["dev", "prod"] super.startBugsnag() } override func run() { abort(); } }
mit
c04a78d46a6fd360fdeb4a7454dbb6ef
27.368421
64
0.584416
4.382114
false
true
false
false
LightD/ivsa-server
Sources/App/Middlewares/SessionAuthMiddleware.swift
1
2012
// // DelegatesSessionAuthMiddleware.swift // ivsa // // Created by Light Dream on 30/01/2017. // // import Foundation import HTTP import Vapor import Auth import TurnstileWeb final class SessionAuthMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { // check if the access token is valid guard let _ = try request.sessionAuth.user() else { throw "user wasn't found" } // authenticated and everything, perform the request return try next.respond(to: request) } catch { // if there's an error, we redirect to root page, and that one decides return Response(redirect: "/") } } } public final class SessionAuthHelper { let request: Request init(request: Request) { self.request = request } public var header: Authorization? { guard let authorization = request.headers["Authorization"] else { return nil } return Authorization(header: authorization) } func login(_ credentials: Credentials) throws -> IVSAUser { let user = try IVSAUser.authenticate(credentials: credentials) as! IVSAUser try request.session().data["user_id"] = user.id return user } func logout() throws { try request.session().destroy() } func user() throws -> IVSAUser? { let userId: String? = try request.session().data["user_id"]?.string guard let id = userId else { return nil } guard let user = try IVSAUser.find(id) else { return nil } return user } } extension Request { public var sessionAuth: SessionAuthHelper { let helper = SessionAuthHelper(request: self) return helper } }
mit
33c7411ccb4c2f8127ea9b1025853dff
22.952381
86
0.562127
4.790476
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Activity/FormattableContent/Factory/ActivityContentFactory.swift
2
828
struct ActivityContentFactory: FormattableContentFactory { public static func content(from blocks: [[String: AnyObject]], actionsParser parser: FormattableContentActionParser) -> [FormattableContent] { return blocks.compactMap { let rawActions = getRawActions(from: $0) let actions = parser.parse(rawActions) let ranges = rangesFrom($0) let text = getText(from: $0) return FormattableTextContent(text: text, ranges: ranges, actions: actions) } } static func rangesFrom(_ dictionary: [String: AnyObject]) -> [FormattableContentRange] { let rawRanges = getRawRanges(from: dictionary) let parsed = rawRanges?.compactMap(ActivityRangesFactory.contentRange) return parsed ?? [] } }
gpl-2.0
bb53d007f264876b31d0143448e812c3
38.428571
110
0.642512
4.987952
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/SharedModels/NextRideFeature/Ride.swift
1
3249
import CoreLocation import Foundation import Helpers import MapKit public struct Ride: Hashable, Codable, Identifiable { public let id: Int public let slug: String? public let title: String public let description: String? public let dateTime: Date public let location: String? public let latitude: Double? public let longitude: Double? public let estimatedParticipants: Int? public let estimatedDistance: Double? public let estimatedDuration: Double? public let enabled: Bool public let disabledReason: String? public let disabledReasonMessage: String? public let rideType: RideType? public init( id: Int, slug: String? = nil, title: String, description: String? = nil, dateTime: Date, location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, estimatedParticipants: Int? = nil, estimatedDistance: Double? = nil, estimatedDuration: Double? = nil, enabled: Bool, disabledReason: String? = nil, disabledReasonMessage: String? = nil, rideType: Ride.RideType? = nil ) { self.id = id self.slug = slug self.title = title self.description = description self.dateTime = dateTime self.location = location self.latitude = latitude self.longitude = longitude self.estimatedParticipants = estimatedParticipants self.estimatedDistance = estimatedDistance self.estimatedDuration = estimatedDuration self.enabled = enabled self.disabledReason = disabledReason self.disabledReasonMessage = disabledReasonMessage self.rideType = rideType } } public extension Ride { var coordinate: Coordinate? { guard let lat = latitude, let lng = longitude else { return nil } return Coordinate(latitude: lat, longitude: lng) } var titleAndTime: String { let titleWithoutDate = title.removedDatePattern() return """ \(titleWithoutDate) \(rideDateAndTime) """ } var rideDateAndTime: String { "\(dateTime.humanReadableDate) - \(dateTime.humanReadableTime)" } var shareMessage: String { guard let location = location else { return titleAndTime } return """ \(titleAndTime) \(location) """ } } public extension Ride { func openInMaps(_ options: [String: Any] = [ MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault ]) { guard let coordinate = coordinate else { debugPrint("Coordinte is nil") return } let placemark = MKPlacemark(coordinate: coordinate.asCLLocationCoordinate, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = location mapItem.openInMaps(launchOptions: options) } } public extension Ride { enum RideType: String, CaseIterable, Codable { case criticalMass = "CRITICAL_MASS" case kidicalMass = "KIDICAL_MASS" case nightride = "NIGHT_RIDE" case lunchride = "LUNCH_RIDE" case dawnride = "DAWN_RIDE" case duskride = "DUSK_RIDE" case demonstration = "DEMONSTRATION" case alleycat = "ALLEYCAT" case tour = "TOUR" case event = "EVENT" public var title: String { rawValue .replacingOccurrences(of: "_", with: " ") .capitalized } } }
mit
511ac689ae03718c229fdc03339bec3a
25.414634
102
0.687904
4.252618
false
false
false
false
chinlam91/edx-app-ios
Source/CourseOutlineViewController.swift
2
14069
// // CourseOutlineViewController.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit ///Controls the space between the ModeChange icon and the View on Web Icon for CourseOutlineViewController and CourseContentPageViewController. Changing this constant changes the spacing in both places. public let barButtonFixedSpaceWidth : CGFloat = 20 public class CourseOutlineViewController : UIViewController, CourseBlockViewController, CourseOutlineTableControllerDelegate, CourseOutlineModeControllerDelegate, CourseContentPageViewControllerDelegate, DownloadProgressViewControllerDelegate, CourseLastAccessedControllerDelegate, OpenOnWebControllerDelegate, PullRefreshControllerDelegate { public struct Environment { private let analytics : OEXAnalytics? private let dataManager : DataManager private let networkManager : NetworkManager private let reachability : Reachability private weak var router : OEXRouter? private let styles : OEXStyles public init(analytics : OEXAnalytics?, dataManager : DataManager, networkManager : NetworkManager, reachability : Reachability, router : OEXRouter, styles : OEXStyles) { self.analytics = analytics self.dataManager = dataManager self.networkManager = networkManager self.reachability = reachability self.router = router self.styles = styles } } private var rootID : CourseBlockID? private var environment : Environment private let courseQuerier : CourseOutlineQuerier private let tableController : CourseOutlineTableController private let blockIDStream = BackedStream<CourseBlockID?>() private let headersLoader = BackedStream<CourseOutlineQuerier.BlockGroup>() private let rowsLoader = BackedStream<[CourseOutlineQuerier.BlockGroup]>() private let loadController : LoadStateViewController private let insetsController : ContentInsetsController private let modeController : CourseOutlineModeController private var lastAccessedController : CourseLastAccessedController /// Strictly a test variable used as a trigger flag. Not to be used out of the test scope private var t_hasTriggeredSetLastAccessed = false public var blockID : CourseBlockID? { return blockIDStream.value ?? nil } public var courseID : String { return courseQuerier.courseID } private lazy var webController : OpenOnWebController = OpenOnWebController(delegate: self) public init(environment: Environment, courseID : String, rootID : CourseBlockID?) { self.rootID = rootID self.environment = environment courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID) loadController = LoadStateViewController(styles: environment.styles) insetsController = ContentInsetsController() modeController = environment.dataManager.courseDataManager.freshOutlineModeController() tableController = CourseOutlineTableController(courseID: courseID) lastAccessedController = CourseLastAccessedController(blockID: rootID , dataManager: environment.dataManager, networkManager: environment.networkManager, courseQuerier: courseQuerier) super.init(nibName: nil, bundle: nil) lastAccessedController.delegate = self modeController.delegate = self addChildViewController(tableController) tableController.didMoveToParentViewController(self) tableController.delegate = self let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) fixedSpace.width = barButtonFixedSpaceWidth navigationItem.rightBarButtonItems = [webController.barButtonItem,fixedSpace,modeController.barItem] navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil) self.blockIDStream.backWithStream(Stream(value: rootID)) } public required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = self.environment.styles.standardBackgroundColor() view.addSubview(tableController.view) loadController.setupInController(self, contentView:tableController.view) tableController.refreshController.setupInScrollView(tableController.tableView) tableController.refreshController.delegate = self insetsController.setupInController(self, scrollView : self.tableController.tableView) insetsController.supportOfflineMode(styles: environment.styles) insetsController.supportDownloadsProgress(interface : environment.dataManager.interface, styles : environment.styles, delegate : self) insetsController.addSource(tableController.refreshController) self.view.setNeedsUpdateConstraints() addListeners() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) lastAccessedController.loadLastAccessed(forMode: modeController.currentMode) lastAccessedController.saveLastAccessed() } override public func updateViewConstraints() { loadController.insets = UIEdgeInsets(top: self.topLayoutGuide.length, left: 0, bottom: self.bottomLayoutGuide.length, right : 0) tableController.view.snp_updateConstraints {make in make.edges.equalTo(self.view) } super.updateViewConstraints() } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.insetsController.updateInsets() } private func setupNavigationItem(block : CourseBlock) { self.navigationItem.title = block.name self.webController.info = OpenOnWebController.Info(courseID : courseID, blockID : block.blockID, supported : block.displayType.isUnknown, URL: block.webURL) } public func viewControllerForCourseOutlineModeChange() -> UIViewController { return self } public func courseOutlineModeChanged(courseMode: CourseOutlineMode) { headersLoader.removeBacking() lastAccessedController.loadLastAccessed(forMode: courseMode) reload() } private func reload() { self.blockIDStream.backWithStream(Stream(value : self.blockID)) } private func emptyState() -> LoadState { switch modeController.currentMode { case .Full: return LoadState.failed(NSError.oex_courseContentLoadError()) case .Video: let message = OEXLocalizedString("NO_VIDEOS_TRY_MODE_SWITCHER", nil) let attributedMessage = loadController.messageStyle.attributedStringWithText(message) let formattedMessage = attributedMessage.oex_formatWithParameters(["mode_switcher" : Icon.CourseModeVideo.attributedTextWithStyle(loadController.messageStyle , inline : true)]) let accessibilityMessage = message.oex_formatWithParameters(["mode_switcher" : OEXLocalizedString("COURSE_MODE_PICKER_DESCRIPTION", nil)]) return LoadState.empty(icon: Icon.CourseModeFull, attributedMessage : formattedMessage, accessibilityMessage : accessibilityMessage) } } private func showErrorIfNecessary(error : NSError) { if self.loadController.state.isInitial { self.loadController.state = LoadState.failed(error) } } private func loadedHeaders(headers : CourseOutlineQuerier.BlockGroup) { self.setupNavigationItem(headers.block) let children = headers.children.map {header in return self.courseQuerier.childrenOfBlockWithID(header.blockID, forMode: self.modeController.currentMode) } rowsLoader.backWithStream(joinStreams(children)) } private func addListeners() { blockIDStream.listen(self, success: {[weak self] blockID in self?.backHeadersLoaderWithBlockID(blockID) }, failure: {[weak self] error in self?.headersLoader.backWithStream(Stream(error: error)) }) headersLoader.listen(self, success: {[weak self] headers in self?.loadedHeaders(headers) }, failure: {[weak self] error in self?.rowsLoader.backWithStream(Stream(error: error)) self?.showErrorIfNecessary(error) } ) rowsLoader.listen(self, success : {[weak self] groups in if let owner = self { owner.tableController.groups = groups owner.tableController.tableView.reloadData() owner.loadController.state = groups.count == 0 ? owner.emptyState() : .Loaded } }, failure : {[weak self] error in self?.showErrorIfNecessary(error) }, finally: {[weak self] in self?.tableController.refreshController.endRefreshing() } ) } private func backHeadersLoaderWithBlockID(blockID : CourseBlockID?) { self.headersLoader.backWithStream(courseQuerier.childrenOfBlockWithID(blockID, forMode: modeController.currentMode)) } // MARK: Outline Table Delegate func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideosRootedAtBlock block: CourseBlock) { let hasWifi = environment.reachability.isReachableViaWiFi() ?? false let onlyOnWifi = environment.dataManager.interface?.shouldDownloadOnlyOnWifi ?? false if onlyOnWifi && !hasWifi { self.loadController.showOverlayError(OEXLocalizedString("NO_WIFI_MESSAGE", nil)) return } let courseID = self.courseID let analytics = environment.analytics let videoStream = courseQuerier.flatMapRootedAtBlockWithID(block.blockID) { block -> [(String)] in block.type.asVideo.map { _ in return [block.blockID] } ?? [] } let parentStream = courseQuerier.parentOfBlockWithID(block.blockID) let stream = joinStreams(parentStream, videoStream) stream.listenOnce(self, success : { [weak self] (parentID, videos) in let interface = self?.environment.dataManager.interface interface?.downloadVideosWithIDs(videos, courseID: courseID) if block.type.asVideo != nil { analytics?.trackSingleVideoDownload(block.blockID, courseID: courseID, unitURL: block.webURL?.absoluteString) } else { analytics?.trackSubSectionBulkVideoDownload(parentID, subsection: block.blockID, courseID: courseID, videoCount: videos.count) } }, failure : {[weak self] error in self?.loadController.showOverlayError(error.localizedDescription) } ) } func outlineTableController(controller: CourseOutlineTableController, choseBlock block: CourseBlock, withParentID parent : CourseBlockID) { self.environment.router?.showContainerForBlockWithID(block.blockID, type:block.displayType, parentID: parent, courseID: courseQuerier.courseID, fromController:self) } private func expandAccessStream(stream : Stream<CourseLastAccessed>) -> Stream<(CourseBlock, CourseLastAccessed)> { return stream.transform {[weak self] lastAccessed in return joinStreams(self?.courseQuerier.blockWithID(lastAccessed.moduleId) ?? Stream<CourseBlock>(), Stream(value: lastAccessed)) } } //MARK: PullRefreshControllerDelegate public func refreshControllerActivated(controller: PullRefreshController) { courseQuerier.needsRefresh = true reload() } //MARK: DownloadProgressViewControllerDelegate public func downloadProgressControllerChoseShowDownloads(controller: DownloadProgressViewController) { self.environment.router?.showDownloadsFromViewController(self) } //MARK: CourseContentPageViewControllerDelegate public func courseContentPageViewController(controller: CourseContentPageViewController, enteredItemInGroup blockID : CourseBlockID) { self.blockIDStream.backWithStream(courseQuerier.parentOfBlockWithID(blockID)) } //MARK: LastAccessedControllerDeleagte public func courseLastAccessedControllerDidFetchLastAccessedItem(item: CourseLastAccessed?) { if let lastAccessedItem = item { self.tableController.showLastAccessedWithItem(lastAccessedItem) } else { self.tableController.hideLastAccessed() } } public func presentationControllerForOpenOnWebController(controller: OpenOnWebController) -> UIViewController { return self } } extension CourseOutlineViewController { public func t_setup() -> Stream<Void> { return rowsLoader.map { _ in } } public func t_currentChildCount() -> Int { return tableController.groups.count } public func t_populateLastAccessedItem(item : CourseLastAccessed) -> Bool { self.tableController.showLastAccessedWithItem(item) return self.tableController.tableView.tableHeaderView != nil } public func t_didTriggerSetLastAccessed() -> Bool { return t_hasTriggeredSetLastAccessed } }
apache-2.0
22d2feca09a08cb25332b1148c9dd917
40.872024
202
0.688109
5.801649
false
false
false
false
IvanVorobei/RateApp
SPRateApp - project/SPRateApp/sparrow/ui/views/views/SPBannerWithTitlesView.swift
1
6594
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @available(iOS, unavailable) class SPBannerWithTitlesView: UIView { let titleLabel: UILabel = UILabel() let subTitleLabel: UILabel = UILabel() private var backgroundView: UIView = UIView() //MARK: layout var titleWidthFactor: CGFloat = 0.8 var subTitleWidthFactor: CGFloat = 0.8 init() { super.init(frame: CGRect.zero) commonInit() } init(title: String, subTitle: String, backgroundView: UIView) { super.init(frame: CGRect.zero) self.titleLabel.text = title self.subTitleLabel.text = subTitle self.backgroundView = backgroundView commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setBackgroundView(_ view: UIView) { self.backgroundView = view self.insertSubview(view, at: 0) } private func commonInit() { self.addSubview(self.backgroundView) self.addSubview(self.titleLabel) self.addSubview(self.subTitleLabel) self.titleLabel.setCenteringAlignment() self.titleLabel.textColor = UIColor.white self.subTitleLabel.setCenteringAlignment() self.subTitleLabel.textColor = UIColor.white self.titleLabel.setShadowOffsetForLetters(blurRadius: 0, widthOffset: 0, heightOffset: 1, opacity: 1) self.subTitleLabel.setShadowOffsetForLetters(blurRadius: 0, widthOffset: 0, heightOffset: 1, opacity: 1) self.titleLabel.numberOfLines = 0 self.subTitleLabel.numberOfLines = 0 } override func layoutSubviews() { super.layoutSubviews() self.backgroundView.frame = self.bounds let titleWidth = self.frame.width * self.titleWidthFactor let subTitleWidth = self.frame.width * self.subTitleWidthFactor self.titleLabel.frame = CGRect.init(x: 0, y: 0, width: titleWidth, height: self.frame.height) self.subTitleLabel.frame = CGRect.init(x: 0, y: 0, width: subTitleWidth, height: self.frame.height) self.titleLabel.sizeToFit() self.subTitleLabel.sizeToFit() let titleHeight = self.titleLabel.frame.height let subTitleHeight = self.subTitleLabel.frame.height let titleYPosition = (self.frame.height - (titleHeight + subTitleHeight)) / 2 let subtitleYPosition = titleYPosition + titleHeight self.titleLabel.frame = CGRect.init(x: 0, y: titleYPosition, width: titleWidth, height: titleHeight) self.titleLabel.center.x = self.frame.width / 2 self.subTitleLabel.frame = CGRect.init(x: 0, y: subtitleYPosition, width: subTitleWidth, height: subTitleHeight) self.subTitleLabel.center.x = self.frame.width / 2 self.backgroundView.frame = self.bounds } } @available(iOS, unavailable) class SPLabelWithSubLabelView: UIView { let additionalLabel: UILabel = UILabel() let mainLabel: UILabel = UILabel() var onTopView: KindView = .main var relativeHeightFactor: CGFloat = 0.758 init() { super.init(frame: CGRect.zero) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.additionalLabel) self.addSubview(self.mainLabel) } override func layoutSubviews() { super.layoutSubviews() if self.onTopView == .main { self.mainLabel.frame = CGRect.init(x: 0, y: 0, width: self.frame.width, height: self.frame.height * self.relativeHeightFactor) self.additionalLabel.frame = CGRect.init(x: 0, y: self.mainLabel.frame.height, width: self.frame.width, height: self.frame.height * (1 - self.relativeHeightFactor)) } else { self.additionalLabel.frame = CGRect.init(x: 0, y: 0, width: self.frame.width, height: self.frame.height * (1 - self.relativeHeightFactor)) self.mainLabel.frame = CGRect.init(x: 0, y: self.additionalLabel.frame.height, width: self.frame.width, height: self.frame.height * self.relativeHeightFactor) } } enum KindView { case main case additional } } @available(iOS, unavailable) class SPLabelWithSubLabelButton: UIButton { let additionalLabel: UILabel = UILabel() let mainLabel: UILabel = UILabel() var relativeHeightFactor: CGFloat = 0.758 init() { super.init(frame: CGRect.zero) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.additionalLabel) self.addSubview(self.mainLabel) } override func layoutSubviews() { super.layoutSubviews() self.additionalLabel.frame = CGRect.init(x: 0, y: 0, width: self.frame.width, height: self.frame.height * (1 - self.relativeHeightFactor)) self.mainLabel.frame = CGRect.init(x: 0, y: self.additionalLabel.frame.height, width: self.frame.width, height: self.frame.height * self.relativeHeightFactor) } }
mit
422b613d067ef4334661dffacd2de2aa
36.039326
176
0.668588
4.377822
false
false
false
false
victorchee/ForceTouch
ForceTouch/ForceTouch/AppDelegate.swift
1
4040
// // AppDelegate.swift // ForceTouch // // Created by qihaijun on 11/12/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. createDynamicShortcuts() 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: - Shortcut Item func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { guard let shortcutType = shortcutItem.type as String? else { return } let navigationController = self.window?.rootViewController as? UINavigationController let master = navigationController?.viewControllers.first master?.navigationItem.prompt = shortcutType } /** You can add 4 shortcuts at most. */ private func createDynamicShortcuts() { if let items = UIApplication.sharedApplication().shortcutItems { for item in items { if item.type == "Custom" { return } } } // Item without icon let item0 = UIApplicationShortcutItem(type: "Custom", localizedTitle: "Item without icon") // Item with icon let icon = UIApplicationShortcutIcon(templateImageName: "momey") let item1 = UIApplicationShortcutItem(type: "Custom", localizedTitle: "Item with icon", localizedSubtitle: "Subtitle", icon: icon, userInfo: nil) let systemIcon = UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.Shuffle) let item2 = UIApplicationShortcutItem(type: "Custom", localizedTitle: "Item with system icon", localizedSubtitle: "", icon: systemIcon, userInfo: nil) if var items = UIApplication.sharedApplication().shortcutItems { for item in [item0, item1, item2] { items.append(item) } UIApplication.sharedApplication().shortcutItems = items } else { UIApplication.sharedApplication().shortcutItems = [item0, item1, item2] } } }
mit
34142c527f1d41ec42d945f084f48bf8
44.382022
285
0.695222
5.664797
false
false
false
false
LiwxCoder/Swift-Weibo
Weibo/Weibo/Classes/Main(主要)/MainViewController.swift
1
2942
// // MainViewController.swift // Weibo // // Created by liwx on 16/2/27. // Copyright © 2016年 liwx. All rights reserved. // import UIKit class MainViewController: UITabBarController { // MARK: ====================================================================== // MARK: - Property (懒加载,属性监听) // 已在storyboard中设置好TabBarButton显示的内容,所以就无需再定义该属性 // lazy var imageNames : [String] = { // return ["tabbar_home", "tabbar_message_center", "", "tabbar_discover", "tabbar_profile"] // }() // MARK: ====================================================================== // MARK: - Life cycle (生命周期,类似addSubview和Notification的监听和销毁都放在这里) override func viewDidLoad() { super.viewDidLoad() // 1.添加加号按钮 setupComposeBtn() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) adjustItems() } /// 添加发布按钮 private func setupComposeBtn() { // 1.创建发布按钮 let composeBtn = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button") // 2.设置加号按钮的位置 composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.bounds.size.height * 0.5) // 3.添加监听 composeBtn.addTarget(self, action: "composeBtnClick:", forControlEvents: .TouchUpInside) // 4.添加到tabBar tabBar.addSubview(composeBtn) } /// 设置中间加按钮不能点击 private func adjustItems() { // 遍历UITabBarItem,设置最中间的item不能点击,目的是为了让中间item的点击事件传递到底部的按钮 for i in 0..<tabBar.items!.count { // 1.取出item let item = tabBar.items![i] // 2.如果是第二个item,则不能交互,这样时间才能传递给下面的加号按钮 if i == 2 { item.enabled = false continue } // 3.设置item显示的图片,因为该操作已经在storyboard中设置过,所以此处不再设置 // item.image = UIImage(named: imageNames[i]) // item.selectedImage = UIImage(named: imageNames[i] + "_highlighted") } } // MARK: ====================================================================== // MARK: - Event response (事件处理) // MARK:- 事件监听的函数 // 事件监听本质是在发送消息 // 如果一个函数声明private,那么该函数不会在对象的方法列表中 // 加上@objc,就可以将函数添加到方法列表中 @objc private func composeBtnClick(composeBtn: UIButton) { WXLog("composeBtnClick"); } }
mit
5c5d715e5936ddf9121e340198f4d114
27.823529
109
0.519804
4.200686
false
false
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Native/SPNativeColors.swift
1
1983
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit enum SPNativeColors { static let red = UIColor.init(hex: "FF3B30") static let orange = UIColor.init(hex: "FF9500") static let yellow = UIColor.init(hex: "FFCC00") static let green = UIColor.init(hex: "4CD964") static let tealBlue = UIColor.init(hex: "5AC8FA") static let blue = UIColor.init(hex: "007AFF") static let purple = UIColor.init(hex: "5856D6") static let pink = UIColor.init(hex: "FF2D55") static let white = UIColor.init(hex: "FFFFFF") static let customGray = UIColor.init(hex: "EFEFF4") static let lightGray = UIColor.init(hex: "E5E5EA") static let lightGray2 = UIColor.init(hex: "D1D1D6") static let midGray = UIColor.init(hex: "C7C7CC") static let gray = UIColor.init(hex: "8E8E93") static let black = UIColor.init(hex: "000000") }
mit
91cd53a94235e98c997a5cf098f73335
47.341463
81
0.726539
3.833656
false
false
false
false
duliodenis/buzzlr
buzzlr/Frameworks/OAuthSwift/OAuthSwift/SHA1.swift
18
4502
// // SHA1.swift // OAuthSwift // // Created by Dongri Jin on 1/28/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation class SHA1 { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len:Int = 64) -> NSMutableData { var tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.length % len != (len - 8) { tmpMessage.appendBytes([0x00]) } return tmpMessage } func calculate() -> NSData { //var tmpMessage = self.prepare() let len = 64 let h:[UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] var tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.length % len != (len - 8) { tmpMessage.appendBytes([0x00]) } // hash values var hh = h // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage.appendBytes((self.message.length * 8).bytes(64 / 8)) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes))) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into eighty 32-bit words: var M:[UInt32] = [UInt32](count: 80, repeatedValue: 0) for x in 0..<M.count { switch (x) { case 0...15: var le:UInt32 = 0 chunk.getBytes(&le, range:NSRange(location:x * sizeofValue(M[x]), length: sizeofValue(M[x]))) M[x] = le.bigEndian break default: M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], 1) break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] // Main loop for j in 0...79 { var f: UInt32 = 0 var k: UInt32 = 0 switch (j) { case 0...19: f = (B & C) | ((~B) & D) k = 0x5A827999 break case 20...39: f = B ^ C ^ D k = 0x6ED9EBA1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8F1BBCDC break case 60...79: f = B ^ C ^ D k = 0xCA62C1D6 break default: break } var temp = (rotateLeft(A,5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff E = D D = C C = rotateLeft(B, 30) B = A A = temp } hh[0] = (hh[0] &+ A) & 0xffffffff hh[1] = (hh[1] &+ B) & 0xffffffff hh[2] = (hh[2] &+ C) & 0xffffffff hh[3] = (hh[3] &+ D) & 0xffffffff hh[4] = (hh[4] &+ E) & 0xffffffff } // Produce the final hash value (big-endian) as a 160 bit number: var buf: NSMutableData = NSMutableData() hh.map({ (item) -> () in var i:UInt32 = item.bigEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData } }
mit
175372784489515e943217bec7b03eeb
32.544776
119
0.455496
4.219718
false
false
false
false
JoMo1970/cordova-plugin-qrcode-reader
src/ios/QRCodeReaderViewController.swift
1
7025
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit import AVFoundation /// Convenient controller to display a view to scan/read 1D or 2D bar codes like the QRCodes. It is based on the `AVFoundation` framework from Apple. It aims to replace ZXing or ZBar for iOS 7 and over. public class QRCodeReaderViewController: UIViewController { /// The code reader object used to scan the bar code. public let codeReader: QRCodeReaderApp let readerView: QRCodeReaderContainer let startScanningAtLoad: Bool let showCancelButton: Bool let showSwitchCameraButton: Bool let showTorchButton: Bool let showOverlayView: Bool // MARK: - Managing the Callback Responders /// The receiver's delegate that will be called when a result is found. public weak var delegate: QRCodeReaderViewControllerDelegate? /// The completion blocak that will be called when a result is found. public var completionBlock: ((QRCodeReaderResult?) -> Void)? deinit { codeReader.stopScanning() NotificationCenter.default.removeObserver(self) } // MARK: - Creating the View Controller /** Initializes a view controller using a builder. - parameter builder: A QRCodeViewController builder object. */ required public init(builder: QRCodeReaderViewControllerBuilder) { readerView = builder.readerView startScanningAtLoad = builder.startScanningAtLoad codeReader = builder.reader showCancelButton = builder.showCancelButton showSwitchCameraButton = builder.showSwitchCameraButton showTorchButton = builder.showTorchButton showOverlayView = builder.showOverlayView super.init(nibName: nil, bundle: nil) view.backgroundColor = .black codeReader.didFindCode = { [weak self] resultAsObject in if let weakSelf = self { if let qrv = weakSelf.readerView.displayable as? QRCodeReaderView { qrv.addGreenBorder() } weakSelf.completionBlock?(resultAsObject) weakSelf.delegate?.reader(weakSelf, didScanResult: resultAsObject) } } codeReader.didFailDecoding = { [weak self] in if let weakSelf = self { if let qrv = weakSelf.readerView.displayable as? QRCodeReaderView { qrv.addRedBorder() } } } setupUIComponentsWithCancelButtonTitle(builder.cancelButtonTitle) } required public init?(coder aDecoder: NSCoder) { codeReader = QRCodeReaderApp() readerView = QRCodeReaderContainer(displayable: QRCodeReaderView()) startScanningAtLoad = false showCancelButton = false showTorchButton = false showSwitchCameraButton = false showOverlayView = false super.init(coder: aDecoder) } // MARK: - Responding to View Events override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if startScanningAtLoad { startScanning() } } override public func viewWillDisappear(_ animated: Bool) { stopScanning() super.viewWillDisappear(animated) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() //init a new rect object let rect: CGRect = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) var innerRect = rect.insetBy(dx: 50, dy: 50) let minSize = min(innerRect.width, innerRect.height) if innerRect.width != minSize { innerRect.origin.x += (innerRect.width - minSize) / 2 innerRect.size.width = minSize } else if innerRect.height != minSize { innerRect.origin.y += (innerRect.height - minSize) / 2 innerRect.size.height = minSize } //set the rect object into place codeReader.previewLayer.frame = innerRect } // MARK: - Initializing the AV Components private func setupUIComponentsWithCancelButtonTitle(_ cancelButtonTitle: String) { view.addSubview(readerView.view) let sscb = showSwitchCameraButton && codeReader.hasFrontDevice let stb = showTorchButton && codeReader.isTorchAvailable readerView.view.translatesAutoresizingMaskIntoConstraints = false readerView.setupComponents(showCancelButton: showCancelButton, showSwitchCameraButton: sscb, showTorchButton: stb, showOverlayView: showOverlayView, reader: codeReader) // Setup action methods readerView.displayable.switchCameraButton?.addTarget(self, action: #selector(switchCameraAction), for: .touchUpInside) readerView.displayable.toggleTorchButton?.addTarget(self, action: #selector(toggleTorchAction), for: .touchUpInside) readerView.displayable.cancelButton?.setTitle(cancelButtonTitle, for: .normal) readerView.displayable.cancelButton?.addTarget(self, action: #selector(cancelAction), for: .touchUpInside) // Setup constraints for attribute in [NSLayoutAttribute.left, NSLayoutAttribute.top, NSLayoutAttribute.right, NSLayoutAttribute.bottom] { view.addConstraint(NSLayoutConstraint(item: readerView.view, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: 1, constant: 0)) } } // MARK: - Controlling the Reader /// Starts scanning the codes. public func startScanning() { codeReader.startScanning() } /// Stops scanning the codes. public func stopScanning() { codeReader.stopScanning() } // MARK: - Catching Button Events func cancelAction(_ button: UIButton) { codeReader.stopScanning() if let _completionBlock = completionBlock { _completionBlock(nil) } delegate?.readerDidCancel(self) } func switchCameraAction(_ button: SwitchCameraButton) { if let newDevice = codeReader.switchDeviceInput() { delegate?.reader(self, didSwitchCamera: newDevice) } } func toggleTorchAction(_ button: ToggleTorchButton) { codeReader.toggleTorch() } }
mit
9dbe79840f689c2146e7002efbffd0ce
33.436275
202
0.722705
4.950669
false
false
false
false
pedrohperalta/StarWars-iOS-BDD
StarWarsTests/Modules/CharactersPresenterTests.swift
1
2710
// // Created by Pedro Henrique Prates Peralta on 5/15/16. // Copyright (c) 2016 Pedro Henrique Peralta. All rights reserved. // @testable import StarWars import Quick import Nimble class CharactersPresenterTests: QuickSpec { var sut: CharactersPresenter! var charactersInteractorMock: CharactersInteractorMock! var charactersViewMock: CharactersViewMock! override func spec() { beforeSuite { self.sut = CharactersPresenter() self.charactersInteractorMock = CharactersInteractorMock() self.charactersViewMock = CharactersViewMock() self.sut.interactor = self.charactersInteractorMock self.sut.view = self.charactersViewMock } describe("The Presenter being loaded") { beforeEach { self.sut.viewDidLoad() } it("Should ask the Interactor to fetch the characters") { expect(self.charactersInteractorMock.fetchCharactersCalled).to(beTrue()) } } describe("The Presenter being notified about the end of the fetch characters operation") { context("When a valid list of characters is fetched") { beforeEach { self.sut.didFetchCharactersWithSuccess([[:]]) } it("Should tell the view to show the list of characters fetched") { expect(self.charactersViewMock.showCharactersListCalled).to(beTrue()) } } context("When the resquest returns a failure response") { beforeEach { self.sut.didFailToFetchCharacters() } it("Should tell the view to show the empty dataset screen") { expect(self.charactersViewMock.showEmptyDatasetScreenCalled).to(beTrue()) } } } afterSuite { self.sut = nil self.charactersInteractorMock = nil } } } class CharactersInteractorMock: CharactersUseCase { var fetchCharactersCalled = false func fetchCharacters() { fetchCharactersCalled = true } } class CharactersViewMock: CharactersView { var showCharactersListCalled = false var showEmptyDatasetScreenCalled = false func showCharactersList(_ characters: [[String: String]]) { self.showCharactersListCalled = true } func showEmptyDatasetScreen() { self.showEmptyDatasetScreenCalled = true } }
mit
ec62b6b4192eb3aa06e58cdef65687eb
26.938144
98
0.576015
5.564682
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/IGListKit/Examples/Examples-macOS/IGListKitExamples/Models/User.swift
2
1201
/** Copyright (c) Facebook, Inc. and its affiliates. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import IGListDiffKit final class User: ListDiffable { let pk: Int let name: String init(pk: Int, name: String) { self.pk = pk self.name = name } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return pk as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard self !== object else { return true } guard let object = object as? User else { return false } return name == object.name } }
apache-2.0
96dbe28d92bb2dc49fb3973472675294
29.025
80
0.706911
4.747036
false
false
false
false
eytanbiala/On-The-Map
On The Map/MapViewController.swift
1
3446
// // MapViewController.swift // On The Map // // Created by Eytan Biala on 4/26/16. // Copyright © 2016 Udacity. All rights reserved. // import Foundation import UIKit import MapKit class MapViewController : UIViewController, MKMapViewDelegate { var mapView: MKMapView! convenience init() { self.init(nibName:nil, bundle:nil) tabBarItem.title = "Map" tabBarItem.image = UIImage(named: "map") } override func viewDidLoad() { super.viewDidLoad() mapView = MKMapView(frame: view.frame) mapView.delegate = self view.addSubview(mapView) } func reload() { if let locations = Model.sharedInstance.studentLocations { addAnnotations(locations) } } func addAnnotations(locations: [User]) { // We will create an MKPointAnnotation for each dictionary in "locations". The // point annotations will be stored in this array, and then provided to the map view. var annotations = [MKPointAnnotation]() // The "locations" array is loaded with the sample data below. We are using the dictionaries // to create map annotations. This would be more stylish if the dictionaries were being // used to create custom structs. Perhaps StudentLocation structs. for user in locations { // Here we create the annotation and set its coordiate, title, and subtitle properties let annotation = MKPointAnnotation() annotation.coordinate = user.coordinate annotation.title = "\(user.first) \(user.last)" annotation.subtitle = user.url // Finally we place the annotation in an array of annotations. annotations.append(annotation) } // Clear any existing annotations mapView.removeAnnotations(mapView.annotations) // Add the annotations to the map. mapView.addAnnotations(annotations) } // MARK: - MKMapViewDelegate // Here we create a view with a "right callout accessory view". You might choose to look into other // decoration alternatives. Notice the similarity between this method and the cellForRowAtIndexPath // method in TableViewDataSource. func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.pinTintColor = UIColor.redColor() pinView!.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) } else { pinView!.annotation = annotation } return pinView } // This delegate method is implemented to respond to taps. It opens the system browser // to the URL specified in the annotationViews subtitle property. func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { let app = UIApplication.sharedApplication() if let toOpen = view.annotation?.subtitle! { app.openURL(NSURL(string: toOpen)!) } } } }
mit
cbf8b31e815cf5feac631b8fa2e02deb
33.46
127
0.661829
5.391236
false
false
false
false
jjatie/Charts
ChartsDemo-iOS/Swift/Demos/LineChartFilledViewController.swift
1
3853
// // LineChartFilledViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class LineChartFilledViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Filled Line Chart" chartView.delegate = self chartView.backgroundColor = .white chartView.gridBackgroundColor = UIColor(red: 51 / 255, green: 181 / 255, blue: 229 / 255, alpha: 150 / 255) chartView.isDrawGridBackgroundEnabled = true chartView.isDrawBordersEnabled = true chartView.chartDescription.isEnabled = false chartView.isPinchZoomEnabled = false chartView.isDragEnabled = true chartView.setScaleEnabled(true) chartView.legend.isEnabled = false chartView.xAxis.isEnabled = false let leftAxis = chartView.leftAxis leftAxis.axisMaximum = 900 leftAxis.axisMinimum = -250 leftAxis.drawAxisLineEnabled = false chartView.rightAxis.isEnabled = false sliderX.value = 100 sliderY.value = 60 slidersValueChanged(nil) } override func updateChartData() { if shouldHideData { chartView.data = nil return } setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let yVals1 = (0 ..< count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 50) return ChartDataEntry(x: Double(i), y: val) } let yVals2 = (0 ..< count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 450) return ChartDataEntry(x: Double(i), y: val) } let set1 = LineChartDataSet(entries: yVals1, label: "DataSet 1") set1.axisDependency = .left set1.setColor(UIColor(red: 255 / 255, green: 241 / 255, blue: 46 / 255, alpha: 1)) set1.isDrawCirclesEnabled = false set1.lineWidth = 2 set1.circleRadius = 3 set1.fillAlpha = 1 set1.isDrawFilledEnabled = true set1.fill = ColorFill(color: .white) set1.highlightColor = UIColor(red: 244 / 255, green: 117 / 255, blue: 117 / 255, alpha: 1) set1.isDrawCircleHoleEnabled = false set1.fillFormatter = DefaultFillFormatter { _, _ -> CGFloat in CGFloat(self.chartView.leftAxis.axisMinimum) } let set2 = LineChartDataSet(entries: yVals2, label: "DataSet 2") set2.axisDependency = .left set2.setColor(UIColor(red: 255 / 255, green: 241 / 255, blue: 46 / 255, alpha: 1)) set2.isDrawCirclesEnabled = false set2.lineWidth = 2 set2.circleRadius = 3 set2.fillAlpha = 1 set2.isDrawFilledEnabled = true set2.fill = ColorFill(color: .white) set2.highlightColor = UIColor(red: 244 / 255, green: 117 / 255, blue: 117 / 255, alpha: 1) set2.isDrawCircleHoleEnabled = false set2.fillFormatter = DefaultFillFormatter { _, _ -> CGFloat in CGFloat(self.chartView.leftAxis.axisMaximum) } let data: LineChartData = [set1, set2] data.setDrawValues(false) chartView.data = data } @IBAction func slidersValueChanged(_: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" updateChartData() } }
apache-2.0
c3cf7e7a2f0c497eb504c3fd1f7fdeab
31.644068
115
0.628764
4.448037
false
false
false
false
fabioalmeida/FAAutoLayout
FAAutoLayout/Classes/UIView+Bottom.swift
1
4494
// // UIView+Bottom.swift // FAAutoLayout // // Created by Fábio Almeida on 27/06/2017. // Copyright (c) 2017 Fábio Almeida. All rights reserved. // import UIKit // MARK: - Bottom public extension UIView { /// Constrains the view bottom space to its container view (i.e. the view **superview**). /// /// This contraint is added directly to the container view and is returned for future manipulation (if needed). /// This method should be used for most of the cases you wish to define a bottom space relation between a view /// and the correspondent container view. /// /// The arguments should only be changed when the desired value is not the default value, to simplify the method readability. /// All the **default values** for this contraint are the same as if the constraint was created on the Interface Builder. /// /// - Parameters: /// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0. /// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal. /// - priority: The priority of the constraint. The default value is 1000 (required). /// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1. /// - Returns: The added constraint between the two views. @discardableResult @objc(constrainBottomSpaceToContainer:relation:priority:multiplier:) func constrainBottomSpaceToContainer(_ constant: CGFloat = Constants.spacing, relation: NSLayoutConstraint.Relation = Constants.relation, priority: UILayoutPriority = Constants.priority, multiplier: CGFloat = Constants.multiplier) -> NSLayoutConstraint { validateViewHierarchy() return constrainBottomSpace(toContainerView: superview!, constant: constant, relation: relation, priority: priority, multiplier: multiplier) } /// Constrains the view bottom space to a container view (e.g. the view **superview** or another view higher in the hierarchy). /// /// This contraint is added directly to the container view and is returned for future manipulation (if needed). /// This method should be used when you wish to define a bottom space relation to a view that is above the direct /// container view hierarchy, for instance, `self.superview.superview`. /// If you wish to just define a relation between the view and the direct superview, please refer to `constrainBottomSpaceToContainer()`. /// /// The arguments should only be changed when the desired value is not the default value, to simplify the method readability. /// All the **default values** for this contraint are the same as if the constraint was created on the Interface Builder. /// /// - Parameters: /// - containerView: The container view for which we want to create the bottom space relation. For example, view.superview.superview. /// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0. /// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal. /// - priority: The priority of the constraint. The default value is 1000 (required). /// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1. /// - Returns: The added constraint between the two views. @discardableResult @objc(constrainBottomSpaceToContainerView:constant:relation:priority:multiplier:) func constrainBottomSpace(toContainerView containerView: UIView, constant: CGFloat = Constants.spacing, relation: NSLayoutConstraint.Relation = Constants.relation, priority: UILayoutPriority = Constants.priority, multiplier: CGFloat = Constants.multiplier) -> NSLayoutConstraint { let constraint = NSLayoutConstraint.bottomSpaceConstraint(fromView: self, toView: containerView, relation: relation, multiplier: multiplier, constant: constant) constraint.priority = priority containerView.addConstraint(constraint) return constraint } }
mit
239beca6077eb9c18fd10e003cb20275
61.388889
168
0.690116
5.211137
false
false
false
false
andrebocchini/SwiftChatty
Pods/Alamofire/Source/Notifications.swift
2
2842
// // Notifications.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Notification.Name { /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") } } // MARK: - extension Notification { /// Used as a namespace for all `Notification` user info dictionary keys. public struct Key { /// User info dictionary key representing the `URLSessionTask` associated with the notification. public static let Task = "org.alamofire.notification.key.task" /// User info dictionary key representing the responseData associated with the notification. public static let ResponseData = "org.alamofire.notification.key.responseData" } }
mit
fa9adf500e6e677f26af8d6840371c1b
50.672727
123
0.741731
4.713101
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Generators/Noise/Pink Noise/AKPinkNoise.swift
1
3205
// // AKPinkNoise.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Faust-based pink noise generator /// /// - parameter amplitude: Amplitude. (Value between 0-1). /// public class AKPinkNoise: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKPinkNoiseAudioUnit? internal var token: AUParameterObserverToken? private var amplitudeParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Amplitude. (Value between 0-1). public var amplitude: Double = 1 { willSet { if amplitude != newValue { amplitudeParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this noise node /// /// - parameter amplitude: Amplitude. (Value between 0-1). /// public init(amplitude: Double = 1) { self.amplitude = amplitude var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = fourCC("pink") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKPinkNoiseAudioUnit.self, asComponentDescription: description, name: "Local AKPinkNoise", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPinkNoiseAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } } } internalAU?.amplitude = Float(amplitude) } /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
fca163484fd3b68bbf42f11a1c500e73
28.675926
87
0.621217
5.368509
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/Keyknox/SyncKeyStorage/SyncKeyStorageError.swift
2
4555
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Declares error types and codes for SyncKeyStorage /// /// - keychainEntryNotFoundWhileUpdating: KeychainEntry not found while updating /// - cloudEntryNotFoundWhileUpdating: CloudEntry not found while updating /// - cloudEntryNotFoundWhileDeleting: CloudEntry not found while deleting /// - keychainEntryNotFoundWhileComparing: KeychainEntry not found while comparing /// - keychainEntryAlreadyExistsWhileStoring: KeychainEntry already exists while storing /// - cloudEntryAlreadyExistsWhileStoring: CloudEntry already exists while storing /// - invalidModificationDateInKeychainEntry: Invalid modificationDate in KeychainEntry /// - invalidCreationDateInKeychainEntry: Invalid creationDate in KeychainEntry /// - noMetaInKeychainEntry: No meta in keychainEntry /// - invalidKeysInEntryMeta: Invalid keys in entry meta /// - inconsistentStateError: Inconsistent state error /// - entrySavingError: Error while saving entry @objc(VSSSyncKeyStorageError) public enum SyncKeyStorageError: Int, LocalizedError { case keychainEntryNotFoundWhileUpdating = 1 case cloudEntryNotFoundWhileUpdating = 2 case cloudEntryNotFoundWhileDeleting = 3 case keychainEntryNotFoundWhileComparing = 4 case keychainEntryAlreadyExistsWhileStoring = 5 case cloudEntryAlreadyExistsWhileStoring = 6 case invalidModificationDateInKeychainEntry = 7 case invalidCreationDateInKeychainEntry = 8 case noMetaInKeychainEntry = 9 case invalidKeysInEntryMeta = 10 case inconsistentStateError = 11 case entrySavingError = 12 /// Human-readable localized description public var errorDescription: String? { switch self { case .keychainEntryNotFoundWhileUpdating: return "KeychainEntry not found while updating" case .cloudEntryNotFoundWhileUpdating: return "CloudEntry not found while updating" case .cloudEntryNotFoundWhileDeleting: return "CloudEntry not found while deleting" case .keychainEntryNotFoundWhileComparing: return "KeychainEntry not found while comparing" case .keychainEntryAlreadyExistsWhileStoring: return "KeychainEntry already exists while storing" case .cloudEntryAlreadyExistsWhileStoring: return "CloudEntry already exists while storing" case .invalidModificationDateInKeychainEntry: return "Invalid modificationDate in KeychainEntry" case .invalidCreationDateInKeychainEntry: return "Invalid creationDate in KeychainEntry" case .noMetaInKeychainEntry: return "No meta in keychainEntry" case .invalidKeysInEntryMeta: return "Invalid keys in entry meta" case .inconsistentStateError: return "Inconsistent state error" case .entrySavingError: return "Error while saving entry" } } }
bsd-3-clause
d97b9460dbdc391c9c8ab34b84966093
46.447917
88
0.749067
5.152715
false
false
false
false
richardpiazza/XCServerAPI
Sources/XCServerWebAPI.swift
2
7108
import Foundation import CodeQuickKit public typealias XCServerWebAPICredentials = (username: String, password: String?) public typealias XCServerWebAPICredentialsHeader = (value: String, key: String) @available(*, deprecated, message: "Use `XCServerClientAuthorizationDelegate`.") public protocol XCServerWebAPICredentialDelegate { func credentials(forAPI api: XCServerWebAPI) -> XCServerWebAPICredentials? func credentialsHeader(forAPI api: XCServerWebAPI) -> XCServerWebAPICredentialsHeader? func clearCredentials(forAPI api: XCServerWebAPI) } @available(*, deprecated) public extension XCServerWebAPICredentialDelegate { public func credentialsHeader(forAPI api: XCServerWebAPI) -> XCServerWebAPICredentialsHeader? { guard let creds = credentials(forAPI: api) else { return nil } let username = creds.username let password = creds.password ?? "" let userpass = "\(username):\(password)" guard let data = userpass.data(using: String.Encoding.utf8, allowLossyConversion: true) else { return nil } let base64 = data.base64EncodedString(options: []) let auth = "Basic \(base64)" return XCServerWebAPICredentialsHeader(value: auth, key: HTTP.Header.authorization.rawValue) } public func clearCredentials(forAPI api: XCServerWebAPI) { Log.info("Reset of XCServerWebAPI requested; Credentials should be cleared.") } } /// Wrapper for `WebAPI` that implements common Xcode Server requests. @available(*, deprecated, message: "Use `XCServerClient`.") public class XCServerWebAPI: WebAPI { public struct HTTPHeaders { public static let xscAPIVersion = "x-xscapiversion" } public enum Errors: Error, LocalizedError { case authorization case noXcodeServer case decodeResponse public var errorDescription: String? { switch self { case .authorization: return "The server returned a 401 response code." case .noXcodeServer: return "This class was initialized without an XcodeServer entity." case .decodeResponse: return "The response object could not be cast into the requested type." } } } /// Class implementing the NSURLSessionDelegate which forcefully bypasses /// untrusted SSL Certificates. public class XCServerDefaultSessionDelegate: NSObject, URLSessionDelegate { // MARK: - NSURLSessionDelegate @objc open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard challenge.previousFailureCount < 1 else { completionHandler(.cancelAuthenticationChallenge, nil) return } var credentials: URLCredential? if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let serverTrust = challenge.protectionSpace.serverTrust { credentials = URLCredential(trust: serverTrust) } } completionHandler(.useCredential, credentials) } } /// Class implementing the XCServerWebAPICredentialDelgate public class XCServerDefaultCredentialDelegate: XCServerWebAPICredentialDelegate { // MARK: - XCServerWebAPICredentialsDelegate open func credentials(forAPI api: XCServerWebAPI) -> XCServerWebAPICredentials? { return nil } } public static var sessionDelegate: URLSessionDelegate = XCServerDefaultSessionDelegate() public static var credentialDelegate: XCServerWebAPICredentialDelegate = XCServerDefaultCredentialDelegate() fileprivate static var apis = [String : XCServerWebAPI]() public static func api(forFQDN fqdn: String) -> XCServerWebAPI { if let api = self.apis[fqdn] { return api } guard let api = XCServerWebAPI(fqdn: fqdn) else { preconditionFailure() } api.session.configuration.timeoutIntervalForRequest = 8 api.session.configuration.timeoutIntervalForResource = 16 api.session.configuration.httpCookieAcceptPolicy = .never api.session.configuration.httpShouldSetCookies = false self.apis[fqdn] = api return api } public static func resetAPI(forFQDN fqdn: String) { guard let api = self.apis[fqdn] else { return } credentialDelegate.clearCredentials(forAPI: api) self.apis[fqdn] = nil } public convenience init?(fqdn: String) { guard let url = URL(string: "https://\(fqdn):20343/api") else { return nil } self.init(baseURL: url, session: nil, delegate: XCServerWebAPI.sessionDelegate) } public func request(method: HTTP.RequestMethod, path: String, queryItems: [URLQueryItem]?, data: Data?) throws -> URLRequest { var request = try super.request(method: method, path: path, queryItems: queryItems, data: data) if let header = XCServerWebAPI.credentialDelegate.credentialsHeader(forAPI: self) { request.setValue(header.value, forHTTPHeaderField: header.key) } return request } // MARK: - Endpoints /// Requests the '`/ping`' endpoint from the Xcode Server API. public func ping(_ completion: @escaping HTTP.DataTaskCompletion) { self.get("ping", completion: completion) } public typealias VersionCompletion = (_ version: XCSVersion?, _ apiVersion: Int?, _ error: Error?) -> Void /// Requests the '`/versions`' endpoint from the Xcode Server API. public func versions(_ completion: @escaping VersionCompletion) { self.get("versions") { (statusCode, headers, data, error) in var apiVersion: Int? guard statusCode != 401 else { completion(nil, apiVersion, Errors.authorization) return } guard statusCode == 200 else { completion(nil, apiVersion, error) return } if let responseHeaders = headers { if let version = responseHeaders[HTTPHeaders.xscAPIVersion] as? String { apiVersion = Int(version) } } guard let responseData = data else { completion(nil, apiVersion, Errors.decodeResponse) return } guard let versions = XCSVersion.decode(data: responseData) else { completion(nil, apiVersion, Errors.decodeResponse) return } completion(versions, apiVersion, nil) } } }
mit
652e0019770646bccef0df00f6c7b739
37.010695
201
0.629854
5.312407
false
false
false
false
practicalswift/swift
test/SILGen/protocol_with_superclass.swift
4
11963
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s // Protocols with superclass-constrained Self. class Concrete { typealias ConcreteAlias = String func concreteMethod(_: ConcreteAlias) {} } class Generic<T> : Concrete { typealias GenericAlias = (T, T) func genericMethod(_: GenericAlias) {} } protocol BaseProto {} protocol ProtoRefinesClass : Generic<Int>, BaseProto { func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) } extension ProtoRefinesClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass17ProtoRefinesClassPAAE019extensionMethodUsesF5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: [[METHOD:%.*]] = class_method [[UPCAST2]] : $Concrete, #Concrete.concreteMethod!1 : (Concrete) -> (String) -> (), $@convention(method) (@guaranteed String, @guaranteed Concrete) -> () // CHECK-NEXT: apply [[METHOD]](%0, [[UPCAST2]]) // CHECK-NEXT: destroy_value [[UPCAST2]] concreteMethod(x) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK: [[METHOD:%.*]] = class_method [[UPCAST]] : $Generic<Int>, #Generic.genericMethod!1 : <T> (Generic<T>) -> ((T, T)) -> (), $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, @guaranteed Generic<τ_0_0>) -> () // CHECK-NEXT: apply [[METHOD]]<Int>({{.*}}, [[UPCAST]]) // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: destroy_value [[UPCAST]] genericMethod(y) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: destroy_value [[UPCAST]] : $Generic<Int> let _: Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: destroy_value [[UPCAST2]] : $Concrete let _: Concrete = self // CHECK: [[BOX:%.*]] = alloc_stack $BaseProto // CHECK-NEXT: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[ADDR:%.*]] = init_existential_addr [[BOX]] : $*BaseProto, $Self // CHECK-NEXT: store [[SELF]] to [init] [[ADDR]] : $*Self // CHECK-NEXT: destroy_addr [[BOX]] : $*BaseProto // CHECK-NEXT: dealloc_stack [[BOX]] : $*BaseProto let _: BaseProto = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Generic<Int> & BaseProto let _: BaseProto & Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Concrete & BaseProto let _: BaseProto & Concrete = self // CHECK: return } } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass22usesProtoRefinesClass1yyAA0eF5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesClass) -> () func usesProtoRefinesClass1(_ t: ProtoRefinesClass) { let x: ProtoRefinesClass.ConcreteAlias = "hi" _ = ProtoRefinesClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesClass.GenericAlias = (1, 2) _ = ProtoRefinesClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass22usesProtoRefinesClass2yyxAA0eF5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesClass> (@guaranteed T) -> () func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class GoodConformingClass : Generic<Int>, ProtoRefinesClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass19GoodConformingClassC015requirementUsesF5TypesyySS_Si_SittF : $@convention(method) (@guaranteed String, Int, Int, @guaranteed GoodConformingClass) -> () func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) } } protocol ProtoRefinesProtoWithClass : ProtoRefinesClass {} extension ProtoRefinesProtoWithClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass012ProtoRefinesD9WithClassPAAE026anotherExtensionMethodUsesG5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesProtoWithClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) let _: Generic<Int> = self let _: Concrete = self let _: BaseProto = self let _: BaseProto & Generic<Int> = self let _: BaseProto & Concrete = self } } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass016usesProtoRefinesE10WithClass1yyAA0efeG5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesProtoWithClass) -> () func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) { let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi" _ = ProtoRefinesProtoWithClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2) _ = ProtoRefinesProtoWithClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass016usesProtoRefinesE10WithClass2yyxAA0efeG5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesProtoWithClass> (@guaranteed T) -> () func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class ClassWithInits<T> { init(notRequiredInit: ()) {} required init(requiredInit: ()) {} } protocol ProtocolWithClassInits : ClassWithInits<Int> {} // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass26useProtocolWithClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolWithClassInits.Type) -> () func useProtocolWithClassInits1(_ t: ProtocolWithClassInits.Type) { // CHECK: [[OPENED:%.*]] = open_existential_metatype %0 : $@thick ProtocolWithClassInits.Type // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[OPENED]] : $@thick (@opened("{{.*}}") ProtocolWithClassInits).Type to $@thick ClassWithInits<Int>.Type // CHECK-NEXT: [[METHOD:%.*]] = class_method [[UPCAST]] : $@thick ClassWithInits<Int>.Type, #ClassWithInits.init!allocator.1 : <T> (ClassWithInits<T>.Type) -> (()) -> ClassWithInits<T>, $@convention(method) <τ_0_0> (@thick ClassWithInits<τ_0_0>.Type) -> @owned ClassWithInits<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]<Int>([[UPCAST]]) // CHECK-NEXT: [[CAST:%.*]] = unchecked_ref_cast [[RESULT]] : $ClassWithInits<Int> to $@opened("{{.*}}") ProtocolWithClassInits // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[CAST]] : $@opened("{{.*}}") ProtocolWithClassInits : $@opened("{{.*}}") ProtocolWithClassInits, $ProtocolWithClassInits // CHECK-NEXT: destroy_value [[EXISTENTIAL]] let _: ProtocolWithClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass26useProtocolWithClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolWithClassInits> (@thick T.Type) -> () func useProtocolWithClassInits2<T : ProtocolWithClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } protocol ProtocolRefinesClassInits : ProtocolWithClassInits {} // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass29useProtocolRefinesClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolRefinesClassInits.Type) -> () func useProtocolRefinesClassInits1(_ t: ProtocolRefinesClassInits.Type) { let _: ProtocolRefinesClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass29useProtocolRefinesClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolRefinesClassInits> (@thick T.Type) -> () func useProtocolRefinesClassInits2<T : ProtocolRefinesClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } class ClassWithDefault<T> { func makeT() -> T { while true {} } } protocol SillyDefault : ClassWithDefault<Int> { func makeT() -> Int } class ConformsToSillyDefault : ClassWithDefault<Int>, SillyDefault {} // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW : $@convention(witness_method: SillyDefault) (@guaranteed ConformsToSillyDefault) -> Int // CHECK: class_method %1 : $ClassWithDefault<Int>, #ClassWithDefault.makeT!1 : <T> (ClassWithDefault<T>) -> () -> T, $@convention(method) <τ_0_0> (@guaranteed ClassWithDefault<τ_0_0>) -> @out τ_0_0 // CHECK: return class BaseClass : BaseProto {} protocol RefinedProto : BaseClass {} func takesBaseProtocol(_: BaseProto) {} func passesRefinedProtocol(_ r: RefinedProto) { takesBaseProtocol(r) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass21passesRefinedProtocolyyAA0E5Proto_pF : $@convention(thin) (@guaranteed RefinedProto) -> () // CHECK: bb0(%0 : @guaranteed $RefinedProto): // CHECK: [[OPENED:%.*]] = open_existential_ref %0 : $RefinedProto to $@opened("{{.*}}") RefinedProto // CHECK-NEXT: [[BASE:%.*]] = alloc_stack $BaseProto // CHECK-NEXT: [[BASE_PAYLOAD:%.*]] = init_existential_addr [[BASE]] : $*BaseProto, $@opened("{{.*}}") RefinedProto // CHECK-NEXT: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] : $@opened("{{.*}}") RefinedProto // CHECK-NEXT: store [[OPENED_COPY]] to [init] [[BASE_PAYLOAD]] : $*@opened("{{.*}}") RefinedProto // CHECK: [[FUNC:%.*]] = function_ref @$s24protocol_with_superclass17takesBaseProtocolyyAA0E5Proto_pF : $@convention(thin) (@in_guaranteed BaseProto) -> () // CHECK-NEXT: apply [[FUNC]]([[BASE]]) : $@convention(thin) (@in_guaranteed BaseProto) -> () // CHECK-NEXT: destroy_addr [[BASE]] : $*BaseProto // CHECK-NEXT: dealloc_stack [[BASE]] : $*BaseProto // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL: sil_witness_table hidden ConformsToSillyDefault: SillyDefault module protocol_with_superclass { // CHECK-NEXT: method #SillyDefault.makeT!1: <Self where Self : SillyDefault> (Self) -> () -> Int : @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW // CHECK-NEXT: }
apache-2.0
8df1f3a868af6dec3bd429b236f4eb14
42.624088
284
0.677236
3.573393
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/SegmentedControl/PrimarySegmentedControl.swift
1
9212
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// PrimarySegmentedControl from the Figma Component Library. /// /// /// # Usage: /// /// The PrimarySegmentedControl can be initialized with any number of items, /// and a selection parameter, which indicates the initial selection state. /// Every item can be initialized with a title and a one of its two possible variants. Plus an identifier. /// /// `PrimarySegmentedControl( /// items: [ /// PrimarySegmentedControlItem(title: "Live", variant: .dot, identifier: "live"), /// PrimarySegmentedControlItem(title: "1D", identifier: "1d"), /// PrimarySegmentedControlItem(title: "1W", identifier: "1w"), /// PrimarySegmentedControlItem(title: "1M", identifier: "1m"), /// PrimarySegmentedControlItem(title: "1Y", identifier: "1y"), /// PrimarySegmentedControlItem(title: "All", identifier: "all") /// ], /// selection: $selected /// )` /// /// - Version: 1.0.1 /// /// # Figma /// /// [Controls](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=6%3A544) public struct PrimarySegmentedControl<Selection: Hashable>: View { private var items: [Item] @Binding private var selection: Selection @Environment(\.layoutDirection) private var layoutDirection /// Create a PrimarySegmentedControl view with any number of items and a selection state. /// - Parameter items: Items who represents the buttons inside the segmented control /// - Parameter selection: Binding for `selection` from `items` for the currently selected item. public init( items: [Item], selection: Binding<Selection> ) { self.items = items _selection = selection } public var body: some View { HStack(spacing: 8) { ForEach(items) { item in Button( title: item.title, variant: item.variant, isOn: Binding( get: { selection == item.identifier }, set: { _ in selection = item.identifier } ) ) .anchorPreference(key: ButtonPreferenceKey.self, value: .bounds, transform: { anchor in [item.identifier: anchor] }) if item.identifier != items.last?.identifier { Spacer() } } } .padding(.horizontal, 24) .padding(.vertical, 16) .backgroundPreferenceValue(ButtonPreferenceKey.self) { value in GeometryReader { proxy in if let anchor = value[selection] { movingRectangle(proxy: proxy, anchor: anchor) } } } .background(Color.semantic.background) } @ViewBuilder private func movingRectangle(proxy: GeometryProxy, anchor: Anchor<CGRect>) -> some View { RoundedRectangle(cornerRadius: 48) .fill( Color( light: .palette.white, dark: .palette.dark800 ) ) .shadow( color: Color( light: .palette.black.opacity(0.06), dark: .palette.black.opacity(0.12) ), radius: 1, x: 0, y: 3 ) .shadow( color: Color( light: .palette.black.opacity(0.15), dark: .palette.black.opacity(0.12) ), radius: 8, x: 0, y: 3 ) .frame( width: proxy[anchor].width, height: proxy[anchor].height ) .offset( x: xOffset(for: proxy[anchor], in: proxy), y: proxy[anchor].minY ) .animation(.interactiveSpring()) } private func xOffset(for rect: CGRect, in proxy: GeometryProxy) -> CGFloat { switch layoutDirection { case .rightToLeft: return proxy.size.width - rect.minX - rect.width default: return rect.minX } } } extension PrimarySegmentedControl { public struct Item: Identifiable { let title: String let variant: Variant let identifier: Selection public var id: Selection { identifier } /// Create an Item which is the element to pass into the PrimarySegmentedControl, /// as a representation for the buttons to be shown on the control. /// The parameters defined on the items are the data used to display a button. /// - Parameter title: title of the item, will be the title of the button /// - Parameter variant: style variant to use on the button /// - Parameter identifier: unique identifier which is used to determine which button is on the selected state. The identifier must to be set in order for the control to work with unique elements. public init( title: String, variant: Variant = .standard, identifier: Selection ) { self.title = title self.variant = variant self.identifier = identifier } /// Style variant for the button public enum Variant { case standard case dot } } } private struct ButtonPreferenceKey: PreferenceKey { static var defaultValue: [AnyHashable: Anchor<CGRect>] = [:] static func reduce( value: inout [AnyHashable: Anchor<CGRect>], nextValue: () -> [AnyHashable: Anchor<CGRect>] ) { value.merge( nextValue(), uniquingKeysWith: { _, next in next } ) } } struct PrimarySegmentedControl_Previews: PreviewProvider { static var previews: some View { Group { PreviewController( items: [ PrimarySegmentedControl.Item(title: "Live", variant: .dot, identifier: "live"), PrimarySegmentedControl.Item(title: "1D", identifier: "1d"), PrimarySegmentedControl.Item(title: "1W", identifier: "1w"), PrimarySegmentedControl.Item(title: "1M", identifier: "1m"), PrimarySegmentedControl.Item(title: "1Y", identifier: "1y"), PrimarySegmentedControl.Item(title: "All", identifier: "all") ], selection: "live" ) .previewLayout(.sizeThatFits) .previewDisplayName("PrimarySegmentedControl") PreviewController( items: [ PrimarySegmentedControl.Item(title: "Live", variant: .dot, identifier: "live"), PrimarySegmentedControl.Item(title: "1D", identifier: "1d"), PrimarySegmentedControl.Item(title: "1W", identifier: "1w"), PrimarySegmentedControl.Item(title: "1M", identifier: "1m"), PrimarySegmentedControl.Item(title: "1Y", identifier: "1y"), PrimarySegmentedControl.Item(title: "All", identifier: "all") ], selection: "1m" ) .previewLayout(.sizeThatFits) .previewDisplayName("Initial Selection") PreviewController( items: [ PrimarySegmentedControl.Item(title: "First", identifier: "first"), PrimarySegmentedControl.Item(title: "Second", identifier: "second"), PrimarySegmentedControl.Item(title: "Third", identifier: "third") ], selection: "first" ) .previewLayout(.sizeThatFits) .previewDisplayName("Short") PreviewController( items: [ PrimarySegmentedControl.Item(title: "Today", variant: .dot, identifier: "today"), PrimarySegmentedControl.Item(title: "Tomorrow", identifier: "tomorrow"), PrimarySegmentedControl.Item(title: "Now", identifier: "now"), PrimarySegmentedControl.Item(title: "Ready", variant: .dot, identifier: "ready") ], selection: "ready" ) .previewLayout(.sizeThatFits) .previewDisplayName("Mixed") } .padding() } struct PreviewController<Selection: Hashable>: View { let items: [PrimarySegmentedControl<Selection>.Item] @State var selection: Selection init( items: [PrimarySegmentedControl<Selection>.Item], selection: Selection ) { self.items = items _selection = State(initialValue: selection) } var body: some View { PrimarySegmentedControl( items: items, selection: $selection ) } } }
lgpl-3.0
e09c6347b0073acc03c03eba0e8254c0
34.70155
204
0.538812
5.09458
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Swift/Extensions/Array+Extensions.swift
1
7755
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // import Foundation extension Array { /// Returns a random subarray of given length. /// /// - Parameter length: Number of random elements to return. /// - Returns: Random subarray of length _n_. public func randomElements(length: Int = 1) -> Self { let size = length let count = self.count if size >= count { return shuffled() } let index = Int.random(in: 0..<(count - size)) return self[index..<(size + index)].shuffled() } /// Returns a random element from `self`. public func randomElement() -> Element { let randomIndex = Int(arc4random()) % count return self[randomIndex] } /// Split array by chunks of given size. /// /// ```swift /// let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] /// let chunks = array.splitBy(5) /// print(chunks) // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]] /// ``` /// - SeeAlso: https://gist.github.com/ericdke/fa262bdece59ff786fcb public func splitBy(_ subSize: Int) -> [[Element]] { stride(from: 0, to: count, by: subSize).map { startIndex in let endIndex = index(startIndex, offsetBy: subSize, limitedBy: count) ?? startIndex + (count - startIndex) return Array(self[startIndex..<endIndex]) } } public func firstElement<T>(type: T.Type) -> T? { for element in self { if let element = element as? T { return element } } return nil } public func lastElement<T>(type: T.Type) -> T? { for element in reversed() { if let element = element as? T { return element } } return nil } } extension Array where Element: NSObjectProtocol { /// Returns the first index where the specified value appears in the collection. /// /// After using `firstIndex(of:)` to find the position of a particular element /// in a collection, you can use it to access the element by subscripting. This /// example shows how you can pop one of the view controller from the /// `UINavigationController`. /// /// ```swift /// let navigationController = UINavigationController() /// if let index = navigationController.viewControllers.firstIndex(of: SearchViewController.self) { /// navigationController.popToViewController(at: index, animated: true) /// } /// ``` /// /// - Parameter elementType: An element type to search for in the collection. /// - Returns: The first index where `element` is found. If `element` is not /// found in the collection, returns `nil`. public func firstIndex(of elementType: Element.Type) -> Int? { firstIndex { $0.isKind(of: elementType) } } /// Returns the last index where the specified value appears in the collection. /// /// After using `lastIndex(of:)` to find the position of a particular element in /// a collection, you can use it to access the element by subscripting. This /// example shows how you can pop one of the view controller from the /// `UINavigationController`. /// /// ```swift /// let navigationController = UINavigationController() /// if let index = navigationController.viewControllers.lastIndex(of: SearchViewController.self) { /// navigationController.popToViewController(at: index, animated: true) /// } /// ``` /// /// - Parameter elementType: An element type to search for in the collection. /// - Returns: The last index where `element` is found. If `element` is not /// found in the collection, returns `nil`. public func lastIndex(of elementType: Element.Type) -> Int? { lastIndex { $0.isKind(of: elementType) } } /// Returns a boolean value indicating whether the sequence contains an element /// that exists in the given parameter. /// /// ```swift /// let navigationController = UINavigationController() /// if navigationController.viewControllers.contains(any: [SearchViewController.self, HomeViewController.self]) { /// _ = navigationController?.popToRootViewController(animated: true) /// } /// ``` /// /// - Parameter any: An array of element types to search for in the collection. /// - Returns: `true` if the sequence contains an element; otherwise, `false`. public func contains(any elementTypes: [Element.Type]) -> Bool { for element in self { if elementTypes.contains(where: { element.isKind(of: $0) }) { return true } } return false } } extension Array where Element: Equatable { /// Sorts the collection in place, using the given preferred order as the /// comparison between elements. /// /// ```swift /// let preferredOrder = ["Z", "A", "B", "C", "D"] /// var alphabets = ["D", "C", "B", "A", "Z", "W"] /// alphabets.sort(by: preferredOrder) /// print(alphabets) /// // Prints ["Z", "A", "B", "C", "D", "W"] /// ``` /// /// - Parameter preferredOrder: The ordered elements, which will be used to sort /// the sequence’s elements. public mutating func sort(by preferredOrder: Self) { sort { a, b -> Bool in guard let first = preferredOrder.firstIndex(of: a), let second = preferredOrder.firstIndex(of: b) else { return false } return first < second } } // Credit: https://stackoverflow.com/a/51683055 /// Returns the elements of the sequence, sorted using the given preferred order /// as the comparison between elements. /// /// ```swift /// let preferredOrder = ["Z", "A", "B", "C", "D"] /// let alphabets = ["D", "C", "B", "A", "Z", "W"] /// let sorted = alphabets.sorted(by: preferredOrder) /// print(sorted) /// // Prints ["Z", "A", "B", "C", "D", "W"] /// ``` /// /// - Parameter preferredOrder: The ordered elements, which will be used to sort /// the sequence’s elements. /// - Returns: A sorted array of the sequence’s elements. public func sorted(by preferredOrder: Self) -> Self { sorted { a, b -> Bool in guard let first = preferredOrder.firstIndex(of: a), let second = preferredOrder.firstIndex(of: b) else { return false } return first < second } } } extension Array where Element: RawRepresentable { /// Return an array containing all corresponding `rawValue`s of `self`. public var rawValues: [Element.RawValue] { map(\.rawValue) } } extension Array where Element == String? { /// Returns a new string by concatenating the elements of the sequence, adding /// the given separator between each element. /// /// The following example shows how an array of strings can be joined to a /// single, comma-separated string: /// /// ```swift /// let cast = ["Vivien", nil, "Kim", "Karl"] /// let list = cast.joined(separator: ", ") /// print(list) /// // Prints "Vivien, Kim, Karl" /// ``` /// /// - Parameter separator: A string to insert between each of the elements in /// this sequence. The default value is an empty string. /// - Returns: A single, concatenated string. public func joined(separator: String = "") -> String { lazy .compactMap { $0 } .filter { !$0.isBlank } .joined(separator: separator) } }
mit
b49c1d9ba94de1be1b2db6dcec52d665
34.058824
118
0.586216
4.374929
false
false
false
false
BlackDragonF/Doooge
My Doooge/NotificationManager.swift
2
1467
// // NotificationManager.swift // Doooge // // Created by VicChan on 2016/11/19. // Copyright © 2016年 VicChan. All rights reserved. // import Foundation struct NotificationModel { var content: String var id: Int var isFinished:Bool = false init(_ content: String, _ id: Int, _ isFinished: Bool = false) { self.content = content self.isFinished = isFinished self.id = id } } protocol NotificationDelegate { func didChangeNotification(index: Int,id: Int) } class NotificationManager { var timer: Timer? var delegate: NotificationDelegate? var queue: [NotificationModel]? var randomNotification: [NotificationModel]? var messageView: MessageView! init(view: MessageView) { self.messageView = view } func showRandom(content: [NotificationModel]) { timer?.invalidate() randomNotification = content self.messageView.appear((content.first?.content)!) var interval: TimeInterval = 0 timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { [unowned self](timer) in interval += 3 var index = Int(interval)/3 index = index%content.count self.messageView.appear(content[index].content) self.delegate?.didChangeNotification(index: index,id: content[index].id) }) } }
apache-2.0
cd078da002b86c126196e052f02aa677
20.850746
106
0.612705
4.546584
false
false
false
false
wolangerxing/LeetCode-Solutions
LeetCodeSolutions/LeetCodeSolutions/AddTwoNumbers.swift
1
1615
// // AddTwoNumbers.swift // LeetCodeSolutions // // Created by bjyangwei on 17/2/24. // Copyright © 2017年 bjyangwei. All rights reserved. // /** https://leetcode.com/problems/add-two-numbers/ #2 Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 */ /** 思路:遍历一遍,处理好进位 */ class addTwoNumbersSolution { class ListNode{ var val : Int var next : ListNode? init(_ val : Int) { self.val = val self.next = nil } } func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { var tmp1 = l1 var tmp2 = l2 let finalList : ListNode = ListNode(0) var head = finalList var sum = 0 while tmp1 != nil || tmp2 != nil { sum /= 10 if let node = tmp1 { sum += node.val tmp1 = node.next } if let node = tmp2 { sum += node.val tmp2 = node.next } head.next = ListNode(sum % 10) if let node = head.next { head = node } } if sum / 10 == 1 { head.next = ListNode(1) } return finalList.next } }
apache-2.0
297ae0b518df41a49180c4e3762ae25b
24.580645
220
0.520177
3.887255
false
false
false
false
cszwdy/Genome
Genome.playground/Sources/Dictionary+KeyPaths.swift
2
1821
// // Array+KeyPaths.swift // Genome // // Created by Logan Wright on 7/2/15. // Copyright © 2015 lowriDevs. All rights reserved. // public extension Dictionary { mutating func gnm_setValue(val: AnyObject, forKeyPath keyPath: String) { var keys = keyPath.gnm_keypathComponents() guard let first = keys.first as? Key else { print("Unable to use string as key on type: \(Key.self)"); return } keys.removeAtIndex(0) if keys.isEmpty, let settable = val as? Value { self[first] = settable } else { let rejoined = keys.joinWithSeparator(".") var subdict: [String : AnyObject] = [:] if let sub = self[first] as? [String : AnyObject] { subdict = sub } subdict.gnm_setValue(val, forKeyPath: rejoined) if let settable = subdict as? Value { self[first] = settable } else { print("Unable to set value: \(subdict) to dictionary of type: \(self.dynamicType)") } } } func gnm_valueForKeyPath<T>(keyPath: String) -> T? { var keys = keyPath.gnm_keypathComponents() guard let first = keys.first as? Key else { print("Unable to use string as key on type: \(Key.self)"); return nil } guard let value = self[first] as? AnyObject else { return nil } keys.removeAtIndex(0) if !keys.isEmpty, let subDict = value as? [String : AnyObject] { let rejoined = keys.joinWithSeparator(".") return subDict.gnm_valueForKeyPath(rejoined) } return value as? T } } private extension String { func gnm_keypathComponents() -> [String] { return characters .split { $0 == "." } .map { String($0) } } }
mit
0a77d77e05e75b193af9decf0e9b33d1
34.705882
123
0.568132
4.174312
false
false
false
false
adrianomazucato/CoreStore
CoreStoreDemo/CoreStoreDemo/Fetching and Querying Demo/QueryingResultsViewController.swift
3
2273
// // QueryingResultsViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/17. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import UIKit class QueryingResultsViewController: UITableViewController { // MARK: Public func setValue(value: AnyObject?, title: String) { switch value { case .Some(let array as [AnyObject]): self.values = array.map { (item: AnyObject) -> (title: String, detail: String) in ( title: item.description, detail: _stdlib_getDemangledTypeName(item) ) } case .Some(let item): self.values = [ ( title: item.description, detail: _stdlib_getDemangledTypeName(item) ) ] default: self.values = [] } self.sectionTitle = title self.tableView?.reloadData() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 60 self.tableView.rowHeight = UITableViewAutomaticDimension } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.values.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) let value = self.values[indexPath.row] cell.textLabel?.text = value.title cell.detailTextLabel?.text = value.detail return cell } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sectionTitle } // MARK: Private var values: [(title: String, detail: String)] = [] var sectionTitle: String? }
mit
6f8be722dcf170652a836ad8d6670f6a
24.829545
118
0.560493
5.654229
false
false
false
false
jjjjaren/jCode
jCode/Classes/HTTPClient/Extensions/HTTPClientProtocol+Extensions.swift
1
5603
// // HTTPClientProtocol+Extensions.swift // Alamofire // // Created by Jaren Hamblin on 11/17/17. // import Foundation /// public extension HTTPClientProtocol { /// <#Description#> /// /// - Parameters: /// - url: <#url description#> /// - parameters: <#parameters description#> /// - headers: <#headers description#> /// - encoding: <#encoding description#> /// - completion: <#completion description#> /// - Returns: <#return value description#> @discardableResult public func get(_ url: URL, parameters: HTTPClientParameters = HTTPClientParameters(), headers: HTTPClientHeaders = HTTPClientHeaders(), encoding: HTTPClientParameterEncoding = HTTPClientParameterEncoding.url, completion: @escaping HTTPClientCompletionHandler) -> URLRequest { return self.request(url, method: HTTPClientMethod.get, parameters: parameters, headers: headers, encoding: encoding, completion: completion) } /// <#Description#> /// /// - Parameters: /// - url: <#url description#> /// - parameters: <#parameters description#> /// - headers: <#headers description#> /// - encoding: <#encoding description#> /// - completion: <#completion description#> /// - Returns: <#return value description#> @discardableResult public func post(_ url: URL, parameters: HTTPClientParameters = HTTPClientParameters(), headers: HTTPClientHeaders = HTTPClientHeaders(), encoding: HTTPClientParameterEncoding = HTTPClientParameterEncoding.json, completion: @escaping HTTPClientCompletionHandler) -> URLRequest { return self.request(url, method: HTTPClientMethod.post, parameters: parameters, headers: headers, encoding: encoding, completion: completion) } /// <#Description#> /// /// - Parameters: /// - url: <#url description#> /// - parameters: <#parameters description#> /// - headers: <#headers description#> /// - encoding: <#encoding description#> /// - completion: <#completion description#> /// - Returns: <#return value description#> @discardableResult public func put(_ url: URL, parameters: HTTPClientParameters = HTTPClientParameters(), headers: HTTPClientHeaders = HTTPClientHeaders(), encoding: HTTPClientParameterEncoding = HTTPClientParameterEncoding.json, completion: @escaping HTTPClientCompletionHandler) -> URLRequest { return self.request(url, method: HTTPClientMethod.put, parameters: parameters, headers: headers, encoding: encoding, completion: completion) } /// <#Description#> /// /// - Parameters: /// - url: <#url description#> /// - parameters: <#parameters description#> /// - headers: <#headers description#> /// - encoding: <#encoding description#> /// - completion: <#completion description#> /// - Returns: <#return value description#> @discardableResult public func delete(_ url: URL, parameters: HTTPClientParameters = HTTPClientParameters(), headers: HTTPClientHeaders = HTTPClientHeaders(), encoding: HTTPClientParameterEncoding = HTTPClientParameterEncoding.json, completion: @escaping HTTPClientCompletionHandler) -> URLRequest { return self.request(url, method: HTTPClientMethod.delete, parameters: parameters, headers: headers, encoding: encoding, completion: completion) } /// Print the contents of URLRequest and HTTPURLResponse in a consistent format that is easy to inspect public func print(_ request: URLRequest, response: HTTPURLResponse, responseData: Data? = nil, error: Error? = nil) { var components: [String] = [] let httpResponse = response let statusCode = httpResponse.statusCode // Method/URL if let url = request.url { components.append([request.httpMethod, url.absoluteString].flatMap{$0}.joined(separator: " ")) } // Request Headers if let headers = request.allHTTPHeaderFields, headers.keys.count > 0 { let headersString: String = "RequestHeaders:\n" + headers.map { "\($0.key): \($0.value)" }.joined(separator: "\n") components.append(headersString) } // Request Data if let data = request.httpBody { components.append("RequestBody:\n\(JSON(data: data))") } // Response Status let httpUrlResponseError = HTTPURLResponse.localizedString(forStatusCode: statusCode).capitalized components.append("ResponseStatus: \(response.statusCode) \(httpUrlResponseError)") // Response Headers let responseHeaders = response.allHeaderFields if responseHeaders.keys.count > 0 { let headersString: String = "ResponseHeaders:\n" + responseHeaders.map { "\($0.key): \($0.value)" }.joined(separator: "\n") components.append(headersString) } // Response Data if let data = responseData { components.append("ResponseBody:\n\(JSON(data: data))") } components.insert("", at: 0) components.append("") let logMessage = components.joined(separator: "\n") LogUtility.shared.debug(logMessage) } }
mit
3aaee7c916f5b631fc81d674a500701b
42.1
151
0.613778
5.320988
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Keyboard/Items/MKeyboardRowItemPercent.swift
1
593
import UIKit class MKeyboardRowItemPercent:MKeyboardRowItem { init() { super.init(icon:#imageLiteral(resourceName: "assetKeyboardPercent")) } override func selected(model:MKeyboard, view:UITextView) { let currentString:String = view.text let scalar:Double = model.stringAsNumber(string:currentString) let percent:Double = scalar / 100 let newString:String = model.numberAsString(scalar:percent) view.text = model.kEmpty view.insertText(newString) model.states.last?.editing = newString } }
mit
ff3660067501c642811e697e0fb7ca00
27.238095
76
0.666105
4.392593
false
false
false
false
jonesgithub/DKChainableAnimationKit
DKChainableAnimationKit/Classes/DKChainableAnimationKit+Transform.swift
1
7996
// // DKChainableAnimationKit+Transform.swift // DKChainableAnimationKit // // Created by Draveness on 15/5/23. // Copyright (c) 2015年 Draveness. All rights reserved. // import UIKit extension DKChainableAnimationKit { public var transformIdentity: DKChainableAnimationKit { get { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") let transform = CATransform3DIdentity transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in let transform = CATransform3DIdentity view.layer.transform = transform } return self } } public func transformX(x: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, x, 0, 0) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, x, 0, 0) view.layer.transform = transform } return self } public func transformY(y: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, 0, y, 0) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, 0, y, 0) view.layer.transform = transform } return self } public func transformZ(z: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, 0, 0, z) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, 0, 0, z) view.layer.transform = transform } return self } public func transformXY(x: CGFloat, _ y: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, x, y, 0) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, x, y, 0) view.layer.transform = transform } return self } public func transformScale(scale: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, scale, scale, 1) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, scale, scale, 1) view.layer.transform = transform } return self } public func transformScaleX(scaleX: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, scaleX, 1, 1) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, scaleX, 1, 1) view.layer.transform = transform } return self } public func transformScaleY(scaleY: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let transformAnimation = self.basicAnimationForKeyPath("transform") var transform = view.layer.transform transform = CATransform3DTranslate(transform, 1, scaleY, 1) transformAnimation.fromValue = NSValue(CATransform3D: view.layer.transform) transformAnimation.toValue = NSValue(CATransform3D: transform) self.addAnimationFromCalculationBlock(transformAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in var transform = view.layer.transform transform = CATransform3DTranslate(transform, 1, scaleY, 1) view.layer.transform = transform } return self } public func rotate(angle: Double) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let rotationAnimation = self.basicAnimationForKeyPath("transform.rotation") let transform = view.layer.transform let originalRotation = Double(atan2(transform.m12, transform.m11)) rotationAnimation.fromValue = originalRotation rotationAnimation.toValue = originalRotation + self.degreesToRadians(angle) self.addAnimationFromCalculationBlock(rotationAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in let transform = view.layer.transform let originalRotation = Double(atan2(transform.m12, transform.m11)) let zRotation = CATransform3DMakeRotation(CGFloat(self.degreesToRadians(angle) + originalRotation), 0.0, 0.0, 1.0) view.layer.transform = zRotation } return self } }
mit
9c5c0488fd4527c727ea69adc157c9d8
46.589286
126
0.666375
5.167421
false
false
false
false
509dave16/udemy_swift_ios_projects
playground/variables-types.playground/Contents.swift
1
874
//: Playground - noun: a place where people can play import UIKit //Testing string operations var helloWorld = "Hello, playground"//String helloWorld += " I'm so cool!" var numA = 1.5//double var numB: Float = 1.5//Float var numC = 3 //Int var sum = 5 + 6 //add var product = 5 * 5 //multiply var divisor = 28 / 5 //divide var remainder = 22 % 5 //modulus var subtraction = 44 - 22 //subtraction var crazyResult = sum * product + (divisor * remainder + subtraction) var newStr = "Hey " + "how are you?" var firstName = "Jon" var lastName = "Smith" var fullName = "\(firstName) \(lastName)" var price = "Price: $\(numA)" price = "Bannana" let total = 5.0 //constant var jack = 0, jill = 1, bob = 2 jill = 6 let beaver = "beaver", stever = "stever", cleaver = "cleaver" var totalPrice: Double //type explicitly declared var sumStr: String = "This is a String"
gpl-2.0
2b950e4b2112d6a6342fb5e0e773a5b0
19.809524
69
0.663616
3.201465
false
false
false
false
alblue/com.packtpub.swift.essentials
CustomViews/CustomViews/RemoteGitRepository.swift
1
2498
// Copyright (c) 2016, Alex Blewitt, Bandlem Ltd // Copyright (c) 2016, Packt Publishing Ltd // // 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 class RemoteGitRepository { let host:String let repo:String let port:Int init(host:String, repo:String, _ port:Int = 9418) { self.host = host self.repo = repo self.port = port } func lsRemote() -> [String:String] { var refs = [String:String]() if let (input,output) = NSStream.open(host,port) { output.writePacketLine("git-upload-pack \(repo)\0host=\(host)\0") while true { if let response = input.readPacketLineString() { let hash = String(response.substringToIndex(41)) let ref = String(response.substringFromIndex(41)) if ref.hasPrefix("HEAD") { continue } else { refs[ref] = hash } } else { break } } output.writePacketLine() input.close() output.close() } return refs } func lsRemoteAsync(fn:(String,String) -> ()) { if let (input,output) = NSStream.connect(host,port) { input.delegate = PacketLineParser(output) { (response:NSString) -> () in let hash = String(response.substringToIndex(41)) let ref = String(response.substringFromIndex(41)) if !ref.hasPrefix("HEAD") { fn(ref,hash) } } input.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) input.open() output.open() output.writePacketLine("git-upload-pack \(repo)\0host=\(host)\0") } } }
mit
0683f64314aa12c5edb78533f767de5f
34.183099
82
0.704564
3.67894
false
false
false
false
ChronicStim/EasyMapping
Tests/EasyMappingTests/EKObjectModelTestCase.swift
1
1240
// // EKObjectModelTestCase.swift // EasyMapping // // Created by Денис Тележкин on 06.05.17. // Copyright © 2017 EasyMapping. All rights reserved. // import XCTest fileprivate final class TestObjectModel: EKObjectModel { var foo: String! override static func objectMapping() -> EKObjectMapping { let mapping = super.objectMapping() mapping.mapKeyPath("bar", toProperty: "foo") return mapping } } class EKObjectModelTestCase: XCTestCase { func testObjectClass() { let mapping = TestObjectModel.objectMapping() XCTAssert(mapping.objectClass == TestObjectModel.self) } func testObjectWithProperties() { let object = TestObjectModel.object(withProperties: ["bar":"123"]) XCTAssertEqual(object.foo, "123") } func testInitWithProperties() { let object = TestObjectModel(properties: ["bar":"123"]) XCTAssertEqual(object.foo, "123") } func testSerializedObject() { let object = TestObjectModel(properties: ["bar":"123"]) let serialized = object.serializedObject() XCTAssertEqual(serialized["bar"] as? String, "123") } }
mit
28c8c4903448672a72d9c87942962d8b
24.541667
74
0.630506
4.523985
false
true
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/PackagePopupContent.swift
1
2241
// // CountryDownloadContent.swift // AdvancedMap.Swift // // Created by Aare Undo on 27/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import UIKit import CartoMobileSDK class PackagePopupContent : UIView, UITableViewDataSource { let IDENTIFIER = "CountryCell" var table: UITableView! var packages: [Package] = [Package]() convenience init() { self.init(frame: CGRect.zero) table = UITableView() table.dataSource = self table.register(PackageCell.self, forCellReuseIdentifier: IDENTIFIER) addSubview(table) } override func layoutSubviews() { table.frame = bounds } func addPackages(packages: [Package]) { self.packages = packages table.reloadData() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return packages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: IDENTIFIER, for: indexPath as IndexPath) as? PackageCell let package = packages[indexPath.row] cell?.update(package: package) return cell! } func findAndUpdate(package: Package, progress: CGFloat) { find(package: package)?.update(package: package, progress: progress) } func findAndUpdate(package: Package) { find(package: package)?.update(package: package) } func findAndUpdate(id: String, status: NTPackageStatus) { find(id: id)?.update(status: status) } func find(package: Package) -> PackageCell? { return find(id: package.id) } func find(id: String) -> PackageCell? { for cell in table.visibleCells { let packageCell = cell as? PackageCell if (packageCell?.package.id == id) { return packageCell } } return nil } }
bsd-2-clause
757ca6bfa1122283242781afb35dbe1e
22.829787
121
0.611161
4.827586
false
false
false
false
couchbits/iOSToolbox
Sources/UserInterface/Transitions/DismissModalDialogTransition.swift
1
1875
// // DismissModalDialogTransition.swift // iOSToolbox // // Created by Dominik Gauggel on 09.04.18. // import Foundation import UIKit public class DismissModalDialogTransition: NSObject, UIViewControllerAnimatedTransitioning { let transitionDuration: TimeInterval public init(transitionDuration: TimeInterval) { self.transitionDuration = transitionDuration } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewController(forKey: .from), let toViewController = transitionContext.viewController(forKey: .to), let snapshot = fromViewController.view.snapshotView(afterScreenUpdates: false) else { transitionContext.completeTransition(false) return } let endY = -toViewController.view.frame.size.height * 1.5 let finalCenter = CGPoint(x: fromViewController.view.center.x, y: endY) let finalFrame = transitionContext.finalFrame(for: toViewController) let containerView = transitionContext.containerView containerView.addSubview(snapshot) containerView.sendSubviewToBack(toViewController.view) fromViewController.view.isHidden = true UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { snapshot.center = finalCenter toViewController.view.frame = finalFrame }, completion: { _ in fromViewController.view.isHidden = false snapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionDuration } }
mit
269118d1f2d3eeda411d638158876f12
37.265306
116
0.720533
6.087662
false
false
false
false
Produkt/Pelican
src/ZIP/ZipPacker.swift
1
3326
// // ZipPacker.swift // Pelican // // Created by Daniel Garcia on 08/12/2016. // Copyright © 2016 Produkt Studio. All rights reserved. // import Foundation import minizip import Result public class ZipPacker: Packer { public let operationQueue: OperationQueue init(operationQueue: OperationQueue) { self.operationQueue = operationQueue } @discardableResult public func pack(files filePaths: [String], in filePath: String, completion: @escaping PackTaskCompletion) -> PackTask { let packOperation = ZipPackOperation(destinationPath: filePath, contentFilePaths: filePaths, completion: completion) operationQueue.addOperation(packOperation) return packOperation } } class ZipPackOperation: Operation, PackTask { private let destinationPath: String private let contentFilePaths: [String] private var zip: zipFile? private let chunkSize: Int = 16384 private let completion: PackTaskCompletion init(destinationPath: String, contentFilePaths: [String], completion: @escaping PackTaskCompletion) { self.destinationPath = destinationPath self.contentFilePaths = contentFilePaths self.completion = completion } override func main() { super.main() zip = zipOpen((destinationPath as NSString).utf8String, APPEND_STATUS_CREATE); for filePath in contentFilePaths { addFile(from: filePath) } zipClose(zip, nil) completion(Result.success()) } func addFile(from path: String) { let input = fopen((path as NSString).utf8String, "r") guard input != nil else { return } let fileName = ((path as NSString).lastPathComponent as NSString).utf8String var zipInfo: zip_fileinfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0) do { let fileAttributes = try FileManager.default.attributesOfItem(atPath: path) as NSDictionary if let fileDate = fileAttributes.fileModificationDate() { let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fileDate) zipInfo.tmz_date.tm_sec = UInt32(components.second!) zipInfo.tmz_date.tm_min = UInt32(components.minute!) zipInfo.tmz_date.tm_hour = UInt32(components.hour!) zipInfo.tmz_date.tm_mday = UInt32(components.day!) zipInfo.tmz_date.tm_mon = UInt32(components.month!) - 1 zipInfo.tmz_date.tm_year = UInt32(components.year!) } } catch {} zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nil, 0) let buffer = malloc(chunkSize) var length: Int = 0 while (feof(input) == 0) { length = fread(buffer, 1, chunkSize, input) zipWriteInFileInZip(zip, buffer, UInt32(length)) } zipCloseFileInZip(zip) free(buffer) fclose(input) } }
gpl-3.0
af6b303ddeaafb3d68ccda35b327a3a7
36.784091
167
0.621654
4.214195
false
false
false
false
atl009/WordPress-iOS
WordPressKit/WordPressKitTests/MediaServiceRemoteRESTTests.swift
1
9961
import XCTest @testable import WordPressKit class MediaServiceRemoteRESTTests: XCTestCase { let mockRemoteApi = MockWordPressComRestApi() var mediaServiceRemote: MediaServiceRemoteREST! let siteID = 99999 override func setUp() { super.setUp() mediaServiceRemote = MediaServiceRemoteREST(wordPressComRestApi: mockRemoteApi, siteID: NSNumber(value: siteID)) } func mockRemoteMedia() -> RemoteMedia { let remoteMedia = RemoteMedia() remoteMedia.mediaID = 1 remoteMedia.postID = 2 remoteMedia.localURL = URL(string: "http://www.wordpress.com") remoteMedia.mimeType = "img/jpeg" remoteMedia.file = "file_name" return remoteMedia } func testGetMediaWithIDPath() { let id = 1 let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media/\(id)", withVersion: ._1_1) mediaServiceRemote.getMediaWithID(id as NSNumber!, success: nil, failure: nil) XCTAssertTrue(mockRemoteApi.getMethodCalled, "Wrong method, expected GET got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testGetMediaWithID() { let id = 1 let response = ["ID": id] var remoteMedia: RemoteMedia? = nil mediaServiceRemote.getMediaWithID(id as NSNumber!, success: { remoteMedia = $0 }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertNotNil(remoteMedia) XCTAssertEqual(remoteMedia?.mediaID.intValue, id) } func testCreateMediaPath() { var progress: Progress? = nil let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media/new", withVersion: ._1_1) let media = mockRemoteMedia() mediaServiceRemote.uploadMedia(media, progress: &progress, success: nil, failure: nil) XCTAssertTrue(mockRemoteApi.postMethodCalled, "Wrong method, expected POST got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testCreateMedia() { let response = ["media": [["ID": 1]]] let media = mockRemoteMedia() var progress: Progress? = nil var remoteMedia: RemoteMedia? = nil mediaServiceRemote.uploadMedia(media, progress: &progress, success: { remoteMedia = $0 }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(media.mediaID, remoteMedia?.mediaID) } func testCreateMediaError() { let response = ["errors": ["some error"]] let media = mockRemoteMedia() var progress: Progress? = nil var errorDescription = "" mediaServiceRemote.uploadMedia(media, progress: &progress, success: nil, failure: { errorDescription = ($0?.localizedDescription)! }) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(errorDescription, response["errors"]![0]) } func testUpdateMediaPath() { let media = mockRemoteMedia() let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media/\(media.mediaID!)", withVersion: ._1_1) mediaServiceRemote.update(media, success: nil, failure: nil) XCTAssertTrue(mockRemoteApi.postMethodCalled, "Wrong method, expected POST got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testUpdateMediaAlt() { let alt = "This is an alternative title" let response = ["alt": alt] let media = mockRemoteMedia() media.alt = alt var remoteMedia: RemoteMedia? = nil mediaServiceRemote.update(media, success: { remoteMedia = $0 }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(remoteMedia?.alt, alt) } func testUpdateMedia() { let response = ["ID": 1] let media = mockRemoteMedia() var remoteMedia: RemoteMedia? = nil mediaServiceRemote.update(media, success: { remoteMedia = $0 }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(media.mediaID, remoteMedia?.mediaID) } func testDeleteMediaPath() { let media = mockRemoteMedia() let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media/\(media.mediaID!)/delete", withVersion: ._1_1) mediaServiceRemote.delete(media, success: nil, failure: nil) XCTAssertTrue(mockRemoteApi.postMethodCalled, "Wrong method, expected POST got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testGetMediaLibraryPath() { let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media", withVersion: ._1_1) mediaServiceRemote.getMediaLibrary(success: nil, failure: nil) XCTAssertTrue(mockRemoteApi.getMethodCalled, "Wrong method, expected GET got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testGetEmptyMediaLibrary() { let response = ["media": []] var remoteMedias = [RemoteMedia]() mediaServiceRemote.getMediaLibrary(success: { (medias) in if let medias = medias as? [RemoteMedia] { remoteMedias = medias } }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertTrue(remoteMedias.isEmpty) } func testGetSingleMediaLibraries() { let response = ["media": [["ID": 2]]] var remoteMedias = [RemoteMedia]() mediaServiceRemote.getMediaLibrary(success: { (medias) in if let medias = medias as? [RemoteMedia] { remoteMedias = medias } }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(remoteMedias.count, 1) } func testGetMultipleMediaLibraries() { let response = ["media": [["ID": 2], ["ID": 3], ["ID": 4]]] var remoteMedias = [RemoteMedia]() mediaServiceRemote.getMediaLibrary(success: { (medias) in if let medias = medias as? [RemoteMedia] { remoteMedias = medias } }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(remoteMedias.count, 3) } func testGetMediaLibraryCountPath() { let expectedPath = mediaServiceRemote.path(forEndpoint: "sites/\(siteID)/media", withVersion: ._1_1) mediaServiceRemote.getMediaLibraryCount(forType: nil, withSuccess: nil, failure: nil) XCTAssertTrue(mockRemoteApi.getMethodCalled, "Wrong method, expected GET got \(mockRemoteApi.methodCalled())") XCTAssertEqual(mockRemoteApi.URLStringPassedIn, expectedPath, "Wrong path") } func testGetMediaLibraryCount() { let expectedCount = 3 let response = ["found": expectedCount] var remoteCount = 0 mediaServiceRemote.getMediaLibraryCount(forType: nil, withSuccess: { (count) in remoteCount = count }, failure: nil) mockRemoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse()) XCTAssertEqual(remoteCount, expectedCount) } func testRemoteMediaJSONParsing() { let id = 1 let url = "http://www.wordpress.com" let guid = "http://www.gravatar.com" let date = "2016-12-14T22:00:00Z" let postID = 2 let file = "file" let mimeType = "img/jpeg" let title = "title" let caption = "caption" let description = "description" let alt = "alt" let height = 321 let width = 432 let jsonDictionary: [String : Any] = ["ID": id, "URL": url, "guid": guid, "date": date, "post_ID": postID, "mime_type": mimeType, "file": file, "title": title, "caption": caption, "description": description, "alt": alt, "height": height, "width": width] let remoteMedia = mediaServiceRemote.remoteMedia(fromJSONDictionary: jsonDictionary) XCTAssertEqual(remoteMedia.mediaID.intValue, id) XCTAssertEqual(remoteMedia.url.absoluteString, url) XCTAssertEqual(remoteMedia.guid.absoluteString, guid) XCTAssertEqual(remoteMedia.date, Date.dateWithISO8601String(date)!) XCTAssertEqual(remoteMedia.postID.intValue, postID) XCTAssertEqual(remoteMedia.file, file) XCTAssertEqual(remoteMedia.mimeType, mimeType) XCTAssertEqual(remoteMedia.title, title) XCTAssertEqual(remoteMedia.caption, caption) XCTAssertEqual(remoteMedia.descriptionText, description) XCTAssertEqual(remoteMedia.alt, alt) XCTAssertEqual(remoteMedia.height.intValue, height) XCTAssertEqual(remoteMedia.width.intValue, width) } }
gpl-2.0
0c7a6dc2af944d4f157c67ea7b1a5973
41.029536
133
0.618412
5.163815
false
true
false
false
efremidze/NumPad
Sources/Extensions.swift
1
2177
// // Extensions.swift // NumPad // // Created by Lasha Efremidze on 1/7/18. // Copyright © 2018 Lasha Efremidze. All rights reserved. // import UIKit extension UIView { @discardableResult func constrainToEdges(_ inset: UIEdgeInsets = UIEdgeInsets()) -> [NSLayoutConstraint] { return constrain {[ $0.topAnchor.constraint(equalTo: $0.superview!.topAnchor, constant: inset.top), $0.leftAnchor.constraint(equalTo: $0.superview!.leftAnchor, constant: inset.left), $0.bottomAnchor.constraint(equalTo: $0.superview!.bottomAnchor, constant: inset.bottom), $0.rightAnchor.constraint(equalTo: $0.superview!.rightAnchor, constant: inset.right) ]} } @discardableResult func constrain(constraints: (UIView) -> [NSLayoutConstraint]) -> [NSLayoutConstraint] { let constraints = constraints(self) self.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(constraints) return constraints } } extension CGSize { func isZero() -> Bool { return self.equalTo(CGSize()) } } extension UIImage { convenience init(color: UIColor) { let size = CGSize(width: 1, height: 1) let rect = CGRect(origin: CGPoint(), size: size) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: (image?.cgImage!)!) } } extension UIButton { var title: String? { get { return title(for: .normal) } set { setTitle(newValue, for: .normal) } } var titleColor: UIColor? { get { return titleColor(for: .normal) } set { setTitleColor(newValue, for: .normal) } } var image: UIImage? { get { return image(for: .normal) } set { setImage(newValue, for: .normal) } } var backgroundImage: UIImage? { get { return backgroundImage(for: .normal) } set { setBackgroundImage(newValue, for: .normal) } } }
mit
55fe58c821b6d4b92932302a23d3fd09
26.897436
100
0.623162
4.533333
false
false
false
false
avdyushin/flatuicolor
UIColor.swift
1
5870
// // UIColor.swift // Flat UI Colors // // Created by Grigory Avdyushin on 22.01.15. // Copyright (c) 2015-2019 Grigory Avdyushin. All rights reserved. // import UIKit extension UIColor { /// Color formats enum ColorFormat: Int { case RGB = 12 case RGBA = 16 case RRGGBB = 24 init?(bitsCount: Int) { self.init(rawValue: bitsCount) } } /// Returns color with given hex string convenience init(string: String) { let string = string.replacingOccurrences(of: "#", with: "") guard let hex = Int(string, radix: 16), let format = ColorFormat(bitsCount: string.count * 4) else { self.init(white: 0, alpha: 0) return } self.init(hex: hex, format: format) } /// Returns color with given hex integer value and color format convenience init(hex: Int, format: ColorFormat = .RRGGBB) { let red: Int, green: Int, blue: Int, alpha: Int switch format { case .RGB: red = ((hex & 0xf00) >> 8) << 4 + ((hex & 0xf00) >> 8) green = ((hex & 0x0f0) >> 4) << 4 + ((hex & 0x0f0) >> 4) blue = ((hex & 0x00f) >> 0) << 4 + ((hex & 0x00f) >> 0) alpha = 255 break; case .RGBA: red = ((hex & 0xf000) >> 12) << 4 + ((hex & 0xf000) >> 12) green = ((hex & 0x0f00) >> 8) << 4 + ((hex & 0x0f00) >> 8) blue = ((hex & 0x00f0) >> 4) << 4 + ((hex & 0x00f0) >> 4) alpha = ((hex & 0x000f) >> 0) << 4 + ((hex & 0x000f) >> 4) break; case .RRGGBB: red = ((hex & 0xff0000) >> 16) green = ((hex & 0x00ff00) >> 8) blue = ((hex & 0x0000ff) >> 0) alpha = 255 break; } self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0 ) } /// Returns integer color representation var asInt: Int { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (Int)(r * 255) << 16 | (Int)(g * 255) << 8 | (Int)(b * 255) << 0 } /// Returns hex string color representation var asHexString: String { return String(format:"#%06x", asInt) } /// Returns color with adjusted saturation or/and brightness func withAdjusted(saturation: CGFloat = 0.0, brightness: CGFloat = 0.0) -> UIColor { var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 guard getHue(&h, saturation: &s, brightness: &b, alpha: &a) else { return self } return UIColor( hue: h, saturation: min(max(s + saturation, 0.0), 1.0), brightness: min(max(b + brightness, 0.0), 1.0), alpha: a ) } /// Returns lighter color by 25% var lighterColor: UIColor { return self.withAdjusted(saturation: -0.25) } /// Return darker color by 25% var darkerColor: UIColor { return self.withAdjusted(brightness: -0.25) } } /// Flat UI Palette v1 /// https://flatuicolors.com/palette/defo extension UIColor { // Green / Sea static let flatTurquoise = UIColor(hex: 0x1ABC9C) static let flatGreenSea = UIColor(hex: 0x16A085) // Green static let flatEmerald = UIColor(hex: 0x2ECC71) static let flatNephritis = UIColor(hex: 0x27AE60) // Blue static let flatPeterRiver = UIColor(hex: 0x3498DB) static let flatBelizeHole = UIColor(hex: 0x2980B9) // Purple static let flatAmethyst = UIColor(hex: 0x9B59B6) static let flatWisteria = UIColor(hex: 0x8E44AD) // Dark blue static let flatWetAsphalt = UIColor(hex: 0x34495E) static let flatMidnightBlue = UIColor(hex: 0x2C3E50) // Yellow static let flatSunFlower = UIColor(hex: 0xF1C40F) static let flatOrange = UIColor(hex: 0xF39C12) // Orange static let flatCarrot = UIColor(hex: 0xE67E22) static let flatPumkin = UIColor(hex: 0xD35400) // Red static let flatAlizarin = UIColor(hex: 0xE74C3C) static let flatPomegranate = UIColor(hex: 0xC0392B) // White static let flatClouds = UIColor(hex: 0xECF0F1) static let flatSilver = UIColor(hex: 0xBDC3C7) // Gray static let flatAsbestos = UIColor(hex: 0x7F8C8D) static let flatConcerte = UIColor(hex: 0x95A5A6) } /// Dutch Palette /// https://flatuicolors.com/palette/nl extension UIColor { // Yellow / Red static let flatSunflower = UIColor(hex: 0xFFC312) static let flatRadianYellow = UIColor(hex: 0xF79F1F) static let flatPuffinsBull = UIColor(hex: 0xEE5A24) static let flatRedPigment = UIColor(hex: 0xEA2027) // Green static let flatEnergos = UIColor(hex: 0xC4E538) static let flatAndroidGreen = UIColor(hex: 0xA3CB38) static let flatPixelatedGrass = UIColor(hex: 0x009432) static let flatTurkishAqua = UIColor(hex: 0x006266) // Blue static let flatBlueMartina = UIColor(hex: 0x12CBC4) static let flatMediterraneanSea = UIColor(hex: 0x1289A7) static let flatMerchantMarineBlue = UIColor(hex: 0x0652DD) static let flat20000LeaguesUnderTheSea = UIColor(hex: 0x1B1464) // Rose / Purpule static let flatLavenderRose = UIColor(hex: 0xFDA7DF) static let flatLavenderTea = UIColor(hex: 0xD980FA) static let flatForgottenPurple = UIColor(hex: 0x9980FA) static let flatCircumorbitalRing = UIColor(hex: 0x5758BB) // Rose / Red static let flatBaraRed = UIColor(hex: 0xED4C67) static let flatVeryBerry = UIColor(hex: 0xB53471) static let flatHollyhock = UIColor(hex: 0x833471) static let flatMargentaPurple = UIColor(hex: 0x6F1E51) }
unlicense
4ce4b002cd6f1e766c1a75d720130e9f
31.611111
88
0.594037
3.318259
false
false
false
false
Sundog-Interactive/DF15-Wearables-On-Salesforce
iOS/Lead_Nurture/Lead_Nurture/Lead_Nurture/Classes/RootVC.swift
1
1228
// // RootVC.swift // Lead_Nurture // // Created by Craig Isakson on 8/24/15. // Copyright (c) 2015 Sundog Interactive. All rights reserved. // import UIKit class RootVC: UIViewController { let leadHandler: LeadHandler = LeadHandler() // #pragma mark - view lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = "Lead Nurture" NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleWatchKitNotification:"), name: "assign-campaign", object: nil) } /* * When we receive a notification from watch, send request for data to Salesforce Platform * and return information back to watch. */ func handleWatchKitNotification(notification: NSNotification) { //do this before any handler methods. if let watchInfo = notification.object as? WatchInfo { self.leadHandler.watchInfo = watchInfo } if(notification.name == "assign-campaign") { self.leadHandler.assignCampaign() } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
apache-2.0
20a93a6df6a63a5013e669d073395718
23.56
113
0.614007
4.723077
false
false
false
false
lichendi/ExtendEverything
Extensions/Kingfisher+imageWithCacheKey.swift
1
2281
// // Kingfisher+imageWithCacheKey.swift // ExtendEverything // github https://github.com/lichendi/ExtendEverything // Created by LiChendi on 2017/3/16. // Copyright © 2017年 Li Chendi. All rights reserved. // import UIKit import Kingfisher extension UIImageView { convenience init(frame: CGRect ,cacheKey: String ,placeholder: UIImage?) { self.init(frame: frame) let imageCache = ImageCache(name: cacheKey) let cacheCheckResult = imageCache.isImageCached(forKey: cacheKey) if cacheCheckResult.cached { guard let cacheType = cacheCheckResult.cacheType else { self.image = placeholder return } switch cacheType { case .memory: self.image = imageCache.retrieveImageInMemoryCache(forKey: cacheKey) case .disk: self.image = imageCache.retrieveImageInDiskCache(forKey: cacheKey) default: self.image = placeholder } } } convenience init(cacheKey: String ,placeholder: UIImage?) { self.init() let imageCache = ImageCache(name: cacheKey) let cacheCheckResult = imageCache.isImageCached(forKey: cacheKey) if cacheCheckResult.cached { guard let cacheType = cacheCheckResult.cacheType else { self.image = placeholder return } switch cacheType { case .memory: self.image = imageCache.retrieveImageInMemoryCache(forKey: cacheKey) case .disk: self.image = imageCache.retrieveImageInDiskCache(forKey: cacheKey) default: self.image = placeholder } } } } extension Kingfisher where Base: UIImageView { public func setImage(with url: URL?, placeholder: Image?, options: KingfisherOptionsInfo?, cacheKey: String?) { guard let url = url else { return } //不需要对cachekey 为nil处理 let resource = ImageResource(downloadURL: url, cacheKey: cacheKey) setImage(with: resource, placeholder: placeholder, options: options, progressBlock: nil, completionHandler: nil) } }
mit
9e5a64ddd2db0a3ba5aaec1a1d958843
33.830769
120
0.60689
5.204598
false
false
false
false
emericspiroux/Open42
correct42/Controllers/ProjectViewController.swift
1
5743
// // ProjectViewController.swift // Open42 // // Created by larry on 24/08/2016. // Copyright © 2016 42. All rights reserved. // import UIKit class ProjectViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - IBOutlets @IBOutlet weak var tableView: UITableView! // MARK: - Singletons /// Singleton of `ProjectsManager` let projectsManager = ProjectsManager.Shared() /// Singleton of `UserManager` let userManager = UserManager.Shared() // MARK: - Proprieties /// Name of the custom cell call by the `projectsTable` let cellName = "ProjectCell" /// Name of the custom cell call by the `projectsTable` for the loading state let cellLoaderName = "LoaderCell" /// If list is already in load loading is set at true var loading = false /// If project is already in load is set at true var loadingDetails = false var selectedProject:NSIndexPath = NSIndexPath(forItem: 0, inSection: 0) /// Lazy array of all projects of `currentUser` sort by Mark var projects:[Project] { get { return (self.projectsManager.list) } set { self.projectsManager.list = newValue } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - View life cycle /** Register Custom cells, fill delegate and dataSource `tableView` by `ProjectsViewController` */ override func viewDidLoad() { super.viewDidLoad() let nibProject = UINib(nibName: cellName, bundle: nil) let nibLoader = UINib(nibName: cellLoaderName, bundle: nil) tableView.registerNib(nibProject, forCellReuseIdentifier: cellName) tableView.registerNib(nibLoader, forCellReuseIdentifier: cellLoaderName) tableView.delegate = self tableView.dataSource = self } /** Set the login user in `titleLabel` like "\(currentUser.login)'s projects" */ override func viewWillAppear(animated: Bool) { if projectsManager.currentPage <= 1 { loadNextPageInTableView() } } // MARK: - Table view delegation /** Count `projects` for the `tableView` numberOfRowsInSection. */ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let loading = projectsManager.isMax && projects.count != 0 ? 0 : 1 return (projects.count + loading) } /** Create a `ProjectTableViewCell` and fill it. - Returns: An `ProjectTableViewCell` filled. */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellOpt:UITableViewCell? if projects.count == indexPath.row { cellOpt = addRowLoading() } else { cellOpt = addRowProject(indexPath) } if let cell = cellOpt { return cell } return (UITableViewCell()) } private func addRowProject(indexPath: NSIndexPath) -> UITableViewCell? { let projectCellPrototypeOpt:ProjectTableViewCell? = { let projectCell = self.tableView.dequeueReusableCellWithIdentifier(self.cellName) if projectCell is ProjectTableViewCell{ return (projectCell as! ProjectTableViewCell) } return (nil) }() if let projectCellPrototype = projectCellPrototypeOpt { projectCellPrototype.fill(projects[indexPath.row].name, validated: userManager.projectIsValidated(projects[indexPath.row].id), tier: projects[indexPath.row].tier) return projectCellPrototype } return nil } private func addRowLoading() -> UITableViewCell? { let loaderCellPrototypeOpt:LoaderTableViewCell? = { let loaderCell = self.tableView.dequeueReusableCellWithIdentifier(self.cellLoaderName) if loaderCell is LoaderTableViewCell{ return (loaderCell as! LoaderTableViewCell) } return (nil) }() if let loaderCellPrototype = loaderCellPrototypeOpt { loaderCellPrototype.activityindicator.startAnimating() return loaderCellPrototype } return nil } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == (projects.count - 1) && !projectsManager.isMax){ loadNextPageInTableView() } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if !loadingDetails && indexPath.row < projects.count { loadingDetails = true selectedProject = indexPath self.performSegueWithIdentifier("goToProjectDetails", sender: self) self.loadingDetails = false } } // MARK: - IBActions @IBAction func NextPageload(sender: UIBarButtonItem) { tableView.reloadData() loadNextPageInTableView() } // 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 let destination = segue.destinationViewController as? ProjectDetailsViewController{ destination.projectOpt = projects[selectedProject.row] } } // MARK: - Private methods /// Load the next page of the cursus projets and reload table view. private func loadNextPageInTableView(){ if !loading { loading = true if let cursus = self.userManager.selectedCursus { projectsManager.fetchNextCursusProjectsData(cursus.id){(errorOpt) in if let error = errorOpt { ApiGeneral(myView: self).check(error, animate: true) } else { self.tableView.reloadData() } self.loading = false } } else { showAlertWithTitle(NSLocalizedString("42school", comment: "Name of 42 school"), message: NSLocalizedString("noCursus", comment: "explanation for no cursus for current user"), view: self) loading = false } } } }
apache-2.0
c974bfe9ada2e3fc6363b31b8b6e3ede
29.705882
190
0.73511
4.026648
false
false
false
false
ivanfoong/MDCSwipeToChoose
Examples/SwiftLikedOrNope/SwiftLikedOrNope/ChoosePersonViewController.swift
14
9170
// // ChoosePersonViewController.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 class ChoosePersonViewController: UIViewController, MDCSwipeToChooseDelegate { var people:[Person] = [] let ChoosePersonButtonHorizontalPadding:CGFloat = 80.0 let ChoosePersonButtonVerticalPadding:CGFloat = 20.0 var currentPerson:Person! var frontCardView:ChoosePersonView! var backCardView:ChoosePersonView! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.people = defaultPeople() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.people = defaultPeople() // Here you can init your properties } override init(){ super.init() } override func viewDidLoad(){ super.viewDidLoad() // Display the first ChoosePersonView in front. Users can swipe to indicate // whether they like or dislike the person displayed. self.setFrontCardView(self.popPersonViewWithFrame(frontCardViewFrame())!) self.view.addSubview(self.frontCardView) // Display the second ChoosePersonView in back. This view controller uses // the MDCSwipeToChooseDelegate protocol methods to update the front and // back views after each user swipe. self.backCardView = self.popPersonViewWithFrame(backCardViewFrame())! self.view.insertSubview(self.backCardView, belowSubview: self.frontCardView) // Add buttons to programmatically swipe the view left or right. // See the `nopeFrontCardView` and `likeFrontCardView` methods. constructNopeButton() constructLikedButton() } func suportedInterfaceOrientations() -> UIInterfaceOrientationMask{ return UIInterfaceOrientationMask.Portrait } // This is called when a user didn't fully swipe left or right. func viewDidCancelSwipe(view: UIView) -> Void{ println("You couldn't decide on \(self.currentPerson.Name)"); } // This is called then a user swipes the view fully left or right. func view(view: UIView, wasChosenWithDirection: MDCSwipeDirection) -> Void{ // MDCSwipeToChooseView shows "NOPE" on swipes to the left, // and "LIKED" on swipes to the right. if(wasChosenWithDirection == MDCSwipeDirection.Left){ println("You noped: \(self.currentPerson.Name)") } else{ println("You liked: \(self.currentPerson.Name)") } // MDCSwipeToChooseView removes the view from the view hierarchy // after it is swiped (this behavior can be customized via the // MDCSwipeOptions class). Since the front card view is gone, we // move the back card to the front, and create a new back card. if(self.backCardView != nil){ self.setFrontCardView(self.backCardView) } backCardView = self.popPersonViewWithFrame(self.backCardViewFrame()) //if(true){ // Fade the back card into view. if(backCardView != nil){ self.backCardView.alpha = 0.0 self.view.insertSubview(self.backCardView, belowSubview: self.frontCardView) UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { self.backCardView.alpha = 1.0 },completion:nil) } } func setFrontCardView(frontCardView:ChoosePersonView) -> Void{ // Keep track of the person currently being chosen. // Quick and dirty, just for the purposes of this sample app. self.frontCardView = frontCardView self.currentPerson = frontCardView.person } func defaultPeople() -> [Person]{ // It would be trivial to download these from a web service // as needed, but for the purposes of this sample app we'll // simply store them in memory. return [Person(name: "Finn", image: UIImage(named: "finn"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "Jake", image: UIImage(named: "jake"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "Fiona", image: UIImage(named: "fiona"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "P.Gumball", image: UIImage(named: "prince"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5)] } func popPersonViewWithFrame(frame:CGRect) -> ChoosePersonView?{ if(self.people.count == 0){ return nil; } // UIView+MDCSwipeToChoose and MDCSwipeToChooseView are heavily customizable. // Each take an "options" argument. Here, we specify the view controller as // a delegate, and provide a custom callback that moves the back card view // based on how far the user has panned the front card view. var options:MDCSwipeToChooseViewOptions = MDCSwipeToChooseViewOptions() options.delegate = self //options.threshold = 160.0 options.onPan = { state -> Void in if(self.backCardView != nil){ var frame:CGRect = self.frontCardViewFrame() self.backCardView.frame = CGRectMake(frame.origin.x, frame.origin.y-(state.thresholdRatio * 10.0), CGRectGetWidth(frame), CGRectGetHeight(frame)) } } // Create a personView with the top person in the people array, then pop // that person off the stack. var personView:ChoosePersonView = ChoosePersonView(frame: frame, person: self.people[0], options: options) self.people.removeAtIndex(0) return personView } func frontCardViewFrame() -> CGRect{ var horizontalPadding:CGFloat = 20.0 var topPadding:CGFloat = 60.0 var bottomPadding:CGFloat = 200.0 return CGRectMake(horizontalPadding,topPadding,CGRectGetWidth(self.view.frame) - (horizontalPadding * 2), CGRectGetHeight(self.view.frame) - bottomPadding) } func backCardViewFrame() ->CGRect{ var frontFrame:CGRect = frontCardViewFrame() return CGRectMake(frontFrame.origin.x, frontFrame.origin.y + 10.0, CGRectGetWidth(frontFrame), CGRectGetHeight(frontFrame)) } func constructNopeButton() -> Void{ let button:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton let image:UIImage = UIImage(named:"nope")! button.frame = CGRectMake(ChoosePersonButtonHorizontalPadding, CGRectGetMaxY(self.backCardView.frame) + ChoosePersonButtonVerticalPadding, image.size.width, image.size.height) button.setImage(image, forState: UIControlState.Normal) button.tintColor = UIColor(red: 247.0/255.0, green: 91.0/255.0, blue: 37.0/255.0, alpha: 1.0) button.addTarget(self, action: "nopeFrontCardView", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func constructLikedButton() -> Void{ let button:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton let image:UIImage = UIImage(named:"liked")! button.frame = CGRectMake(CGRectGetMaxX(self.view.frame) - image.size.width - ChoosePersonButtonHorizontalPadding, CGRectGetMaxY(self.backCardView.frame) + ChoosePersonButtonVerticalPadding, image.size.width, image.size.height) button.setImage(image, forState:UIControlState.Normal) button.tintColor = UIColor(red: 29.0/255.0, green: 245.0/255.0, blue: 106.0/255.0, alpha: 1.0) button.addTarget(self, action: "likeFrontCardView", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func nopeFrontCardView() -> Void{ self.frontCardView.mdc_swipe(MDCSwipeDirection.Left) } func likeFrontCardView() -> Void{ self.frontCardView.mdc_swipe(MDCSwipeDirection.Right) } }
mit
81286155e49aded703168adffd984f29
47.52381
464
0.680807
4.46446
false
false
false
false
inkyfox/SwiftySQL
Sources/SQL.swift
3
605
// // SQL.swift // SwiftySQL // // Created by Yongha Yoo (inkyfox) on 2016. 10. 21.. // Copyright © 2016년 Gen X Hippies Company. All rights reserved. // import Foundation public struct SQL { public static let null: SQLKeyword = SQLKeyword(.null) public static let currentDate: SQLKeyword = SQLKeyword(.currentDate) public static let currentTime: SQLKeyword = SQLKeyword(.currentTime) public static let currentTimestamp: SQLKeyword = SQLKeyword(.currentTimestamp) public static let all: SQLAsteriskMark = .all public static let prepared: SQLPreparedMark = .prepared }
mit
ed8046cbd14c8de4c4b96421e0c7f5f5
25.173913
82
0.727575
4.095238
false
false
false
false
sealgair/UniversalChords
UniversalChords/Instrument.swift
1
2183
// // Instrument.swift // UniversalChords // // Created by Chase Caster on 5/16/15. // Copyright (c) 2015 chasecaster. All rights reserved. // import UIKit import MusicKit let fingerCache = NSCache<AnyObject, AnyObject>() struct Instrument { let name: String let strings: [Chroma] func nextFingerings(_ thisString: [Finger], otherStrings: [[Finger]]) -> [Fingering] { if otherStrings.count == 0 { return thisString.map {f in [f]} } var fingerings: [Fingering] = [] for finger in thisString { for fingering in nextFingerings(otherStrings[0], otherStrings: Array(otherStrings[1..<otherStrings.count])) { fingerings.append([finger] + fingering) } } return fingerings } func fingerings(_ pitchset: PitchSet) -> [Fingering] { let cacheKey = pitchset.description + self.name if let wrapper = fingerCache.object(forKey: cacheKey as NSString) as? ObjectWrapper<[Fingering]> { return wrapper.value } var notes = Set<Chroma>() for note in pitchset { notes.insert(note.chroma!) } let goodFretsByString: [[Finger]] = strings.map { string in let frets = (0...15).filter { i in return notes.contains(string + i) } return frets.map { i in return Finger(position: i, string: string) } } var fingerings: [Fingering] = nextFingerings(goodFretsByString[0], otherStrings: Array(goodFretsByString[1..<goodFretsByString.count])) fingerings = fingerings.filter { fingering in if Set(fingering.map { f in f.note }) != notes { return false } let top = fingering.reduce(0) {a, b in max(a, b.position)} let bottom = fingering.reduce(12) {a, b in min(a, b.position)} if bottom - top > 5 { return false } return true } fingerCache.setObject(ObjectWrapper(fingerings), forKey: cacheKey as NSString) return fingerings } }
gpl-3.0
4640c0eff16284e6c4b06a9014083bdf
32.075758
143
0.569858
4.15019
false
false
false
false
mliudev/hayaku
xcode/Food Tracker/Food Tracker/MealTableViewController.swift
1
4782
// // MealTableViewController.swift // Food Tracker // // Created by Manwe on 4/16/16. // Copyright © 2016 Manwe. All rights reserved. // import UIKit class MealTableViewController: UITableViewController { // MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem() // load sample data loadSampleMeals() } func loadSampleMeals() { let photo1 = UIImage(named: "meal1")! let meal1 = Meal(name: "Tasty", photo: photo1, rating: 4)! let photo2 = UIImage(named: "meal2")! let meal2 = Meal(name: "Gross", photo: photo2, rating: 5)! let photo3 = UIImage(named: "meal3")! let meal3 = Meal(name: "Too Full", photo: photo3, rating: 3)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier( cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.photo cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source meals.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destinationViewController as! MealViewController if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == "AddItem" { print("Adding new meal.") } } // MARK: Actions @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { // Update an existing meal. meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { // Add a new meal. let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } } } }
mit
f31615b79dc550451862efb2839b98e5
34.414815
157
0.646936
5.324053
false
false
false
false
fabiola-ramirez-coderoad-com/DrawerController
KitchenSink/ExampleFiles/ViewControllers/ExampleRightSideDrawerViewController.swift
4
4065
// Copyright (c) 2014 evolved.io (http://evolved.io) // // 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 class ExampleRightSideDrawerViewController: ExampleSideDrawerViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.restorationIdentifier = "ExampleRightSideDrawerController" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.restorationIdentifier = "ExampleRightSideDrawerController" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) print("Right will appear") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) print("Right did appear") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) print("Right will disappear") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) print("Right did disappear") } override func viewDidLoad() { super.viewDidLoad() self.title = "Right Drawer" } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == DrawerSection.DrawerWidth.rawValue { return "Right Drawer Width" } else { return super.tableView(tableView, titleForHeaderInSection: section) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if indexPath.section == DrawerSection.DrawerWidth.rawValue { let width = self.drawerWidths[indexPath.row] let drawerWidth = self.evo_drawerController?.maximumRightDrawerWidth if drawerWidth == width { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } cell.textLabel?.text = "Width \(self.drawerWidths[indexPath.row])" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == DrawerSection.DrawerWidth.rawValue { self.evo_drawerController?.setMaximumRightDrawerWidth(self.drawerWidths[indexPath.row], animated: true, completion: { (finished) -> Void in tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .None) tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) tableView.deselectRowAtIndexPath(indexPath, animated: true) }) } else { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) } } }
mit
dc4d8177749b18462f2fe94270765387
40.479592
151
0.682903
5.306789
false
false
false
false
victorlin/ReactiveCocoa
ReactiveCocoaTests/Swift/SignalLifetimeSpec.swift
1
10319
// // SignalLifetimeSpec.swift // ReactiveCocoa // // Created by Vadim Yelagin on 2015-12-13. // Copyright (c) 2015 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa class SignalLifetimeSpec: QuickSpec { override func spec() { describe("init") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() } it("should deallocate") { weak var signal: Signal<AnyObject, NoError>? = Signal { _ in nil } expect(signal).to(beNil()) } it("should deallocate if it does not have any observers") { weak var signal: Signal<AnyObject, NoError>? = { let signal: Signal<AnyObject, NoError> = Signal { _ in nil } return signal }() expect(signal).to(beNil()) } it("should deallocate if no one retains it") { var signal: Signal<AnyObject, NoError>? = Signal { _ in nil } weak var weakSignal = signal expect(weakSignal).toNot(beNil()) var reference = signal signal = nil expect(weakSignal).toNot(beNil()) reference = nil expect(weakSignal).to(beNil()) } it("should deallocate even if the generator observer is retained") { var observer: Signal<AnyObject, NoError>.Observer? weak var signal: Signal<AnyObject, NoError>? = { let signal: Signal<AnyObject, NoError> = Signal { innerObserver in observer = innerObserver return nil } return signal }() expect(observer).toNot(beNil()) expect(signal).to(beNil()) } it("should not deallocate if it has at least one observer") { var disposable: Disposable? = nil weak var signal: Signal<AnyObject, NoError>? = { let signal: Signal<AnyObject, NoError> = Signal { _ in nil } disposable = signal.observe(Observer()) return signal }() expect(signal).toNot(beNil()) disposable?.dispose() expect(signal).to(beNil()) } it("should be alive until erroring if it has at least one observer, despite not being explicitly retained") { var errored = false weak var signal: Signal<AnyObject, TestError>? = { let signal = Signal<AnyObject, TestError> { observer in testScheduler.schedule { observer.sendFailed(TestError.default) } return nil } signal.observeFailed { _ in errored = true } return signal }() expect(errored) == false expect(signal).toNot(beNil()) testScheduler.run() expect(errored) == true expect(signal).to(beNil()) } it("should be alive until completion if it has at least one observer, despite not being explicitly retained") { var completed = false weak var signal: Signal<AnyObject, NoError>? = { let signal = Signal<AnyObject, NoError> { observer in testScheduler.schedule { observer.sendCompleted() } return nil } signal.observeCompleted { completed = true } return signal }() expect(completed) == false expect(signal).toNot(beNil()) testScheduler.run() expect(completed) == true expect(signal).to(beNil()) } it("should be alive until interruption if it has at least one observer, despite not being explicitly retained") { var interrupted = false weak var signal: Signal<AnyObject, NoError>? = { let signal = Signal<AnyObject, NoError> { observer in testScheduler.schedule { observer.sendInterrupted() } return nil } signal.observeInterrupted { interrupted = true } return signal }() expect(interrupted) == false expect(signal).toNot(beNil()) testScheduler.run() expect(interrupted) == true expect(signal).to(beNil()) } } describe("Signal.pipe") { it("should deallocate") { weak var signal = Signal<(), NoError>.pipe().0 expect(signal).to(beNil()) } it("should be alive until erroring if it has at least one observer, despite not being explicitly retained") { let testScheduler = TestScheduler() var errored = false weak var weakSignal: Signal<(), TestError>? // Use an inner closure to help ARC deallocate things as we // expect. let test = { let (signal, observer) = Signal<(), TestError>.pipe() weakSignal = signal testScheduler.schedule { // Note that the input observer has a weak reference to the signal. observer.sendFailed(TestError.default) } signal.observeFailed { _ in errored = true } } test() expect(weakSignal).toNot(beNil()) expect(errored) == false testScheduler.run() expect(weakSignal).to(beNil()) expect(errored) == true } it("should be alive until completion if it has at least one observer, despite not being explicitly retained") { let testScheduler = TestScheduler() var completed = false weak var weakSignal: Signal<(), TestError>? // Use an inner closure to help ARC deallocate things as we // expect. let test = { let (signal, observer) = Signal<(), TestError>.pipe() weakSignal = signal testScheduler.schedule { // Note that the input observer has a weak reference to the signal. observer.sendCompleted() } signal.observeCompleted { completed = true } } test() expect(weakSignal).toNot(beNil()) expect(completed) == false testScheduler.run() expect(weakSignal).to(beNil()) expect(completed) == true } it("should be alive until interruption if it has at least one observer, despite not being explicitly retained") { let testScheduler = TestScheduler() var interrupted = false weak var weakSignal: Signal<(), NoError>? let test = { let (signal, observer) = Signal<(), NoError>.pipe() weakSignal = signal testScheduler.schedule { // Note that the input observer has a weak reference to the signal. observer.sendInterrupted() } signal.observeInterrupted { interrupted = true } } test() expect(weakSignal).toNot(beNil()) expect(interrupted) == false testScheduler.run() expect(weakSignal).to(beNil()) expect(interrupted) == true } } describe("testTransform") { it("should deallocate") { weak var signal: Signal<AnyObject, NoError>? = Signal { _ in nil }.testTransform() expect(signal).to(beNil()) } it("should not deallocate if it has at least one observer, despite not being explicitly retained") { weak var signal: Signal<AnyObject, NoError>? = { let signal: Signal<AnyObject, NoError> = Signal { _ in nil }.testTransform() signal.observe(Observer()) return signal }() expect(signal).toNot(beNil()) } it("should not deallocate if it has at least one observer, despite not being explicitly retained") { var disposable: Disposable? = nil weak var signal: Signal<AnyObject, NoError>? = { let signal: Signal<AnyObject, NoError> = Signal { _ in nil }.testTransform() disposable = signal.observe(Observer()) return signal }() expect(signal).toNot(beNil()) disposable?.dispose() expect(signal).to(beNil()) } it("should deallocate if it is unreachable and has no observer") { let (sourceSignal, sourceObserver) = Signal<Int, NoError>.pipe() var firstCounter = 0 var secondCounter = 0 var thirdCounter = 0 func run() { _ = sourceSignal .map { value -> Int in firstCounter += 1 return value } .map { value -> Int in secondCounter += 1 return value } .map { value -> Int in thirdCounter += 1 return value } } run() sourceObserver.sendNext(1) expect(firstCounter) == 0 expect(secondCounter) == 0 expect(thirdCounter) == 0 sourceObserver.sendNext(2) expect(firstCounter) == 0 expect(secondCounter) == 0 expect(thirdCounter) == 0 } it("should not deallocate if it is unreachable but still has at least one observer") { let (sourceSignal, sourceObserver) = Signal<Int, NoError>.pipe() var firstCounter = 0 var secondCounter = 0 var thirdCounter = 0 var disposable: Disposable? func run() { disposable = sourceSignal .map { value -> Int in firstCounter += 1 return value } .map { value -> Int in secondCounter += 1 return value } .map { value -> Int in thirdCounter += 1 return value } .observe { _ in } } run() sourceObserver.sendNext(1) expect(firstCounter) == 1 expect(secondCounter) == 1 expect(thirdCounter) == 1 sourceObserver.sendNext(2) expect(firstCounter) == 2 expect(secondCounter) == 2 expect(thirdCounter) == 2 disposable?.dispose() sourceObserver.sendNext(3) expect(firstCounter) == 2 expect(secondCounter) == 2 expect(thirdCounter) == 2 } } describe("observe") { var signal: Signal<Int, TestError>! var observer: Signal<Int, TestError>.Observer! var token: NSObject? = nil weak var weakToken: NSObject? func expectTokenNotDeallocated() { expect(weakToken).toNot(beNil()) } func expectTokenDeallocated() { expect(weakToken).to(beNil()) } beforeEach { let (signalTemp, observerTemp) = Signal<Int, TestError>.pipe() signal = signalTemp observer = observerTemp token = NSObject() weakToken = token signal.observe { [token = token] _ in _ = token!.description } } it("should deallocate observe handler when signal completes") { expectTokenNotDeallocated() observer.sendNext(1) expectTokenNotDeallocated() token = nil expectTokenNotDeallocated() observer.sendNext(2) expectTokenNotDeallocated() observer.sendCompleted() expectTokenDeallocated() } it("should deallocate observe handler when signal fails") { expectTokenNotDeallocated() observer.sendNext(1) expectTokenNotDeallocated() token = nil expectTokenNotDeallocated() observer.sendNext(2) expectTokenNotDeallocated() observer.sendFailed(.default) expectTokenDeallocated() } } } } private extension SignalProtocol { func testTransform() -> Signal<Value, Error> { return Signal { observer in return self.observe(observer.action) } } }
mit
ccffb29e0a8c7eca39f50e2919fc7471
23.925121
116
0.643279
3.853249
false
true
false
false
overtake/TelegramSwift
Telegram-Mac/CallSettingsModalController.swift
1
773
// // CallSettingsModalController.swift // Telegram // // Created by Mikhail Filimonov on 21/02/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TelegramCore import SwiftSignalKit import Postbox import TGUIKit func CallSettingsModalController(_ sharedContext: SharedAccountContext) -> InputDataModalController { var close: (()->Void)? = nil let controller = CallSettingsController(sharedContext: sharedContext) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { close?() }) let modalController = InputDataModalController(controller) close = { [weak modalController] in modalController?.close() } return modalController }
gpl-2.0
6e2c45b60cafd12e90f1ad36fe4a72f6
20.444444
101
0.709845
5.181208
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/AutoLayoutCookbook/SizeClassSpecificLayouts.swift
1
4900
// // SizeClassSpecificLayouts.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/10/25. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class SizeClassSpecificLayouts: AutoLayoutBaseController { private var redViewTrailingConstraint: NSLayoutConstraint! private var redViewBottomConstraintH: NSLayoutConstraint! private var greenViewTopConstraint: NSLayoutConstraint! private var greenViewTopConstraintH: NSLayoutConstraint! private var greenViewLeadingConstraint: NSLayoutConstraint! private var greenViewLeadingConstraintH: NSLayoutConstraint! private var redView: UIView! private var greenView: UIView! override func initSubviews() { redView = generateView(with: UIColor(hex: 0xCC3300)) view.addSubview(redView) do { redView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20).isActive = true redViewTrailingConstraint = redView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16) redViewTrailingConstraint.isActive = true redView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true redViewBottomConstraintH = redView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -20) } let redLabel = generatLabel(with: "Red") redView.addSubview(redLabel) do { redLabel.centerXAnchor.constraint(equalTo: redView.centerXAnchor).isActive = true redLabel.centerYAnchor.constraint(equalTo: redView.centerYAnchor).isActive = true } greenView = generateView(with: UIColor(hex: 0x1B811D)) view.addSubview(greenView) do { greenViewTopConstraint = greenView.topAnchor.constraint(equalTo: redView.bottomAnchor, constant: 8) greenViewTopConstraint.isActive = true greenViewLeadingConstraintH = greenView.leadingAnchor.constraint(equalTo: redView.trailingAnchor, constant: 8) greenView.heightAnchor.constraint(equalTo: redView.heightAnchor).isActive = true greenView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true greenViewTopConstraintH = greenView.topAnchor.constraint(equalTo: redView.topAnchor) greenView.widthAnchor.constraint(equalTo: redView.widthAnchor).isActive = true greenViewLeadingConstraint = greenView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16) greenViewLeadingConstraint.isActive = true if #available(iOS 11, *) { greenView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true } else { greenView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -20).isActive = true } } let greenLabel = generatLabel(with: "Green") greenView.addSubview(greenLabel) do { greenLabel.centerXAnchor.constraint(equalTo: greenView.centerXAnchor).isActive = true greenLabel.centerYAnchor.constraint(equalTo: greenView.centerYAnchor).isActive = true } } // https://onevcat.com/2014/07/ios-ui-unique/ override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { if newCollection.verticalSizeClass == .compact { greenViewTopConstraint.isActive = false redViewTrailingConstraint.isActive = false greenViewLeadingConstraint.isActive = false redViewBottomConstraintH.isActive = true greenViewTopConstraintH.isActive = true greenViewLeadingConstraintH.isActive = true } else { redViewBottomConstraintH.isActive = false greenViewTopConstraintH.isActive = false greenViewLeadingConstraintH.isActive = false greenViewTopConstraint.isActive = true redViewTrailingConstraint.isActive = true greenViewLeadingConstraint.isActive = true } } private func generateView(with color: UIColor) -> UIView { let subview = UIView() subview.backgroundColor = color subview.translatesAutoresizingMaskIntoConstraints = false return subview } private func generatLabel(with text: String) -> UILabel { let label = UILabel() label.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .vertical) label.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .horizontal) label.text = text label.font = UIFont.systemFont(ofSize: 36) label.translatesAutoresizingMaskIntoConstraints = false return label } }
mit
1b4545c78c6e30e72c40efaea951c0f5
43.009009
128
0.695803
5.62788
false
false
false
false
huangboju/Moots
Examples/SwiftUI/PokeMaster/PokeMaster/Model/ViewModel/PokemonViewModel.swift
1
4752
// // PokemonViewModel.swift // PokeMaster // // Created by 王 巍 on 2019/08/06. // Copyright © 2019 OneV's Den. All rights reserved. // import SwiftUI struct PokemonViewModel: Identifiable, Codable { var id: Int { pokemon.id } let pokemon: Pokemon let species: PokemonSpecies init(pokemon: Pokemon, species: PokemonSpecies) { self.pokemon = pokemon self.species = species } var color: Color { species.color.name.color } var height: String { "\(Double(pokemon.height) / 10)m" } var weight: String { "\(Double(pokemon.weight) / 10)kg" } var name: String { species.names.CN } var nameEN: String { species.names.EN } var genus: String { species.genera.CN } var genusEN: String { species.genera.EN } var types: [Type] { self.pokemon.types .sorted { $0.slot < $1.slot } .map { Type(pokemonType: $0) } } var iconImageURL: URL { URL(string: "https://raw.githubusercontent.com/onevcat/pokemaster-images/master/images/Pokemon-\(id).png")! } var detailPageURL: URL { URL(string: "https://cn.portal-pokemon.com/play/pokedex/\(String(format: "%03d", id))")! } var descriptionText: String { species.flavorTextEntries.CN.newlineRemoved } var descriptionTextEN: String { species.flavorTextEntries.EN.newlineRemoved } } extension PokemonViewModel: CustomStringConvertible { var description: String { "PokemonViewModel - \(id) - \(self.name)" } } extension PokemonViewModel { struct `Type`: Identifiable { var id: String { return name } let name: String let color: Color init(name: String, color: Color) { self.name = name self.color = color } init(pokemonType: Pokemon.`Type`) { if let v = TypeInternal(rawValue: pokemonType.type.name)?.value { self = v } else { self.name = "???" self.color = .gray } } enum TypeInternal: String { case normal case fighting case flying case poison case ground case rock case bug case ghost case steel case fire case water case grass case electric case psychic case ice case dragon case dark case fairy case unknown case shadow var value: Type { switch self { case .normal: return Type(name: "一般", color: Color(hex: 0xBBBBAC)) case .fighting: return Type(name: "格斗", color: Color(hex: 0xAE5B4A)) case .flying: return Type(name: "飞行", color: Color(hex: 0x7199F8)) case .poison: return Type(name: "毒", color: Color(hex: 0x9F5A96)) case .ground: return Type(name: "地面", color: Color(hex: 0xD8BC65)) case .rock: return Type(name: "岩石", color: Color(hex: 0xB8AA6F)) case .bug: return Type(name: "虫", color: Color(hex: 0xADBA44)) case .ghost: return Type(name: "幽灵", color: Color(hex: 0x6667B5)) case .steel: return Type(name: "钢", color: Color(hex: 0xAAAABA)) case .fire: return Type(name: "火", color: Color(hex: 0xEB5435)) case .water: return Type(name: "水", color: Color(hex: 0x5198F7)) case .grass: return Type(name: "草", color: Color(hex: 0x8BC965)) case .electric: return Type(name: "电", color: Color(hex: 0xF7CD55)) case .psychic: return Type(name: "超能力", color: Color(hex: 0xEC6298)) case .ice: return Type(name: "冰", color: Color(hex: 0x90DBFB)) case .dragon: return Type(name: "龙", color: Color(hex: 0x7469E6)) case .dark: return Type(name: "恶", color: Color(hex: 0x725647)) case .fairy: return Type(name: "妖精", color: Color(hex: 0xF3AFFA)) case .unknown: return Type(name: "???", color: Color(hex: 0x749E91)) case .shadow: return Type(name: "暗", color: Color(hex: 0x9F5A96)) } } } } }
mit
5f140b388e1b81ea1d02a5ca53f80472
31.351724
115
0.505223
4.047455
false
false
false
false
thedistance/TheDistanceForms
TheDistanceForms/Classes/ErrorStack.swift
1
5497
// // ErrorStack.swift // StackView // // Created by Josh Campion on 09/02/2016. // import Foundation import TDStackView /** Abstract class that shows an icon, error label and error image around a given center component view. This class has convenience properties for the `errorText` which will then set `hidden` of the error label and image view. This is the core view of all form components that can show errors. - seealso: `TextStack` - seealso: `TextFieldStack` - seealso: `TextViewStack` - seealso: `SwitchStack` - seealso: `SegmentedTextFieldStack` */ open class ErrorStack:CreatedStack { // MARK: Errors /// Sets the text of the `errorLabel` and shows / hides `errorLabel` and `errorImageView` based on whether this string `.isEmpty`. This can be configured manually or setting `self.validation` and calling `validateValue()`. open var errorText:String? { didSet { errorLabel.text = errorText errorLabel.isHidden = errorText?.isEmpty ?? true errorImageView.isHidden = errorLabel.isHidden // TODO: Weak link to TextResponder Cocoapod // this will cause layout to occur which could affect the position of other text input items, after which the keyboard responder should be notified to update the scroll accordingly. DispatchQueue.main.async { () -> Void in // NSNotificationCenter.defaultCenter().postNotificationName(KeyboardResponderRequestUpdateScrollNotification, object: nil) } } } /// The label showing the error associated with the user's input. The text for this label should be set through the `errorText` property, which configures properties such as showing and hiding the label. open let errorLabel:UILabel /// The `UIImageView` to show an error icon centered on the text input if there is an error. open let errorImageView:UIImageView /// The `UIImageView` to show an icon aligned to the left of the text input. open let iconImageView:UIImageView /// A horizontal `StackView` containing the `errorImageView` and `centerComponent` from the default initialiser open let centerStack:StackView /// A vertical `StackView` containing the `centerStack` and `errorLabel`. open let errorStack:StackView /** Default initialiser. Creates the necessary views as sub-stacks. It has many optional parameters to allow for customisation using custom subclasses, perhaps a class which configures the components to match your apps branding. - seealso: TheDistanceFormsThemed - parameter centerComponent: The view to use that is supplemented with an icon, error label and error image. - parameter errorLabel: The `UILabel` or subclass to use to show the error text. Default value is a new `UILabel`. - parameter iconImageView: The `UIImageView` or subclass to use to show the icon. Default value is a new `UIImageView`. - parameter errorImageView: The `UIImageView` or subclass to use to show the error icon. Default value is a new `UIImageView`. */ public init(centerComponent:UIView, errorLabel:UILabel = UILabel(), errorImageView:UIImageView = UIImageView(), iconImageView:UIImageView = UIImageView()) { self.errorLabel = errorLabel self.errorImageView = errorImageView self.iconImageView = iconImageView if errorImageView.image == nil { errorImageView.image = UIImage(named: "ic_warning", in: Bundle(for: ErrorStack.self), compatibleWith: nil) } errorLabel.numberOfLines = 0 errorLabel.isHidden = true errorLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) for iv in [errorImageView, iconImageView] { iv.contentMode = .scaleAspectFit iv.backgroundColor = UIColor.clear iv.isHidden = true iv.setContentHuggingPriority(255, for: .horizontal) iv.setContentCompressionResistancePriority(760, for: .horizontal) iv.setContentCompressionResistancePriority(760, for: .vertical) } centerStack = CreateStackView([centerComponent, errorImageView]) centerStack.axis = .horizontal centerStack.spacing = 8.0 errorStack = CreateStackView([centerStack.view, errorLabel]) errorStack.axis = UILayoutConstraintAxis.vertical errorStack.stackAlignment = .fill errorStack.stackDistribution = .fill errorStack.spacing = 8.0 super.init(arrangedSubviews: [iconImageView, errorStack.view]) /* // this layout should work but doesn't due to a bug in UIStackView errorStack = CreateStackView([errorImageView, errorLabel]) errorStack.axis = .Horizontal errorStack.spacing = 8.0 centerStack = CreateStackView([centerComponent, errorStack.view]) centerStack.axis = UILayoutConstraintAxis.Vertical centerStack.stackAlignment = .Fill centerStack.stackDistribution = .Fill centerStack.spacing = 8.0 super.init(arrangedSubviews: [iconImageView, centerStack.view]) */ stack.axis = .horizontal stack.spacing = 8.0 } }
mit
db52066094cecc42409b85453dce6f23
40.643939
290
0.666727
5.270374
false
false
false
false
RLovelett/langserver-swift
Sources/BaseProtocol/Types/Header.swift
1
3838
// // Header.swift // langserver-swift // // Created by Ryan Lovelett on 12/8/16. // // import Foundation private let terminator = Data(bytes: [0x0D, 0x0A]) // "\r\n" private let separatorBytes = Data(bytes: [0x3A, 0x20]) // ": " /// The `Header` provides an iterator interface to the header part of the base protocol of language /// server protocol. /// /// Communications between the server and the client in the language server protocol consist of a header (comparable to /// HTTP) and a content part (which conforms to [JSON-RPC](http://www.jsonrpc.org)). struct Header : IteratorProtocol { /// Each `Header.Field` can be viewed as a single, logical line of ASCII characters, comprising a field-name and a /// field-body. /// /// - Warning: While `Header`, `Fields` and `Field` strive to be spec compliant they may not actually be. Any /// any discrepancies should be reported. /// /// - SeeAlso: [RFC 822 Section 3.1](http://www.ietf.org/rfc/rfc0822.txt) /// - SeeAlso: [RFC 7230, Section 3.2 - Header Fields](https://tools.ietf.org/html/rfc7230#section-3.2) struct Field { /// The name of a field in a header. let name: String /// The body, or value, of a field in a header. let body: String /// Initialize a `Field` by parsing the byte buffer. If the buffer does not conform to the specification then /// the `Field` will fail to initialize. /// /// Where possible the data should conform to RFC 7230, Section 3.2 - Header Fields. /// /// - Parameter data: A byte buffer that contains a RFC 7230 header field. /// - SeeAlso: [RFC 7230, Section 3.2 - Header Fields](https://tools.ietf.org/html/rfc7230#section-3.2) init?(_ data: Data) { guard let seperator = data.range(of: separatorBytes) else { return nil } guard let n = String(data: data.subdata(in: data.startIndex..<seperator.lowerBound), encoding: .utf8) else { return nil } guard let b = String(data: data.subdata(in: seperator.upperBound..<data.endIndex), encoding: .utf8) else { return nil } name = n body = b } } /// A byte buffer that contains the complete header information of a message. private let header: Data /// The index of the first byte of the next `Header.Field`. private var index: Data.Index /// Initialize a `Header` iterator with the provided byte buffer. /// /// - Parameter data: A byte buffer that contains the header part of the base protocol. init(_ data: Data) { header = data index = data.startIndex } /// The range of the byte buffer that should be checked for the next `Header.Field`. private var range: Range<Data.Index> { return index..<header.endIndex } /// Attempt to parse a `Header.Field` from the `Header`'s byte buffer. /// /// - Returns: The next valid `Header.Field` or nil if all valid `Header.Fields` have been parsed. mutating func next() -> Header.Field? { let foo = header.range(of: terminator, options: [], in: range) ?? (header.endIndex..<header.endIndex) let bar = Range<Data.Index>(index..<foo.lowerBound) let fieldData = header.subdata(in: bar) index = foo.upperBound return Header.Field(fieldData) } /// A conveinence property to find the `Header.Field` with the name `Content-Length`. If it exists, and convert it /// then convert the field's body to an `Int`. /// /// - Note: This field may not exist in the `Header`. In that case the `Optional` is `none`. var contentLength: Int? { return AnySequence({ self }) .first(where: { $0.name.lowercased() == "content-length" }) .flatMap({ Int($0.body, radix: 10) }) } }
apache-2.0
6d7778fa11e0753febe08bee012f0495
40.268817
133
0.633924
3.920327
false
false
false
false
5calls/ios
FiveCalls/FiveCalls/UserStats.swift
1
1128
// // UserStats.swift // FiveCalls // // Created by Melville Stanley on 3/5/18. // Copyright © 2018 5calls. All rights reserved. // // We expect the JSON to look like this: // { // "contact": 221, // "voicemail": 158, // "unavailable": 32 // } struct UserStats { let contact: Int? let voicemail: Int? let unavailable: Int? let weeklyStreak: Int? } extension UserStats : JSONSerializable { init?(dictionary: JSONDictionary) { let weeklyStreak = dictionary["weeklyStreak"] as? Int var contact: Int? var voicemail: Int? var unavailable: Int? if let stats = dictionary["stats"] as? JSONDictionary { contact = stats["contact"] as? Int voicemail = stats["voicemail"] as? Int unavailable = stats["unavailable"] as? Int } self.init(contact: contact, voicemail: voicemail, unavailable: unavailable, weeklyStreak: weeklyStreak) } func totalCalls() -> Int { return (contact ?? 0) + (voicemail ?? 0) + (unavailable ?? 0) } }
mit
3366e1be758d86147c25f486323f1676
23.5
69
0.571429
4.025
false
false
false
false
rnelson/SwiftFI
SwiftFI/ViewController.swift
1
2007
// // ViewController.swift // SwiftFI // // Created by Ross Nelson on 7/11/14. // Copyright (c) 2014 Food Inspections. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController { let METERS_PER_MILE = 1609.344 @IBOutlet var mapView: MKMapView override func viewDidLoad() { super.viewDidLoad() var lnk: CLLocationCoordinate2D var viewDistance: CLLocationDistance var viewRegion: MKCoordinateRegion // Zoom to LNK by default... lnk = CLLocationCoordinate2DMake(40.85, -96.61) viewDistance = 5 * METERS_PER_MILE viewRegion = MKCoordinateRegionMakeWithDistance(lnk, viewDistance, viewDistance) mapView.setRegion(viewRegion, animated: true) // ...but go ahead and go to where the user is if they want mapView.showsUserLocation = true // Display the map view and populate it self.view.addSubview(mapView) self.addCitiesToMap() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addCitiesToMap() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { var annotations: NSArray = self.loadFirms() self.mapView.addAnnotations(annotations) }) } func loadFirms() -> NSArray { var annotations = NSMutableArray() var firms: NSArray = FIFirm.loadWithinMapView(self.mapView) for o in firms { var firm: FIFirm = o as FIFirm var annotation: MapAnnotation var violations: NSString var coordinate: CLLocationCoordinate2D violations = "Critical: " + String(firm.totalCritical) + ", Noncritical: " + String(firm.totalNoncritical) coordinate = CLLocationCoordinate2D(latitude: firm.coordinate.latitude, longitude: firm.coordinate.longitude) annotation = MapAnnotation() annotation.title = firm.name annotation.subtitle = violations annotation.coordinate = coordinate annotations.addObject(annotation) } return annotations } }
mit
7705e5b16bf7e67de632f117e4e331df
25.407895
112
0.735426
3.815589
false
false
false
false
KarmaPulse/KPGallery
Sources/KP_Grid.swift
1
1594
// // KP_Grid.swift // Kboard_Gallery // // Created by Jose De Jesus Garfias Lopez on 8/15/17. // Copyright © 2017 Karmapulse. All rights reserved. // import UIKit class KP_Grid: UIView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { var collectionView: UICollectionView! override init(frame: CGRect) { super.init(frame : frame); let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout(); layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10); layout.itemSize = CGSize(width: 300, height: 300); collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout); collectionView.dataSource = self; collectionView.delegate = self; collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell"); collectionView.backgroundColor = UIColor.white; self.addSubview(collectionView); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 30 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) cell.backgroundColor = UIColor.orange return cell } }
mit
aa85d748a7554389c173be7850e2fc97
32.1875
121
0.677338
5.345638
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/UserProfileView.swift
3
9958
// // UserProfileView.swift // edX // // Created by Akiva Leffert on 4/4/16. // Copyright © 2016 edX. All rights reserved. // class UserProfileView : UIView, UIScrollViewDelegate { private let margin = 4 private class SystemLabel: UILabel { private override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { return CGRectInset(super.textRectForBounds(bounds, limitedToNumberOfLines: numberOfLines), 10, 0) } private override func drawTextInRect(rect: CGRect) { let newRect = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, newRect)) } } private let scrollView = UIScrollView() private let usernameLabel = UILabel() private let messageLabel = UILabel() private let countryLabel = UILabel() private let languageLabel = UILabel() private let bioText = UITextView() private let tabs = TabContainerView() private let bioSystemMessage = SystemLabel() private let avatarImage = ProfileImageView() private let header = ProfileBanner() private let bottomBackground = UIView() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(scrollView) setupViews() setupConstraints() } private func setupViews() { scrollView.backgroundColor = OEXStyles.sharedStyles().primaryBaseColor() scrollView.delegate = self avatarImage.borderWidth = 3.0 scrollView.addSubview(avatarImage) usernameLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(usernameLabel) messageLabel.hidden = true messageLabel.numberOfLines = 0 messageLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(messageLabel) languageLabel.accessibilityHint = Strings.Profile.languageAccessibilityHint languageLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(languageLabel) countryLabel.accessibilityHint = Strings.Profile.countryAccessibilityHint countryLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(countryLabel) bioText.backgroundColor = UIColor.clearColor() bioText.textAlignment = .Natural bioText.scrollEnabled = false bioText.editable = false bioText.textContainer.lineFragmentPadding = 0; bioText.textContainerInset = UIEdgeInsetsZero tabs.layoutMargins = UIEdgeInsets(top: StandardHorizontalMargin, left: StandardHorizontalMargin, bottom: StandardHorizontalMargin, right: StandardHorizontalMargin) tabs.items = [bioTab] scrollView.addSubview(tabs) bottomBackground.backgroundColor = bioText.backgroundColor scrollView.insertSubview(bottomBackground, belowSubview: tabs) bioSystemMessage.hidden = true bioSystemMessage.numberOfLines = 0 bioSystemMessage.backgroundColor = OEXStyles.sharedStyles().neutralXLight() scrollView.insertSubview(bioSystemMessage, aboveSubview: tabs) header.style = .LightContent header.backgroundColor = scrollView.backgroundColor header.hidden = true self.addSubview(header) bottomBackground.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupConstraints() { scrollView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self) } avatarImage.snp_makeConstraints { (make) -> Void in make.width.equalTo(avatarImage.snp_height) make.width.equalTo(166) make.centerX.equalTo(scrollView) make.top.equalTo(scrollView.snp_topMargin).offset(20) } usernameLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(avatarImage.snp_bottom).offset(margin) make.centerX.equalTo(scrollView) } messageLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(usernameLabel.snp_bottom).offset(margin).priorityHigh() make.centerX.equalTo(scrollView) } languageLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(messageLabel.snp_bottom) make.centerX.equalTo(scrollView) } countryLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(languageLabel.snp_bottom) make.centerX.equalTo(scrollView) } tabs.snp_makeConstraints { (make) -> Void in make.top.equalTo(countryLabel.snp_bottom).offset(35).priorityHigh() make.bottom.equalTo(scrollView) make.leading.equalTo(scrollView) make.trailing.equalTo(scrollView) make.width.equalTo(scrollView) } bioSystemMessage.snp_makeConstraints { (make) -> Void in make.top.equalTo(tabs) make.bottom.greaterThanOrEqualTo(self) make.leading.equalTo(scrollView) make.trailing.equalTo(scrollView) make.width.equalTo(scrollView) } bottomBackground.snp_makeConstraints {make in make.edges.equalTo(bioSystemMessage) } header.snp_makeConstraints { (make) -> Void in make.top.equalTo(scrollView) make.leading.equalTo(scrollView) make.trailing.equalTo(scrollView) make.height.equalTo(56) } } private func setMessage(message: String?) { if let message = message { let messageStyle = OEXTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().primaryXLightColor()) messageLabel.hidden = false messageLabel.snp_remakeConstraints { (make) -> Void in make.top.equalTo(usernameLabel.snp_bottom).offset(margin).priorityHigh() make.centerX.equalTo(scrollView) } countryLabel.hidden = true languageLabel.hidden = true messageLabel.attributedText = messageStyle.attributedStringWithText(message) } else { messageLabel.hidden = true messageLabel.snp_updateConstraints(closure: { (make) -> Void in make.height.equalTo(0) }) countryLabel.hidden = false languageLabel.hidden = false } } private func messageForProfile(profile : UserProfile, editable : Bool) -> String? { if profile.sharingLimitedProfile { return editable ? Strings.Profile.showingLimited : Strings.Profile.learnerHasLimitedProfile(platformName: OEXConfig.sharedConfig().platformName()) } else { return nil } } private var bioTab : TabItem { return TabItem(name: "About", view: bioText, identifier: "bio") } func populateFields(profile: UserProfile, editable : Bool, networkManager : NetworkManager) { let usernameStyle = OEXTextStyle(weight : .Normal, size: .XXLarge, color: OEXStyles.sharedStyles().neutralWhiteT()) let infoStyle = OEXTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().primaryXLightColor()) let bioStyle = OEXStyles.sharedStyles().textAreaBodyStyle let messageStyle = OEXMutableTextStyle(weight: .Bold, size: .Large, color: OEXStyles.sharedStyles().neutralDark()) messageStyle.alignment = .Center usernameLabel.attributedText = usernameStyle.attributedStringWithText(profile.username) bioSystemMessage.hidden = true avatarImage.remoteImage = profile.image(networkManager) setMessage(messageForProfile(profile, editable: editable)) if profile.sharingLimitedProfile { if (profile.parentalConsent ?? false) && editable { let message = NSMutableAttributedString(attributedString: messageStyle.attributedStringWithText(Strings.Profile.ageLimit)) bioSystemMessage.attributedText = message bioSystemMessage.hidden = false } } else { self.bioText.text = "" if let language = profile.language { let icon = Icon.Comment.attributedTextWithStyle(infoStyle) let langText = infoStyle.attributedStringWithText(language) languageLabel.attributedText = NSAttributedString.joinInNaturalLayout([icon, langText]) } if let country = profile.country { let icon = Icon.Country.attributedTextWithStyle(infoStyle) let countryText = infoStyle.attributedStringWithText(country) countryLabel.attributedText = NSAttributedString.joinInNaturalLayout([icon, countryText]) } if let bio = profile.bio { bioText.attributedText = bioStyle.attributedStringWithText(bio) } else { let message = messageStyle.attributedStringWithText(Strings.Profile.noBio) bioSystemMessage.attributedText = message bioSystemMessage.hidden = false } } header.showProfile(profile, networkManager: networkManager) } var extraTabs : [ProfileTabItem] = [] { didSet { let instantiatedTabs = extraTabs.map {tab in tab(scrollView) } tabs.items = [bioTab] + instantiatedTabs } } @objc func scrollViewDidScroll(scrollView: UIScrollView) { UIView.animateWithDuration(0.25) { self.header.hidden = scrollView.contentOffset.y < CGRectGetMaxY(self.avatarImage.frame) } } func chooseTab(identifier: String) { tabs.showTabWithIdentifier(identifier) } }
apache-2.0
842cc92cb2b0097f9017d5bb7a117623
37.596899
171
0.65823
5.224029
false
false
false
false
february29/Learning
swift/Fch_Contact/Fch_Contact/AppClasses/Model/PersonModel.swift
1
1211
// // PersonModel.swift // Fch_Contact // // Created by bai on 2017/11/22. // Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved. // import Foundation import HandyJSON class PersonModel: HandyJSON { required init() { } var id : Int! var book_id : Int! var dept_id : Int! var column1 : String! var column2 : String! var column3 : String! var column4 : String! var column5 : String! var column6 : String! var deleted : Int! var is_title : Int! } extension String{ public var isFchPhone:Bool { if self.isPhoneNumber { return true; } let mobile = "^6[0-9]\\d{3}" let tel = "^0(10|2[0-5789]|\\d{3})(-)?\\d{7,8}$"; let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile) let regextesttle = NSPredicate(format: "SELF MATCHES %@",tel) if ((regextestmobile.evaluate(with: self) == true)||(regextesttle.evaluate(with: self) == true)) { return true } else { return false } } }
mit
401c1cb2e680e3cfd0660327ff7a97ce
17.793651
104
0.511824
3.819355
false
true
false
false