repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wikimedia/wikipedia-ios
WMF Framework/Remote Notifications/Operations/RemoteNotificationsPagingOperation.swift
1
6139
import Foundation /// Base class for operations that deal with fetching and persisting user notifications. Operation will recursively call the next page, with overrideable hooks to adjust this behavior. class RemoteNotificationsPagingOperation: RemoteNotificationsProjectOperation { private let needsCrossWikiSummary: Bool private(set) var crossWikiSummaryNotification: RemoteNotificationsAPIController.NotificationsResult.Notification? required init(project: WikimediaProject, apiController: RemoteNotificationsAPIController, modelController: RemoteNotificationsModelController, needsCrossWikiSummary: Bool) { self.needsCrossWikiSummary = needsCrossWikiSummary super.init(project: project, apiController: apiController, modelController: modelController) } required init(project: WikimediaProject, apiController: RemoteNotificationsAPIController, modelController: RemoteNotificationsModelController) { fatalError("init(project:apiController:modelController:) has not been implemented") } required init(apiController: RemoteNotificationsAPIController, modelController: RemoteNotificationsModelController) { fatalError("init(apiController:modelController:) has not been implemented") } // MARK: Overridable hooks /// Boolean logic for allowing operation execution. Override to add any validation before executing this operation. var shouldExecute: Bool { return true } /// Hook to exit early from recursively paging and persisting the API response. This is called right before the next page is fetched from the API. This value will take priority even if last response indicates that there are additional pages to fetch. /// - Parameter lastNotification: The last notification returned from the previous response /// - Returns: Boolean flag indicating recursive paging should continue or not in this operation. func shouldContinueToPage(lastNotification: RemoteNotificationsAPIController.NotificationsResult.Notification) -> Bool { return true } /// Hook that is called when the last page of notifications has been fetched and saved locally. Do any additional cleanup here. func didFetchAndSaveAllPages() { } /// Hook that is called when we are about to fetch and persist a new page from the API. /// - Parameter newContinueId: Continue Id the operation will send in the next API call. func willFetchAndSaveNewPage(newContinueId: String) { } /// Override to provide an initial continue Id to send into the first API call var initialContinueId: String? { return nil } /// Override to allow operation to page through a filtered list (read, unread, etc.) var filter: RemoteNotificationsAPIController.Query.Filter { return .none } // MARK: General Fetch and Save functionality override func execute() { guard shouldExecute else { finish() return } recursivelyFetchAndSaveNotifications(continueId: initialContinueId) } private func recursivelyFetchAndSaveNotifications(continueId: String? = nil) { apiController.getAllNotifications(from: project, needsCrossWikiSummary: needsCrossWikiSummary, filter: filter, continueId: continueId) { [weak self] apiResult, error in guard let self = self else { return } if let error = error { self.finish(with: error) return } guard let fetchedNotifications = apiResult?.list else { self.finish(with: RequestError.unexpectedResponse) return } var fetchedNotificationsToPersist = fetchedNotifications var lastNotification = fetchedNotifications.last if self.needsCrossWikiSummary { let notificationIsSummaryType: (RemoteNotificationsAPIController.NotificationsResult.Notification) -> Bool = { notification in notification.id == "-1" && notification.type == "foreign" } let crossWikiSummaryNotification = fetchedNotificationsToPersist.first(where: notificationIsSummaryType) self.crossWikiSummaryNotification = crossWikiSummaryNotification fetchedNotificationsToPersist = fetchedNotifications.filter({ notification in !notificationIsSummaryType(notification) }) lastNotification = fetchedNotificationsToPersist.last } guard let lastNotification = lastNotification else { // Empty notifications list so nothing to import. Exit early. self.didFetchAndSaveAllPages() self.finish() return } let backgroundContext = self.modelController.newBackgroundContext() self.modelController.createNewNotifications(moc: backgroundContext, notificationsFetchedFromTheServer: Set(fetchedNotificationsToPersist), completion: { [weak self] result in guard let self = self else { return } switch result { case .success: guard let newContinueId = apiResult?.continueId, newContinueId != continueId, self.shouldContinueToPage(lastNotification: lastNotification) else { self.didFetchAndSaveAllPages() self.finish() return } self.willFetchAndSaveNewPage(newContinueId: newContinueId) self.recursivelyFetchAndSaveNotifications(continueId: newContinueId) case .failure(let error): self.finish(with: error) } }) } } }
mit
f9130e0a2cff43b253c8c2785da305f8
44.139706
254
0.649291
6.489429
false
false
false
false
OpenKitten/MongoKitten
Sources/Meow/Model.swift
2
3392
import MongoKitten import MongoCore import NIO //public struct PartialChange<M: Model> { // public let entity: M.Identifier // public let changedFields: Document // public let removedFields: Document //} public typealias MeowIdentifier = Primitive & Equatable public protocol BaseModel { associatedtype Identifier: MeowIdentifier /// The collection name instances of the model live in. A default implementation is provided. static var collectionName: String { get } /// The `_id` of the model. *This property MUST be encoded with `_id` as key* var _id: Identifier { get } } public protocol ReadableModel: BaseModel, Decodable { static func decode(from document: Document) throws -> Self static var decoder: BSONDecoder { get } } public protocol MutableModel: ReadableModel, Encodable { func encode(to document: Document.Type) throws -> Document static var encoder: BSONEncoder { get } } public typealias Model = MutableModel extension BaseModel { public static var collectionName: String { return String(describing: Self.self) // Will be the name of the type } } extension ReadableModel { @inlinable public static var decoder: BSONDecoder { .init() } @inlinable public static func decode(from document: Document) throws -> Self { try Self.decoder.decode(Self.self, from: document) } public static func watch(options: ChangeStreamOptions = .init(), in database: MeowDatabase) -> EventLoopFuture<ChangeStream<Self>> { return database.collection(for: Self.self).watch(options: options) } public static func count( where filter: Document = Document(), in database: MeowDatabase ) -> EventLoopFuture<Int> { return database.collection(for: Self.self).count(where: filter) } public static func count<Q: MongoKittenQuery>( where filter: Q, in database: MeowDatabase ) -> EventLoopFuture<Int> { return database.collection(for: Self.self).count(where: filter) } } // MARK: - Default implementations extension MutableModel { @available(*, renamed: "save") public func create(in database: MeowDatabase) -> EventLoopFuture<MeowOperationResult> { save(in: database) } public func save(in database: MeowDatabase) -> EventLoopFuture<MeowOperationResult> { return database.collection(for: Self.self).upsert(self).map { reply in return MeowOperationResult( success: reply.updatedCount == 1, n: reply.updatedCount, writeErrors: reply.writeErrors ) } } @inlinable public static var encoder: BSONEncoder { .init() } @inlinable public func encode(to document: Document.Type) throws -> Document { try Self.encoder.encode(self) } } public enum MeowHook<M: Model> {} public struct MeowOperationResult { public struct NotSuccessful: Error {} public let success: Bool public let n: Int public let writeErrors: [MongoWriteError]? } extension EventLoopFuture where Value == MeowOperationResult { public func assertCompleted() -> EventLoopFuture<Void> { return flatMapThrowing { result in guard result.success else { throw MeowOperationResult.NotSuccessful() } } } }
mit
acfc01ace6ff136ce3605151e8f03f38
29.558559
136
0.669811
4.608696
false
false
false
false
huankong/Weibo
Weibo/Weibo/Main/Base/BaseViewController.swift
1
1384
// // BaseViewController.swift // Weibo // // Created by ldy on 16/6/22. // Copyright © 2016年 ldy. All rights reserved. // import UIKit class BaseViewController: UIViewController,VisitorViewDelegate { var islogin = UserAcount.userLogin() var vistorView: VisitorView? override func loadView() { islogin ? super.loadView() : createVistorView() } // deinit { // print("BaseViewController销毁") // } private func createVistorView() { vistorView = VisitorView() vistorView!.delegate = self view = vistorView navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(registBtnDidAction)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(loginBtnDidAction)) } override func viewDidLoad() { super.viewDidLoad() } //登录回调 func loginBtnDidAction() { let navi = BaseNavigationViewController(rootViewController: Oauth2ViewController()) self.presentViewController(navi, animated: true, completion: nil) } //注册回调 func registBtnDidAction() { print(UserAcount.readAccount()) } func attenBtnDidAction() { } }
apache-2.0
25c3c0792a203bb9552b0b7714238971
26.06
159
0.656319
4.747368
false
false
false
false
exsortis/TenCenturiesKit
Sources/TenCenturiesKit/Models/StatusResponse.swift
1
1152
import Foundation public struct StatusResponse { public let account : [Account] public let isActive : Bool public let updatedAt : Date public let updatedUnix : Int } extension StatusResponse : Serializable { public init?(from json : JSONDictionary) { guard let accounts = json["account"] as? [JSONDictionary], let isActive = json["is_active"] as? Bool, let u = json["updated_at"] as? String, let updatedAt = ISO8601DateFormatter().date(from: u), let updatedUnix = json["updated_unix"] as? Int else { return nil } self.account = accounts.flatMap(Account.init(from:)) self.isActive = isActive self.updatedAt = updatedAt self.updatedUnix = updatedUnix } public func toDictionary() -> JSONDictionary { let dict : JSONDictionary = [ "account" : account.map({ $0.toDictionary() }), "is_active" : isActive, "updated_at" : ISO8601DateFormatter().string(from: updatedAt), "updated_unix" : updatedUnix, ] return dict } }
mit
271ecb66485c042c9fde6b40ab77e6c1
27.8
74
0.585938
4.740741
false
false
false
false
BanyaKrylov/Learn-Swift
Part 2.playground/Contents.swift
1
354
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var namee: String? var num1 = 5 var num2 = 5 if num1 > num2 { print("\(num1) > \(num2)") } else if num1 < num2 { print("\(num1) < \(num2)") } else { print("\(num1) = \(num2)") } if let <#constant name#> = <#optional#> { <#statements#> }
apache-2.0
8b966c92257d93aaa5974e579838d563
15.136364
52
0.570621
2.878049
false
false
false
false
mownier/photostream
Photostream/Modules/User Profile/Interactor/UserProfileInteractor.swift
1
3005
// // UserProfileInteractor.swift // Photostream // // Created by Mounir Ybanez on 10/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // protocol UserProfileInteractorInput: BaseModuleInteractorInput { func fetchProfile(user id: String) func follow(user id: String) func unfollow(user id: String) } protocol UserProfileInteractorOutput: BaseModuleInteractorOutput { func userProfileDidFetch(with data: UserProfileData) func userProfileDidFetch(with error: UserServiceError) func userProfileDidFollow() func userProfileDidFollow(with error: UserServiceError) func userProfileDidUnfollow() func userProfileDidUnfollow(with error: UserServiceError) } protocol UserProfileInteractorInterface: BaseModuleInteractor { var service: UserService! { set get } init(service: UserService) } class UserProfileInteractor: UserProfileInteractorInterface { typealias Output = UserProfileInteractorOutput weak var output: Output? var service: UserService! required init(service: UserService) { self.service = service } } extension UserProfileInteractor: UserProfileInteractorInput { func fetchProfile(user id: String) { service.fetchProfile(id: id) { (result) in guard result.error == nil else { self.output?.userProfileDidFetch(with: result.error!) return } guard let profile = result.profile, let user = result.user else { let error: UserServiceError = .failedToFetchProfile(message: "Profile not found") self.output?.userProfileDidFetch(with: error) return } var item = UserProfileDataItem() item.id = user.id item.avatarUrl = user.avatarUrl item.firstName = user.firstName item.lastName = user.lastName item.username = user.username item.bio = profile.bio item.postCount = profile.postsCount item.followerCount = profile.followersCount item.followingCount = profile.followingCount item.isFollowed = result.isFollowed self.output?.userProfileDidFetch(with: item) } } func follow(user id: String) { service.follow(id: id) { [unowned self] error in guard error == nil else { self.output?.userProfileDidFollow(with: error!) return } self.output?.userProfileDidFollow() } } func unfollow(user id: String) { service.unfollow(id: id) { [unowned self] error in guard error == nil else { self.output?.userProfileDidUnfollow(with: error!) return } self.output?.userProfileDidUnfollow() } } }
mit
92101768f125fcdb21008ac757711ee0
28.165049
97
0.606858
5.279438
false
false
false
false
KennethTsang/GrowingTextView
Example/GrowingTextView/Example1.swift
1
4473
// // ViewController.swift // GrowingTextView // // Created by Kenneth Tsang on 02/17/2016. // Copyright (c) 2016 Kenneth Tsang. All rights reserved. // import UIKit import GrowingTextView class Example1: UIViewController { private var inputToolbar: UIView! private var textView: GrowingTextView! private var textViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) // *** Create Toolbar inputToolbar = UIView() inputToolbar.backgroundColor = .systemGray inputToolbar.translatesAutoresizingMaskIntoConstraints = false view.addSubview(inputToolbar) // *** Create GrowingTextView *** textView = GrowingTextView() textView.delegate = self textView.layer.cornerRadius = 4.0 textView.maxLength = 200 textView.maxHeight = 70 textView.trimWhiteSpaceWhenEndEditing = true textView.placeholder = "Say something..." textView.placeholderColor = UIColor(white: 0.8, alpha: 1.0) textView.font = UIFont.systemFont(ofSize: 15) textView.translatesAutoresizingMaskIntoConstraints = false inputToolbar.addSubview(textView) // *** Autolayout *** let topConstraint = textView.topAnchor.constraint(equalTo: inputToolbar.topAnchor, constant: 8) topConstraint.priority = UILayoutPriority(999) NSLayoutConstraint.activate([ inputToolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor), inputToolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor), inputToolbar.bottomAnchor.constraint(equalTo: view.bottomAnchor), topConstraint ]) if #available(iOS 11, *) { textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.bottomAnchor, constant: -8) NSLayoutConstraint.activate([ textView.leadingAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.leadingAnchor, constant: 8), textView.trailingAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.trailingAnchor, constant: -8), textViewBottomConstraint ]) } else { textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: inputToolbar.bottomAnchor, constant: -8) NSLayoutConstraint.activate([ textView.leadingAnchor.constraint(equalTo: inputToolbar.leadingAnchor, constant: 8), textView.trailingAnchor.constraint(equalTo: inputToolbar.trailingAnchor, constant: -8), textViewBottomConstraint ]) } // *** Listen to keyboard show / hide *** NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) // *** Hide keyboard when tapping outside *** let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler)) view.addGestureRecognizer(tapGesture) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func keyboardWillChangeFrame(_ notification: Notification) { if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y if #available(iOS 11, *) { if keyboardHeight > 0 { keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom } } textViewBottomConstraint.constant = -keyboardHeight - 8 view.layoutIfNeeded() } } @objc private func tapGestureHandler() { view.endEditing(true) } } extension Example1: GrowingTextViewDelegate { // *** Call layoutIfNeeded on superview for animation when changing height *** func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } }
mit
a4d5ebc299e41602c697c6af92082aac
41.6
166
0.669126
5.749357
false
false
false
false
aloneee/MVPSwift
AFNSwift/AFNSwift/RequestAPI.swift
1
1915
// // RequestAPI.swift // AFNSwift // // Created by liurihua on 15/12/22. // Copyright © 2015年 刘日华. All rights reserved. // typealias Succeed = (NSURLSessionDataTask?,AnyObject?)->Void typealias Failure = (NSURLSessionDataTask?,NSError)->Void protocol FetchDataProtocol { func fetch(url:String!,body:AnyObject?,succeed:Succeed,failed:Failure) } protocol RequestParameters { var token: String { get } var size: Int { get } } extension RequestParameters { var token: String { return "ItachiSan" } var size: Int { return 100 } } enum RequestAPI: FetchDataProtocol, RequestParameters { case GET, POST //普通get网络请求 func fetch(url:String!,body:AnyObject?,succeed:Succeed,failed:Failure) { var paras = body as! [String:AnyObject] paras["token"] = self.token paras["size"] = self.size switch self { case .GET: { RequestClient.sharedInstance.GET(url, parameters:paras, progress: { (progress: NSProgress?) -> Void in }, success: { (task:NSURLSessionDataTask?, responseObject: AnyObject?) -> Void in succeed(task,responseObject) }) { (task: NSURLSessionDataTask?, error: NSError) -> Void in failed(task, error) } }() case .POST: { RequestClient.sharedInstance.POST(url, parameters: body, progress: { (progress: NSProgress?) -> Void in }, success: { (task:NSURLSessionDataTask?, responseObject: AnyObject?) -> Void in succeed(task,responseObject) }) { (task: NSURLSessionDataTask?, error: NSError) -> Void in failed(task, error) } }() } } }
mit
420ace48046b1523969a041e9f784c22
25.690141
119
0.554382
4.676543
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSURLCredential.swift
1
7247
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /*! @enum NSURLCredentialPersistence @abstract Constants defining how long a credential will be kept around @constant NSURLCredentialPersistenceNone This credential won't be saved. @constant NSURLCredentialPersistenceForSession This credential will only be stored for this session. @constant NSURLCredentialPersistencePermanent This credential will be stored permanently. Note: Whereas in Mac OS X any application can access any credential provided the user gives permission, in iPhone OS an application can access only its own credentials. @constant NSURLCredentialPersistenceSynchronizable This credential will be stored permanently. Additionally, this credential will be distributed to other devices based on the owning AppleID. Note: Whereas in Mac OS X any application can access any credential provided the user gives permission, on iOS an application can access only its own credentials. */ extension URLCredential { public enum Persistence : UInt { case none case forSession case permanent case synchronizable } } /*! @class NSURLCredential @discussion This class is an immutable object representing an authentication credential. The actual type of the credential is determined by the constructor called in the categories declared below. */ public class URLCredential : NSObject, NSSecureCoding, NSCopying { private var _user : String private var _password : String private var _persistence : Persistence /*! @method initWithUser:password:persistence: @abstract Initialize a NSURLCredential with a user and password @param user the username @param password the password @param persistence enum that says to store per session, permanently or not at all @result The initialized NSURLCredential */ public init(user: String, password: String, persistence: Persistence) { guard persistence != .permanent && persistence != .synchronizable else { NSUnimplemented() } _user = user _password = password _persistence = persistence super.init() } /*! @method credentialWithUser:password:persistence: @abstract Create a new NSURLCredential with a user and password @param user the username @param password the password @param persistence enum that says to store per session, permanently or not at all @result The new autoreleased NSURLCredential */ public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encode(with aCoder: NSCoder) { NSUnimplemented() } static public func supportsSecureCoding() -> Bool { return true } public override func copy() -> AnyObject { return copy(with: nil) } public func copy(with zone: NSZone? = nil) -> AnyObject { NSUnimplemented() } /*! @method persistence @abstract Determine whether this credential is or should be stored persistently @result A value indicating whether this credential is stored permanently, per session or not at all. */ public var persistence: Persistence { return _persistence } /*! @method user @abstract Get the username @result The user string */ public var user: String? { return _user } /*! @method password @abstract Get the password @result The password string @discussion This method might actually attempt to retrieve the password from an external store, possible resulting in prompting, so do not call it unless needed. */ public var password: String? { return _password } /*! @method hasPassword @abstract Find out if this credential has a password, without trying to get it @result YES if this credential has a password, otherwise NO @discussion If this credential's password is actually kept in an external store, the password method may return nil even if this method returns YES, since getting the password may fail, or the user may refuse access. */ public var hasPassword: Bool { // Currently no support for SecTrust/SecIdentity, always return true return true } } // TODO: We have no implementation for Security.framework primitive types SecIdentity and SecTrust yet /* extension NSURLCredential { /*! @method initWithIdentity:certificates:persistence: @abstract Initialize an NSURLCredential with an identity and array of at least 1 client certificates (SecCertificateRef) @param identity a SecIdentityRef object @param certArray an array containing at least one SecCertificateRef objects @param persistence enum that says to store per session, permanently or not at all @result the Initialized NSURLCredential */ public convenience init(identity: SecIdentity, certificates certArray: [AnyObject]?, persistence: NSURLCredentialPersistence) /*! @method credentialWithIdentity:certificates:persistence: @abstract Create a new NSURLCredential with an identity and certificate array @param identity a SecIdentityRef object @param certArray an array containing at least one SecCertificateRef objects @param persistence enum that says to store per session, permanently or not at all @result The new autoreleased NSURLCredential */ /*! @method identity @abstract Returns the SecIdentityRef of this credential, if it was created with a certificate and identity @result A SecIdentityRef or NULL if this is a username/password credential */ public var identity: SecIdentity? { NSUnimplemented() } /*! @method certificates @abstract Returns an NSArray of SecCertificateRef objects representing the client certificate for this credential, if this credential was created with an identity and certificate. @result an NSArray of SecCertificateRef or NULL if this is a username/password credential */ public var certificates: [AnyObject] { NSUnimplemented() } } extension NSURLCredential { /*! @method initWithTrust: @abstract Initialize a new NSURLCredential which specifies that the specified trust has been accepted. @result the Initialized NSURLCredential */ public convenience init(trust: SecTrust) { NSUnimplemented() } /*! @method credentialForTrust: @abstract Create a new NSURLCredential which specifies that a handshake has been trusted. @result The new autoreleased NSURLCredential */ public convenience init(forTrust trust: SecTrust) { NSUnimplemented() } } */
apache-2.0
41236337b15fc22887ad008fd795738d
39.261111
262
0.698358
5.622188
false
false
false
false
jhurray/SQLiteModel-Example-Project
tvOS+SQLiteModel/Pods/SQLite.swift/SQLite/Helpers.swift
11
4403
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 CSQLite public typealias Star = (Expression<Binding>?, Expression<Binding>?) -> Expression<Void> public func *(_: Expression<Binding>?, _: Expression<Binding>?) -> Expression<Void> { return Expression(literal: "*") } public protocol _OptionalType { associatedtype WrappedType } extension Optional : _OptionalType { public typealias WrappedType = Wrapped } // let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self) let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self) extension String { @warn_unused_result func quote(mark: Character = "\"") -> String { let escaped = characters.reduce("") { string, character in string + (character == mark ? "\(mark)\(mark)" : "\(character)") } return "\(mark)\(escaped)\(mark)" } @warn_unused_result func join(expressions: [Expressible]) -> Expressible { var (template, bindings) = ([String](), [Binding?]()) for expressible in expressions { let expression = expressible.expression template.append(expression.template) bindings.appendContentsOf(expression.bindings) } return Expression<Void>(template.joinWithSeparator(self), bindings) } @warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> { let expression = Expression<T>(" \(self) ".join([lhs, rhs]).expression) guard wrap else { return expression } return "".wrap(expression) } @warn_unused_result func prefix(expressions: Expressible) -> Expressible { return "\(self) ".wrap(expressions) as Expression<Void> } @warn_unused_result func prefix(expressions: [Expressible]) -> Expressible { return "\(self) ".wrap(expressions) as Expression<Void> } @warn_unused_result func wrap<T>(expression: Expressible) -> Expression<T> { return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings) } @warn_unused_result func wrap<T>(expressions: [Expressible]) -> Expression<T> { return wrap(", ".join(expressions)) } } @warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true, function: String = #function) -> Expression<T> { return function.infix(lhs, rhs, wrap: wrap) } @warn_unused_result func wrap<T>(expression: Expressible, function: String = #function) -> Expression<T> { return function.wrap(expression) } @warn_unused_result func wrap<T>(expressions: [Expressible], function: String = #function) -> Expression<T> { return function.wrap(", ".join(expressions)) } @warn_unused_result func transcode(literal: Binding?) -> String { guard let literal = literal else { return "NULL" } switch literal { case let blob as Blob: return blob.description case let string as String: return string.quote("'") case let binding: return "\(binding)" } } @warn_unused_result func value<A: Value>(v: Binding) -> A { return A.fromDatatypeValue(v as! A.Datatype) as! A } @warn_unused_result func value<A: Value>(v: Binding?) -> A { return value(v!) }
mit
f0ce9084306ba7275ae4c00e9c1ec870
34.5
139
0.681963
4.236766
false
false
false
false
JackieQu/QP_DouYu
QP_DouYu/QP_DouYu/Classes/Main/View/CollectionViewBaseCell.swift
1
1225
// // CollectionViewBaseCell.swift // QP_DouYu // // Created by JackieQu on 2017/2/16. // Copyright © 2017年 JackieQu. All rights reserved. // import UIKit class CollectionViewBaseCell: UICollectionViewCell { // MARK:- 控件的属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! // MARK:- 定义模型属性 var anchor : AnchorModel? { didSet { // 0.检查模型是否有值 guard let anchor = anchor else { return } // 1.取出在线人数显示文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" } else { onlineStr = "\(anchor.online)在线" } onlineBtn.setTitle(onlineStr, for: .normal) // 2.昵称的显示 nickNameLabel.text = anchor.nickname // 3.设置封面图片 guard let iconURL = URL(string : anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
mit
b85d17d2304c54c1d21c98673367db9b
26.609756
81
0.545936
4.620408
false
false
false
false
hujiaweibujidao/Gank
Gank/Class/Login/AHRegisterViewController.swift
2
7698
// // AHRegisterViewController.swift // Gank // // Created by AHuaner on 2017/2/8. // Copyright © 2017年 CoderAhuan. All rights reserved. // import UIKit class AHRegisterViewController: BaseViewController { // MARK: - control @IBOutlet weak var accountTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var authcodeTextField: UITextField! @IBOutlet weak var autocodeBtn: UIButton! @IBOutlet weak var registerBtn: UIButton! // MARK: - property var registerClouse: (() -> Void)? var timer: Timer? var time: Int = 60 // 用户是否获取短信验证码 var isGetAutoCode: Bool = false // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.statusBarStyle = .default } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - event && methods fileprivate func setupUI() { view.backgroundColor = UIColor.white accountTextField.addTarget(self, action: #selector(chectRegisterCanClick), for: .editingChanged) passwordTextField.addTarget(self, action: #selector(chectRegisterCanClick), for: .editingChanged) authcodeTextField.addTarget(self, action: #selector(chectRegisterCanClick), for: .editingChanged) } func chectRegisterCanClick() { if accountTextField.text != "" && passwordTextField.text != "" && authcodeTextField.text != "" { registerBtn.backgroundColor = UIColorMainBlue registerBtn.isEnabled = true } else { registerBtn.backgroundColor = UIColor.lightGray registerBtn.isEnabled = false } } @IBAction func registerAction() { if Validate.checkMobile(accountTextField.text!) { if Validate.checkPassword(passwordTextField.text!) { if isGetAutoCode { requestRegister() } else { ToolKit.showInfo(withStatus: "请获取短信验证码", style: .dark) } } else { ToolKit.showInfo(withStatus: "密码为6-18位字母数字组合", style: .dark) } } else { ToolKit.showInfo(withStatus: "请输入正确的手机号码", style: .dark) } } @IBAction func popAction() { timer?.invalidate() self.navigationController!.popViewController(animated: true) } @IBAction func showSecureTextAction(_ btn: UIButton) { passwordTextField.isSecureTextEntry = !passwordTextField.isSecureTextEntry if passwordTextField.isSecureTextEntry { btn.setImage(UIImage(named: "icon_show"), for: .normal) } else { btn.setImage(UIImage(named: "icon_show_blue"), for: .normal) } } @IBAction func autocodeAction() { if accountTextField.text?.characters.count == 0 { ToolKit.showInfo(withStatus: "请输入手机号码", style: .dark) } else { if Validate.checkMobile(accountTextField.text!) { if passwordTextField.text?.characters.count == 0 { ToolKit.showInfo(withStatus: "请输入密码", style: .dark) } else { if Validate.checkPassword(passwordTextField.text!) { checkRegistered() } else { ToolKit.showInfo(withStatus: "密码为6-18位字母数字组合", style: .dark) } } } else { ToolKit.showInfo(withStatus: "请输入正确的手机号码", style: .dark) } } } // 检验账号是否已注册 fileprivate func checkRegistered() { self.view.endEditing(true) ToolKit.show(withStatus: "正在获取验证码", style: .dark, maskType: .clear) let query = BmobUser.query()! query.whereKey("username", equalTo: accountTextField.text) query.findObjectsInBackground { (array, error) in AHLog(array!) if array!.count > 0 { // 该账号已注册 ToolKit.dismissHUD() self.showAlertController(locationVC: self, title: "该账号已注册, 要去登陆吗?", message: "", cancelTitle: "取消", confirmTitle: "好的", confrimClouse: { (_) in self.navigationController!.popViewController(animated: true) }, cancelClouse: { (_) in }) } else { // 该账号未注册 // 重置时间 self.time = 60 self.autocodeBtn.isUserInteractionEnabled = false self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timeRun), userInfo: nil, repeats: true) RunLoop.current.add(self.timer!, forMode: .commonModes) self.requestSMSCode() } } } // 获取短信验证码 func requestSMSCode() { isGetAutoCode = true BmobSMS.requestCodeInBackground(withPhoneNumber: accountTextField.text, andTemplate: "干货") { (SMSID, error) in if error != nil { let nserror = error! as NSError ToolKit.showError(withStatus: "获取失败") AHLog(nserror.code) } else { ToolKit.showSuccess(withStatus: "获取成功") AHLog("SMSID --\(SMSID)") } } } // 验证码倒计时 func timeRun() { autocodeBtn.setTitleColor(UIColor.lightGray, for: .normal) autocodeBtn.setTitle("重新获取(\(self.time))", for: .normal) time = time - 1 if time <= 0 { autocodeBtn.isUserInteractionEnabled = true autocodeBtn.setTitleColor(UIColorMainBlue, for: .normal) autocodeBtn.setTitle("获取验证码", for: .normal) timer?.invalidate() } } // 发送注册请求 func requestRegister() { self.view.endEditing(true) ToolKit.show(withStatus: "正在注册中", style: .dark, maskType: .clear) let user = BmobUser() user.username = accountTextField.text user.mobilePhoneNumber = accountTextField.text user.password = passwordTextField.text user.setObject("\(Bundle.appName)用户", forKey: "nickName") user.setObject(UIDevice.getUUID(), forKey: "uuid") user.signUpOrLoginInbackground(withSMSCode: authcodeTextField.text) { (isSuccessful, error) in if error == nil { User.update() AHLog("注册成功---\(String(describing: User.info))") ToolKit.showSuccess(withStatus: "注册成功") UserDefaults.AHData.mobilePhoneNumber.store(value: user.mobilePhoneNumber) DispatchQueue.main.asyncAfter(deadline: 1, execute: { if self.registerClouse != nil { self.registerClouse!() } }) }else{ AHLog("\(String(describing: error))") let nserror = error! as NSError switch nserror.code { case 207: ToolKit.showError(withStatus: "验证码错误") default: ToolKit.showError(withStatus: "注册失败, 请稍后重试") } } } } }
mit
4efd23e14460d5d07815ee011c44328f
35.262376
159
0.569283
4.844577
false
false
false
false
cipriancaba/SwiftFSM
Pod/Classes/SwiftFSM.swift
1
3310
// // SwiftFSM.swift // OneUCore // // Created by Ciprian Caba on 03/07/15. // Copyright (c) 2015 Cipri. All rights reserved. // import Foundation import UIKit /// A simple, enum based FSM implementation open class SwiftFSM<State: Hashable, Transition: Hashable> { fileprivate let _id: String fileprivate let _willLog: Bool fileprivate var _states = [State: SwiftFSMState<State, Transition>]() fileprivate var _currentState: SwiftFSMState<State, Transition>? /// Returns the current state of the fsm open var currentState: State { get { return _currentState!.state } } /** Initializes a new fsm with the provided id and logging specifications Also defines the State and Transition generics :param: id The id of the fsm.. Might come in handy if you use multiple fsm instances :param: willLog Parameter that will enable/disable logging of this fsm instance :returns: A new SwiftFSM instance */ public init (id: String = "SwiftFSM", willLog: Bool = true) { _id = id _willLog = willLog } /** Adds and returns a new or an already existing fsm state If the state was defined before, that SwiftFSMState instance will be returned :param: newState The enum of the new fsm state :returns: A SwiftFSMState instance for the newState */ open func addState(_ newState: State) -> SwiftFSMState<State, Transition> { if let existingState = _states[newState] { log("State \(newState) already added") return existingState } else { let newFsmState = SwiftFSMState<State, Transition>(state: newState) _states[newState] = newFsmState return newFsmState } } /** Starts the fsm in the specified state. The state must be defined with the addState method This method will not trigger any onEnter or onExit methods :param: state The initial state of the fsm */ open func startFrom(_ state: State) { if _currentState == nil { if let fsmState = _states[state] { _currentState = fsmState } else { log("Cannot find the \(state) start state") } } else { log("Fsm already started. Cannot startFrom again") } } /** Try transitioning the fsm with the specified transition :param: transition The transition to be used :returns: This method will return the new state if the state transition was successful or nil otherwise */ @discardableResult open func transitionWith(_ transition: Transition) -> State? { if let oldState = _currentState { if let newState = oldState.transitionWith(transition) { if let newFsmState = _states[newState] { log("\(oldState.state) -> \(transition) -> \(newState)") _currentState = newFsmState oldState.exit(transition) newFsmState.enter(transition) return newState } else { log("The \(transition) transitions to an unregistered \(newState) state") } } else { log("There is no transition defined from the [\(oldState.state)] state with the [\(transition)] transition") } } else { log("Please start the fsm first") } return nil } fileprivate func log(_ message: String) { if _willLog { print("\(_id) \(message)") } } }
mit
9e785e82679cc40e0fa0dc3a1a3be02b
28.035088
116
0.658308
4.49118
false
false
false
false
HassanEskandari/Eureka
Source/Validations/RuleLength.swift
3
2910
// RuleLength.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct RuleMinLength: RuleType { let min: UInt public var id: String? public var validationError: ValidationError public init(minLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have at least \(minLength) characters" min = minLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count < Int(min) ? validationError : nil } } public struct RuleMaxLength: RuleType { let max: UInt public var id: String? public var validationError: ValidationError public init(maxLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters" max = maxLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count > Int(max) ? validationError : nil } } public struct RuleExactLength: RuleType { let length: UInt public var id: String? public var validationError: ValidationError public init(exactLength: UInt, msg: String? = nil) { let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters" length = exactLength validationError = ValidationError(msg: ruleMsg) } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count != Int(length) ? validationError : nil } }
mit
bd2473f8fa7119aed6e870b7ca3cf14c
34.925926
86
0.695189
4.597156
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/ID3v2/ID3v2TagArtistsTest.swift
1
14437
// // ID3v2TagArtistsTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest @testable import Metatron class ID3v2TagArtistsTest: XCTestCase { // MARK: Instance Methods func test() { let tag = ID3v2Tag() do { let value: [String] = [] tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } do { let value = [""] tag.artists = value XCTAssert(tag.artists == []) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == []) } do { let value = ["Abc 123"] tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } do { let value = ["Абв 123"] tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } do { let value = ["Abc 1", "Abc 2"] tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } do { let value = ["", "Abc 2"] tag.artists = value XCTAssert(tag.artists == ["Abc 2"]) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == ["Abc 2"]) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 2"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 2"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 2"]) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == ["Abc 2"]) } do { let value = ["Abc 1", ""] tag.artists = value XCTAssert(tag.artists == ["Abc 1"]) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == ["Abc 1"]) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 1"]) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 1"]) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == ["Abc 1"]) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == ["Abc 1"]) } do { let value = ["", ""] tag.artists = value XCTAssert(tag.artists == []) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff == nil) do { tag.version = ID3v2Version.v2 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v3 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v2Version.v4 XCTAssert(tag.toData() == nil) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == []) } do { let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")] tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } do { let value = Array<String>(repeating: "Abc", count: 123) tag.artists = value XCTAssert(tag.artists == value) let frame = tag.appendFrameSet(ID3v2FrameID.tpe1).mainFrame XCTAssert(frame.stuff(format: ID3v2TextInformationFormat.regular).fields == value) do { tag.version = ID3v2Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v3 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } do { tag.version = ID3v2Version.v4 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v2Tag(fromData: data) else { return XCTFail() } XCTAssert(other.artists == value) } frame.imposeStuff(format: ID3v2TextInformationFormat.regular).fields = value XCTAssert(tag.artists == value) } } }
mit
6ad0b68c7e5d5f268f60e92a64552cd2
25.484404
98
0.476445
4.916213
false
false
false
false
noehou/myDouYuZB
DYZB/DYZB/Classes/Main/View/Cell/CollectionBaseCell.swift
1
1169
// // CollectionBaseCell.swift // DYZB // // Created by Tommaso on 2016/12/12. // Copyright © 2016年 Tommaso. All rights reserved. // import UIKit class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onLineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor : AnchorModel? { didSet { //0、校验模型是否有值 guard let anchor = anchor else {return} //1、取出在线人数显示文字 var onLineStr : String = "" if anchor.online >= 10000 { onLineStr = "\(Int(anchor.online / 10000))万在线" }else{ onLineStr = "\(anchor.online)在线" } onLineBtn.setTitle(onLineStr, for: .normal) //2、昵称的显示 nickNameLabel.text = anchor.nickname //4、设置封面图片 guard let iconURL = URL(string:anchor.vertical_src) else {return} iconImageView.kf.setImage(with: iconURL) } } }
mit
621eff4f0b01f2231250f0067bd257bc
26.25
77
0.538532
4.65812
false
false
false
false
euro02/EarthquakeApp
EarthquakeApp/EarthquakeApp/Controllers/DetailViewController.swift
1
2106
// // ViewController.swift // EarthquakeApp // // Created by Eduardo Antonio Pérez Muñoz on 11/03/15. // Copyright (c) 2015 Eduardo Perez. All rights reserved. // import UIKit import MapKit class DetailViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var txtMag: UITextField! @IBOutlet weak var txtDate: UITextField! @IBOutlet weak var txtLocation: UITextField! var feature: Feature! override func viewDidLoad() { super.viewDidLoad() self.title = feature!.properties!.place! txtMag.text = feature!.properties!.mag!.description txtDate.text = getLocalDateFromTimestamp() txtLocation.text = "["+feature!.geometry!.coordinates![1].description+", "+feature!.geometry!.coordinates![0].description+", "+feature!.geometry!.coordinates![2].description+"]" setLocationInMapView(CLLocationCoordinate2D( latitude: feature!.geometry!.coordinates![1], longitude: feature!.geometry!.coordinates![0] )) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getLocalDateFromTimestamp() -> String{ let timestamp = Double(feature!.properties!.time!/1000) let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.stringFromDate(NSDate(timeIntervalSince1970:timestamp)) } func setLocationInMapView(location:CLLocationCoordinate2D){ let span = MKCoordinateSpanMake(0.25, 0.25) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.setCoordinate(location) annotation.title = self.title annotation.subtitle = "["+location.latitude.description+", "+location.longitude.description+"]" mapView.addAnnotation(annotation) mapView.selectAnnotation(annotation, animated: true) } }
gpl-2.0
ef862ab2cb23325a16e686dcd39d6eaf
34.066667
185
0.678232
4.847926
false
false
false
false
jonnguy/HSTracker
HSTracker/HSReplay/UploadMetaData.swift
1
8032
// // UploadMetaData.swift // HSTracker // // Created by Benjamin Michotte on 12/08/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import Wrap class UploadMetaData { private var statistic: InternalGameStats? private var game: Game? private var log: [String] = [] var dateStart: Date? var serverIp: String? var serverPort: String? var gameHandle: String? var clientHandle: String? var reconnected: String? var resumable: Bool? var spectatePassword: String? var auroraPassword: String? var serverVersion: String? var matchStart: String? var hearthstoneBuild: Int? var gameType: Int? var spectatorMode: Bool? var _friendlyPlayerId: Int? var friendlyPlayerId: Int? var ladderSeason: Int? var brawlSeason: Int? var scenarioId: Int? var format: Int? var player1: Player = Player() var player2: Player = Player() public static let iso8601StringFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }() static func generate(stats: InternalGameStats, buildNumber: Int, deck: PlayingDeck?) -> (UploadMetaData, String) { let metaData = UploadMetaData() let playerInfo = getPlayerInfo(stats: stats, deck: deck) if let _playerInfo = playerInfo { metaData.player1 = _playerInfo.player1 metaData.player2 = _playerInfo.player2 } if let serverInfo = stats.serverInfo { if !serverInfo.address.isBlank { metaData.serverIp = serverInfo.address } if serverInfo.port > 0 { metaData.serverPort = "\(serverInfo.port)" } if serverInfo.gameHandle > 0 { metaData.gameHandle = "\(serverInfo.gameHandle)" } if serverInfo.clientHandle > 0 { metaData.clientHandle = "\(serverInfo.clientHandle)" } if !serverInfo.spectatorPassword.isBlank { metaData.spectatePassword = serverInfo.spectatorPassword } if !serverInfo.auroraPassword.isBlank { metaData.auroraPassword = serverInfo.auroraPassword } if !serverInfo.version.isBlank { metaData.serverVersion = serverInfo.version } } if stats.startTime > Date.distantPast { metaData.matchStart = UploadMetaData.iso8601StringFormatter.string(from: stats.startTime) } metaData.gameType = stats.gameType != .gt_unknown ? BnetGameType.getBnetGameType(gameType: stats.gameType, format: stats.format).rawValue : BnetGameType.getGameType(mode: stats.gameMode, format: stats.format).rawValue if let format = stats.format { metaData.format = format.toFormatType().rawValue } if stats.brawlSeasonId > 0 { metaData.brawlSeason = stats.brawlSeasonId } if stats.rankedSeasonId > 0 { metaData.ladderSeason = stats.rankedSeasonId } metaData.spectatorMode = stats.gameMode == .spectator //metaData.reconnected = gameMetaData?.reconnected ?? false metaData.resumable = stats.serverInfo?.resumable ?? false var friendlyPlayerId: Int? if stats.friendlyPlayerId > 0 { friendlyPlayerId = stats.friendlyPlayerId } else if let _playerFriendlyPlayerId = playerInfo?.friendlyPlayerId, _playerFriendlyPlayerId > 0 { friendlyPlayerId = _playerFriendlyPlayerId } metaData.friendlyPlayerId = friendlyPlayerId let scenarioId = stats.serverInfo?.mission ?? 0 if scenarioId > 0 { metaData.scenarioId = scenarioId } metaData.hearthstoneBuild = buildNumber return (metaData, stats.statId) } static func getPlayerInfo(stats: InternalGameStats, deck: PlayingDeck?) -> PlayerInfo? { if stats.friendlyPlayerId == 0 { return nil } let friendly = Player() let opposing = Player() if let deck = deck { friendly.add(deck: deck) } if stats.rank > 0 { friendly.rank = stats.rank } if stats.legendRank > 0 { friendly.legendRank = stats.legendRank } if stats.playerCardbackId > 0 { friendly.cardBack = stats.playerCardbackId } if stats.stars > 0 { friendly.stars = stats.stars } if let hsDeckId = stats.hsDeckId, hsDeckId > 0 { friendly.deckId = hsDeckId } if stats.gameMode == .arena { if stats.arenaWins > 0 { friendly.wins = stats.arenaWins } if stats.arenaLosses > 0 { friendly.losses = stats.arenaLosses } } else if stats.gameMode == .brawl { if stats.brawlWins > 0 { friendly.wins = stats.brawlWins } if stats.brawlLosses > 0 { friendly.losses = stats.brawlLosses } } if stats.opponentRank > 0 { opposing.rank = stats.opponentRank } if stats.opponentLegendRank > 0 { opposing.legendRank = stats.opponentLegendRank } if stats.opponentCardbackId > 0 { opposing.cardBack = stats.opponentCardbackId } return PlayerInfo(player1: stats.friendlyPlayerId == 1 ? friendly : opposing, player2: stats.friendlyPlayerId == 2 ? friendly : opposing) } class Player { var rank: Int? var legendRank: Int? var stars: Int? var wins: Int? var losses: Int? var deck: [String]? var deckId: Int64? var cardBack: Int? func add(deck: PlayingDeck) { var cards = [String]() for card in deck.cards { for _ in 0 ..< card.count { cards.append(card.id) } } self.deck = cards } } struct PlayerInfo { let player1: Player let player2: Player let friendlyPlayerId: Int init(player1: Player, player2: Player, friendlyPlayerId: Int = -1) { self.player1 = player1 self.player2 = player2 self.friendlyPlayerId = friendlyPlayerId } } } extension UploadMetaData.Player: WrapCustomizable { func keyForWrapping(propertyNamed propertyName: String) -> String? { switch propertyName { case "legendRank": return "legend_rank" case "deckId": return "deck_id" case "cardBack": return "cardback" default: break } return propertyName } } extension UploadMetaData: WrapCustomizable { func keyForWrapping(propertyNamed propertyName: String) -> String? { switch propertyName { case "serverIp": return "server_ip" case "serverPort": return "server_port" case "gameHandle": return "game_handle" case "clientHandle": return "client_handle" case "reconnected": return "reconnecting" case "spectatePassword": return "spectator_password" case "auroraPassword": return "aurora_password" case "serverVersion": return "server_version" case "matchStart": return "match_start" case "hearthstoneBuild": return "build" case "gameType": return "game_type" case "spectatorMode": return "spectator_mode" case "friendlyPlayerId": return "friendly_player" case "scenarioId": return "scenario_id" case "ladderSeason": return "ladder_season" case "brawlSeason": return "brawl_season" case "statistic", "game", "log", "gameStart": return nil default: break } return propertyName } }
mit
1de97875e4684746eab13587b5d070cd
30.249027
118
0.592703
4.763345
false
false
false
false
Egibide-DAM/swift
02_ejemplos/05_funciones_clausuras/05_clausuras/01_ejemplo_sorted_by.playground/Contents.swift
1
816
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backward(_ s1: String, _ s2: String) -> Bool { return s1 > s2 } var reversedNames = names.sorted(by: backward) // reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"] // Clausura reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 }) // En una línea reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } ) // Inferencia de tipos reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } ) // Retorno implícito para expresiones de una sola línea reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } ) // Nombres de parámetros abreviados reversedNames = names.sorted(by: { $0 > $1 } ) // Función operador reversedNames = names.sorted(by: >)
apache-2.0
acedbc028dce8af058e04cebf2011a1f
27.964286
89
0.654747
2.806228
false
false
false
false
gkye/TheMovieDatabaseSwiftWrapper
Sources/TMDBSwift/OldModels/CreditsMDB.swift
1
2832
// // CreditsMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-03-07. // Copyright © 2016 George Kye. All rights reserved. // import Foundation public struct CreditsEpisodes: Decodable { public var air_date: String! public var episode_number: Int! public var overview: String! public var season_number: Int! public var still_path: String? } public struct CreditsSeasons: Decodable { public var air_date: String! public var poster_path: String! public var season_number: Int! } public struct CreditsMedia: Decodable { public var id: Int! public var name: String! public var original_name: String! public var character: String! public var episodes = [CreditsEpisodes]() public var seasons = [CreditsSeasons]() } public struct CreditsMDB: Decodable { public var credit_type: String! public var department: String! public var job: String! public var media: CreditsMedia! public var media_Type: String! public var id: String! public var person: (name: String?, id: Int?) enum CodingKeys: String, CodingKey { case credit_type case department case job case media case media_Type = "media_type" case id case person case name } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) credit_type = try? container.decode(String?.self, forKey: .credit_type) department = try? container.decode(String.self, forKey: .department) job = try? container.decode(String.self, forKey: .job) media = try? container.decode(CreditsMedia.self, forKey: .media) media_Type = try? container.decode(String.self, forKey: .media_Type) id = try? container.decode(String.self, forKey: .id) let personObject = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .person) person = (name: try? personObject.decode(String.self, forKey: .name), id: try? personObject.decode(Int.self, forKey: .id)) } /// Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for people. The episodes object returns a list of episodes and are generally going to be guest stars. The season array will return a list of season numbers. public static func credits(creditID: String, completion: @escaping (_ clientReturn: ClientReturn, _ data: CreditsMDB?) -> Void) { Client.Credits(creditID: creditID) { apiReturn in let data: CreditsMDB? = apiReturn.decode() completion(apiReturn, data) } } }
mit
8f93fea48286a47bc52d4015d4d1686d
36.746667
405
0.678206
4.250751
false
false
false
false
bravelocation/yeltzland-ios
yeltzland/Data Providers/LocationDataProvider.swift
1
2860
// // LocationManager.swift // yeltzland // // Created by John Pollard on 06/07/2016. // Copyright © 2016 John Pollard. All rights reserved. // import Foundation import UIKit import MapKit public class LocationDataProvider { fileprivate static let sharedInstance = LocationDataProvider() fileprivate var locationList: [Location] = [Location]() private let dataProvider: JSONDataProvider<[Location]> class var shared: LocationDataProvider { get { return sharedInstance } } public var locations: [Location] { return self.locationList } init() { self.dataProvider = JSONDataProvider<[Location]>(fileName: "locations.json", remoteURL: URL(string: "https://bravelocation.com/locations.json")!) self.dataProvider.loadData() { result in switch result { case .success(let data): self.locationList = data print("Loaded locations from cache") case .failure: print("A problem occurred loading locations from cache") } } } public func refreshData() { self.dataProvider.refreshData() { result in switch result { case .success(let data): self.locationList = data print("Loaded locations from server") case .failure: print("A problem occurred loading locations from server") } } } func mapRegion() -> MKCoordinateRegion { var smallestLat = 190.0 var largestLat = -190.0 var smallestLong = 190.0 var largestLong = -190.0 for location in self.locations { if (location.latitude < smallestLat) { smallestLat = location.latitude } if (location.latitude > largestLat) { largestLat = location.latitude } if (location.longitude < smallestLong) { smallestLong = location.longitude } if (location.longitude > largestLong) { largestLong = location.longitude } } // Set locations for edge points let centerPoint = CLLocation(latitude: ((largestLat + smallestLat) / 2.0), longitude: ((largestLong + smallestLong) / 2.0)) // Set deltas between largest and smallest (with a bit extra longitude) let latitudeDelta = largestLat - smallestLat let longitudeDelta = largestLong - smallestLong + 0.8 // Now center map around the points return MKCoordinateRegion.init(center: centerPoint.coordinate, span: MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)) } }
mit
24d3b2cc2babf4c89f499fd479e7f323
31.862069
156
0.579923
5.284658
false
false
false
false
Ahrodite/LigaFix
LigaFix/DataModel/IDDictSingleton.swift
1
2657
// // IDDictSingleton.swift // LigaFix // // Created by JiaDuan on 15/12/25. // Copyright © 2015年 JiaDuan. All rights reserved. // import Foundation import CoreData class IDDictSingleton { class var sharedInstance: IDDictSingleton { struct Static { static let instance: IDDictSingleton = IDDictSingleton() } if Static.instance.idDict == nil { Static.instance.initIDDict() } return Static.instance } var idDict: IDDict? private func initIDDict() { let fetchIDDict = NSFetchRequest(entityName: "IDDict") let idDictPredicate = NSPredicate(format: "id = %@", NSNumber(int: 0)) fetchIDDict.predicate = idDictPredicate var idDicts: NSArray? do { idDicts = try appDelegate.managedObjectContext.executeFetchRequest(fetchIDDict) } catch let error as NSError { print("=============error=============") print("initIDDict() error") print("fetch IDDict error") print(error.localizedDescription) } if idDicts != nil && idDicts?.count > 0 { self.idDict = idDicts![0] as? IDDict } else { let idDict: IDDict = NSEntityDescription.insertNewObjectForEntityForName("IDDict", inManagedObjectContext: appDelegate.managedObjectContext) as! IDDict idDict.id = 0 idDict.users = 0 idDict.cases = 0 idDict.records = 0 // saveContext("initIDDict()") self.idDict = idDict } } private func saveContext(funcName: String) { do { try appDelegate.managedObjectContext.save() } catch let error as NSError { print("=============error=============") print(funcName + " error") print("save context error") print(error.localizedDescription) } } internal func getUserID() -> NSNumber { self.idDict?.users = NSNumber(short: (self.idDict?.users!.shortValue)! + 1) let ret = self.idDict?.users // saveContext("getUserID()") return ret! } internal func getCaseID() -> NSNumber { self.idDict?.cases = NSNumber(short: (self.idDict?.cases!.shortValue)! + 1) let ret = self.idDict?.cases // saveContext("getCaseID()") return ret! } internal func getRecordID() -> NSNumber { self.idDict?.records = NSNumber(int: (self.idDict?.records!.intValue)! + 1) let ret = self.idDict?.records // saveContext("getRecordID()") return ret! } }
mit
10124a980b4ac44b9046167e930569fa
30.975904
163
0.57046
4.85192
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Modules/Accounts/AccountsFlowController.swift
1
4502
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.net // // 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 FranticApparatus import Reddit import Common public class AccountsFlowController : NavigationFlowController { weak var factory: MainFactory! var dataController: AccountsDataController var oauthService: OAuthService! var aboutUserPromise: Promise<Account>! var accountsMenuViewController: MenuViewController! var addAccountFlowController: OAuthFlowController! public init(dataController: AccountsDataController) { self.dataController = dataController } public override func viewControllerDidLoad() { accountsMenuViewController = buildAccountsMenuViewController() pushViewController(accountsMenuViewController, animated: false) } public override func flowDidStart(animated: Bool) { super.flowDidStart(animated) dataController.reloadMenu() } func buildAccountsMenuViewController() -> MenuViewController { let viewController = MenuViewController() viewController.title = "Accounts" viewController.navigationItem.rightBarButtonItem = UIBarButtonItem.edit(target: self, action: Selector("editAccounts")) return viewController } func editAccounts() { } func addAccount() { if addAccountFlowController != nil { return } addAccountFlowController = factory.oauthFlowController() addAccountFlowController.delegate = self presentAndStartFlow(addAccountFlowController) } func lurkerMode() { oauthService.lurkerMode() dataController.reloadMenu() } func switchToUsername(username: String) { oauthService.switchToUsername(username) dataController.reloadMenu() } func handleAccountMenuEvent(event: AccountMenuEvent) { switch event { case .AddAccount: addAccount() case .LurkerMode: lurkerMode() case .SwitchToUsername(let username): switchToUsername(username) case .Unimplemented: UIAlertView(title: "Unimplemented", message: nil, delegate: nil, cancelButtonTitle: "OK").show() } } } extension AccountsFlowController : OAuthFlowControllerDelegate { func oauthFlowControllerDidCancel(oauthFlowController: OAuthFlowController) { addAccountFlowController.stopAnimated(true) { [weak self] in if let strongSelf = self { strongSelf.addAccountFlowController = nil } } } func oauthFlowController(oauthFlowController: OAuthFlowController, didCompleteWithResponse response: OAuthAuthorizeResponse) { addAccountFlowController.stopAnimated(true) { [weak self] in if let strongSelf = self { strongSelf.addAccountFlowController = nil strongSelf.dataController.reloadMenu() } } } } extension AccountsFlowController : AccountsDataControllerDelegate { public func accountsDataController(dataController: AccountsDataController, didLoadMenu menu: Menu<AccountMenuEvent>) { menu.eventHandler = handleAccountMenuEvent if accountsMenuViewController.isViewLoaded() { accountsMenuViewController.reloadMenu(menu) } else { accountsMenuViewController.menu = menu } } }
mit
9729c2286a474987ea596323ba910433
36.206612
130
0.703909
5.523926
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine_Editor/ITransformCell.swift
1
2771
// // InspectorCellView.swift // DrakkenEngine // // Created by Allison Lindner on 20/10/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Cocoa import Foundation class ITransformCell: NSTableCellView, NSTextFieldDelegate { @IBOutlet weak var transformNameLabel: NSTextField! @IBOutlet weak var xpTF: NSTextField! @IBOutlet weak var ypTF: NSTextField! @IBOutlet weak var zpTF: NSTextField! @IBOutlet weak var xrTF: NSTextField! @IBOutlet weak var yrTF: NSTextField! @IBOutlet weak var zrTF: NSTextField! @IBOutlet weak var wsTF: NSTextField! @IBOutlet weak var hsTF: NSTextField! internal var transform: dTransform! override func awakeFromNib() { setup() } private func setup() { self.xpTF.delegate = self self.ypTF.delegate = self self.zpTF.delegate = self self.xrTF.delegate = self self.yrTF.delegate = self self.zrTF.delegate = self self.wsTF.delegate = self self.hsTF.delegate = self } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) } @IBAction func xStepper(_ sender: NSStepper) { } override func controlTextDidEndEditing(_ obj: Notification) { let fieldEditor = obj.object as! NSTextField if fieldEditor.identifier == "posXID" { let x = fieldEditor.floatValue transform.Position.Set(x, transform.Position.y, transform.Position.z) } else if fieldEditor.identifier == "posYID" { let y = fieldEditor.floatValue transform.Position.Set(transform.Position.x, y, transform.Position.z) } else if fieldEditor.identifier == "posZID" { let z = fieldEditor.floatValue transform.Position.Set(transform.Position.x, transform.Position.y, z) } else if fieldEditor.identifier == "rotXID" { let x = fieldEditor.floatValue transform.Rotation.Set(x, transform.Rotation.y, transform.Rotation.z) } else if fieldEditor.identifier == "rotYID" { let y = fieldEditor.floatValue transform.Rotation.Set(transform.Rotation.x, y, transform.Rotation.z) } else if fieldEditor.identifier == "rotZID" { let z = fieldEditor.floatValue transform.Rotation.Set(transform.Rotation.x, transform.Rotation.y, z) } else if fieldEditor.identifier == "scaleWID" { let w = fieldEditor.floatValue transform.Scale.Set(w, transform.Scale.height) } else if fieldEditor.identifier == "scaleHID" { let h = fieldEditor.floatValue transform.Scale.Set(transform.Scale.width, h) } } }
gpl-3.0
d3b76b6966c1158ce8eb31fec3f3beb9
33.625
81
0.635379
4.355346
false
false
false
false
iamtomcat/color
Color/HSL.swift
1
1143
// // HSL.swift // ColorSpace // // Created by Tom Clark on 2016-03-07. // Copyright © 2016 FluidDynamics. All rights reserved. // import Foundation public struct HSL { public let h: CGFloat public let s: CGFloat public let l: CGFloat public let a: CGFloat } extension HSL: ColorData { var toHSL: HSL { return self } var toRGB: RGB { var q: CGFloat { return l < 0.5 ? l * (1 + s) : l + s - l * s } var p: CGFloat { return 2 * l - q } func hue2rgb(p: CGFloat, q: CGFloat, t: CGFloat) -> CGFloat { var tempt = t if tempt < 0 { tempt += CGFloat(1.0) } if tempt > 1 { tempt -= 1.0 } if tempt < 1/6 { return p + (q - p) * 6 * tempt } if tempt < 1/2 { return q } if tempt < 2/3 { return p + (q - p) * (2/3 - tempt) * 6 } return p } let r = hue2rgb(p, q: q, t: h + 1/3) let g = hue2rgb(p, q: q, t: h) let b = hue2rgb(p, q: q, t: h - 1/3) return RGB(r: r, g: g, b: b, a: a) } var toHSV: HSV { let v = ((2*l) + (self.s*(1-abs(2*l-1))))/2 let s = v == 0 ? 0 : (2*(v-l))/v return HSV(h: h, s: s, v: v, a: a) } }
mit
cb9a7058458ecac976614cb4342dd7c9
20.961538
65
0.503503
2.668224
false
false
false
false
nerd0geek1/TableViewManager
TableViewManager/classes/implementation/SelectableTableViewDataSource.swift
1
1786
// // SelectableTableViewDataSource.swift // TableViewManager // // Created by Kohei Tabata on 2016/07/19. // Copyright © 2016 Kohei Tabata. All rights reserved. // import Foundation public class SelectableTableViewDataSource: TableViewDataSource { public var didUpdateSelectedState: (() -> Void)? override func didUpdateSectionDataList() { for sectionData in sectionDataList { if let sectionData = sectionData as? SelectableSectionData { sectionData.didUpdateSelectedState = { [weak self] () -> Void in self?.didUpdateSelectedState?() } } } } public func selectedRowDataList() -> [SelectableRowData] { var allSelectedRowDataList: [SelectableRowData] = [] if let sectionDataList = sectionDataList as? [SelectableSectionData] { for sectionData in sectionDataList { allSelectedRowDataList.append(contentsOf: sectionData.selectedRowDataList()) } } return allSelectedRowDataList } public func makeSameOrToggleAllRowDataSelectedState() { guard let allRowDataList: [SelectableRowData] = self.allRowDataList() as? [SelectableRowData] else { return } let selectedState: Bool = allRowDataList.count == 0 || allRowDataList.count != selectedRowDataList().count for rowData in allRowDataList { rowData.setSelectedState(selectedState) } } public func clearAllRowDataSelectedState() { guard let allRowDataList: [SelectableRowData] = self.allRowDataList() as? [SelectableRowData] else { return } for rowData in allRowDataList { rowData.setSelectedState(false) } } }
mit
2150efd0f6f316379a39a8153bcc9263
30.875
114
0.645378
5.630915
false
false
false
false
ahoppen/swift
test/SPI/Inputs/spi_helper.swift
12
2641
/// Library defining SPI decls public protocol PublicProto { associatedtype Assoc } public func publicFunc() { print("publicFunc") } func internalFunc() {} @_specialize(exported: true, spi: HelperSPI, where T == Int) public func genericFunc<T>(_ t: T) { print(t) } @_spi(HelperSPI) public func spiFunc() { print("spiFunc") } @_spi(HelperSPI) public class SPIStruct { @_spi(HelperSPI) public init() { print("SPIStruct.init") } @_spi(HelperSPI) public func spiMethod() { print("SPIStruct.spiMethod") } @_spi(HelperSPI) public var spiVar = "text" @_spi(HelperSPI) public var spiComputedVar: Int { get { return 42 } set {} } @_spi(HelperSPI) public var spiComputedVarInherit: Int { @_spi(HelperSPI) get { return 42 } @_spi(HelperSPI) set {} } @_spi(HelperSPI) public subscript(index: Int) -> String { return spiVar } public func spiInherit() {} @_spi(DifferentSPI) public func spiDontInherit() {} @_specialize(exported: true, spi: HelperSPI, where T == Int) @_spi(HelperSPI) public func genericFunc2<T>(_ t: T) { print(t) } } public extension SPIStruct { func spiExtensionHidden() {} @_spi(HelperSPI) func spiExtension() {} } @_spi(HelperSPI) public extension SPIStruct { func spiExtensionInherited() {} } @_spi(HelperSPI) public class SPIClass { @_spi(HelperSPI) public init() { print("SPIClass.init") } @_spi(HelperSPI) public func spiMethod() { print("SPIClass.spiMethod") } @_spi(HelperSPI) public var spiVar = "text" @_specialize(exported: true, spi: HelperSPI, where T == Int) @_spi(HelperSPI) public func genericFunc3<T>(_ t: T) { print(t) } } @_spi(HelperSPI) public enum SPIEnum { case A case B @_spi(HelperSPI) public init() { print("SPIEnum.init") self = .A } @_spi(HelperSPI) public func spiMethod() { print("SPIEnum.spiMethod") } @_specialize(exported: true, spi: HelperSPI, where T == Int) public func genericFunc4<T>(_ t: T) { print(t) } } public struct PublicStruct { public init() {} @_spi(HelperSPI) public init(alt_init: Int) { print("PublicStruct.init alt_init") } @_spi(HelperSPI) public func spiMethod() { print("PublicStruct.spiMethod") } @_spi(HelperSPI) public var spiVar = "text" @_specialize(exported: true, spi: HelperSPI, where T == Int) public func prespecializedMethod<T>(_ t: T) { print(t) } } @_spi(OtherSPI) public func otherApiFunc() {} @_spi(HelperSPI) public struct ConformsToNormalProto: PublicProto { @_spi(HelperSPI) public typealias Assoc = Int } @_spi(HelperSPI) public struct IntLike: ExpressibleByIntegerLiteral, Equatable { @_spi(HelperSPI) public init(integerLiteral: Int) {} }
apache-2.0
fbd76ac3b4347a4e5e948e2dc52d4d64
28.021978
85
0.681181
3.607923
false
false
false
false
uxmstudio/UXMBatchDownloader
Example/Tests/Tests.swift
1
1168
// https://github.com/Quick/Quick import Quick import Nimble import UXMBatchDownloader 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" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
65d6217cca9f946552e8f06f88a3027c
22.24
60
0.362306
5.507109
false
false
false
false
idikic/idikic-youtube-dl-gui
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/Swift/SignalProducer.swift
1
40638
import Result /// A SignalProducer creates Signals that can produce values of type `T` and/or /// error out with errors of type `E`. If no errors should be possible, NoError /// can be specified for `E`. /// /// SignalProducers can be used to represent operations or tasks, like network /// requests, where each invocation of start() will create a new underlying /// operation. This ensures that consumers will receive the results, versus a /// plain Signal, where the results might be sent before any observers are /// attached. /// /// Because of the behavior of start(), different Signals created from the /// producer may see a different version of Events. The Events may arrive in a /// different order between Signals, or the stream might be completely /// different! public struct SignalProducer<T, E: ErrorType> { private let startHandler: (Signal<T, E>.Observer, CompositeDisposable) -> () /// Initializes a SignalProducer that will invoke the given closure once /// for each invocation of start(). /// /// The events that the closure puts into the given sink will become the /// events sent by the started Signal to its observers. /// /// If the Disposable returned from start() is disposed or a terminating /// event is sent to the observer, the given CompositeDisposable will be /// disposed, at which point work should be interrupted and any temporary /// resources cleaned up. public init(_ startHandler: (Signal<T, E>.Observer, CompositeDisposable) -> ()) { self.startHandler = startHandler } /// Creates a producer for a Signal that will immediately send one value /// then complete. public init(value: T) { self.init({ observer, disposable in sendNext(observer, value) sendCompleted(observer) }) } /// Creates a producer for a Signal that will immediately send an error. public init(error: E) { self.init({ observer, disposable in sendError(observer, error) }) } /// Creates a producer for a Signal that will immediately send one value /// then complete, or immediately send an error, depending on the given /// Result. public init(result: Result<T, E>) { switch result { case let .Success(value): self.init(value: value.value) case let .Failure(error): self.init(error: error.value) } } /// Creates a producer for a Signal that will immediately send the values /// from the given sequence, then complete. public init<S: SequenceType where S.Generator.Element == T>(values: S) { self.init({ observer, disposable in for value in values { sendNext(observer, value) if disposable.disposed { break } } sendCompleted(observer) }) } /// A producer for a Signal that will immediately complete without sending /// any values. public static var empty: SignalProducer { return self { observer, disposable in sendCompleted(observer) } } /// A producer for a Signal that never sends any events to its observers. public static var never: SignalProducer { return self { _ in () } } /// Creates a buffer for Events, with the given capacity, and a /// SignalProducer for a signal that will send Events from the buffer. /// /// When events are put into the returned observer (sink), they will be /// added to the buffer. If the buffer is already at capacity, the earliest /// (oldest) event will be dropped to make room for the new event. /// /// Signals created from the returned producer will stay alive until a /// terminating event is added to the buffer. If the buffer does not contain /// such an event when the Signal is started, all events sent to the /// returned observer will be automatically forwarded to the Signal’s /// observers until a terminating event is received. /// /// After a terminating event has been added to the buffer, the observer /// will not add any further events. public static func buffer(_ capacity: Int = Int.max) -> (SignalProducer, Signal<T, E>.Observer) { precondition(capacity >= 0) let lock = NSLock() lock.name = "org.reactivecocoa.ReactiveCocoa.SignalProducer.buffer" var events: [Event<T, E>] = [] var terminationEvent: Event<T,E>? let observers: Atomic<Bag<Signal<T, E>.Observer>?> = Atomic(Bag()) let producer = self { observer, disposable in lock.lock() var token: RemovalToken? observers.modify { (var observers) in token = observers?.insert(observer) return observers } for event in events { observer.put(event) } if let terminationEvent = terminationEvent { observer.put(terminationEvent) } lock.unlock() if let token = token { disposable.addDisposable { observers.modify { (var observers) in observers?.removeValueForToken(token) return observers } } } } let bufferingObserver = Signal<T, E>.Observer { event in let oldObservers = observers.modify { (var observers) in if event.isTerminating { return nil } else { return observers } } // If not disposed… if let liveObservers = oldObservers { lock.lock() if event.isTerminating { terminationEvent = event } else { events.append(event) while events.count > capacity { events.removeAtIndex(0) } } for observer in liveObservers { observer.put(event) } lock.unlock() } } return (producer, bufferingObserver) } /// Creates a SignalProducer that will attempt the given operation once for /// each invocation of start(). /// /// Upon success, the started signal will send the resulting value then /// complete. Upon failure, the started signal will send the error that /// occurred. public static func try(operation: () -> Result<T, E>) -> SignalProducer { return self { observer, disposable in operation().analysis(ifSuccess: { value in sendNext(observer, value) sendCompleted(observer) }, ifFailure: { error in sendError(observer, error) }) } } /// Creates a Signal from the producer, passes it into the given closure, /// then starts sending events on the Signal when the closure has returned. /// /// The closure will also receive a disposable which can be used to /// interrupt the work associated with the signal and immediately send an /// `Interrupted` event. public func startWithSignal(@noescape setUp: (Signal<T, E>, Disposable) -> ()) { let (signal, sink) = Signal<T, E>.pipe() // Disposes of the work associated with the SignalProducer and any // upstream producers. let producerDisposable = CompositeDisposable() // Directly disposed of when start() or startWithSignal() is disposed. let cancelDisposable = ActionDisposable { sendInterrupted(sink) producerDisposable.dispose() } setUp(signal, cancelDisposable) if cancelDisposable.disposed { return } let wrapperObserver = Signal<T, E>.Observer { event in sink.put(event) if event.isTerminating { // Dispose only after notifying the Signal, so disposal // logic is consistently the last thing to run. producerDisposable.dispose() } } startHandler(wrapperObserver, producerDisposable) } /// Creates a Signal from the producer, then attaches the given sink to the /// Signal as an observer. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the signal and immediately send an `Interrupted` event. public func start<S: SinkType where S.Element == Event<T, E>>(sink: S) -> Disposable { var disposable: Disposable! startWithSignal { signal, innerDisposable in signal.observe(sink) disposable = innerDisposable } return disposable } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callbacks when events are /// received. /// /// Returns a Disposable which can be used to interrupt the work associated /// with the Signal, and prevent any future callbacks from being invoked. public func start(error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil) -> Disposable { return start(Event.sink(next: next, error: error, completed: completed, interrupted: interrupted)) } /// Lifts an unary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new SignalProducer which will apply /// the given Signal operator to _every_ created Signal, just as if the /// operator had been applied to each Signal yielded from start(). public func lift<U, F>(transform: Signal<T, E> -> Signal<U, F>) -> SignalProducer<U, F> { return SignalProducer<U, F> { observer, outerDisposable in self.startWithSignal { signal, innerDisposable in outerDisposable.addDisposable(innerDisposable) transform(signal).observe(observer) } } } /// Lifts a binary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new SignalProducer which will apply /// the given Signal operator to _every_ Signal created from the two /// producers, just as if the operator had been applied to each Signal /// yielded from start(). public func lift<U, F, V, G>(transform: Signal<U, F> -> Signal<T, E> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> { return { otherProducer in return SignalProducer<V, G> { observer, outerDisposable in self.startWithSignal { signal, disposable in outerDisposable.addDisposable(disposable) otherProducer.startWithSignal { otherSignal, otherDisposable in outerDisposable.addDisposable(otherDisposable) transform(otherSignal)(signal).observe(observer) } } } } } } /// Applies a Signal operator to a SignalProducer (equivalent to /// SignalProducer.lift). /// /// This will create a new SignalProducer which will apply the given Signal /// operator to _every_ created Signal, just as if the operator had been applied /// to each Signal yielded from start(). /// /// Example: /// /// let filteredProducer = intProducer |> filter { num in num % 2 == 0 } public func |> <T, E, U, F>(producer: SignalProducer<T, E>, transform: Signal<T, E> -> Signal<U, F>) -> SignalProducer<U, F> { return producer.lift(transform) } /// Applies a SignalProducer operator to a SignalProducer. /// /// Example: /// /// filteredProducer /// |> startOn(UIScheduler()) /// |> start { signal in /// signal.observe(next: { num in println(num) }) /// } public func |> <T, E, X>(producer: SignalProducer<T, E>, @noescape transform: SignalProducer<T, E> -> X) -> X { return transform(producer) } /// Creates a repeating timer of the given interval, with a reasonable /// default leeway, sending updates on the given scheduler. /// /// This timer will never complete naturally, so all invocations of start() must /// be disposed to avoid leaks. public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<NSDate, NoError> { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return timer(interval, onScheduler: scheduler, withLeeway: interval * 0.1) } /// Creates a repeating timer of the given interval, sending updates on the /// given scheduler. /// /// This timer will never complete naturally, so all invocations of start() must /// be disposed to avoid leaks. public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType, withLeeway leeway: NSTimeInterval) -> SignalProducer<NSDate, NoError> { precondition(interval >= 0) precondition(leeway >= 0) return SignalProducer { observer, compositeDisposable in let disposable = scheduler.scheduleAfter(scheduler.currentDate.dateByAddingTimeInterval(interval), repeatingEvery: interval, withLeeway: leeway) { sendNext(observer, scheduler.currentDate) } compositeDisposable.addDisposable(disposable) } } /// Injects side effects to be performed upon the specified signal events. public func on<T, E>(started: (() -> ())? = nil, event: (Event<T, E> -> ())? = nil, error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (T -> ())? = nil) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return SignalProducer { observer, compositeDisposable in started?() disposed.map(compositeDisposable.addDisposable) producer.startWithSignal { signal, disposable in compositeDisposable.addDisposable(disposable) let innerObserver = Signal<T, E>.Observer { receivedEvent in event?(receivedEvent) switch receivedEvent { case let .Next(value): next?(value.value) case let .Error(err): error?(err.value) case .Completed: completed?() case .Interrupted: interrupted?() } if receivedEvent.isTerminating { terminated?() } observer.put(receivedEvent) } signal.observe(innerObserver) } } } } /// Starts the returned signal on the given Scheduler. /// /// This implies that any side effects embedded in the producer will be /// performed on the given scheduler as well. /// /// Events may still be sent upon other schedulers—this merely affects where /// the `start()` method is run. public func startOn<T, E>(scheduler: SchedulerType) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return SignalProducer { observer, compositeDisposable in let schedulerDisposable = scheduler.schedule { producer.startWithSignal { signal, signalDisposable in compositeDisposable.addDisposable(signalDisposable) signal.observe(observer) } } compositeDisposable.addDisposable(schedulerDisposable) } } } /// Combines the latest value of the receiver with the latest value from /// the given producer. /// /// Signals started by the returned producer will not send a value until both /// inputs have sent at least one value each. public func combineLatestWith<T, U, E>(otherSignalProducer: SignalProducer<U, E>) -> SignalProducer<T, E> -> SignalProducer<(T, U), E> { return { producer in return producer.lift(combineLatestWith)(otherSignalProducer) } } internal func combineLatestWith<T, E>(otherSignalProducer: SignalProducer<T, E>) -> SignalProducer<[T], E> -> SignalProducer<[T], E> { return { producer in return producer.lift(combineLatestWith)(otherSignalProducer) } } /// Zips elements of two signal producers into pairs. The elements of any Nth /// pair are the Nth elements of the two input producers. public func zipWith<T, U, E>(otherSignalProducer: SignalProducer<U, E>) -> SignalProducer<T, E> -> SignalProducer<(T, U), E> { return { producer in return producer.lift(zipWith)(otherSignalProducer) } } internal func zipWith<T, E>(otherSignalProducer: SignalProducer<T, E>) -> SignalProducer<[T], E> -> SignalProducer<[T], E> { return { producer in return producer.lift(zipWith)(otherSignalProducer) } } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> { return a |> combineLatestWith(b) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> { return combineLatest(a, b) |> combineLatestWith(c) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> { return combineLatest(a, b, c) |> combineLatestWith(d) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> { return combineLatest(a, b, c, d) |> combineLatestWith(e) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> { return combineLatest(a, b, c, d, e) |> combineLatestWith(f) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> { return combineLatest(a, b, c, d, e, f) |> combineLatestWith(g) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> { return combineLatest(a, b, c, d, e, f, g) |> combineLatestWith(h) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>, i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> { return combineLatest(a, b, c, d, e, f, g, h) |> combineLatestWith(i) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>, i: SignalProducer<I, Error>, j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> { return combineLatest(a, b, c, d, e, f, g, h, i) |> combineLatestWith(j) |> map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty. public func combineLatest<S: SequenceType, T, Error where S.Generator.Element == SignalProducer<T, Error>>(signalProducers: S) -> SignalProducer<[T], Error> { var generator = signalProducers.generate() if let first = generator.next() { let initial = first |> map { [$0] } return reduce(GeneratorSequence(generator), initial) { $0 |> combineLatestWith($1) } } return SignalProducer.empty } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> { return a |> zipWith(b) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> { return zip(a, b) |> zipWith(c) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> { return zip(a, b, c) |> zipWith(d) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> { return zip(a, b, c, d) |> zipWith(e) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> { return zip(a, b, c, d, e) |> zipWith(f) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> { return zip(a, b, c, d, e, f) |> zipWith(g) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> { return zip(a, b, c, d, e, f, g) |> zipWith(h) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>, i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> { return zip(a, b, c, d, e, f, g, h) |> zipWith(i) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, b: SignalProducer<B, Error>, c: SignalProducer<C, Error>, d: SignalProducer<D, Error>, e: SignalProducer<E, Error>, f: SignalProducer<F, Error>, g: SignalProducer<G, Error>, h: SignalProducer<H, Error>, i: SignalProducer<I, Error>, j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> { return zip(a, b, c, d, e, f, g, h, i) |> zipWith(j) |> map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty. public func zip<S: SequenceType, T, Error where S.Generator.Element == SignalProducer<T, Error>>(signalProducers: S) -> SignalProducer<[T], Error> { var generator = signalProducers.generate() if let first = generator.next() { let initial = first |> map { [$0] } return reduce(GeneratorSequence(generator), initial) { $0 |> zipWith($1) } } return SignalProducer.empty } /// Forwards the latest value from `producer` whenever `sampler` sends a Next /// event. /// /// If `sampler` fires before a value has been observed on `producer`, nothing /// happens. /// /// Returns a producer that will send values from `producer`, sampled (possibly /// multiple times) by `sampler`, then complete once both inputs have completed. public func sampleOn<T, E>(sampler: SignalProducer<(), NoError>) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return producer.lift(sampleOn)(sampler) } } /// Forwards events from `producer` until `trigger` sends a Next or Completed /// event, at which point the returned producer will complete. public func takeUntil<T, E>(trigger: SignalProducer<(), NoError>) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return producer.lift(takeUntil)(trigger) } } /// Forwards events from `producer` until `replacement` begins sending events. /// /// Returns a signal which passes through `next`s and `error` from `producer` /// until `replacement` sends an event, at which point the returned producer /// will send that event and switch to passing through events from `replacement` /// instead, regardless of whether `producer` has sent events already. public func takeUntilReplacement<T, E>(replacement: SignalProducer<T, E>) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return producer.lift(takeUntilReplacement)(replacement) } } /// Catches any error that may occur on the input producer, then starts a new /// producer in its place. public func catch<T, E, F>(handler: E -> SignalProducer<T, F>) -> SignalProducer<T, E> -> SignalProducer<T, F> { return { producer in return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable.addDisposable(serialDisposable) producer.startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observe(next: { value in sendNext(observer, value) }, error: { error in handler(error).startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observe(observer) } }, completed: { sendCompleted(observer) }, interrupted: { sendInterrupted(observer) }) } } } } /// Create a fix point to enable recursive calling of a closure. private func fix<T, U>(f: (T -> U) -> T -> U) -> T -> U { return { f(fix(f))($0) } } /// `concat`s `next` onto `producer`. public func concat<T, E>(next: SignalProducer<T, E>) -> SignalProducer<T, E> -> SignalProducer<T, E> { return { producer in return SignalProducer(values: [producer, next]) |> flatten(.Concat) } } /// Repeats `producer` a total of `count` times. /// Repeating `1` times results in a equivalent signal producer. public func times<T, E>(count: Int) -> SignalProducer<T, E> -> SignalProducer<T, E> { precondition(count >= 0) return { producer in if count == 0 { return .empty } else if count == 1 { return producer } return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable.addDisposable(serialDisposable) let iterate: Int -> () = fix { recur in { current in producer.startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observe(Signal.Observer { event in switch event { case .Completed: let remainingTimes = current - 1 if remainingTimes > 0 { recur(remainingTimes) } else { sendCompleted(observer) } default: observer.put(event) } }) } } } iterate(count) } } } /// Ignores errors up to `count` times. public func retry<T, E>(count: Int) -> SignalProducer<T, E> -> SignalProducer<T, E> { precondition(count >= 0) return { producer in if count == 0 { return producer } else { return producer |> catch { _ in producer |> retry(count - 1) } } } } /// Waits for completion of `producer`, *then* forwards all events from /// `replacement`. Any error sent from `producer` is forwarded immediately, in /// which case `replacement` will not be started, and none of its events will be /// be forwarded. All values sent from `producer` are ignored. public func then<T, U, E>(replacement: SignalProducer<U, E>) -> SignalProducer<T, E> -> SignalProducer<U, E> { return { producer in let relay = SignalProducer<U, E> { observer, observerDisposable in producer.startWithSignal { signal, signalDisposable in observerDisposable.addDisposable(signalDisposable) signal.observe(error: { error in sendError(observer, error) }, completed: { sendCompleted(observer) }, interrupted: { sendInterrupted(observer) }) } } return relay |> concat(replacement) } } /// Starts the producer, then blocks, waiting for the first value. public func first<T, E>(producer: SignalProducer<T, E>) -> Result<T, E>? { return producer |> take(1) |> single } /// Starts the producer, then blocks, waiting for events: Next and Completed. /// When a single value or error is sent, the returned `Result` will represent /// those cases. However, when no values are sent, or when more than one value /// is sent, `nil` will be returned. public func single<T, E>(producer: SignalProducer<T, E>) -> Result<T, E>? { let semaphore = dispatch_semaphore_create(0) var result: Result<T, E>? producer |> take(2) |> start(next: { value in if result != nil { // Move into failure state after recieving another value. result = nil return } result = .success(value) }, error: { error in result = .failure(error) dispatch_semaphore_signal(semaphore) }, completed: { dispatch_semaphore_signal(semaphore) }, interrupted: { dispatch_semaphore_signal(semaphore) }) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) return result } /// Starts the producer, then blocks, waiting for the last value. public func last<T, E>(producer: SignalProducer<T, E>) -> Result<T, E>? { return producer |> takeLast(1) |> single } /// Starts the producer, then blocks, waiting for completion. public func wait<T, E>(producer: SignalProducer<T, E>) -> Result<(), E> { let result = producer |> then(SignalProducer(value: ())) |> last return result ?? .success(()) } /// SignalProducer.startWithSignal() as a free function, for easier use with |>. public func startWithSignal<T, E>(setUp: (Signal<T, E>, Disposable) -> ()) -> SignalProducer<T, E> -> () { return { producer in return producer.startWithSignal(setUp) } } /// SignalProducer.start() as a free function, for easier use with |>. public func start<T, E, S: SinkType where S.Element == Event<T, E>>(sink: S) -> SignalProducer<T, E> -> Disposable { return { producer in return producer.start(sink) } } /// SignalProducer.start() as a free function, for easier use with |>. public func start<T, E>(error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil) -> SignalProducer<T, E> -> Disposable { return { producer in return producer.start(next: next, error: error, completed: completed, interrupted: interrupted) } } /// Describes how multiple producers should be joined together. public enum FlattenStrategy: Equatable { /// The producers should be merged, so that any value received on any of the /// input producers will be forwarded immediately to the output producer. /// /// The resulting producer will complete only when all inputs have completed. case Merge /// The producers should be concatenated, so that their values are sent in the /// order of the producers themselves. /// /// The resulting producer will complete only when all inputs have completed. case Concat /// Only the events from the latest input producer should be considered for /// the output. Any producers received before that point will be disposed of. /// /// The resulting producer will complete only when the producer-of-producers and /// the latest producer has completed. case Latest } extension FlattenStrategy: Printable { public var description: String { switch self { case .Merge: return "merge" case .Concat: return "concatenate" case .Latest: return "latest" } } } /// Flattens the inner producers sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner producer emits an error, the returned /// producer will forward that error immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. public func flatten<T, E>(strategy: FlattenStrategy) -> SignalProducer<SignalProducer<T, E>, E> -> SignalProducer<T, E> { return { producer in switch strategy { case .Merge: return producer |> merge case .Concat: return producer |> concat case .Latest: return producer |> switchToLatest } } } /// Maps each event from `producer` to a new producer, then flattens the /// resulting producers (into a single producer of values), according to the /// semantics of the given strategy. /// /// If `producer` or any of the created producers emit an error, the returned /// producer will forward that error immediately. public func flatMap<T, U, E>(strategy: FlattenStrategy, transform: T -> SignalProducer<U, E>) -> SignalProducer<T, E> -> SignalProducer<U, E> { return { producer in return producer |> map(transform) |> flatten(strategy) } } /// Returns a producer which sends all the values from each producer emitted from /// `producer`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers emit an error, the returned producer will emit /// that error. /// /// The returned producer completes only when `producer` and all producers /// emitted from `producer` complete. private func concat<T, E>(producer: SignalProducer<SignalProducer<T, E>, E>) -> SignalProducer<T, E> { return SignalProducer { observer, disposable in let state = ConcatState(observer: observer, disposable: disposable) producer.startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(next: { producer in state.enqueueSignalProducer(producer) }, error: { error in sendError(observer, error) }, completed: { // Add one last producer to the queue, whose sole job is to // "turn out the lights" by completing `observer`. let completion = SignalProducer<T, E> { innerObserver, _ in sendCompleted(innerObserver) sendCompleted(observer) } state.enqueueSignalProducer(completion) }, interrupted: { sendInterrupted(observer) }) } } } private final class ConcatState<T, E: ErrorType> { /// The observer of a started `concat` producer. let observer: Signal<T, E>.Observer /// The top level disposable of a started `concat` producer. let disposable: CompositeDisposable /// The active producer, if any, and the producers waiting to be started. let queuedSignalProducers: Atomic<[SignalProducer<T, E>]> = Atomic([]) init(observer: Signal<T, E>.Observer, disposable: CompositeDisposable) { self.observer = observer self.disposable = disposable } func enqueueSignalProducer(producer: SignalProducer<T, E>) { if disposable.disposed { return } var shouldStart = true queuedSignalProducers.modify { (var queue) in // An empty queue means the concat is idle, ready & waiting to start // the next producer. shouldStart = queue.isEmpty queue.append(producer) return queue } if shouldStart { startNextSignalProducer(producer) } } func dequeueSignalProducer() -> SignalProducer<T, E>? { if disposable.disposed { return nil } var nextSignalProducer: SignalProducer<T, E>? queuedSignalProducers.modify { (var queue) in // Active producers remain in the queue until completed. Since // dequeueing happens at completion of the active producer, the // first producer in the queue can be removed. if !queue.isEmpty { queue.removeAtIndex(0) } nextSignalProducer = queue.first return queue } return nextSignalProducer } /// Subscribes to the given signal producer. func startNextSignalProducer(signalProducer: SignalProducer<T, E>) { signalProducer.startWithSignal { signal, disposable in let handle = self.disposable.addDisposable(disposable) signal.observe(Signal.Observer { event in switch event { case .Completed, .Interrupted: handle.remove() if let nextSignalProducer = self.dequeueSignalProducer() { self.startNextSignalProducer(nextSignalProducer) } default: self.observer.put(event) } }) } } } /// Merges a `producer` of SignalProducers down into a single producer, biased toward the producers /// added earlier. Returns a SignalProducer that will forward events from the inner producers as they arrive. private func merge<T, E>(producer: SignalProducer<SignalProducer<T, E>, E>) -> SignalProducer<T, E> { return SignalProducer<T, E> { relayObserver, disposable in let inFlight = Atomic(1) let decrementInFlight: () -> () = { let orig = inFlight.modify { $0 - 1 } if orig == 1 { sendCompleted(relayObserver) } } producer.startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(next: { producer in producer.startWithSignal { innerSignal, innerDisposable in inFlight.modify { $0 + 1 } let handle = disposable.addDisposable(innerDisposable) innerSignal.observe(Signal<T,E>.Observer { event in switch event { case .Completed, .Interrupted: if event.isTerminating { handle.remove() } decrementInFlight() default: relayObserver.put(event) } }) } }, error: { error in sendError(relayObserver, error) }, completed: { decrementInFlight() }, interrupted: { sendInterrupted(relayObserver) }) } } } /// Returns a producer that forwards values from the latest producer sent on /// `producer`, ignoring values sent on previous inner producers. /// /// An error sent on `producer` or the latest inner producer will be sent on the /// returned producer. /// /// The returned producer completes when `producer` and the latest inner /// producer have both completed. private func switchToLatest<T, E>(producer: SignalProducer<SignalProducer<T, E>, E>) -> SignalProducer<T, E> { return SignalProducer<T, E> { sink, disposable in let latestInnerDisposable = SerialDisposable() disposable.addDisposable(latestInnerDisposable) let state = Atomic(LatestState<T, E>()) producer.startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(next: { innerProducer in innerProducer.startWithSignal { innerSignal, innerDisposable in state.modify { (var state) in // When we replace the disposable below, this prevents the // generated Interrupted event from doing any work. state.replacingInnerSignal = true return state } latestInnerDisposable.innerDisposable = innerDisposable state.modify { (var state) in state.replacingInnerSignal = false state.innerSignalComplete = false return state } innerSignal.observe(Signal.Observer { event in switch event { case .Interrupted: // If interruption occurred as a result of a new signal // arriving, we don't want to notify our observer. let original = state.modify { (var state) in if !state.replacingInnerSignal { state.innerSignalComplete = true } return state } if !original.replacingInnerSignal && original.outerSignalComplete { sendCompleted(sink) } case .Completed: let original = state.modify { (var state) in state.innerSignalComplete = true return state } if original.outerSignalComplete { sendCompleted(sink) } default: sink.put(event) } }) } }, error: { error in sendError(sink, error) }, completed: { let original = state.modify { (var state) in state.outerSignalComplete = true return state } if original.innerSignalComplete { sendCompleted(sink) } }, interrupted: { sendInterrupted(sink) }) } } } private struct LatestState<T, E: ErrorType> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false }
mit
4949aec0d37f63898174814194989516
34.147924
411
0.692722
3.819062
false
true
false
false
e78l/swift-corelibs-foundation
Foundation/NSData+DataProtocol.swift
2
1956
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 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 // //===----------------------------------------------------------------------===// extension NSData : DataProtocol { @nonobjc public var startIndex: Int { return 0 } @nonobjc public var endIndex: Int { return length } @nonobjc public func lastRange<D, R>(of data: D, in r: R) -> Range<Int>? where D : DataProtocol, R : RangeExpression, NSData.Index == R.Bound { return Range<Int>(range(of: Data(data), options: .backwards, in: NSRange(r))) } @nonobjc public func firstRange<D, R>(of data: D, in r: R) -> Range<Int>? where D : DataProtocol, R : RangeExpression, NSData.Index == R.Bound { return Range<Int>(range(of: Data(data), in: NSRange(r))) } @nonobjc public var regions: [Data] { var datas = [Data]() enumerateBytes { (ptr, range, stop) in datas.append(Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr), count: range.length, deallocator: .custom({ (ptr: UnsafeMutableRawPointer, count: Int) -> Void in withExtendedLifetime(self) { } }))) } return datas } @nonobjc public subscript(position: Int) -> UInt8 { var byte = UInt8(0) enumerateBytes { (ptr, range, stop) in if range.location <= position && position < range.upperBound { byte = ptr.load(fromByteOffset: range.location - position, as: UInt8.self) stop.pointee = true } } return byte } }
apache-2.0
9b4582a3d2b105ee4e19156ce8588f9c
35.222222
180
0.560838
4.486239
false
false
false
false
DAloG/BlueCap
BlueCapKit/SerDe/Int16Extensions.swift
1
1504
// // Int16Extensions.swift // BlueCap // // Created by Troy Stribling on 7/8/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation extension Int16 : Deserializable { public static var size : Int { return sizeof(Int16) } public init?(doubleValue:Double) { if doubleValue >= 32767.0 || doubleValue <= -32768.0 { return nil } else { self = Int16(doubleValue) } } public static func deserialize(data:NSData) -> Int16? { if data.length >= sizeof(Int16) { var value : Int16 = 0 data.getBytes(&value , length:sizeof(Int16)) return toHostByteOrder(value) } else { return nil } } public static func deserialize(data:NSData, start:Int) -> Int16? { if data.length >= (sizeof(Int16) + start) { var value : Int16 = 0 data.getBytes(&value, range:NSMakeRange(start, sizeof(Int16))) return toHostByteOrder(value) } else { return nil } } public static func deserialize(data:NSData) -> [Int16] { let size = sizeof(Int16) let count = data.length / size return [Int](0..<count).reduce([]) {(result, idx) in if let value = self.deserialize(data, start:idx*size) { return result + [value] } else { return result } } } }
mit
8e03430e87d02c39dabbb81a788458d2
25.385965
74
0.52992
4.177778
false
false
false
false
IC2017/NewsWatch
NewsSeconds/NewsSeconds/SettingsViewController.swift
1
5321
// // SettingsViewController.swift // NewsSeconds // // Created by Anantha Krishnan K G on 03/03/17. // Copyright © 2017 Ananth. All rights reserved. // import UIKit import DropDown import UserNotifications class SettingsViewController: UIViewController { @IBOutlet weak var pushDescriptionLabel: UILabel! @IBOutlet weak var paperSwitch1: paperSwitch! @IBOutlet var sourceButton: UIButton! @IBOutlet var paperSwitch2: paperSwitch! @IBOutlet var watsonDescriptionLabel: UILabel! let chooseArticleDropDown = DropDown() let appDelegate = UIApplication.shared.delegate as! AppDelegate lazy var dropDowns: [DropDown] = { return [ self.chooseArticleDropDown ] }() let keyValues = [ "abc-news-au", "cnn", "bbc-sport", "bloomberg", "buzzfeed", "financial-times", "reddit-r-all", "time", "usa-today", "t3n", "google-news", "business-insider-uk", "the-wall-street-journal" ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.appDelegate.valueChanged = false self.paperSwitch1.animationDidStartClosure = {(onAnimation: Bool) in self.animateLabel(self.pushDescriptionLabel, onAnimation: onAnimation, duration: self.paperSwitch1.duration) } self.paperSwitch2.animationDidStartClosure = {(onAnimation: Bool) in self.animateLabel(self.watsonDescriptionLabel, onAnimation: onAnimation, duration: self.paperSwitch2.duration) } setupChooseArticleDropDown(); dropDowns.forEach { $0.dismissMode = .onTap } dropDowns.forEach { $0.direction = .any } if (UserDefaults.standard.bool(forKey: "isPushEnabled")){ self.paperSwitch1.setOn(true, animated: false) } if (UserDefaults.standard.bool(forKey: "isWatsonEnabled")){ self.paperSwitch2.setOn(true, animated: false) } sourceButton.setTitle(chooseArticleDropDown.dataSource[appDelegate.sourceID], for: .normal) } func setupChooseArticleDropDown() { chooseArticleDropDown.anchorView = sourceButton chooseArticleDropDown.bottomOffset = CGPoint(x: 0, y: sourceButton.bounds.height) chooseArticleDropDown.dataSource = [ "ABC News (AU)", "CNN general", "BBC Sport", "Bloomberg business", "Buzzfeed entertainment", "Financial Times business", "Reddit", "Time general", "USA Today general", "T3n technology", "Google News general", "Business Insider business", "The Wall Street Journal" ] chooseArticleDropDown.selectionAction = { [unowned self] (index, item) in self.sourceButton.setTitle(item, for: .normal) self.appDelegate.oldSource = self.appDelegate.source self.appDelegate.source = self.keyValues[index] as String self.appDelegate.sourceID = index self.appDelegate.sourceDescription = self.chooseArticleDropDown.dataSource[self.appDelegate.sourceID] UserDefaults.standard.set(self.appDelegate.oldSource, forKey: "oldSourceValue") UserDefaults.standard.set(self.appDelegate.source, forKey: "sourceValue") UserDefaults.standard.set(self.appDelegate.sourceID, forKey: "sourceValueID") UserDefaults.standard.set(self.appDelegate.sourceDescription, forKey: "sourceDescription") UserDefaults.standard.synchronize() self.appDelegate.valueChanged = true self.appDelegate.registerForTag() } } @IBAction func chooseArticle(_ sender: AnyObject) { chooseArticleDropDown.show() } @IBAction func BackButton(_ sender: UIBarButtonItem) { self.navigationController?.popViewController(animated: true) } fileprivate func animateLabel(_ label: UILabel, onAnimation: Bool, duration: TimeInterval) { UIView.transition(with: label, duration: duration, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { label.textColor = onAnimation ? UIColor.white : UIColor.black }, completion:nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func enablePush(_ sender: UISwitch) { if(sender.isOn){ UserDefaults.standard.set(true, forKey: "isPushEnabled") self.appDelegate.registerForPush() }else{ UserDefaults.standard.set(false, forKey: "isPushEnabled") self.appDelegate.unRegisterPush() } UserDefaults.standard.synchronize() } @IBAction func enableWatson(_ sender: UISwitch) { if(sender.isOn){ UserDefaults.standard.set(true, forKey: "isWatsonEnabled") }else{ UserDefaults.standard.set(false, forKey: "isWatsonEnabled") } UserDefaults.standard.synchronize() } }
apache-2.0
883952f9463f8aa81e3cf2fe19385f77
33.771242
129
0.631203
4.981273
false
false
false
false
Mobilette/AniMee
AniMee/Classes/Commons/Domain/Episode/EpisodeRepository.swift
1
1443
// // EpisodeRepository.swift // AniMee // // Created by Romain ASNAR on 9/12/15. // Copyright (c) 2015 Mobilette. All rights reserved. // import Foundation class EpisodeRepository: Equatable, CustomStringConvertible { // MARK: - Property var episodes: [Episode] = [] // MARK: - Life cycle init() {} // MARK: - Repository func addEpisodes(episodes: [Episode]) { self.episodes.appendContentsOf(episodes) } func addEpisode(episode: Episode) { self.episodes.append(episode) } func removeAllEpisodes() { self.episodes.removeAll(keepCapacity: false) } func removeEpisode(episode: Episode) { if let index = self.episodes.indexOf(episode) { self.episodes.removeAtIndex(index) } } func findAllEpisodes() -> [Episode] { return self.episodes } func findEpisodeWithIdentifier(identifier: String?) -> [Episode] { return self.episodes.filter({ return $0.identifier == identifier }) } // MARK: - Printable protocol var description: String { return "{ EpisodeRepository" + "\n" + "episodes: \(self.episodes)" + "\n" + "}" + "\n" } } // MARK: - Equatable protocol func ==(lhs: EpisodeRepository, rhs: EpisodeRepository) -> Bool { return lhs.episodes == rhs.episodes }
mit
973d05b049f50c85b319015a45e33a2a
19.055556
68
0.576577
4.372727
false
false
false
false
buscarini/JMSSwiftParse
Source/conversions.swift
1
5015
// // conversions.swift // JMSSwiftParse // // Created by Jose Manuel Sánchez Peñarroja on 10/11/14. // Copyright (c) 2014 José Manuel Sánchez. All rights reserved. // import Foundation extension String { func toDouble() -> Double? { numberFormatter.numberStyle = .DecimalStyle let number = numberFormatter.numberFromString(self) return number?.doubleValue } } func convert<T: Hashable,U: Hashable>(value : T) -> U? { return value as? U } /* func convert<T,U>(value : T) -> U? { if let converted = value as? U { return converted } return nil } */ /* public protocol Convertible {} extension Int : Convertible {} extension Bool : Convertible {} extension String : Convertible {} extension NSInteger : Convertible {} extension NSNumber : Convertible {} extension NSString : Convertible {} extension NSURL : Convertible {} func convert<T: Convertible,U: Convertible>(value : T) -> U? { if let converted = value as? U { return converted } return nil } // MARK: Bool func convert<T: BooleanLiteralConvertible>(string : String) -> T? { let lowercase = string.lowercaseString if lowercase=="true" { return true } else if lowercase=="false" { return false } return nil } func convert<T: BooleanLiteralConvertible>(value : T) -> String? { if let boolValue = value as? Bool { if boolValue { return "true" } else { return "false" } } return nil } func convert<T: BooleanLiteralConvertible>(value : NSString) -> T? { return convert(value as String) } func convert<T: BooleanLiteralConvertible>(value : T) -> NSString? { return convert(value) } */ // MARK: NSNumber <-> String /* func convert(number : NSNumber) -> NSString? { return number.stringValue } func convert(string : NSString) -> NSNumber? { return NSNumber(double: string.doubleValue) } func convert(number : NSNumber) -> String? { return number.stringValue } func convert(string : String) -> NSNumber? { if let num = string.toDouble() { return NSNumber(double: num) } return nil }*/ // MARK: NSNull func convert<T: Hashable>(value : NSNull) -> T? { return nil } // MARK: Bool <-> NSNumber func convert(value : NSNumber) -> Bool? { return value.boolValue } func convert(value : Bool) -> NSNumber? { return NSNumber(bool: value) } // MARK: Bool <-> String func convert(value : String) -> Bool? { let lowercase = value.lowercaseString if lowercase=="true" { return true } else if lowercase=="false" { return false } return nil } func convert(value : Bool) -> String? { if value { return "true" } return "false" } // MARK: Bool <-> NSString func convert(value : NSString) -> Bool? { let lowercase = value.lowercaseString if lowercase=="true" { return true } else if lowercase=="false" { return false } return nil } func convert(value : Bool) -> NSString? { if value { return "true" } return "false" } // MARK: String <-> NSURL func convert(string : String) -> NSURL? { return NSURL(string: string) } func convert(value : NSString) -> NSURL? { return convert(value as String) } func convert(url : NSURL) -> String? { return url.absoluteString } func convert(value : NSURL) -> NSString? { return convert(value) as NSString? } // MARK: Int <-> NSNumber func convert(value : NSNumber) -> Int? { return value.integerValue } func convert(value : Int) -> NSNumber? { return NSNumber(integer: value) } // MARK: Int <-> String func convert(value : String) -> Int? { return value.toInt() } func convert(value : Int) -> String? { return value.description } // MARK: Int <-> NSString func convert(value : NSString) -> Int? { let string = value as String return string.toInt() } func convert(value : Int) -> NSString? { return value.description } // MARK: Double <-> NSNumber func convert(value : NSNumber) -> Double? { return value.doubleValue } func convert(value : Double) -> NSNumber? { return NSNumber(double: value) } // MARK: Double <-> String func convert(value : String) -> Double? { return value.toDouble() } func convert(value : Double) -> String? { return value.description } // MARK: Double <-> NSString func convert(value : NSString) -> Double? { let string = value as String return string.toDouble() } func convert(value : Double) -> NSString? { return value.description } // MARK: NSDate <-> String var cache = Cache() //var cache = NSCache() func cachedDateFormatter(format: String) -> NSDateFormatter { let cachedFormatter = cache.objectForKey(format) if let dateFormatter = cachedFormatter { return dateFormatter } else { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format cache.setObject(dateFormatter, forKey: format) return dateFormatter } } func convert(value : String,format: String) -> NSDate? { let dateFormatter = cachedDateFormatter(format) return dateFormatter.dateFromString(value) } func convert(value : NSDate,format: String) -> String? { let dateFormatter = cachedDateFormatter(format) return dateFormatter.stringFromDate(value) }
mit
6dd7aeb20579973eca8949d26825c167
17.221818
68
0.687687
3.418145
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MediaPicker/View/ThumbnailsView/ThumbnailsView.swift
1
11243
import ImageSource import UIKit final class ThumbnailsView: UIView, UICollectionViewDataSource, MediaRibbonLayoutDelegate, ThemeConfigurable { typealias ThemeType = MediaPickerRootModuleUITheme var onDragStart: (() -> ())? { get { return layout.onDragStart } set { layout.onDragStart = newValue } } var onDragFinish: (() -> ())? { get { return layout.onDragFinish } set { layout.onDragFinish = newValue } } private let layout: ThumbnailsViewLayout private let collectionView: UICollectionView private let dataSource = MediaRibbonDataSource() private var theme: MediaPickerRootModuleUITheme? // MARK: - Constrants private let mediaRibbonInteritemSpacing = CGFloat(7) private let photoCellReuseId = "PhotoCell" private let cameraCellReuseId = "CameraCell" // MARK: - Init init() { layout = ThumbnailsViewLayout() layout.spacing = mediaRibbonInteritemSpacing collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.clipsToBounds = false collectionView.backgroundColor = .clear collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.register(MediaItemThumbnailCell.self, forCellWithReuseIdentifier: photoCellReuseId) collectionView.register(CameraThumbnailCell.self, forCellWithReuseIdentifier: cameraCellReuseId) super.init(frame: .zero) collectionView.dataSource = self collectionView.delegate = self addSubview(collectionView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIView override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds } // MARK: - ThemeConfigurable func setTheme(_ theme: ThemeType) { self.theme = theme } // MARK: - ThumbnailRibbonView var cameraOutputParameters: CameraOutputParameters? { didSet { updateCameraCell() } } var contentInsets = UIEdgeInsets.zero { didSet { layout.sectionInset = contentInsets } } var onPhotoItemSelect: ((MediaPickerItem) -> ())? var onItemMove: ((Int, Int) -> ())? var onCameraItemSelect: (() -> ())? func selectCameraItem() { collectionView.selectItem(at: dataSource.indexPathForCameraItem(), animated: false, scrollPosition: []) } func selectMediaItem(_ item: MediaPickerItem, animated: Bool = false) { layout.cancelDrag() if let indexPath = dataSource.indexPathForItem(item) { collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: []) } } func scrollToItemThumbnail(_ item: MediaPickerItem, animated: Bool) { if let indexPath = dataSource.indexPathForItem(item) { collectionView.scrollToItem( at: indexPath, at: .centeredHorizontally, animated: animated ) } } func scrollToCameraThumbnail(animated: Bool) { collectionView.scrollToItem( at: dataSource.indexPathForCameraItem(), at: .centeredHorizontally, animated: animated ) } func setControlsTransform(_ transform: CGAffineTransform) { layout.itemsTransform = transform layout.invalidateLayout() cameraIconTransform = transform } func setHapticFeedbackEnabled(_ enabled: Bool) { layout.hapticFeedbackEnabled = enabled } func addItems(_ items: [MediaPickerItem], animated: Bool, completion: @escaping () -> ()) { collectionView.performBatchUpdates( animated: animated, updates: { [weak self] in if let indexPaths = self?.dataSource.addItems(items) { self?.collectionView.insertItems(at: indexPaths) if let indexPathsToReload = self?.collectionView.indexPathsForVisibleItems.filter({ !indexPaths.contains($0) }), indexPathsToReload.count > 0 { self?.collectionView.reloadItems(at: indexPathsToReload) } } }, completion: { _ in completion() } ) } func updateItem(_ item: MediaPickerItem) { if let indexPath = dataSource.updateItem(item) { let selectedIndexPaths = collectionView.indexPathsForSelectedItems let cellWasSelected = selectedIndexPaths?.contains(indexPath) == true collectionView.reloadItems(at: [indexPath]) if cellWasSelected { collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) } } } func removeItem(_ item: MediaPickerItem, animated: Bool) { collectionView.deleteItems(animated: animated) { [weak self] in self?.dataSource.removeItem(item).flatMap { [$0] } } } func setCameraItemVisible(_ visible: Bool) { if dataSource.cameraCellVisible != visible { let updatesFunction = { [weak self] () -> [IndexPath]? in self?.dataSource.cameraCellVisible = visible return (self?.dataSource.indexPathForCameraItem()).flatMap { [$0] } } if visible { collectionView.insertItems(animated: false, updatesFunction) } else { collectionView.deleteItems(animated: false, updatesFunction) } } } func setCameraOutputParameters(_ parameters: CameraOutputParameters) { cameraOutputParameters = parameters } func setCameraOutputOrientation(_ orientation: ExifOrientation) { cameraOutputParameters?.orientation = orientation if let cell = cameraCell() { cell.setOutputOrientation(orientation) } } func reloadCamera() { if dataSource.cameraCellVisible { let cameraIndexPath = dataSource.indexPathForCameraItem() let cameraIsSelected = collectionView.indexPathsForSelectedItems?.contains(cameraIndexPath) == true collectionView.performNonAnimatedBatchUpdates( updates: { self.collectionView.reloadItems(at: [cameraIndexPath]) }, completion: { _ in if cameraIsSelected { self.collectionView.selectItem(at: cameraIndexPath, animated: false, scrollPosition: []) } } ) } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.numberOfItems } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch dataSource[indexPath] { case .camera: return cameraCell(forIndexPath: indexPath, inCollectionView: collectionView) case .photo(let mediaPickerItem): return photoCell(forIndexPath: indexPath, inCollectionView: collectionView, withItem: mediaPickerItem) } } // MARK: - MediaRibbonLayoutDelegate func shouldApplyTransformToItemAtIndexPath(_ indexPath: IndexPath) -> Bool { switch dataSource[indexPath] { case .photo: return true case .camera: return false } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch dataSource[indexPath] { case .photo(let photo): onPhotoItemSelect?(photo) case .camera: onCameraItemSelect?() } } func canMove(to indexPath: IndexPath) -> Bool { let cameraCellVisible = dataSource.cameraCellVisible ? 1 : 0 let lastSectionIndex = collectionView.numberOfSections - 1 let lastItemIndex = collectionView.numberOfItems(inSection: lastSectionIndex) - cameraCellVisible let lastIndexPath = IndexPath(item: lastItemIndex, section: lastSectionIndex) return indexPath != lastIndexPath } func moveItem(from sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { onItemMove?(sourceIndexPath.item, destinationIndexPath.item) dataSource.moveItem(from: sourceIndexPath.item, to: destinationIndexPath.item) } // MARK: - Private private var cameraIconTransform = CGAffineTransform.identity { didSet { cameraCell()?.setCameraIconTransform(cameraIconTransform) } } private func photoCell( forIndexPath indexPath: IndexPath, inCollectionView collectionView: UICollectionView, withItem mediaPickerItem: MediaPickerItem ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: photoCellReuseId, for: indexPath ) if let cell = cell as? MediaItemThumbnailCell { cell.selectedBorderColor = theme?.mediaRibbonSelectionColor cell.customizeWithItem(mediaPickerItem) cell.setAccessibilityId("\(AccessibilityId.mediaItemThumbnailCell)-\(indexPath.row)") } return cell } private func cameraCell( forIndexPath indexPath: IndexPath, inCollectionView collectionView: UICollectionView ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cameraCellReuseId, for: indexPath ) setUpCameraCell(cell) return cell } private func setUpCameraCell(_ cell: UICollectionViewCell) { if let cell = cell as? CameraThumbnailCell { cell.selectedBorderColor = theme?.mediaRibbonSelectionColor cell.setCameraIcon(theme?.returnToCameraIcon) cell.setCameraIconTransform(cameraIconTransform) if let cameraOutputParameters = cameraOutputParameters, !isHidden { cell.setOutputParameters(cameraOutputParameters) } } } private func updateCameraCell() { if let cell = cameraCell() { setUpCameraCell(cell) } } private func cameraCell() -> CameraThumbnailCell? { let indexPath = dataSource.indexPathForCameraItem() return collectionView.cellForItem(at: indexPath) as? CameraThumbnailCell } }
mit
2f82258f2abf668bd834a2d1ad0b1699
31.874269
132
0.608023
6.19449
false
false
false
false
drougojrom/RUCropController
RUCropController/Model/RUActivityCroppedImageProvider.swift
1
1597
// // RUActivityCroppedImageProvider.swift // RUCropController // // Created by Roman Ustiantcev on 06/10/2017. // Copyright © 2017 Roman Ustiantcev. All rights reserved. // import UIKit @objc class RUActivityCroppedImageProvider: UIActivityItemProvider { private(set) var image: UIImage? private(set) var cropFrame = CGRect.zero private(set) var angle: Int = 0 private(set) var isCircular = false var croppedImage: UIImage? @objc init(image: UIImage, cropFrame: CGRect, angle: Int, circular: Bool) { super.init(placeholderItem: UIImage()) self.image = image self.cropFrame = cropFrame self.angle = angle isCircular = circular } // MARK: - UIActivity Protocols - override func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return UIImage() } override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? { return croppedImage } // MARK: - Image Generation - override var item: Any { //If the user didn't touch the image, just forward along the original if angle == 0 && cropFrame.equalTo(CGRect(origin: CGPoint.zero, size: self.image!.size)) { croppedImage = self.image return croppedImage } let image: UIImage? = self.image?.croppedImage(withFrame: cropFrame, angle: angle, circularClip: isCircular) croppedImage = image return croppedImage } }
mit
f50912a121ea9a5fc3cd46df293105a3
32.957447
153
0.676692
4.707965
false
false
false
false
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Renderers/LineChartRenderer.swift
18
23445
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/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 CoreGraphics import UIKit public class LineChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: LineChartDataProvider? public init(dataProvider: LineChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let lineData = dataProvider?.lineData else { return } for (var i = 0; i < lineData.dataSetCount; i++) { guard let set = lineData.getDataSetByIndex(i) else { continue } if set.isVisible { drawDataSet(context: context, dataSet: set as! LineChartDataSet) } } } internal struct CGCPoint { internal var x: CGFloat = 0.0 internal var y: CGFloat = 0.0 /// x-axis distance internal var dx: CGFloat = 0.0 /// y-axis distance internal var dy: CGFloat = 0.0 internal init(x: CGFloat, y: CGFloat) { self.x = x self.y = y } } internal func drawDataSet(context context: CGContext, dataSet: LineChartDataSet) { let entries = dataSet.yVals if (entries.count < 1) { return } CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.lineWidth) if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet, entries: entries) } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet, entries: entries) } CGContextRestoreGState(context) } internal func drawCubic(context context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { let trans = dataProvider?.getTransformer(dataSet.axisDependency) let entryFrom = dataSet.entryForXIndex(_minX)! let entryTo = dataSet.entryForXIndex(_maxX)! let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo, isEqual: true) + 1), entries.count) let phaseX = _animator.phaseX let phaseY = _animator.phaseY // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGPathCreateMutable() var valueToPixelMatrix = trans!.valueToPixelMatrix let size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) if (size - minx >= 2) { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 var prevPrev = entries[minx] var prev = entries[minx] var cur = entries[minx] var next = entries[minx + 1] // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity prevDy = CGFloat(cur.value - prev.value) * intensity curDx = CGFloat(next.xIndex - cur.xIndex) * intensity curDy = CGFloat(next.value - cur.value) * intensity // the first cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++) { prevPrev = entries[j == 1 ? 0 : j - 2] prev = entries[j - 1] cur = entries[j] next = entries[j + 1] prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } if (size > entries.count - 1) { prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)] prev = entries[entries.count - 2] cur = entries[entries.count - 1] next = cur prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } } CGContextSaveGState(context) if (dataSet.isDrawFilledEnabled) { drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size) } CGContextBeginPath(context) CGContextAddPath(context, cubicPath) CGContextSetStrokeColorWithColor(context, drawingColor.CGColor) CGContextStrokePath(context) CGContextRestoreGState(context) } internal func drawCubicFill(context context: CGContext, dataSet: LineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, from: Int, to: Int) { guard let dataProvider = dataProvider else { return } if to - from <= 1 { return } CGContextSaveGState(context) let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin) var pt2 = CGPoint(x: CGFloat(from), y: fillMin) pt1 = CGPointApplyAffineTransform(pt1, matrix) pt2 = CGPointApplyAffineTransform(pt2, matrix) CGContextBeginPath(context) CGContextAddPath(context, spline) CGContextAddLineToPoint(context, pt1.x, pt1.y) CGContextAddLineToPoint(context, pt2.x, pt2.y) CGContextClosePath(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) CGContextSetAlpha(context, dataSet.fillAlpha) CGContextFillPath(context) CGContextRestoreGState(context) } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawLinear(context context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency) else { return } let valueToPixelMatrix = trans.valueToPixelMatrix let phaseX = _animator.phaseX let phaseY = _animator.phaseY CGContextSaveGState(context) let entryFrom = dataSet.entryForXIndex(_minX)! let entryTo = dataSet.entryForXIndex(_maxX)! let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo, isEqual: true) + 1), entries.count) // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != 2) { _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) } for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break } var e = entries[j] _lineSegments[0].x = CGFloat(e.xIndex) _lineSegments[0].y = CGFloat(e.value) * phaseY _lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix) if (j + 1 < count) { e = entries[j + 1] _lineSegments[1].x = CGFloat(e.xIndex) _lineSegments[1].y = CGFloat(e.value) * phaseY _lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix) } else { _lineSegments[1] = _lineSegments[0] } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextStrokeLineSegments(context, _lineSegments, 2) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! if (_lineSegments.count != max((entries.count - 1) * 2, 2)) { _lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint()) } e1 = entries[minx] let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++) { e1 = entries[x == 0 ? 0 : (x - 1)] e2 = entries[x] _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix) _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix) } let size = max((count - minx - 1) * 2, 2) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextStrokeLineSegments(context, _lineSegments, size) } CGContextRestoreGState(context) // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entries.count > 0) { drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans) } } internal func drawLinearFill(context context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer) { guard let dataProvider = dataProvider else { return } CGContextSaveGState(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) // filled is usually drawn with less alpha CGContextSetAlpha(context, dataSet.fillAlpha) let filled = generateFilledPath( entries, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, from: minx, to: maxx, matrix: trans.valueToPixelMatrix) CGContextBeginPath(context) CGContextAddPath(context, filled) CGContextFillPath(context) CGContextRestoreGState(context) } /// Generates the path that is used for filled drawing. private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath { let phaseX = _animator.phaseX let phaseY = _animator.phaseY let filled = CGPathCreateMutable() CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin) CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY) // create a new path for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++) { let e = entries[x] CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // close up CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin) CGPathCloseSubpath(filled) return filled } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData else { return } if (CGFloat(lineData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets for (var i = 0; i < dataSets.count; i++) { guard let dataSet = dataSets[i] as? LineChartDataSet else { continue } if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor let formatter = dataSet.valueFormatter let trans = dataProvider.getTransformer(dataSet.axisDependency) // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2 } var entries = dataSet.yVals let entryFrom = dataSet.entryForXIndex(_minX)! let entryTo = dataSet.entryForXIndex(_maxX)! let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo, isEqual: true) + 1), entries.count) var positions = trans.generateTransformedValuesLine( entries, phaseX: _animator.phaseX, phaseY: _animator.phaseY, from: minx, to: maxx) for (var j = 0, count = positions.count; j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break } if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y)) { continue } let val = entries[j + minx].value ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext) { drawCircles(context: context) } private func drawCircles(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData else { return } let phaseX = _animator.phaseX let phaseY = _animator.phaseY let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() CGContextSaveGState(context) for (var i = 0, count = dataSets.count; i < count; i++) { let dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet! if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix var entries = dataSet.yVals let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleDiameter = circleRadius let circleHoleRadius = circleHoleDiameter / 2.0 let isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled let entryFrom = dataSet.entryForXIndex(_minX)! let entryTo = dataSet.entryForXIndex(_maxX)! let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo, isEqual: true) + 1), entries.count) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { let e = entries[j] pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter CGContextFillEllipseInRect(context, rect) if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor) rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter CGContextFillEllipseInRect(context, rect) } } } CGContextRestoreGState(context) } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let lineData = dataProvider?.lineData, chartXMax = dataProvider?.chartXMax else { return } CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { guard let set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as? LineChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue } let yValue = set.yValForXIndex(xIndex) if (yValue.isNaN) { continue } let y = CGFloat(yValue) * _animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider?.getTransformer(set.axisDependency) trans?.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
c6252371c91038f1cad7ba3adcaa4188
38.141903
306
0.544466
5.453594
false
false
false
false
aducret/vj-ios-tp2
Shooter/Shooter/Components/Player.swift
1
5371
// // Player.swift // Shooter // // Created by Argentino Ducret on 6/15/17. // Copyright © 2017 ITBA. All rights reserved. // import Foundation import SpriteKit import UIKit public class Player: SKSpriteNode { public var pointTouched: CGPoint? = .none private var path: [Node]? = .none public enum AnimationState { case idle case walk } public var animationState: AnimationState = .idle { didSet { switch animationState { case .idle: setIdleAnimation() case .walk: setWalkAnimation() } } } var bullet: SKSpriteNode? = .none private let playerSpeed = 80 let brakeDistance: CGFloat = 5.0 public var lifes = 3 public func shooted() { if lifes > 0 { lifes -= 1 } if lifes == 0 { removeFromParent() } } public func updateMovement(byTimeDelta timeDelta: TimeInterval) { if let point = pointTouched { let enemy = scene!.nodes(at: point).first { $0.name ?? "" == "Enemy"} if let enemy = enemy { if let bullet = bullet { if bullet.parent == .none { shot(to: enemy.position) } } else { shot(to: enemy.position) } return } } if let point = pointTouched { let grid = Grid(scene: scene!, width: 1800, height: 1800, nodeRadius: 25, collisionBitMask: physicsBody!.collisionBitMask) let origin = grid.nodeFromWorldPoint(point: position).worldPosition let target = grid.nodeFromWorldPoint(point: point).worldPosition path = AStar.findPath(origin: origin, target: target, grid: grid) pointTouched = .none } if let path = path { if path.count > 0 { if case animationState = AnimationState.idle { animationState = .walk } let point = path[0].worldPosition let distanceLeft = sqrt(pow(position.x - point.x, 2) + pow(position.y - point.y, 2)) if (distanceLeft > brakeDistance) { let distanceToTravel = CGFloat(timeDelta) * CGFloat(playerSpeed) let angle = atan2(point.y - position.y, point.x - position.x) let yOffset = distanceToTravel * sin(angle) let xOffset = distanceToTravel * cos(angle) position = CGPoint(x: position.x + xOffset, y: position.y + yOffset) zRotation = CGFloat(Double(angle) - 270.degreesToRadians) } let aux = point - position if abs(aux.x) < brakeDistance && abs(aux.y) < brakeDistance { self.path!.remove(at: 0) if self.path!.count == 0 { animationState = .idle } } } } } func shot(to point: CGPoint) { let angle = atan2(point.y - position.y, point.x - position.x) zRotation = CGFloat(Double(angle) - 270.degreesToRadians) let texture = SKTexture(imageNamed: "shot") let shot = SKSpriteNode(texture: texture, size: CGSize(width: 10, height: 18)) shot.physicsBody = SKPhysicsBody(rectangleOf: shot.frame.size) shot.physicsBody?.categoryBitMask = PhysicsCategory.Shot shot.physicsBody?.contactTestBitMask = PhysicsCategory.Wall | PhysicsCategory.Enemy shot.physicsBody?.collisionBitMask = 0 shot.physicsBody?.mass = 5 shot.physicsBody?.affectedByGravity = false shot.physicsBody?.isDynamic = true shot.physicsBody?.usesPreciseCollisionDetection = true shot.zPosition = 2 shot.position = convert(children[0].position, to: parent!) shot.zRotation = zRotation shot.name = "Shot" + name! bullet = shot parent!.addChild(shot) let offset = point - shot.position let direction = offset.normalized() let shootAmount = direction * 1000 let realDest = shootAmount + shot.position let move = SKAction.move(to: realDest, duration: 2.5) shot.run(move) } } // MARK: Private Methods fileprivate extension Player { fileprivate func setWalkAnimation() { let animation = SKAction.animate(with: [SKTexture(imageNamed: "player_walk_1"), SKTexture(imageNamed: "player_walk_2"), SKTexture(imageNamed: "player_walk_3"), SKTexture(imageNamed: "player_walk_4"), SKTexture(imageNamed: "player_walk_5"), SKTexture(imageNamed: "player_walk_6"), SKTexture(imageNamed: "player_walk_7"), SKTexture(imageNamed: "player_walk_8")], timePerFrame: 0.1, resize: false, restore: true) let repetAnimation = SKAction.repeatForever(animation) run(repetAnimation) } fileprivate func setIdleAnimation() { removeAllActions() } }
mit
651699403d4dbde66c907f289243360b
34.8
177
0.539851
4.855335
false
false
false
false
cuappdev/podcast-ios
old/Podcast/NullProfileCollectionViewCell.swift
1
1979
// // NullProfileCollectionViewCell.swift // Podcast // // Created by Jack Thompson on 2/28/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit import SnapKit class NullProfileCollectionViewCell: UICollectionViewCell { let addIconSize: CGFloat = 16 //current user null profile var addIcon: UIImageView! //other user null profile var nullLabel: UILabel! let labelHeight: CGFloat = 21 static var heightForCurrentUser: CGFloat = 100 static var heightForUser: CGFloat = 24 override init(frame: CGRect) { super.init(frame: frame) addIcon = UIImageView() addIcon.image = #imageLiteral(resourceName: "add_icon") addSubview(addIcon) addIcon.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.height.equalTo(addIconSize) } nullLabel = UILabel() nullLabel.text = "" nullLabel.font = ._14RegularFont() nullLabel.textColor = .slateGrey nullLabel.textAlignment = .left addSubview(nullLabel) nullLabel.snp.makeConstraints { (make) in make.top.leading.equalToSuperview() make.height.equalTo(labelHeight) } } override func layoutSubviews() { super.layoutSubviews() addCornerRadius(height: frame.height) } func setup(for user: User, isMe: Bool) { if isMe { backgroundColor = .lightGrey nullLabel.isHidden = true addIcon.isHidden = false } else { backgroundColor = .clear nullLabel.text = "\(user.firstName) has not subscribed to any series yet." nullLabel.isHidden = false addIcon.isHidden = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
55f12280379f37a31827e79a2a6e5457
25.72973
86
0.603134
4.982368
false
false
false
false
jkolb/Shkadov
Sources/PlatformXCB/GetGeometry.swift
1
1873
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 ShkadovXCB public struct GetGeometry { private let connection: OpaquePointer private let drawable: xcb_drawable_t init(connection: OpaquePointer, drawable: xcb_drawable_t) { self.connection = connection self.drawable = drawable } public func reply() throws -> xcb_get_geometry_reply_t { let cookie = xcb_get_geometry(connection, drawable) var errorPointer: UnsafeMutablePointer<xcb_generic_error_t>? if let replyPointer = xcb_get_geometry_reply(connection, cookie, &errorPointer) { defer { free(replyPointer) } return replyPointer.pointee } else if let errorPointer = errorPointer { defer { free(errorPointer) } throw XCBError.generic(errorPointer.pointee) } else { throw XCBError.improbable } } }
mit
9ca5faaac325fa700cbdc3546fd4f7f0
31.293103
83
0.75921
4.171492
false
false
false
false
bradhilton/SwiftCallbacks
Example/ViewController.swift
1
832
// // ViewController.swift // Example // // Created by Bradley Hilton on 11/15/16. // Copyright © 2016 Brad Hilton. All rights reserved. // import UIKit import SwiftCallbacks class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let button = UIButton(type: .system) button.frame = CGRect(x: 0, y: 60, width: 100, height: 44) button.setTitle("Button", for: .normal) button.controlEvents(.touchUpInside) { _ in self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Item", style: .plain) { _ in self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Second Item", style: .plain, callback: nil) } } view.addSubview(button) } }
mit
bbcca03b0811a092389be50607441990
27.655172
123
0.638989
4.283505
false
false
false
false
Asura19/My30DaysOfSwift
3DTouch/3DTouch/AppDelegate.swift
1
4393
// // AppDelegate.swift // 3DTouch // // Created by Phoenix on 2017/4/22. // Copyright © 2017年 Phoenix. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var isFirstLaunch: Bool = false fileprivate enum AppShortcut: String { case NewProject case List case Weigh init?(fullType: String) { guard let lastString = fullType.components(separatedBy: ".").last else { return nil } self.init(rawValue: lastString) } } var launchedShortcutItem: UIApplicationShortcutItem? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] { launchedShortcutItem = shortcutItem as? UIApplicationShortcutItem } isFirstLaunch = true if let shortcut = launchedShortcutItem { _ = handleShortcutItem(shortcut) launchedShortcutItem = nil } return true } func applicationDidBecomeActive(_ application: UIApplication) { } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handleAction = handleShortcutItem(shortcutItem) completionHandler(handleAction) } func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool { if isFirstLaunch { isFirstLaunch = false } var isHandled = false let shortcutType = AppShortcut(fullType: shortcutItem.type) guard shortcutType != nil else { return false } let storyboard = UIStoryboard(name: "Main", bundle: nil) var controller = UIViewController() switch shortcutType! { case .NewProject: controller = storyboard.instantiateViewController(withIdentifier: "NewProjectViewController") as! NewProjectViewController isHandled = true break case .List: controller = storyboard.instantiateViewController(withIdentifier: "ListViewController") as! ListViewController isHandled = true break case .Weigh: controller = storyboard.instantiateViewController(withIdentifier: "WeighViewController") as! WeighViewController isHandled = true break } if !isFirstLaunch { window?.rootViewController?.dismiss(animated: false, completion: nil) } window?.rootViewController?.present(controller, animated: true, completion: nil) return isHandled } 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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
4f480845e0b9e2c0c7f929d2105c41d7
35.583333
285
0.667198
6.174402
false
false
false
false
RobotsAndPencils/SwiftCharts
SwiftCharts/ChartPoint/ChartPoint.swift
2
596
// // ChartPoint.swift // swift_charts // // Created by ischuetz on 01/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartPoint: Equatable, CustomStringConvertible { public let x: ChartAxisValue public let y: ChartAxisValue required public init(x: ChartAxisValue, y: ChartAxisValue) { self.x = x self.y = y } public var description: String { return "\(self.x), \(self.y)" } } public func ==(lhs: ChartPoint, rhs: ChartPoint) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y }
apache-2.0
b54fd697575b2b70e4aa39c77e767f71
20.321429
64
0.619128
3.820513
false
false
false
false
jay0420/jigsaw
JKPinTu-Swift/Util/AppConstants.swift
1
828
// // AppConstants.swift // PingTu-swift // // Created by bingjie-macbookpro on 15/12/8. // Copyright © 2015年 Bingjie. All rights reserved. // import Foundation import UIKit import SwiftyBeaver //let jk_log = SwiftyBeaver.self let jacklog = SwiftyBeaver.self let SCREEN_BOUNDS = UIScreen.main.bounds let SCREEN_WIDTH = UIScreen.main.bounds.width let SCREEN_HEIGHT = UIScreen.main.bounds.height let STATUSBARHEIGHT = CGFloat(20) let TOPBARHEIGHT = CGFloat(44) let BOTTOMHEIGHT = CGFloat(49) /*! 生成随机数 x , start <= x < end - parameter start: start - parameter end: end - returns: arc4random */ func arc4randomInRange(_ start:Int ,to end:Int)->Int{ let count = UInt32(end - start) return Int(arc4random_uniform(count)) + start } public func JKLog(_ items: Any...){ print(items) }
mit
16b66dfed56a65199f9ba511e9c7e8b7
18.404762
53
0.705521
3.196078
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/Courses/CourseProgressViewController.swift
1
3951
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import BrightFutures import Common import CoreData import SafariServices import UIKit class CourseProgressViewController: UITableViewController { private var dataSource: CoreDataTableViewDataSourceWrapper<SectionProgress>! @IBOutlet private weak var courseProgressView: CourseProgressView! var course: Course! weak var scrollDelegate: CourseAreaScrollDelegate? override func viewDidLoad() { super.viewDidLoad() self.addRefreshControl() self.setupEmptyState() // setup table view data let request = SectionProgressHelper.FetchRequest.sectionProgresses(forCourse: course) let reuseIdentifier = R.reuseIdentifier.sectionProgressCell.identifier let resultsController = CoreDataHelper.createResultsController(request, sectionNameKeyPath: nil) self.dataSource = CoreDataTableViewDataSource.dataSource(for: self.tableView, fetchedResultsController: resultsController, cellReuseIdentifier: reuseIdentifier, delegate: self) self.refresh() self.configureCourseProgress() } func configureCourseProgress() { let fetchRequest = CourseProgressHelper.FetchRequest.courseProgress(forCourse: self.course) let progress = CoreDataHelper.viewContext.fetchSingle(fetchRequest).value self.courseProgressView.configure(for: progress) self.tableView.tableHeaderView?.isHidden = progress == nil self.tableView.resizeTableHeaderView() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { _ in self.tableView.resizeTableHeaderView() } } override func scrollViewDidScroll(_ scrollView: UIScrollView) { self.scrollDelegate?.scrollViewDidScroll(scrollView) } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.scrollDelegate?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.scrollDelegate?.scrollViewDidEndDecelerating(scrollView) } } extension CourseProgressViewController: CourseAreaViewController { var area: CourseArea { return .progress } func configure(for course: Course, with area: CourseArea, delegate: CourseAreaViewControllerDelegate) { assert(area == self.area) self.course = course self.scrollDelegate = delegate } } extension CourseProgressViewController: RefreshableViewController { func refreshingAction() -> Future<Void, XikoloError> { return CourseProgressHelper.syncProgress(forCourse: self.course).asVoid() } func didRefresh() { self.configureCourseProgress() } } extension CourseProgressViewController: CoreDataTableViewDataSourceDelegate { func configure(_ cell: SectionProgressCell, for object: SectionProgress) { cell.configure(for: object, showCourseTitle: self.course == nil) } } extension CourseProgressViewController: EmptyStateDataSource, EmptyStateDelegate { var emptyStateTitleText: String { return NSLocalizedString("empty-view.course-progress.title", comment: "title for empty course progress view") } func didTapOnEmptyStateView() { self.refresh() } func setupEmptyState() { self.tableView.emptyStateDataSource = self self.tableView.emptyStateDelegate = self self.tableView.tableFooterView = UIView() } }
gpl-3.0
d525aa97c3c1f9c26e91791cae0a1fe5
32.193277
117
0.699494
5.808824
false
true
false
false
Stitch7/Instapod
Instapod/Podcast/TableView/PodcastListEditingMode.swift
1
682
// // PodcastListEditingMode.swift // Instapod // // Created by Christopher Reitz on 06.09.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import Foundation enum PodcastListEditingMode: Int, EnumIteratable { case on case off var boolValue: Bool { switch self { case .on: return true case .off: return false } } mutating func nextValue() { let sorted = PodcastListEditingMode.values() let currentIndex = sorted.index(of: self)! var nextIndex = currentIndex + 1 if sorted.count <= nextIndex { nextIndex = 0 } self = sorted[nextIndex] } }
mit
d2eebbd2bb872d770d1a87628babfcfd
19.636364
60
0.604993
4.393548
false
false
false
false
SettlePad/client-iOS
SettlePad/TabBarController.swift
1
1642
// // TabBarController.swift // SettlePad // // Created by Rob Everhardt on 24/10/15. // Copyright © 2015 SettlePad. All rights reserved. // import UIKit protocol TabBarDelegate { func updateBadges() } class TabBarController: UITabBarController, TabBarDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. activeUser?.transactions.tabBarDelegate = self updateBadges() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateBadges() { //Update badgeCount let tabArray = tabBar.items as NSArray! let tabItem = tabArray.objectAtIndex(1) as! UITabBarItem dispatch_async(dispatch_get_main_queue()) { if let badgeCount = activeUser?.transactions.badgeCount { if badgeCount > 0 { tabItem.badgeValue = badgeCount.description } else { tabItem.badgeValue = nil } } else { tabItem.badgeValue = nil } } //Also update appBadge if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate, badgeCount = activeUser?.transactions.badgeCount { appDelegate.setBadgeNumber(badgeCount) } } /* // 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. } */ }
mit
134a79164ac6b307b1101630cc8bec37
24.640625
133
0.697136
4.423181
false
false
false
false
FreddyZeng/Charts
ChartsDemo-iOS/Swift/Demos/ScatterChartViewController.swift
1
4078
// // ScatterChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class ScatterChartViewController: DemoBaseViewController { @IBOutlet var chartView: ScatterChartView! @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. self.title = "Scatter Bar Chart" self.options = [.toggleValues, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.maxVisibleCount = 200 chartView.pinchZoomEnabled = true let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .top l.orientation = .vertical l.drawInside = false l.font = .systemFont(ofSize: 10, weight: .light) l.xOffset = 5 let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10, weight: .light) leftAxis.axisMinimum = 0 chartView.rightAxis.enabled = false let xAxis = chartView.xAxis xAxis.labelFont = .systemFont(ofSize: 10, weight: .light) sliderX.value = 45 sliderY.value = 100 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value + 1), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let values1 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i), y: val) } let values2 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i) + 0.33, y: val) } let values3 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i) + 0.66, y: val) } let set1 = ScatterChartDataSet(values: values1, label: "DS 1") set1.setScatterShape(.square) set1.setColor(ChartColorTemplates.colorful()[0]) set1.scatterShapeSize = 8 let set2 = ScatterChartDataSet(values: values2, label: "DS 2") set2.setScatterShape(.circle) set2.scatterShapeHoleColor = ChartColorTemplates.colorful()[3] set2.scatterShapeHoleRadius = 3.5 set2.setColor(ChartColorTemplates.colorful()[1]) set2.scatterShapeSize = 8 let set3 = ScatterChartDataSet(values: values3, label: "DS 3") set3.setScatterShape(.cross) set3.setColor(ChartColorTemplates.colorful()[2]) set3.scatterShapeSize = 8 let data = ScatterChartData(dataSets: [set1, set2, set3]) data.setValueFont(.systemFont(ofSize: 7, weight: .light)) chartView.data = data } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
614e8c2a1bf211766566d4629727d093
31.879032
79
0.580819
4.729698
false
false
false
false
KinoAndWorld/Meizhi-Swift
Meizhi-Swift/Scene/Gallary.swift
1
2125
// // Gallary.swift // Meizhi-Swift // // Created by kino on 14/11/25. // Copyright (c) 2014年 kino. All rights reserved. // import UIKit import Alamofire class Gallary: MeizhiObject { var imageUrl:String = "" var coverID:String = "" class func gallaryWithUrl(imageUrl:String, andCoverID coverID:String) ->Gallary { let gallary = Gallary() gallary.imageUrl = imageUrl gallary.coverID = coverID return gallary } } class GallaryManager : NSObject { // public func responseString(completionHandler: (String?, NSError?) -> Void) -> Self { class func fetchGallary(completeHandler:(Array<Gallary>) -> Void) -> Void { Alamofire.request(.GET, "http://meizhi.im", parameters: nil).responseString { (request, response, dataString, error) in var gallary:[Gallary] = [] if error != nil { println(error) completeHandler(gallary) return } // println(dataString) let htmlData:NSData? = dataString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) as NSData? let xPathParser = TFHpple(HTMLData: htmlData) if let element:Array = xPathParser.searchWithXPathQuery("//*[@class='box']/a"){ for aTagEle in element{ let aTagNode:TFHppleElement = aTagEle as TFHppleElement let coversPath = aTagNode.objectForKey("href") if let imageNode = aTagNode.firstChildWithTagName("img"){ if let imageUrl = imageNode.objectForKey("src") { gallary.append(Gallary.gallaryWithUrl(imageUrl, andCoverID: coversPath)) } } } println(gallary.count) completeHandler(gallary) } } // return gallary } }
apache-2.0
1577d89dd94ffda37489651e59e723c3
31.661538
125
0.525671
5.140436
false
false
false
false
mindbody/Conduit
Sources/Conduit/Networking/Serialization/HTTPRequestSerializer.swift
1
5690
// // HTTPRequestSerializer.swift // Conduit // // Created by John Hammerlund on 7/16/16. // Copyright © 2016 MINDBODY. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #elseif canImport(WatchKit) import WatchKit #endif private struct HTTPHeader { let name: String let value: String } /// An _Abstract_ base class for HTTP request serializers. /// /// Subclassing: Subclasses should override serializedRequestWith(request:bodyParameters:queryParameters) /// and MUST call super. open class HTTPRequestSerializer: RequestSerializer { // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 private static let acceptLanguageHeader: HTTPHeader = { func languageComponentFor(languageIdentifier: String, preferenceLevel: Float) -> String { return String(format: "\(languageIdentifier);q=%0.1g", preferenceLevel) } var languageComponents: [String] = [] var preferenceLevel: Float = 1 var preferredLanguageIterator = Locale.preferredLanguages.makeIterator() while let preferredLanguage = preferredLanguageIterator.next(), preferenceLevel >= 0.5 { languageComponents.append(languageComponentFor(languageIdentifier: preferredLanguage, preferenceLevel: preferenceLevel)) preferenceLevel -= 0.1 } return HTTPHeader(name: "Accept-Language", value: languageComponents.joined(separator: ", ")) }() // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 private static let userAgentHeader: HTTPHeader? = { let product: String let productVersion: String let platform: String? var deviceModel: String? var operatingSystemVersion: String? var deviceScale: String? if let executableName = Bundle.main.object(forInfoDictionaryKey: kCFBundleExecutableKey as String) as? String { product = executableName } else { product = Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String ?? "Unknown" } if let bundleVersionShort = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String { productVersion = bundleVersionShort } else { let versionKey = kCFBundleVersionKey as String productVersion = Bundle.main.object(forInfoDictionaryKey: versionKey) as? String ?? "Unknown" } #if os(iOS) platform = "iOS" deviceModel = UIDevice.current.model operatingSystemVersion = UIDevice.current.systemVersion deviceScale = String(format: "%0.2f", UIScreen.main.scale) #elseif os(watchOS) platform = "watchOS" deviceModel = WKInterfaceDevice.current().model operatingSystemVersion = WKInterfaceDevice.current().systemVersion deviceScale = String(format: "%0.2f", WKInterfaceDevice.current().screenScale) #elseif os(tvOS) platform = "tvOS" deviceModel = UIDevice.current.model operatingSystemVersion = UIDevice.current.systemVersion #elseif os(OSX) platform = "Mac OS X" operatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersionString #endif var headerValue: String if let platform = platform, let operatingSystemVersion = operatingSystemVersion { if let deviceModel = deviceModel { if let deviceScale = deviceScale { headerValue = "\(product)/\(productVersion) (\(deviceModel); \(platform) " + "\(operatingSystemVersion); Scale/\(deviceScale))" } else { headerValue = "\(product)/\(productVersion) (\(deviceModel); \(platform) \(operatingSystemVersion)" } } else { headerValue = "\(product)/\(productVersion) (\(platform) \(operatingSystemVersion)" } return HTTPHeader(name: "User-Agent", value: headerValue) } return nil }() /// The subset of HTTP verbs that will never have a request body. static let httpMethodsWithNoBody: Set<HTTPRequestBuilder.Method> = [.GET, .HEAD] /// Required request headers for HTTP transport according to the W3 spec public static let defaultHTTPHeaders: [(String, String)] = { return [HTTPRequestSerializer.acceptLanguageHeader, HTTPRequestSerializer.userAgentHeader].compactMap { header in guard let header = header else { return nil } return (header.name, header.value) } }() open func serialize(request: URLRequest, bodyParameters: Any? = nil) throws -> URLRequest { guard let httpMethod = request.httpMethod, request.url != nil else { throw RequestSerializerError.invalidURL } let httpMethodsWithNoBody = HTTPRequestSerializer.httpMethodsWithNoBody.map { $0.rawValue } if bodyParameters != nil && httpMethodsWithNoBody.contains(httpMethod) { throw RequestSerializerError.httpVerbDoesNotAllowBodyParameters } var mutableRequest = request let defaultHTTPHeaders = HTTPRequestSerializer.defaultHTTPHeaders for header in defaultHTTPHeaders { if mutableRequest.value(forHTTPHeaderField: header.0) == nil { mutableRequest.setValue(header.1, forHTTPHeaderField: header.0) } } return mutableRequest } }
apache-2.0
3d244d103ffe3cc57a13a4d9a217274d
38.506944
121
0.641589
5.496618
false
false
false
false
WilliamNi/SwiftXmlSerializable
XmlSerializableExample/Test.swift
1
2484
// // Test.swift // XmlSerializable // // Created by ixprt13 on 9/16/15. // Copyright © 2015 williamni. All rights reserved. // import Foundation struct InternalStruct: XmlSavable, XmlRetrievable{ var a:Int = 10 var b:String = "b" var c:Bool = true var d:Double = 20.20 var e:NSDate = NSDate() var optA:Int? = nil var optB:String? = "optB" } // //conforming XmlSerializable extension InternalStruct{ static func fromXmlElem(root:AEXMLElement)throws -> InternalStruct { var ret = InternalStruct() do{ ret.a = try Int.fromXmlElem(root["a"]) ret.b = try String.fromXmlElem(root["b"]) ret.c = try Bool.fromXmlElem(root["c"]) ret.d = try Double.fromXmlElem(root["d"]) ret.e = try NSDate.fromXmlElem(root["e"]) ret.optA = try (Int?).fromXmlElem(root["optA"]) ret.optB = try (String?).fromXmlElem(root["optB"]) } return ret } } class MyClass: XmlSavable, XmlRetrievable{ var internalStruct:InternalStruct var arr:[String] var dict:[String: Int] required init(){ internalStruct = InternalStruct() arr = [String]() dict = [:] } } // //conforming XmlSerializable extension MyClass{ static func fromXmlElem(root:AEXMLElement)throws -> Self { let ret = self.init() do{ ret.internalStruct = try InternalStruct.fromXmlElem(root["internalStruct"]) ret.arr = try [String].fromXmlElem(root["arr"]) ret.dict = try [String: Int].fromXmlElem(root["dict"]) } return ret } } func compare(lVal:MyClass, rVal:MyClass) -> Bool{ if lVal.internalStruct.a != rVal.internalStruct.a {return false} if lVal.internalStruct.b != rVal.internalStruct.b {return false} if lVal.internalStruct.c != rVal.internalStruct.c {return false} if lVal.internalStruct.d != rVal.internalStruct.d {return false} if (lVal.internalStruct.e.timeIntervalSince1970 - rVal.internalStruct.e.timeIntervalSince1970) > 0.01 {return false} if lVal.internalStruct.optA != rVal.internalStruct.optA {return false} if lVal.internalStruct.optB != rVal.internalStruct.optB {return false} for var i = 0; i < lVal.arr.count; i++ { if lVal.arr[i] != rVal.arr[i] {return false} } for (key, _) in lVal.dict { if lVal.dict[key] != rVal.dict[key] {return false} } return true }
mit
4034b9d10f3fd40a4b2c5e1c5eab83a8
27.872093
120
0.619815
3.83179
false
false
false
false
drichardson/SwiftyHex
SwiftyHex/Codec.swift
1
3934
// // Codec.swift // SwiftyHex // // Created by Doug Richardson on 8/25/15. // Copyright (c) 2015 Doug Richardson. All rights reserved. // import Foundation /** Encode a UInt8 sequence as a hexidecimal String. - parameter bytes: Byte sequence to encode. - parameter letterCase: Output uppercase or lowercase hex - returns: The hex encoded string. */ public func Encode<S : Sequence>(_ bytes : S, letterCase : LetterCase = .Lower) -> String where S.Iterator.Element == UInt8 { var result = String() EncodeByteSequence(bytes, outputStream: &result, letterCase: letterCase) return result } /** Decode a hexidecimal String to a [UInt8]. The input string must contain an even number valid characters (0-9, a-f, and A-F). - parameter str: String to decode. Should be characters 0-9, a-f, and A-F. - returns: (byte array, true) on success, ([], false) on failure due to invalid character or odd number of input characters. */ public func Decode(_ str : String) -> ([UInt8], Bool) { return DecodeUTF8Sequence(str.utf8) } /** Case to use to encode hexidecimal strings. - Upper: Encode string using upper case hex characters. - Lower: Encode string using lower case hex characters. */ public enum LetterCase { case Upper case Lower } /** Encode a UInt8 sequence to an output stream. - parameter bytes: Byte sequence to encode. - parameter outputStream: Destination for the encoded string. - parameter letterCase: Output uppercase or lowercase hex */ public func EncodeByteSequence<ByteSequence : Sequence, TargetStream : TextOutputStream> (_ bytes : ByteSequence, outputStream : inout TargetStream, letterCase : LetterCase) where ByteSequence.Iterator.Element == UInt8 { let table : [String] switch letterCase { case .Lower: table = lowercaseTable case .Upper: table = uppercaseTable } for b in bytes { let nibble1 = (b & 0b11110000) >> 4 let nibble2 = b & 0b00001111 outputStream.write(table[Int(nibble1)]) outputStream.write(table[Int(nibble2)]) } } /** Decode a sequence of hexidecimal ASCII/UTF-8 characters to a [UInt8]. The input string must contain an even number valid characters (0-9, a-f, and A-F). - parameter str: String to decode. Should be characters 0-9, a-f, and A-F. - returns: (byte array, true) on success, ([], false) on failure due to invalid character or odd number of input characters. */ public func DecodeUTF8Sequence<UTF8Sequence : Sequence> (_ sequence : UTF8Sequence) -> ([UInt8], Bool) where UTF8Sequence.Iterator.Element == UInt8 { // ASCII values let uppercaseA = UInt8(65) let uppercaseF = UInt8(70) let lowercaseA = UInt8(97) let lowercaseF = UInt8(102) let zero = UInt8(48) let nine = UInt8(57) var nibbles = [UInt8]() nibbles.reserveCapacity(2) var result = [UInt8]() for codeUnit in sequence { if codeUnit >= uppercaseA && codeUnit <= uppercaseF { nibbles.append(10 + codeUnit - uppercaseA) } else if codeUnit >= lowercaseA && codeUnit <= lowercaseF { nibbles.append(10 + codeUnit - lowercaseA) } else if codeUnit >= zero && codeUnit <= nine { nibbles.append(codeUnit - zero) } else { return ([], false) } if nibbles.count == 2 { let byte = (nibbles[0] << 4) | nibbles[1] result.append(byte) nibbles.removeAll(keepingCapacity: true) } } if nibbles.count != 0 { return ([], false) } return (result, true) } // Table to encode bytes with lowercase hexidecimal characters. private let lowercaseTable : [String] = [ "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f" ] // Table to encode bytes with uppercase hexidecimal characters. private let uppercaseTable : [String] = [ "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" ]
unlicense
414d5dc897cc0402fbd5e30ed977a8cd
30.98374
149
0.651246
3.853085
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-16/ImageMetalling-16/AppDelegate.swift
1
5107
// // AppDelegate.swift // ImageMetalling-16 // // Created by denis svinarchuk on 06.06.2018. // Copyright © 2018 ImageMetalling. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var controller:ViewController! { return (NSApplication.shared.keyWindow?.contentViewController as? ViewController) } func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application DispatchQueue.main.asyncAfter(deadline: .now() + 2) { guard self.controller != nil else { return } if self.controller.plane01GridView.mlsKind == .affine { self.affineItem.state = .on } else if self.controller.plane01GridView.mlsKind == .similarity { self.singularityItem.state = .on } else if self.controller.plane01GridView.mlsKind == .rigid { self.rigidItem.state = .on } if self.controller.plane01GridView.solverLang == .cpp { self.cpp.state = .on } else if self.controller.plane01GridView.solverLang == .metal { self.metal.state = .on } } } func applicationDidBecomeActive(_ notification: Notification) { } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @IBOutlet weak var affineItem: NSMenuItem! @IBOutlet weak var singularityItem: NSMenuItem! @IBOutlet weak var rigidItem: NSMenuItem! @IBOutlet weak var swift: NSMenuItem! @IBOutlet weak var cpp: NSMenuItem! @IBOutlet weak var metal: NSMenuItem! lazy var items: [NSMenuItem] = [self.affineItem, self.singularityItem, self.rigidItem] lazy var langItems: [NSMenuItem] = [self.swift, self.cpp, self.metal] @IBAction func reset(_ sender: NSMenuItem) { controller?.alphaSlider.floatValue = GridView.defaultSolverAlpha controller?.plane01GridView.reset() controller?.plane12GridView.reset() } @IBAction func toggleAffine(_ sender: NSMenuItem) { for m in items { m.state = .off } affineItem.state = .on controller?.plane01GridView.mlsKind = .affine } @IBAction func toggleSimilarity(_ sender: NSMenuItem) { for m in items { m.state = .off } singularityItem.state = .on controller?.plane01GridView.mlsKind = .similarity controller?.plane12GridView.mlsKind = .similarity } @IBAction func toggleRigid(_ sender: NSMenuItem) { for m in items { m.state = .off } rigidItem.state = .on controller?.plane01GridView.mlsKind = .rigid controller?.plane12GridView.mlsKind = .rigid } @IBAction func solveInMetal(_ sender: NSMenuItem) { for m in langItems { m.state = .off } metal.state = .on controller?.plane01GridView.solverLang = .metal controller?.plane12GridView.solverLang = .metal } @IBAction func solveInCpp(_ sender: NSMenuItem) { for m in langItems { m.state = .off } cpp.state = .on controller?.plane01GridView.solverLang = .cpp controller?.plane12GridView.solverLang = .cpp } @IBAction func pinEdges(_ sender: NSMenuItem) { controller?.plane01GridView.knotsGrid.pinEdges() controller?.plane12GridView.knotsGrid.pinEdges() } @IBAction func openFile(_ sender: NSMenuItem) { guard let controller = self.controller else { return } if openPanel.runModal() == NSApplication.ModalResponse.OK { if let url = openPanel.urls.first{ controller.imageFile = url } } } @IBAction func saveImage(_ sender: NSMenuItem) { guard let controller = self.controller else { return } let p = NSSavePanel() p.isExtensionHidden = false p.allowedFileTypes = [ "png", "jpg", "cr2", "tiff" ] p.nameFieldStringValue = "" if p.runModal() == NSApplication.ModalResponse.OK { if let url = p.url { controller.imageSavingFile = url } } } lazy var openPanel:NSOpenPanel = { let p = NSOpenPanel() p.canChooseFiles = true p.canChooseDirectories = false p.resolvesAliases = true p.isExtensionHidden = false p.allowedFileTypes = [ "png", "jpg", "cr2", "tiff", "orf" ] return p }() lazy var savePanel:NSSavePanel = { let p = NSSavePanel() p.isExtensionHidden = false p.allowedFileTypes = [ "png", "jpg", "cr2", "tiff" ] return p }() }
mit
c985328332b39c6a95d487c8a5ea509f
29.392857
91
0.577164
4.767507
false
false
false
false
xedin/swift
test/stdlib/Accelerate_vDSPBiquad.swift
2
10107
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var Accelerate_vDSPBiquadTests = TestSuite("Accelerate_vDSPBiquad") //===----------------------------------------------------------------------===// // // vDSP Biquad Filters // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { let n = 256 // low pass let b0 = 0.0001 let b1 = 0.001 let b2 = 0.0005 let a1 = -1.9795 let a2 = 0.98 let sections = vDSP_Length(1) Accelerate_vDSPBiquadTests.test("vDSP/BiquadNil") { let biquad = vDSP.Biquad(coefficients: [0.0], channelCount: 9999, sectionCount: 9999, ofType: Float.self) expectTrue(biquad == nil) } Accelerate_vDSPBiquadTests.test("vDSP/SingleChannelSinglePrecision") { let channels = vDSP_Length(1) let signal: [Float] = (0 ..< n).map { i in return sin(Float(i) * 0.1) + sin(Float(i) * 0.01) } var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], channelCount: sections, sectionCount: channels, ofType: Float.self)! var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], channelCount: sections, sectionCount: channels, ofType: Float.self)! var output = [Float](repeating: 0, count: n) // Legacy... var legacyOutput = [Float](repeating: -1, count: n) var delays = [Float](repeating: 0.0, count: Int(2 * sections) + 2) let setup = vDSP_biquad_CreateSetup([b0, b1, b2, a1, a2], sections)! for _ in 0 ... 3 { biquad.apply(input: signal, output: &output) let returnedOutput = returningBiquad.apply(input: signal) vDSP_biquad(setup, &delays, signal, 1, &legacyOutput, 1, vDSP_Length(n)) expectTrue(output.elementsEqual(legacyOutput)) expectTrue(output.elementsEqual(returnedOutput)) } } Accelerate_vDSPBiquadTests.test("vDSP/MultiChannelSinglePrecision") { let channelCount = vDSP_Length(2) let signal: [Float] = (0 ..< n).map { i in return sin(Float(i) * 0.1) + sin(Float(i) * 0.01) } var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], channelCount: channelCount, sectionCount: sections, ofType: Float.self)! var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], channelCount: channelCount, sectionCount: sections, ofType: Float.self)! var output = [Float](repeating: 0, count: n) // Legacy... var legacyOutput = [Float](repeating: -1, count: n) let setup = vDSP_biquadm_CreateSetup([b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], vDSP_Length(sections), vDSP_Length(channelCount))! for _ in 0 ... 3 { biquad.apply(input: signal, output: &output) let returnedOutput = returningBiquad.apply(input: signal) signal.withUnsafeBufferPointer { inputBuffer in let inputPointer = inputBuffer.baseAddress! legacyOutput.withUnsafeMutableBufferPointer { outputBuffer in let outputPointer = outputBuffer.baseAddress! let length = vDSP_Length(n) / channelCount var inputs: [UnsafePointer<Float>] = (0 ..< channelCount).map { i in return inputPointer.advanced(by: Int(i * length)) } var outputs: [UnsafeMutablePointer<Float>] = (0 ..< channelCount).map { i in return outputPointer.advanced(by: Int(i * length)) } vDSP_biquadm(setup, &inputs, 1, &outputs, 1, vDSP_Length(n) / channelCount) } } expectTrue(output.elementsEqual(legacyOutput)) expectTrue(output.elementsEqual(returnedOutput)) } } Accelerate_vDSPBiquadTests.test("vDSP/SingleChannelDoublePrecision") { let channels = vDSP_Length(1) let signal: [Double] = (0 ..< n).map { i in return sin(Double(i) * 0.1) + sin(Double(i) * 0.01) } var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], channelCount: sections, sectionCount: channels, ofType: Double.self)! var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], channelCount: sections, sectionCount: channels, ofType: Double.self)! var output = [Double](repeating: 0, count: n) // Legacy... var legacyOutput = [Double](repeating: -1, count: n) var delays = [Double](repeating: 0.0, count: Int(2 * sections) + 2) let setup = vDSP_biquad_CreateSetupD([b0, b1, b2, a1, a2], sections)! for _ in 0 ... 3 { biquad.apply(input: signal, output: &output) let returnedOutput = returningBiquad.apply(input: signal) vDSP_biquadD(setup, &delays, signal, 1, &legacyOutput, 1, vDSP_Length(n)) expectTrue(output.elementsEqual(legacyOutput)) expectTrue(output.elementsEqual(returnedOutput)) } } Accelerate_vDSPBiquadTests.test("vDSP/MultiChannelDoublePrecision") { let channelCount = vDSP_Length(2) let signal: [Double] = (0 ..< n).map { i in return sin(Double(i) * 0.1) + sin(Double(i) * 0.01) } var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], channelCount: channelCount, sectionCount: sections, ofType: Double.self)! var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], channelCount: channelCount, sectionCount: sections, ofType: Double.self)! var output = [Double](repeating: 0, count: n) // Legacy... var legacyOutput = [Double](repeating: -1, count: n) let setup = vDSP_biquadm_CreateSetupD([b0, b1, b2, a1, a2, b0, b1, b2, a1, a2], vDSP_Length(sections), vDSP_Length(channelCount))! for _ in 0 ... 3 { biquad.apply(input: signal, output: &output) let returnedOutput = returningBiquad.apply(input: signal) signal.withUnsafeBufferPointer { inputBuffer in let inputPointer = inputBuffer.baseAddress! legacyOutput.withUnsafeMutableBufferPointer { outputBuffer in let outputPointer = outputBuffer.baseAddress! let length = vDSP_Length(n) / channelCount var inputs: [UnsafePointer<Double>] = (0 ..< channelCount).map { i in return inputPointer.advanced(by: Int(i * length)) } var outputs: [UnsafeMutablePointer<Double>] = (0 ..< channelCount).map { i in return outputPointer.advanced(by: Int(i * length)) } vDSP_biquadmD(setup, &inputs, 1, &outputs, 1, vDSP_Length(n) / channelCount) } } expectTrue(output.elementsEqual(legacyOutput)) expectTrue(output.elementsEqual(returnedOutput)) } } } runAllTests()
apache-2.0
d1f120a508610be9809feaacab0fc447
37.576336
97
0.419115
5.448518
false
true
false
false
ZhaoBingDong/CYPhotosLibrary
CYPhotoKit/Model/CYPhotosAsset.swift
1
3196
// // CYPhotosAsset.swift // CYPhotosKit // // Created by 董招兵 on 2017/8/6. // Copyright © 2017年 大兵布莱恩特. All rights reserved. // import UIKit import Photos public typealias CYPhotosAsset = PHAsset private var SelectKey : String = "isSelect" public extension CYPhotosAsset { public var isSelect : Bool { set { objc_setAssociatedObject(self, &SelectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } get { if let select = objc_getAssociatedObject(self, &SelectKey) as? Bool { return select } return false } } public var originalImg : UIImage { get { let data = self.tuple.data return UIImage(data: data) ?? UIImage() } } private var tuple : (data : Data , info : [AnyHashable : Any]?) { var imageData = Data() var dict : [AnyHashable : Any]? self.imageManager.requestImageData(for: self, options: self.requestOption) { (data, dataUTI, orientation, info) in dict = info if let da = data { imageData = da } } return (imageData,dict) } public var imageData : Data? { get { if CYPhotosManager.default.isFullMode { return UIImageJPEGRepresentation(self.originalImg,0.5) } else { return UIImageJPEGRepresentation(self.thumbnail,1.0) } } } public var thumbnail : UIImage { var thumbnail = UIImage() self.imageManager.requestImage(for: self, targetSize: CGSize.init(width: 250.0, height: 250.0), contentMode: .aspectFill, options: self.requestOption) { (image, info) in thumbnail = image ?? UIImage() } return thumbnail } public var imageURL : URL? { get { if let info = self.tuple.info { return info["PHImageFileURLKey"] as? URL } else { return nil } } } public var originalImgLength : Double { let tuple = self.tuple let info = tuple.info let data = tuple.data guard info != nil else { return 0.0 } guard let obj = (info!["PHImageFileDataKey"] as? NSObject) else { return Double(data.count) } guard !obj.isKind(of: NSData.self) else { return Double((obj as! NSData).length) } guard let dataLength = obj.value(forKey: "dataLength") as? Double else { return Double(data.count) } return dataLength } private var requestOption : PHImageRequestOptions { get { let option = PHImageRequestOptions() option.isSynchronous = true option.resizeMode = .fast option.deliveryMode = .highQualityFormat return option } } private var imageManager : PHImageManager { return PHImageManager.default() } }
apache-2.0
a19799b9c391e0be227deeea42bf6c49
28.672897
177
0.535433
4.731744
false
false
false
false
roambotics/swift
test/SILGen/ternary_expr.swift
2
2415
// RUN: %target-swift-emit-silgen %s | %FileCheck %s func fizzbuzz(i: Int) -> String { return i % 3 == 0 ? "fizz" : i % 5 == 0 ? "buzz" : "\(i)" // CHECK: cond_br {{%.*}}, [[OUTER_TRUE:bb[0-9]+]], [[OUTER_FALSE:bb[0-9]+]] // CHECK: [[OUTER_TRUE]]: // CHECK: br [[OUTER_CONT:bb[0-9]+]] // CHECK: [[OUTER_FALSE]]: // CHECK: cond_br {{%.*}}, [[INNER_TRUE:bb[0-9]+]], [[INNER_FALSE:bb[0-9]+]] // CHECK: [[INNER_TRUE]]: // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_FALSE]]: // CHECK: function_ref {{.*}}stringInterpolation // CHECK: br [[INNER_CONT]] // CHECK: [[INNER_CONT]]({{.*}}): // CHECK: br [[OUTER_CONT]] // CHECK: [[OUTER_CONT]]({{.*}}): // CHECK: return } protocol AddressOnly {} struct A : AddressOnly {} struct B : AddressOnly {} func consumeAddressOnly(_: AddressOnly) {} // CHECK: sil hidden [ossa] @$s12ternary_expr010addr_only_A2_1{{[_0-9a-zA-Z]*}}F func addr_only_ternary_1(x: Bool) -> AddressOnly { // CHECK: bb0([[RET:%.*]] : $*any AddressOnly, {{.*}}): // CHECK: [[a:%[0-9]+]] = alloc_box ${ var any AddressOnly }, var, name "a" // CHECK: [[a_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[a]] // CHECK: [[PBa:%.*]] = project_box [[a_LIFETIME]] var a : AddressOnly = A() // CHECK: [[b:%[0-9]+]] = alloc_box ${ var any AddressOnly }, var, name "b" // CHECK: [[b_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[b]] // CHECK: [[PBb:%.*]] = project_box [[b_LIFETIME]] var b : AddressOnly = B() // CHECK: cond_br {{%.*}}, [[TRUE:bb[0-9]+]], [[FALSE:bb[0-9]+]] // CHECK: [[TRUE]]: // CHECK: [[READa:%.*]] = begin_access [read] [unknown] [[PBa]] // CHECK: copy_addr [[READa]] to [init] [[RET]] // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[FALSE]]: // CHECK: [[READb:%.*]] = begin_access [read] [unknown] [[PBb]] // CHECK: copy_addr [[READb]] to [init] [[RET]] // CHECK: br [[CONT]] return x ? a : b } // <rdar://problem/31595572> - crash when conditional expression is an // lvalue of IUO type // CHECK-LABEL: sil hidden [ossa] @$s12ternary_expr011iuo_lvalue_A01xSiSbSgz_tF : $@convention(thin) (@inout Optional<Bool>) -> Int // CHECK: [[IUO_BOOL_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*Optional<Bool> // CHECK: [[IUO_BOOL:%.*]] = load [trivial] [[IUO_BOOL_ADDR]] : $*Optional<Bool> // CHECK: switch_enum [[IUO_BOOL]] func iuo_lvalue_ternary(x: inout Bool!) -> Int { return x ? 1 : 0 }
apache-2.0
cf905a3cee09d1307b4e074b6a72ba21
36.153846
131
0.548654
3.014981
false
false
false
false
MichaelSelsky/TheBeatingAtTheGates
Carthage/Checkouts/VirtualGameController/Samples/Peripheral_OSX/vgcPeripheral_OSX/ViewController.swift
1
3533
// // ViewController.swift // vgcPeripheral_OSX // // Created by Rob Reuss on 10/17/15. // Copyright © 2015 Rob Reuss. All rights reserved. // import Cocoa import GameController import VirtualGameController let peripheral = VgcManager.peripheral let elements = VgcManager.elements class ViewController: NSViewController { @IBOutlet weak var playerIndexLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() // This is triggered by the developer on the Central side, by setting the playerIndex value on the controller, triggering a // system message being sent over the wire to this Peripheral, resulting in this notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotPlayerIndex:", name: VgcNewPlayerIndexNotification, object: nil) VgcManager.startAs(.Peripheral, appIdentifier: "vgc", customElements: CustomElements(), customMappings: CustomMappings(), includesPeerToPeer: true) // REQUIRED: Set device info peripheral.deviceInfo = DeviceInfo(deviceUID: NSUUID().UUIDString, vendorName: "", attachedToDevice: false, profileType: .ExtendedGamepad, controllerType: .Software, supportsMotion: false) print(peripheral.deviceInfo) VgcManager.peripheral.browseForServices() NSNotificationCenter.defaultCenter().addObserver(self, selector: "foundService:", name: VgcPeripheralFoundService, object: nil) } @objc func foundService(notification: NSNotification) { if VgcManager.peripheral.haveConnectionToCentral == true { return } let service = notification.object as! VgcService vgcLogDebug("Automatically connecting to service \(service.fullName) because Central-selecting functionality is not implemented in this project") VgcManager.peripheral.connectToService(service) } override func viewDidAppear() { super.viewDidAppear() self.view.window?.title = VgcManager.appRole.description } func sendButtonPush(element: Element) { element.value = 1 peripheral.sendElementState(element) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { element.value = 0 peripheral.sendElementState(element) } } @objc func gotPlayerIndex(notification: NSNotification) { let playerIndex: Int = notification.object as! Int playerIndexLabel.stringValue = "Player: \(playerIndex + 1)" } @IBAction func rightShoulderPush(sender: NSButton) { sendButtonPush(elements.rightShoulder) } @IBAction func leftShoulderPush(sender: NSButton) { sendButtonPush(elements.leftShoulder) } @IBAction func rightTriggerPush(sender: NSButton) { sendButtonPush(elements.rightTrigger) } @IBAction func leftTriggerPush(sender: NSButton) { sendButtonPush(elements.leftTrigger) } @IBAction func yPush(sender: NSButton) { sendButtonPush(elements.buttonY) } @IBAction func xPush(sender: NSButton) { sendButtonPush(elements.buttonX) } @IBAction func aPush(sender: NSButton) { sendButtonPush(elements.buttonA) } @IBAction func bPush(sender: NSButton) { sendButtonPush(elements.buttonB) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
7a201be1916ce68eb0526dc9a6b68ba9
37.391304
196
0.69564
4.960674
false
false
false
false
practicalswift/swift
test/Frontend/dump-parse.swift
5
3278
// RUN: not %target-swift-frontend -dump-parse %s 2>&1 | %FileCheck %s // RUN: not %target-swift-frontend -dump-ast %s | %FileCheck %s -check-prefix=CHECK-AST // CHECK-LABEL: (func_decl{{.*}}"foo(_:)" // CHECK-AST-LABEL: (func_decl{{.*}}"foo(_:)" func foo(_ n: Int) -> Int { // CHECK: (brace_stmt // CHECK: (return_stmt // CHECK: (integer_literal_expr type='<null>' value=42 {{.*}}))) // CHECK-AST: (brace_stmt // CHECK-AST: (return_stmt // CHECK-AST: (integer_literal_expr type='{{[^']+}}' {{.*}} value=42 {{.*}}) return 42 } // -dump-parse should print an AST even though this code is invalid. // CHECK-LABEL: (func_decl{{.*}}"bar()" // CHECK-AST-LABEL: (func_decl{{.*}}"bar()" func bar() { // CHECK: (brace_stmt // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo // CHECK-AST: (brace_stmt // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo // CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo foo foo foo } // CHECK-LABEL: (enum_decl{{.*}}trailing_semi "TrailingSemi" enum TrailingSemi { // CHECK-LABEL: (enum_case_decl{{.*}}trailing_semi // CHECK-NOT: (enum_element_decl{{.*}}trailing_semi // CHECK: (enum_element_decl{{.*}}"A") // CHECK: (enum_element_decl{{.*}}"B") case A,B; // CHECK-LABEL: (subscript_decl{{.*}}trailing_semi // CHECK-NOT: (func_decl{{.*}}trailing_semi 'anonname={{.*}}' get_for=subscript(_:) // CHECK: (accessor_decl{{.*}}'anonname={{.*}}' get_for=subscript(_:) subscript(x: Int) -> Int { // CHECK-LABEL: (pattern_binding_decl{{.*}}trailing_semi // CHECK-NOT: (var_decl{{.*}}trailing_semi "y" // CHECK: (var_decl{{.*}}"y" var y = 1; // CHECK-LABEL: (sequence_expr {{.*}} trailing_semi y += 1; // CHECK-LABEL: (return_stmt{{.*}}trailing_semi return y; }; }; // The substitution map for a declref should be relatively unobtrustive. // CHECK-AST-LABEL: (func_decl{{.*}}"generic(_:)" <T : Hashable> interface type='<T where T : Hashable> (T) -> ()' access=internal captures=(<generic> ) func generic<T: Hashable>(_: T) {} // CHECK-AST: (pattern_binding_decl // CHECK-AST: (declref_expr type='(Int) -> ()' location={{.*}} range={{.*}} decl=main.(file).generic@{{.*}} [with (substitution_map generic_signature=<T where T : Hashable> (substitution T -> Int))] function_ref=unapplied)) let _: (Int) -> () = generic // Closures should be marked as escaping or not. func escaping(_: @escaping (Int) -> Int) {} escaping({ $0 }) // CHECK-AST: (declref_expr type='(@escaping (Int) -> Int) -> ()' // CHECK-AST-NEXT: (paren_expr // CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=0 escaping single-expression func nonescaping(_: (Int) -> Int) {} nonescaping({ $0 }) // CHECK-AST: (declref_expr type='((Int) -> Int) -> ()' // CHECK-AST-NEXT: (paren_expr // CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=1 single-expression
apache-2.0
5efc4d9f2374b2260621046aedb2b48f
42.706667
231
0.576876
3.382869
false
false
false
false
practicalswift/swift
test/decl/init/failable.swift
29
8375
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation struct S0 { init!(int: Int) { } init! (uint: UInt) { } init !(float: Float) { } init?(string: String) { } init ?(double: Double) { } init ? (char: Character) { } } struct S1<T> { init?(value: T) { } } class DuplicateDecls { init!() { } // expected-note{{'init()' previously declared here}} init?() { } // expected-error{{invalid redeclaration of 'init()'}} init!(string: String) { } // expected-note{{'init(string:)' previously declared here}} init(string: String) { } // expected-error{{invalid redeclaration of 'init(string:)'}} init(double: Double) { } // expected-note{{'init(double:)' previously declared here}} init?(double: Double) { } // expected-error{{invalid redeclaration of 'init(double:)'}} } // Construct via a failable initializer. func testConstruction(_ i: Int, s: String) { let s0Opt = S0(string: s) assert(s0Opt != nil) var _: S0 = s0Opt // expected-error{{value of optional type 'S0?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let s0IUO = S0(int: i) assert(s0IUO != nil) _ = s0IUO } // ---------------------------------------------------------------------------- // Superclass initializer chaining // ---------------------------------------------------------------------------- class Super { init?(fail: String) { } init!(failIUO: String) { } init() { } // expected-note 2{{non-failable initializer 'init()' overridden here}} } class Sub : Super { override init() { super.init() } // okay, never fails init(nonfail: Int) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} super.init(fail: "boom") // expected-error{{a non-failable initializer cannot chain to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } convenience init(forceNonfail: Int) { self.init(nonfail: forceNonfail)! // expected-error{{cannot force unwrap value of non-optional type 'Sub'}} {{37-38=}} } init(nonfail2: Int) { // okay, traps on nil super.init(failIUO: "boom") } init(nonfail3: Int) { super.init(fail: "boom")! } override init?(fail: String) { super.init(fail: fail) // okay, propagates ? } init?(fail2: String) { // okay, propagates ! as ? super.init(failIUO: fail2) } init?(fail3: String) { // okay, can introduce its own failure super.init() } override init!(failIUO: String) { super.init(failIUO: failIUO) // okay, propagates ! } init!(failIUO2: String) { // okay, propagates ? as ! super.init(fail: failIUO2) } init!(failIUO3: String) { // okay, can introduce its own failure super.init() } } // ---------------------------------------------------------------------------- // Initializer delegation // ---------------------------------------------------------------------------- extension Super { convenience init(convenienceNonFailNonFail: String) { // okay, non-failable self.init() } convenience init(convenienceNonFailFail: String) { // expected-note{{propagate the failure with 'init?'}}{{19-19=?}} self.init(fail: convenienceNonFailFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{44-44=!}} } convenience init(convenienceNonFailFailForce: String) { self.init(fail: convenienceNonFailFailForce)! } convenience init(convenienceNonFailFailIUO: String) { // okay, trap on failure self.init(failIUO: convenienceNonFailFailIUO) } convenience init?(convenienceFailNonFail: String) { self.init() // okay, can introduce its own failure } convenience init?(convenienceFailFail: String) { self.init(fail: convenienceFailFail) // okay, propagates ? } convenience init?(convenienceFailFailIUO: String) { // okay, propagates ! as ? self.init(failIUO: convenienceFailFailIUO) } convenience init!(convenienceFailIUONonFail: String) { self.init() // okay, can introduce its own failure } convenience init!(convenienceFailIUOFail: String) { self.init(fail: convenienceFailIUOFail) // okay, propagates ? as ! } convenience init!(convenienceFailIUOFailIUO: String) { // okay, propagates ! self.init(failIUO: convenienceFailIUOFailIUO) } } struct SomeStruct { init(nonFail: Int) { // expected-note{{propagate the failure with 'init?'}}{{8-8=?}} self.init(fail: nonFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } init(nonFail2: Int) { self.init(fail: nonFail2)! } init?(fail: Int) {} } // ---------------------------------------------------------------------------- // Initializer overriding // ---------------------------------------------------------------------------- class Sub2 : Super { override init!(fail: String) { // okay to change ? to ! super.init(fail: fail) } override init?(failIUO: String) { // okay to change ! to ? super.init(failIUO: failIUO) } override init() { super.init() } // no change } // Dropping optionality class Sub3 : Super { override init(fail: String) { // okay, strengthened result type super.init() } override init(failIUO: String) { // okay, strengthened result type super.init() } override init() { } // no change } // Adding optionality class Sub4 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init?() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } class Sub5 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init!() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } // ---------------------------------------------------------------------------- // Initializer conformances // ---------------------------------------------------------------------------- protocol P1 { init(string: String) } @objc protocol P1_objc { init(string: String) } protocol P2 { init?(fail: String) } protocol P3 { init!(failIUO: String) } class C1a : P1 { required init?(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} } class C1b : P1 { required init!(string: String) { } // okay } class C1b_objc : P1_objc { @objc required init!(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' in Objective-C protocol cannot be satisfied by a failable initializer ('init!')}} } class C1c { required init?(string: String) { } // expected-note {{'init(string:)' declared here}} } extension C1c: P1 {} // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} class C2a : P2 { required init(fail: String) { } // okay to remove failability } class C2b : P2 { required init?(fail: String) { } // okay, ? matches } class C2c : P2 { required init!(fail: String) { } // okay to satisfy init? with init! } class C3a : P3 { required init(failIUO: String) { } // okay to remove failability } class C3b : P3 { required init?(failIUO: String) { } // okay to satisfy ! with ? } class C3c : P3 { required init!(failIUO: String) { } // okay, ! matches } // ---------------------------------------------------------------------------- // Initiating failure // ---------------------------------------------------------------------------- struct InitiateFailureS { init(string: String) { // expected-note{{use 'init?' to make the initializer 'init(string:)' failable}}{{7-7=?}} return (nil) // expected-error{{only a failable initializer can return 'nil'}} } init(int: Int) { return 0 // expected-error{{'nil' is the only return value permitted in an initializer}} } init?(double: Double) { return nil // ok } init!(char: Character) { return nil // ok } }
apache-2.0
921589316678c374ab136af3d09c04ec
28.489437
196
0.599403
3.944889
false
false
false
false
KevinGong2013/Printer
Sources/Printer/Ticket/Ticket.swift
1
901
// // Ticket.swift // Ticket // // Created by gix on 2019/6/30. // Copyright © 2019 gix. All rights reserved. // import Foundation public struct Ticket { public var feedLinesOnTail: UInt8 = 3 public var feedLinesOnHead: UInt8 = 0 private var blocks = [Block]() public init(_ blocks: Block...) { self.blocks = blocks } public mutating func add(block: Block) { blocks.append(block) } public func data(using encoding: String.Encoding) -> [Data] { var ds = blocks.map { Data.reset + $0.data(using: encoding) } if feedLinesOnHead > 0 { ds.insert(Data(esc_pos: .printAndFeed(lines: feedLinesOnHead)), at: 0) } if feedLinesOnTail > 0 { ds.append(Data(esc_pos: .printAndFeed(lines: feedLinesOnTail))) } return ds } }
apache-2.0
6fd4641d69a8565c5b7208f379bb5201
21.5
82
0.56
3.947368
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Scenes/Log In/LogInViewController.swift
1
5007
// // Created by Maxim Pervushin on 22/01/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit class LogInViewController: ThemedViewController { // MARK: LogInViewController @IB @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var containerToBottomConstraint: NSLayoutConstraint! @IBAction func logInButtonAction(sender: AnyObject) { if let username = userNameTextField.text, password = passwordTextField.text { App.logInWithUsername(username, password: password, block: { success, error in if let error = error { self.showError(error) } if success { self.completionHandler?() } }) } } @IBAction func signUpButtonAction(sender: AnyObject) { performSegueWithIdentifier("ShowSignUp", sender: self) } @IBAction func forgotPasswordButtonAction(sender: AnyObject) { let alertController = UIAlertController(title: "Reset Password", message: "Please enter the email address for your account.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in if let textField = alertController.textFields?.first, let email = textField.text { App.resetPasswordWithUsername(email) { success, error in if let error = error { self.showError(error) } } } })) alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) alertController.addTextFieldWithConfigurationHandler(){ textField in textField.placeholder = "Email" } presentViewController(alertController, animated: true, completion: nil) } @IBAction func cancelButtonAction(sender: AnyObject) { if userNameTextField.isFirstResponder() { userNameTextField.resignFirstResponder() } if passwordTextField.isFirstResponder() { passwordTextField.resignFirstResponder() } completionHandler?() } // MARK: LogInViewController var completionHandler: (Void -> Void)? private func showError(error: NSError) { let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } private func setContainerBottomOffset(offset: CGFloat) { if !isViewLoaded() { return } view.layoutIfNeeded() containerToBottomConstraint?.constant = offset UIView.animateWithDuration(0.5, animations: { self.view.layoutIfNeeded() }) } private func keyboardWillShowNotification(notification: NSNotification) { guard let userInfo = notification.userInfo, let endFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return } setContainerBottomOffset(endFrameValue.CGRectValue().height - 80) } private func keyboardWillHideNotification(notification: NSNotification) { setContainerBottomOffset(0) } private func subscribe() { NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillShowNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: keyboardWillShowNotification) NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillHideNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: keyboardWillHideNotification) } private func unsubscribe() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } private func commonInit() { subscribe() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { unsubscribe() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let signUpViewController = segue.destinationViewController as? SignUpViewController { signUpViewController.completionHandler = { self.dismissViewControllerAnimated(true, completion: nil) } } super.prepareForSegue(segue, sender: sender) } }
mit
f19ef1e751cde8f87905e3554c38edc6
34.510638
187
0.656281
5.911452
false
false
false
false
Jnosh/swift
test/Constraints/assignment.swift
23
1396
// RUN: %target-typecheck-verify-swift struct X { } struct Y { } struct WithOverloadedSubscript { subscript(i: Int) -> X { get {} set {} } subscript(i: Int) -> Y { get {} set {} } } func test_assign() { var a = WithOverloadedSubscript() a[0] = X() a[0] = Y() } var i: X var j: X var f: Y func getXY() -> (X, Y) {} var ift : (X, Y) var ovl = WithOverloadedSubscript() var slice: [X] i = j (i, f) = getXY() (i, f) = ift (i, f) = (i, f) (ovl[0], ovl[0]) = ift (ovl[0], ovl[0]) = (i, f) (_, ovl[0]) = (i, f) (ovl[0], _) = (i, f) _ = (i, f) slice[7] = i slice[7] = f // expected-error{{cannot assign value of type 'Y' to type 'X'}} slice[7] = _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} func value(_ x: Int) {} func value2(_ x: inout Int) {} value2(&_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} value(_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/23798944> = vs. == in Swift if string character count statement causes segmentation fault func f23798944() { let s = "" if s.characters.count = 0 { // expected-error {{cannot assign to property: 'count' is a get-only property}} } } .sr_3506 = 0 // expected-error {{reference to member 'sr_3506' cannot be resolved without a contextual type}}
apache-2.0
1ee056269f090fdc4ad0c757a182b149
22.283333
109
0.603868
2.878351
false
false
false
false
boolkybear/iOS-Challenge
CatViewer/CatViewer/RatingsController.swift
1
4637
// // RatingsController.swift // CatViewer // // Created by Boolky Bear on 8/2/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import UIKit import JLToast class RatingsController: UITableViewController { var fetchedResultsController: NSFetchedResultsController? = nil override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() if let mainContext = AppDelegate.mainContext() { let model = mainContext.managedObjectModel() if let rateFetchRequest = model.fetchRequestFromTemplateWithName("Rates", substitutionVariables: [ NSObject : AnyObject ]() ) { rateFetchRequest.sortDescriptors = [ NSSortDescriptor(key: "rate", ascending: false) ] self.fetchedResultsController = NSFetchedResultsController(fetchRequest: rateFetchRequest, managedObjectContext: mainContext, sectionNameKeyPath: nil, cacheName: nil) self.fetchedResultsController?.delegate = self self.fetchedResultsController?.performFetch(nil) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension RatingsController { // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return self.fetchedResultsController?.sections?.count ?? 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if let sectionInfo = self.fetchedResultsController?.sections?[section] as? NSFetchedResultsSectionInfo { return sectionInfo.numberOfObjects } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("rateCell", forIndexPath: indexPath) as RateCell // Configure the cell... cell.rate = self.fetchedResultsController?.objectAtIndexPath(indexPath) as? Rate return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 if let rate = self.fetchedResultsController?.objectAtIndexPath(indexPath) as? Rate { if let context = rate.managedObjectContext { context.deleteObject(rate) if !context.save(nil) { // TODO: log error JLToast.makeText(NSLocalizedString("Error deleting rating", comment: "DB Error")) } } } } 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 NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. if segue.identifier == "ViewerPushSegue" { if let cell = sender as? RateCell { let viewerController = segue.destinationViewController as ViewerController viewerController.cat = cell.rate?.cat } } } } extension FavouriteController: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(controller: NSFetchedResultsController) { self.fetchedResultsController?.performFetch(nil) self.tableView?.reloadData() } }
mit
5074fbeb0c8dc189259dba635c447efe
30.760274
170
0.748113
4.637
false
false
false
false
stuffrabbit/SwiftCoAP
SwiftCoAP_Library/SCClient.swift
2
19382
// // SCClient.swift // SwiftCoAP // // Created by Wojtek Kordylewski on 03.05.15. // Copyright (c) 2015 Wojtek Kordylewski. All rights reserved. // import UIKit //MARK: //MARK: SC Client Delegate Protocol declaration @objc protocol SCClientDelegate { //Tells the delegate that a valid CoAP message was received func swiftCoapClient(_ client: SCClient, didReceiveMessage message: SCMessage) //Tells the delegate that an error occured during or before transmission (refer to the "SCClientErrorCode" Enum) @objc optional func swiftCoapClient(_ client: SCClient, didFailWithError error: NSError) //Tells the delegate that the respective message was sent. The property "number" indicates the amount of (re-)transmission attempts @objc optional func swiftCoapClient(_ client: SCClient, didSendMessage message: SCMessage, number: Int) } //MARK: //MARK: SC Client Error Code Enumeration enum SCClientErrorCode: Int { case transportLayerSendError, messageInvalidForSendingError, receivedInvalidMessageError, noResponseExpectedError, proxyingError func descriptionString() -> String { switch self { case .transportLayerSendError: return "Failed to send data via the given Transport Layer" case .messageInvalidForSendingError: return "CoAP-Message is not valid" case .receivedInvalidMessageError: return "Data received was not a valid CoAP Message" case .noResponseExpectedError: return "The recipient does not respond" case .proxyingError: return "HTTP-URL Request could not be sent" } } } //MARK: //MARK: SC Client IMPLEMENTATION class SCClient: NSObject { //MARK: Constants and Properties //CONSTANTS let kMaxObserveOptionValue: UInt = 8388608 //INTERNAL PROPERTIES (allowed to modify) weak var delegate: SCClientDelegate? var sendToken = true //If true, a token with 4-8 Bytes is sent var autoBlock1SZX: UInt? = 2 { didSet { if let newValue = autoBlock1SZX { autoBlock1SZX = min(6, newValue) } } } //If not nil, Block1 transfer will be used automatically when the payload size exceeds the value 2^(autoBlock1SZX + 4). Valid Values: 0-6. var httpProxyingData: (hostName: String, port: UInt16)? //If not nil, all messages will be sent via http to the given proxy address var cachingActive = false //Activates caching var disableRetransmissions = false //READ-ONLY PROPERTIES fileprivate (set) var isMessageInTransmission = false //Indicates whether a message is in transmission and/or responses are still expected (e.g. separate, block, observe) //PRIVATE PROPERTIES fileprivate var transportLayerObject: SCCoAPTransportLayerProtocol! fileprivate var transmissionTimer: Timer! fileprivate var messageInTransmission: SCMessage! fileprivate var currentMessageId: UInt16 = UInt16(arc4random_uniform(0xFFFF) &+ 1) fileprivate var retransmissionCounter = 0 fileprivate var currentTransmitWait = 0.0 fileprivate var recentNotificationInfo: (Date, UInt)! lazy fileprivate var cachedMessagePairs = [SCMessage : SCMessage]() //MARK: Internal Methods (allowed to use) init(delegate: SCClientDelegate?, transportLayerObject: SCCoAPTransportLayerProtocol = SCCoAPUDPTransportLayer()) { self.delegate = delegate super.init() self.transportLayerObject = transportLayerObject self.transportLayerObject.transportLayerDelegate = self } func sendCoAPMessage(_ message: SCMessage, hostName: String, port: UInt16) { currentMessageId = (currentMessageId % 0xFFFF) + 1 message.hostName = hostName message.port = port message.messageId = currentMessageId message.timeStamp = Date() messageInTransmission = message if sendToken { message.token = UInt64(arc4random_uniform(0xFFFFFFFF) + 1) + (UInt64(arc4random_uniform(0xFFFFFFFF) + 1) << 32) } if cachingActive && message.code == SCCodeValue(classValue: 0, detailValue: 01) { for cachedMessage in cachedMessagePairs.keys { if cachedMessage.equalForCachingWithMessage(message) { if cachedMessage.isFresh() { if message.options[SCOption.observe.rawValue] == nil { cachedMessage.options[SCOption.observe.rawValue] = nil } delegate?.swiftCoapClient(self, didReceiveMessage: cachedMessagePairs[cachedMessage]!) handleBlock2WithMessage(cachedMessagePairs[cachedMessage]!) return } else { cachedMessagePairs[cachedMessage] = nil break } } } } if httpProxyingData != nil { sendHttpMessageFromCoAPMessage(message) } else { if message.blockBody == nil, let autoB1SZX = autoBlock1SZX { let fixedByteSize = pow(2, Double(autoB1SZX) + 4) if let payload = message.payload { let blocksCount = ceil(Double(payload.count) / fixedByteSize) if blocksCount > 1 { message.blockBody = payload let blockValue = 8 + UInt(autoB1SZX) sendBlock1MessageForCurrentContext(payload: payload.subdata(in: (0 ..< Int(fixedByteSize))), blockValue: blockValue) return } } } initiateSending() } } // Cancels observe directly, sending the previous message with an Observe-Option Value of 1. Only effective, if the previous message initiated a registration as observer with the respective server. To cancel observer indirectly (forget about the current state) call "closeTransmission()" or send another Message (this cleans up the old state automatically) func cancelObserve() { let cancelMessage = SCMessage(code: SCCodeValue(classValue: 0, detailValue: 01)!, type: .nonConfirmable, payload: nil) cancelMessage.token = messageInTransmission.token cancelMessage.options = messageInTransmission.options currentMessageId = (currentMessageId % 0xFFFF) + 1 cancelMessage.messageId = currentMessageId cancelMessage.hostName = messageInTransmission.hostName cancelMessage.port = messageInTransmission.port var cancelByte: UInt8 = 1 cancelMessage.options[SCOption.observe.rawValue] = [Data(bytes: &cancelByte, count: 1)] if let messageData = cancelMessage.toData() { sendCoAPMessageOverTransportLayerWithData(messageData, host: messageInTransmission.hostName!, port: messageInTransmission.port!) } } //Closes the transmission. It is recommended to call this method anytime you do not expect to receive a response any longer. func closeTransmission() { transportLayerObject.closeTransmission() messageInTransmission = nil isMessageInTransmission = false transmissionTimer?.invalidate() transmissionTimer = nil recentNotificationInfo = nil cachedMessagePairs = [:] } // MARK: Private Methods fileprivate func initiateSending() { isMessageInTransmission = true transmissionTimer?.invalidate() transmissionTimer = nil recentNotificationInfo = nil if messageInTransmission.type == .confirmable && !disableRetransmissions { retransmissionCounter = 0 currentTransmitWait = 0 sendWithRentransmissionHandling() } else { sendPendingMessage() } } //Actually PRIVATE! Do not call from outside. Has to be internally visible as NSTimer won't find it otherwise @objc func sendWithRentransmissionHandling() { sendPendingMessage() if retransmissionCounter < SCMessage.kMaxRetransmit { let timeout = SCMessage.kAckTimeout * pow(2.0, Double(retransmissionCounter)) * (SCMessage.kAckRandomFactor - ((Double(arc4random()) / Double(UINT32_MAX)).truncatingRemainder(dividingBy: 0.5))); currentTransmitWait += timeout transmissionTimer = Timer(timeInterval: timeout, target: self, selector: #selector(SCClient.sendWithRentransmissionHandling), userInfo: nil, repeats: false) retransmissionCounter += 1 } else { transmissionTimer = Timer(timeInterval: SCMessage.kMaxTransmitWait - currentTransmitWait, target: self, selector: #selector(SCClient.notifyNoResponseExpected), userInfo: nil, repeats: false) } RunLoop.current.add(transmissionTimer, forMode: RunLoop.Mode.common) } //Actually PRIVATE! Do not call from outside. Has to be internally visible as NSTimer won't find it otherwise @objc func notifyNoResponseExpected() { closeTransmission() notifyDelegateWithErrorCode(.noResponseExpectedError) } fileprivate func sendPendingMessage() { if let data = messageInTransmission.toData() { sendCoAPMessageOverTransportLayerWithData(data as Data, host: messageInTransmission.hostName!, port: messageInTransmission.port!, notifyDelegateAfterSuccess: true) } else { closeTransmission() notifyDelegateWithErrorCode(.messageInvalidForSendingError) } } fileprivate func sendEmptyMessageWithType(_ type: SCType, messageId: UInt16, toHost host: String, port: UInt16) { let emptyMessage = SCMessage() emptyMessage.type = type; emptyMessage.messageId = messageId if let messageData = emptyMessage.toData() { sendCoAPMessageOverTransportLayerWithData(messageData as Data, host: host, port: port) } } fileprivate func sendCoAPMessageOverTransportLayerWithData(_ data: Data, host: String, port: UInt16, notifyDelegateAfterSuccess: Bool = false) { do { try transportLayerObject.sendCoAPData(data, toHost: host, port: port) if notifyDelegateAfterSuccess { delegate?.swiftCoapClient?(self, didSendMessage: messageInTransmission, number: retransmissionCounter + 1) } } catch SCCoAPTransportLayerError.sendError(let errorDescription) { notifyDelegateWithTransportLayerErrorDescription(errorDescription) } catch SCCoAPTransportLayerError.setupError(let errorDescription) { notifyDelegateWithTransportLayerErrorDescription(errorDescription) } catch {} } fileprivate func notifyDelegateWithTransportLayerErrorDescription(_ errorDescription: String) { delegate?.swiftCoapClient?(self, didFailWithError: NSError(domain: SCMessage.kCoapErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : errorDescription])) } fileprivate func notifyDelegateWithErrorCode(_ clientErrorCode: SCClientErrorCode) { delegate?.swiftCoapClient?(self, didFailWithError: NSError(domain: SCMessage.kCoapErrorDomain, code: clientErrorCode.rawValue, userInfo: [NSLocalizedDescriptionKey : clientErrorCode.descriptionString()])) } fileprivate func handleBlock2WithMessage(_ message: SCMessage) { if let block2opt = message.options[SCOption.block2.rawValue], let blockData = block2opt.first { let actualValue = UInt.fromData(blockData) if actualValue & 8 == 8 { //more bit is set, request next block let blockMessage = SCMessage(code: messageInTransmission.code, type: messageInTransmission.type, payload: messageInTransmission.payload) blockMessage.options = messageInTransmission.options let newValue = (actualValue & ~8) + 16 var byteArray = newValue.toByteArray() blockMessage.options[SCOption.block2.rawValue] = [Data(bytes: &byteArray, count: byteArray.count)] sendCoAPMessage(blockMessage, hostName: messageInTransmission.hostName!, port: messageInTransmission.port!) } else { isMessageInTransmission = false } } } fileprivate func continueBlock1ForBlockNumber(_ block: Int, szx: UInt) { let byteSize = pow(2, Double(szx) + 4) let blocksCount = ceil(Double(messageInTransmission.blockBody!.count) / byteSize) if block < Int(blocksCount) { var nextBlockLength: Int var blockValue: UInt = (UInt(block) << 4) + UInt(szx) if block < Int(blocksCount - 1) { nextBlockLength = Int(byteSize) blockValue += 8 } else { nextBlockLength = messageInTransmission.blockBody!.count - Int(byteSize) * block } let startPos = Int(byteSize) * block sendBlock1MessageForCurrentContext(payload: messageInTransmission.blockBody!.subdata(in: (startPos ..< startPos + nextBlockLength)), blockValue: blockValue) } } fileprivate func sendBlock1MessageForCurrentContext(payload: Data, blockValue: UInt) { let blockMessage = SCMessage(code: messageInTransmission.code, type: messageInTransmission.type, payload: payload) blockMessage.options = messageInTransmission.options blockMessage.blockBody = messageInTransmission.blockBody var byteArray = blockValue.toByteArray() blockMessage.options[SCOption.block1.rawValue] = [Data(bytes: &byteArray, count: byteArray.count)] sendCoAPMessage(blockMessage, hostName: messageInTransmission.hostName!, port: messageInTransmission.port!) } fileprivate func sendHttpMessageFromCoAPMessage(_ message: SCMessage) { let urlRequest = message.toHttpUrlRequestWithUrl() let urlString = "http://\(httpProxyingData!.hostName):\(httpProxyingData!.port)/\(message.hostName!):\(message.port!)" urlRequest.url = URL(string: urlString) urlRequest.timeoutInterval = SCMessage.kMaxTransmitWait urlRequest.cachePolicy = .useProtocolCachePolicy NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: OperationQueue.main) { (response, data, error) -> Void in if error != nil { self.notifyDelegateWithErrorCode(.proxyingError) } else { let coapResponse = SCMessage.fromHttpUrlResponse(response as! HTTPURLResponse, data: data) coapResponse.timeStamp = Date() if self.cachingActive && self.messageInTransmission.code == SCCodeValue(classValue: 0, detailValue: 01) { self.cachedMessagePairs[self.messageInTransmission] = SCMessage.copyFromMessage(coapResponse) } self.delegate?.swiftCoapClient(self, didReceiveMessage: coapResponse) self.handleBlock2WithMessage(coapResponse) } } } } // MARK: // MARK: SC Client Extension // MARK: SC CoAP Transport Layer Delegate extension SCClient: SCCoAPTransportLayerDelegate { func transportLayerObject(_ transportLayerObject: SCCoAPTransportLayerProtocol, didReceiveData data: Data, fromHost host: String, port: UInt16) { if let message = SCMessage.fromData(data) { //Check for spam if message.messageId != messageInTransmission.messageId && message.token != messageInTransmission.token { if message.type.rawValue <= SCType.nonConfirmable.rawValue { sendEmptyMessageWithType(.reset, messageId: message.messageId, toHost: host, port: port) } return } //Invalidate Timer transmissionTimer?.invalidate() transmissionTimer = nil //Set timestamp message.timeStamp = Date() //Set return address message.hostName = host //Handle Caching, Separate, etc if cachingActive && messageInTransmission.code == SCCodeValue(classValue: 0, detailValue: 01) { cachedMessagePairs[messageInTransmission] = SCMessage.copyFromMessage(message) } //Handle Observe-Option (Observe Draft Section 3.4) if let observeValueArray = message.options[SCOption.observe.rawValue], let observeValue = observeValueArray.first { let currentNumber = UInt.fromData(observeValue) if recentNotificationInfo == nil || (recentNotificationInfo.1 < currentNumber && currentNumber - recentNotificationInfo.1 < kMaxObserveOptionValue) || (recentNotificationInfo.1 > currentNumber && recentNotificationInfo.1 - currentNumber > kMaxObserveOptionValue) || (recentNotificationInfo.0 .compare(message.timeStamp!.addingTimeInterval(128)) == .orderedAscending) { recentNotificationInfo = (message.timeStamp!, currentNumber) } else { return } } //Notify Delegate delegate?.swiftCoapClient(self, didReceiveMessage: message) //Handle Block2 handleBlock2WithMessage(message) //Handle Block1 if message.code.toCodeSample() == SCCodeSample.continue, let block1opt = message.options[SCOption.block1.rawValue], let blockData = block1opt.first { var actualValue = UInt.fromData(blockData) let serverSZX = actualValue & 0b111 actualValue >>= 4 if serverSZX <= 6 { var blockOffset = 1 if serverSZX < autoBlock1SZX! { blockOffset = Int(pow(2, Double(autoBlock1SZX! - serverSZX))) autoBlock1SZX = serverSZX } continueBlock1ForBlockNumber(Int(actualValue) + blockOffset, szx: serverSZX) } } //Further Operations if message.type == .confirmable { sendEmptyMessageWithType(.acknowledgement, messageId: message.messageId, toHost: host, port: port) } if (message.type != .acknowledgement || message.code.toCodeSample() != .empty) && message.options[SCOption.block2.rawValue] == nil && message.code.toCodeSample() != SCCodeSample.continue { isMessageInTransmission = false } } else { notifyDelegateWithErrorCode(.receivedInvalidMessageError) } } func transportLayerObject(_ transportLayerObject: SCCoAPTransportLayerProtocol, didFailWithError error: NSError) { notifyDelegateWithErrorCode(.transportLayerSendError) transmissionTimer?.invalidate() transmissionTimer = nil } }
mit
7fb18e23cf3d12cf4979c56dabce8f83
44.92891
360
0.646321
5.56794
false
false
false
false
ElvishJerricco/DispatchKit
Sources/DispatchTime.swift
2
2629
// // DispatchTime.swift // DispatchKit <https://github.com/anpol/DispatchKit> // // Copyright (c) 2014 Andrei Polushin. All rights reserved. // import Foundation public enum DispatchTime { case Forever case Now case NowDelta(Int64) case WallClock(UnsafePointer<timespec>) case WallClockDelta(UnsafePointer<timespec>, Int64) public var rawValue: dispatch_time_t { switch self { case .Forever: return DISPATCH_TIME_FOREVER case .Now: return DISPATCH_TIME_NOW case let .NowDelta(nsec): return dispatch_time(DISPATCH_TIME_NOW, nsec) case let .WallClock(timespec): return dispatch_walltime(timespec, 0) case let .WallClockDelta(timespec, nsec): return dispatch_walltime(timespec, nsec) } } } public enum DispatchTimeDelta { case Nanoseconds(Int64) case Microseconds(Int64) case Milliseconds(Int64) case Seconds(Int64) case Minutes(Int) case Hours(Int) case Days(Int) case Weeks(Int) public var rawValue: UInt64 { var t: UInt64 switch self { case let .Nanoseconds(nsec): t = UInt64(nsec) case let .Microseconds(usec): t = UInt64(usec) * NSEC_PER_USEC case let .Milliseconds(msec): t = UInt64(msec) * NSEC_PER_MSEC case let .Seconds(sec): t = UInt64(sec) * NSEC_PER_SEC case let .Minutes(mins): t = UInt64(mins * 60) * NSEC_PER_SEC case let .Hours(hrs): t = UInt64(hrs * 3600) * NSEC_PER_SEC case let .Days(days): t = UInt64(days * 3600 * 24) * NSEC_PER_SEC case let .Weeks(wks): t = UInt64(wks * 3600 * 24 * 7) * NSEC_PER_SEC } return t } public func toNanoseconds() -> Int64 { return Int64(rawValue) } } public func +(time: DispatchTime, delta: DispatchTimeDelta) -> DispatchTime { switch time { case .Forever: return time case .Now: return .NowDelta(delta.toNanoseconds()) case let .NowDelta(nsec): return .NowDelta(nsec + delta.toNanoseconds()) case let .WallClock(timespec): return .WallClockDelta(timespec, delta.toNanoseconds()) case let .WallClockDelta(timespec, nsec): return .WallClockDelta(timespec, nsec + delta.toNanoseconds()) } } public func +(delta: DispatchTimeDelta, time: DispatchTime) -> DispatchTime { return time + delta } public func +(delta1: DispatchTimeDelta, delta2: DispatchTimeDelta) -> DispatchTimeDelta { return .Nanoseconds(delta1.toNanoseconds() + delta2.toNanoseconds()) }
mit
b29e81e4083b4511c79d4b6203e49cd9
27.576087
90
0.628376
3.953383
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/SwiftApp/UIScrollView/collectionview/RayCollectionViewController.swift
1
4421
// // RayCollectionViewController.swift // SwiftApp // // Created by wuyp on 2018/1/10. // Copyright © 2018年 raymond. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa fileprivate let kShadowEdge: UIEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 9, right: 9) class RayCollectionViewController: UIViewController { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 20 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) let list = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) list.frame = self.view.bounds list.layer.borderColor = UIColor.red.cgColor list.layer.borderWidth = 0.5 list.dataSource = self list.delegate = self list.backgroundColor = .clear list.register(RayBaseCollectionViewCell.self, forCellWithReuseIdentifier: "cell") list.register(RayCollectionHeaderReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header") return list }() lazy var btn: UIButton = { let temp = UIButton(frame: CGRect(x: 0, y: kNavigationBarH + kStatusBarH, width: 100, height: 30)) temp.backgroundColor = UIColor.orange temp.addTarget(self, action: #selector(testAction), for: .touchUpInside) return temp }() override func viewDidLoad() { super.viewDidLoad() self.title = "collection" self.view.addSubview(self.collectionView) // self.view.addSubview(btn) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @objc func testAction() { } } extension RayCollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 10 case 1: return 25 case 2: return 15 default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RayBaseCollectionViewCell cell.setTitleAndSubTitle(title: "\(indexPath.item)", subTitle: "section\(indexPath.section)") return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionFooter { return UICollectionReusableView() } let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! RayCollectionHeaderReusableView header.titleLbl.text = "Section Header: \(indexPath.section)" header.backgroundColor = UIColor.purple return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: kScreenWidth, height: 50) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch indexPath.section { case 0: // if indexPath.item % 3 == 0 { // return CGSize(width: 110, height: 130) // } else { // return CGSize(width: 100, height: 100) // } return CGSize(width: 100, height: 130) case 1: return CGSize(width: 80, height: 100) case 2: return CGSize(width: 60, height: 90) default: return .zero } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } }
apache-2.0
36c26f957b9bc3efc7457847be96afa0
35.213115
170
0.662743
5.387805
false
false
false
false
akane/Gaikan
Gaikan/UIKit/Extension/UIView.swift
1
3490
// // This file is part of Gaikan // // Created by JC on 30/08/15. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation import KVOController var ViewStyleStateAttribute = "ViewStyleStateAttribute" var ViewStyleClassAttr = "ViewStyleClassAttr" var ViewStyleInlineAttr = "ViewStyleInlineAttr" extension UIView : Stylable { public var styleClass: Style? { get { let value = objc_getAssociatedObject(self, &ViewStyleClassAttr) as? AssociatedObject<Style?> return value.map { $0.value } ?? nil } set { if (newValue == nil) { self.unregisterStyleKeyPaths() } objc_setAssociatedObject(self, &ViewStyleClassAttr, AssociatedObject(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addStyleLayerIfNeeded() self.computeStyle() if (newValue != nil) { self.registerStyleKeyPaths() } } } public var styleInline: StyleRule? { get { let value = objc_getAssociatedObject(self, &ViewStyleInlineAttr) as? AssociatedObject<StyleRule> return value.map { $0.value } } set { objc_setAssociatedObject(self, &ViewStyleInlineAttr, newValue.map { AssociatedObject($0) }, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addStyleLayerIfNeeded() self.computeStyle() } } public var styleState: String? { get { return objc_getAssociatedObject(self, &ViewStyleStateAttribute) as? String } set { objc_setAssociatedObject(self, &ViewStyleStateAttribute, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.computeStyle() } } public func updateStyle() { guard let computedStyle = self.computedStyle else { return } ViewStyleRenderer.render(self, styleRule: computedStyle) } public class func keyPathsAffectingStyle() -> [String] { return [] } } internal extension UIView { func registerStyleKeyPaths() { let keyPaths = type(of: self).keyPathsAffectingStyle() if keyPaths.count > 0 { self.kvoController.observe(self, keyPaths: keyPaths, options: .new) { [weak self] _ in self?.computeStyle() } } } func unregisterStyleKeyPaths() { type(of: self).keyPathsAffectingStyle().map { self.kvoController.unobserve(self, keyPath: $0) } } } var StyleKeyAttribute = "StyleLayer" extension UIView { var styleLayer: StyleLayer! { get { return objc_getAssociatedObject(self, &StyleKeyAttribute) as? StyleLayer } set { objc_setAssociatedObject(self, &StyleKeyAttribute, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func addStyleLayerIfNeeded() { if let _ = self.styleLayer { return } let styleLayer = StyleLayer() self.styleLayer = styleLayer self.layer.insertSublayer(styleLayer, at: 0) styleLayer.frame = self.layer.bounds self.registerBounds() } func registerBounds() { self.kvoController.observe(self.layer, keyPath: "bounds", options: .new) { [weak self] _ in guard let weakSelf = self else { return } weakSelf.styleLayer?.frame = weakSelf.layer.bounds } } }
mit
50eeb93c9085ce806f939be3a8d8310d
27.842975
139
0.620057
4.57405
false
false
false
false
jcanizales/grpc
src/objective-c/examples/SwiftSample/ViewController.swift
36
3733
/* * * Copyright 2015, Google 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ import UIKit import RemoteTest class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let RemoteHost = "grpc-test.sandbox.googleapis.com" let request = RMTSimpleRequest() request.responseSize = 10 request.fillUsername = true request.fillOauthScope = true // Example gRPC call using a generated proto client library: let service = RMTTestService(host: RemoteHost) service.unaryCallWithRequest(request) { response, error in if let response = response { NSLog("1. Finished successfully with response:\n\(response)") } else { NSLog("1. Finished with error: \(error!)") } } // Same but manipulating headers: var RPC : GRPCProtoCall! // Needed to convince Swift to capture by reference (__block) RPC = service.RPCToUnaryCallWithRequest(request) { response, error in if let response = response { NSLog("2. Finished successfully with response:\n\(response)") } else { NSLog("2. Finished with error: \(error!)") } NSLog("2. Response headers: \(RPC.responseHeaders)") NSLog("2. Response trailers: \(RPC.responseTrailers)") } // TODO(jcanizales): Revert to using subscript syntax once XCode 8 is released. RPC.requestHeaders.setObject("My value", forKey: "My-Header") RPC.start() // Same example call using the generic gRPC client library: let method = GRPCProtoMethod(package: "grpc.testing", service: "TestService", method: "UnaryCall") let requestsWriter = GRXWriter(value: request.data()) let call = GRPCCall(host: RemoteHost, path: method.HTTPPath, requestsWriter: requestsWriter) call.requestHeaders.setObject("My value", forKey: "My-Header") call.startWithWriteable(GRXWriteable { response, error in if let response = response as? NSData { NSLog("3. Received response:\n\(try! RMTSimpleResponse(data: response))") } else { NSLog("3. Finished with error: \(error!)") } NSLog("3. Response headers: \(call.responseHeaders)") NSLog("3. Response trailers: \(call.responseTrailers)") }) } }
bsd-3-clause
37b40d467784651fb774e2f6629aa5fe
35.598039
102
0.709081
4.513906
false
false
false
false
weibo3721/WBLayout
WBLayout/ViewControllerV.swift
1
4070
// // ViewController.swift // WBLayout // // Created by weibo on 2017/3/6. // Copyright © 2017年 weibo. All rights reserved. // import UIKit class ViewControllerV: UIViewController { let view1 = UIButton() let viewRed = UILabel() let viewYellow = UILabel() let viewBlue = UILabel() let view2 = UIButton() let v2s1 = UIView() let v2s2 = UILabel() let v2s3 = UIView() let view3 = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white addLayoutForView1() addLayoutForView2() addLayoutForView3() view.wbAddLayoutView(newView: view1) view.wbAddLayoutView(newView: view2) view.wbAddLayoutView(newView: view3) view.wbLayoutSubviews() } func addLayoutForView1() { view1.addTarget(self, action: #selector(ViewControllerV.onClickChangeText), for: UIControlEvents.touchUpInside) view1.backgroundColor = UIColor.black view1.wbPinEdge(edge: .top,64).wbPinEdge(edge: .left).wbPinEdge(edge: .right) viewRed.text = "viewRed" viewRed.numberOfLines = 0 viewRed.backgroundColor = UIColor.red viewRed.wbPinEdge(edge: .top,15).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15) viewYellow.text = "viewYellow" viewYellow.backgroundColor = UIColor.yellow viewYellow.wbPinEdge(edge: .top).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15) viewBlue.text = "viewBlue\nline2" viewBlue.backgroundColor = UIColor.blue viewBlue.wbPinEdge(edge: .top).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15).wbPinEdge(edge: .bottom,15) view1.wbSetLayoutViews(arr: [viewRed,viewYellow,viewBlue]) } func addLayoutForView2() { view2.addTarget(self, action: #selector(ViewControllerV.onClickRemove), for: UIControlEvents.touchUpInside) view2.backgroundColor = UIColor.purple view2.wbPinEdge(edge: .top,20).wbPinEdge(edge: .left).wbPinEdge(edge: .right) v2s1.backgroundColor = UIColor.red v2s1.isUserInteractionEnabled = false v2s1.wbPinEdge(edge: .top,15).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15).wbHeight(size: 30) v2s2.text = "点击后这个区域会消失,再次点击显示" v2s2.backgroundColor = UIColor.yellow v2s2.isUserInteractionEnabled = false v2s2.wbPinEdge(edge: .top).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15).wbHeight(size: 30) v2s3.backgroundColor = UIColor.blue v2s3.isUserInteractionEnabled = false v2s3.wbPinEdge(edge: .top).wbPinEdge(edge: .left,15).wbPinEdge(edge: .right,15).wbPinEdge(edge: .bottom,15).wbHeight(size: 30) view2.wbSetLayoutViews(arr: [v2s1,v2s2,v2s3]) } func addLayoutForView3() { view3.text = "黑色块点击用于演示文字改变的布局更新\n紫色块点击用于演示view的添加和删除时,布局的更新" view3.numberOfLines = 0 view3.backgroundColor = UIColor.green view3.wbPinEdge(edge: .top,30).wbPinEdge(edge: .left).wbPinEdge(edge: .right) } var isChanged = false func onClickChangeText() { isChanged = !isChanged if isChanged { viewRed.text = "viewRed\nline2" } else { viewRed.text = "viewRed" } view.wbLayoutSubviews() } var isRemove = false func onClickRemove() { isRemove = !isRemove if isRemove { view2.wbGoneView(thisView: v2s2) } else { view2.wbSetLayoutViews(arr: [v2s1,v2s2,v2s3]) } view.wbLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1eda5c6c1f073f3215bff833c3939e9f
29.206107
134
0.613596
3.953047
false
false
false
false
AxziplinLib/TabNavigations
TabNavigations/Classes/Generals/Views/TextView.swift
1
2355
// // TextView.swift // AxReminder // // Created by devedbox on 2017/7/18. // Copyright © 2017年 devedbox. All rights reserved. // import UIKit @IBDesignable class TextView: UITextView { @IBInspectable public var placeholder: String? { get { return _placeholderLabel.text } set { _placeholderLabel.text = newValue _refresh() } } @IBInspectable public var attributedPlaceholder: NSAttributedString? { get { return _placeholderLabel.attributedText } set { _placeholderLabel.attributedText = newValue _refresh() } } private var _placeholderLabel: UILabel = { () -> UILabel in let label = UILabel() label.backgroundColor = .clear label.translatesAutoresizingMaskIntoConstraints = false return label }() override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) _initializer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _initializer() } override func awakeFromNib() { super.awakeFromNib() _initializer() } private func _initializer() { textContainer.lineFragmentPadding = 0.0 textContainer.widthTracksTextView = true _placeholderLabel.font = self.font _placeholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0) addSubview(_placeholderLabel) _placeholderLabel.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true _placeholderLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true _placeholderLabel.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor).isActive = true } override var text: String! { didSet { _refresh() } } override var font: UIFont? { didSet { _placeholderLabel.font = font } } override var delegate: UITextViewDelegate? { get { _refresh() return super.delegate } set { super.delegate = newValue } } private func _refresh() { if !text.isEmpty { _placeholderLabel.alpha = 0.0 } else { _placeholderLabel.alpha = 1.0 } } }
apache-2.0
a9bfdc44131e8df7fa885b9ea023e4df
26.670588
96
0.605017
5.090909
false
false
false
false
CD1212/Doughnut
Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeedEntryCategory.swift
2
3613
// // AtomFeedEntryCategory.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// The "atom:category" element conveys information about a category /// associated with an entry or feed. This specification assigns no /// meaning to the content (if any) of this element. public class AtomFeedEntryCategory { /// The element's attributes public class Attributes { /// The "term" attribute is a string that identifies the category to /// which the entry or feed belongs. Category elements MUST have a /// "term" attribute. public var term: String? /// The "scheme" attribute is an IRI that identifies a categorization /// scheme. Category elements MAY have a "scheme" attribute. public var scheme: String? /// The "label" attribute provides a human-readable label for display in /// end-user applications. The content of the "label" attribute is /// Language-Sensitive. Entities such as "&amp;" and "&lt;" represent /// their corresponding characters ("&" and "<", respectively), not /// markup. Category elements MAY have a "label" attribute. public var label: String? } /// The element's attributes. public var attributes: Attributes? } // MARK: - Initializers extension AtomFeedEntryCategory { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = AtomFeedEntryCategory.Attributes(attributes: attributeDict) } } extension AtomFeedEntryCategory.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.term = attributeDict["term"] self.scheme = attributeDict["scheme"] self.label = attributeDict["label"] } } // MARK: - Equatable extension AtomFeedEntryCategory: Equatable { public static func ==(lhs: AtomFeedEntryCategory, rhs: AtomFeedEntryCategory) -> Bool { return lhs.attributes == rhs.attributes } } extension AtomFeedEntryCategory.Attributes: Equatable { public static func ==(lhs: AtomFeedEntryCategory.Attributes, rhs: AtomFeedEntryCategory.Attributes) -> Bool { return lhs.term == rhs.term && lhs.scheme == rhs.scheme && lhs.label == rhs.label } }
gpl-3.0
012e35ee2c2ae615735e540170685bce
33.084906
113
0.666482
4.889039
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Login/CAuth.swift
1
2394
import UIKit import LocalAuthentication class CAuth:CController { private weak var viewAuth:VAuth! override func loadView() { let viewAuth:VAuth = VAuth(controller:self) self.viewAuth = viewAuth view = viewAuth } //MARK: private private func authSuccess() { DispatchQueue.main.async { [weak self] in self?.parentController.dismiss( centered:true, completion:nil) } } private func authError(error:String) { VAlert.message(message:error) DispatchQueue.main.async { [weak self] in self?.viewAuth.showTryAgain() } } //MARK: public func askAuth() { let laContext:LAContext = LAContext() laContext.evaluatePolicy( LAPolicy.deviceOwnerAuthentication, localizedReason: NSLocalizedString("CAuth_reason", comment:"")) { [weak self] (success:Bool, error:Error?) in if success { self?.authSuccess() } else { if let errorLA:LAError = error as? LAError { if errorLA.code == LAError.Code.passcodeNotSet { self?.authSuccess() let notSet:String = NSLocalizedString("CAuth_passCodeNotSet", comment:"") VAlert.message(message:notSet) } else { if let errorString:String = error?.localizedDescription { self?.authError(error:errorString) } else { let errorString:String = NSLocalizedString("CAuth_errorUnknown", comment:"") self?.authError(error:errorString) } } } else { let errorString:String = NSLocalizedString("CAuth_errorUnknown", comment:"") self?.authError(error:errorString) } } } } }
mit
e3ebd66150a8a6e1b4ca968dc4268205
26.517241
104
0.440267
5.970075
false
false
false
false
SuPair/VPNOn
VPNOn/Theme/LTThemeManager.swift
1
3906
// // LTThemeManager.swift // VPNOn // // Created by Lex on 1/15/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit let kCurrentThemeIndexKey = "CurrentThemeIndex" class LTThemeManager { var currentTheme : LTTheme? = .None let themes: [LTTheme] = [LTDarkTheme(), LTLightTheme(), LTHelloKittyTheme(), LTDarkGreenTheme(), LTDarkPurpleTheme()] class var sharedManager : LTThemeManager { struct Static { static let sharedInstance = LTThemeManager() } return Static.sharedInstance } var themeIndex: Int { get { if let index = NSUserDefaults.standardUserDefaults().objectForKey(kCurrentThemeIndexKey) as? NSNumber { if index.isKindOfClass(NSNumber.self) { return min(themes.count - 1, index.integerValue ?? 0) } } return 0 } set { let newNumber = NSNumber(integer: newValue) NSUserDefaults.standardUserDefaults().setObject(newNumber, forKey: kCurrentThemeIndexKey) NSUserDefaults.standardUserDefaults().synchronize() } } func activateTheme() { activateTheme(themes[themeIndex]) } func activateTheme(theme : LTTheme) { currentTheme = theme UIWindow.appearance().tintColor = theme.tintColor LTViewControllerBackground.appearance().backgroundColor = theme.defaultBackgroundColor // Switch UISwitch.appearance().tintColor = theme.switchBorderColor UISwitch.appearance().onTintColor = theme.tintColor UISwitch.appearance().thumbTintColor = theme.switchBorderColor // Navigation UINavigationBar.appearance().barTintColor = theme.navigationBarColor UINavigationBar.appearance().tintColor = theme.tintColor UINavigationBar.appearance().backgroundColor = UIColor.clearColor() UINavigationBar.appearance().titleTextAttributes = NSDictionary(objects: [theme.textColor], forKeys: [NSForegroundColorAttributeName]) as [NSObject : AnyObject] as [NSObject : AnyObject] // TableView UITableView.appearance().backgroundColor = theme.tableViewBackgroundColor UITableView.appearance().separatorColor = theme.tableViewLineColor UITableViewCell.appearance().backgroundColor = theme.tableViewCellColor UITableViewCell.appearance().tintColor = theme.tintColor UITableViewCell.appearance().selectionStyle = UITableViewCellSelectionStyle.None UILabel.lt_appearanceWhenContainedIn(UITableViewHeaderFooterView.self).textColor = theme.textColor LTTableViewCellTitle.appearance().textColor = theme.textColor UILabel.lt_appearanceWhenContainedIn(LTTableViewActionCell.self).textColor = theme.tintColor UILabel.lt_appearanceWhenContainedIn(VPNTableViewCell.self).textColor = theme.textColor UITextView.lt_appearanceWhenContainedIn(UITableViewCell.self).backgroundColor = theme.tableViewCellColor UITextView.lt_appearanceWhenContainedIn(UITableViewCell.self).textColor = theme.textColor // TextField UITextField.appearance().tintColor = theme.tintColor UITextField.appearance().textColor = theme.textFieldColor } func activateNextTheme() { var index = themeIndex index++ if index >= themes.count { themeIndex = 0 } else { themeIndex = index } activateTheme(themes[themeIndex]) let windows = UIApplication.sharedApplication().windows for window in windows { for view in window.subviews { view.removeFromSuperview() window.addSubview(view ) } } } }
mit
ddfc1a0248a53b334a4b903065db74af
35.166667
194
0.65489
5.864865
false
false
false
false
SuPair/firefox-ios
Account/KeyBundle.swift
1
5180
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import FxA import SwiftyJSON public let KeyLength = 32 open class KeyBundle: Hashable { open let encKey: Data open let hmacKey: Data open class func fromKSync(_ kSync: Data) -> KeyBundle { return KeyBundle(encKey: kSync.subdata(in: 0..<KeyLength), hmacKey: kSync.subdata(in: KeyLength..<(2 * KeyLength))) } open class func random() -> KeyBundle { // Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which // on iOS is populated by the OS from kernel-level sources of entropy. // That should mean that we don't need to seed or initialize anything before calling // this. That is probably not true on (some versions of) OS X. return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32)) } open class var invalid: KeyBundle { return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")! } public init?(encKeyB64: String, hmacKeyB64: String) { guard let e = Bytes.decodeBase64(encKeyB64), let h = Bytes.decodeBase64(hmacKeyB64) else { return nil } self.encKey = e self.hmacKey = h } public init(encKey: Data, hmacKey: Data) { self.encKey = encKey self.hmacKey = hmacKey } fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) { let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256) let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result) return (result, digestLen) } open func hmac(_ ciphertext: Data) -> Data { let (result, digestLen) = _hmac(ciphertext) let data = NSMutableData(bytes: result, length: digestLen) result.deinitialize(count: digestLen) result.deallocate() return data as Data } /** * Returns a hex string for the HMAC. */ open func hmacString(_ ciphertext: Data) -> String { let (result, digestLen) = _hmac(ciphertext) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize(count: digestLen) result.deallocate() return String(hash) } open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? { let iv = iv ?? Bytes.generateRandomBytes(16) let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) b.deallocate() return (d, iv) } b.deallocate() return nil } // You *must* verify HMAC before calling this. open func decrypt(_ ciphertext: Data, iv: Data) -> String? { let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) let s = String(data: d, encoding: .utf8) b.deallocate() return s } b.deallocate() return nil } fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) { let resultSize = input.count + kCCBlockSizeAES128 var copied: Int = 0 let result = UnsafeMutableRawPointer.allocate(byteCount: resultSize, alignment: MemoryLayout<Void>.size) let success: CCCryptorStatus = CCCrypt(op, CCHmacAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), encKey.getBytes(), kCCKeySizeAES256, iv.getBytes(), input.getBytes(), input.count, result, resultSize, &copied ) return (success, result, copied) } open func verify(hmac: Data, ciphertextB64: Data) -> Bool { let expectedHMAC = hmac let computedHMAC = self.hmac(ciphertextB64) return (expectedHMAC == computedHMAC) } open func asPair() -> [String] { return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString] } open var hashValue: Int { return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue } public static func ==(lhs: KeyBundle, rhs: KeyBundle) -> Bool { return lhs.encKey == rhs.encKey && lhs.hmacKey == rhs.hmacKey } }
mpl-2.0
64c31903204a627052ab28f16b11604d
34
144
0.606757
4.592199
false
false
false
false
brentdax/swift
benchmark/single-source/PolymorphicCalls.swift
9
7051
//===--- PolymorphicCalls.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 benchmark is used to check the performance of polymorphic invocations. Essentially, it checks how good a compiler can optimize virtual calls of class methods in cases where multiple sub-classes of a given class are available. In particular, this benchmark would benefit from a good devirtualization. In case of applying a speculative devirtualization, it would be benefit from applying a jump-threading in combination with the speculative devirtualization. */ import TestsUtils public var PolymorphicCalls = BenchmarkInfo( name: "PolymorphicCalls", runFunction: run_PolymorphicCalls, tags: [.abstraction, .cpubench] ) public class A { let b: B init(b:B) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B has no known subclasses public class B { let x: Int init(x:Int) { self.x = x } public func f1() -> Int { return x + 1 } public func f2() -> Int { return x + 11 } public func f3() -> Int { return x + 111 } public func run() -> Int { return f1() + f2() + f3() } } public class A1 { let b: B1 public init(b:B1) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B1 has 1 known subclass public class B1 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C1: B1 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 2 } override public func f2() -> Int { return x + 22 } override public func f3() -> Int { return x + 222 } } public class A2 { let b:B2 public init(b:B2) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B2 has 2 known subclasses public class B2 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C2 : B2 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 3 } override public func f2() -> Int { return x + 33 } override public func f3() -> Int { return x + 333 } } public class D2 : B2 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 4 } override public func f2() -> Int { return x + 44 } override public func f3() -> Int { return x + 444 } } public class A3 { let b: B3 public init(b:B3) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B3 has 3 known subclasses public class B3 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C3: B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 5 } override public func f2() -> Int { return x + 55 } override public func f3() -> Int { return x + 555 } } public class D3: B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 6 } override public func f2() -> Int { return x + 66 } override public func f3() -> Int { return x + 666 } } public class E3:B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 7 } override public func f2() -> Int { return x + 77 } override public func f3() -> Int { return x + 777 } } public class F3 : B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 8 } override public func f2() -> Int { return x + 88 } override public func f3() -> Int { return x + 888 }} // Test the cost of polymorphic method invocation // on a class without any subclasses @inline(never) func test(_ a:A, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += Int64(a.run2()) } return cnt } // Test the cost of polymorphic method invocation // on a class with 1 subclass @inline(never) func test(_ a:A1, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += Int64(a.run2()) } return cnt } // Test the cost of polymorphic method invocation // on a class with 2 subclasses @inline(never) func test(_ a:A2, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += Int64(a.run2()) } return cnt } // Test the cost of polymorphic method invocation // on a class with 2 subclasses on objects // of different subclasses @inline(never) func test(_ a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO/2 { cnt += Int64(a2_c2.run2()) cnt += Int64(a2_d2.run2()) } return cnt } // Test the cost of polymorphic method invocation // on a class with 4 subclasses on objects // of different subclasses @inline(never) func test(_ a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO/4 { cnt += Int64(a3_c3.run2()) cnt += Int64(a3_d3.run2()) cnt += Int64(a3_e3.run2()) cnt += Int64(a3_f3.run2()) } return cnt } @inline(never) public func run_PolymorphicCalls(_ N:Int) { let UPTO = 10000 * N let a = A(b:B(x:1)) _ = test(a, UPTO) let a1 = A1(b:C1(x:1)) _ = test(a1, UPTO) let a2 = A2(b:C2(x:1)) _ = test(a2, UPTO) let a2_c2 = A2(b:C2(x:1)) let a2_d2 = A2(b:D2(x:1)) _ = test(a2_c2, a2_d2, UPTO) let a3_c3 = A3(b:C3(x:1)) let a3_d3 = A3(b:D3(x:1)) let a3_e3 = A3(b:E3(x:1)) let a3_f3 = A3(b:F3(x:1)) _ = test(a3_c3, a3_d3, a3_e3, a3_f3, UPTO) }
apache-2.0
afa8bdecd788edfdfde1055b1a0c4c38
19.79941
85
0.524323
3.143558
false
false
false
false
viWiD/VIAddressBookKit
VIAddressBookKit/AlphabeticOrdering.swift
1
1949
// // AlphabeticOrdering.swift // VIAddressBookKit // // Created by Nils Fischer on 09.10.14. // Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved. // import Foundation import Evergreen /* TODO: remove @objc flag when this works without runtime exception: protocol P {} class Foo: P {} let foos = [ Foo() ] let ps: [P] = foos // Casting here requires protocol conformance check which is only available for @objc protocols */ @objc public protocol AlphabeticOrdering { var alphabeticOrderingString: String? { get } } public func isOrderedAlphabetically(lhs: AlphabeticOrdering, rhs: AlphabeticOrdering) -> Bool { let a = lhs.alphabeticOrderingString let b = rhs.alphabeticOrderingString if let rhsAlphabeticOrderingString = rhs.alphabeticOrderingString { if let lhsAlphabeticOrderingString = lhs.alphabeticOrderingString { return lhsAlphabeticOrderingString < rhsAlphabeticOrderingString } else { return false } } else { return true } } public func alphabeticSectioningLetter(element: AlphabeticOrdering) -> String? { if let orderingString = element.alphabeticOrderingString { return orderingString.substringToIndex(advance(orderingString.startIndex, 1)).uppercaseString } else { return nil } } public func attributedStringWithBoldAlphabeticOrderingString(element: AlphabeticOrdering, string: String, ofSize fontSize: CGFloat) -> NSAttributedString { var mutableAttributedString = NSMutableAttributedString(string: string, attributes: [ NSFontAttributeName : UIFont.systemFontOfSize(fontSize) ]) if let orderingString = element.alphabeticOrderingString { let range = (string as NSString).rangeOfString(orderingString) mutableAttributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(fontSize), range: range) } return mutableAttributedString }
mit
e7cce8b9e387b91b5d368b1d8cf48856
33.803571
153
0.743971
5.128947
false
false
false
false
amitaymolko/react-native-rsa-native
ios/RSAECNative.swift
1
25105
// // RSANative.swift // BVLinearGradient import Foundation import CommonCrypto typealias SecKeyPerformBlock = (SecKey) -> () class RSAECNative: NSObject { var publicKey: SecKey? var privateKey: SecKey? var keyTag: String? let publicKeyTag: String? let privateKeyTag: String? var publicKeyBits: Data? var keyAlgorithm = KeyAlgorithm.rsa(signatureType: .sha512) public init(keyTag: String?){ self.publicKeyTag = "\(keyTag ?? "").public" self.privateKeyTag = "\(keyTag ?? "").private" self.keyTag = keyTag super.init() } public convenience override init(){ self.init(keyTag: nil) } public func generate(keySize: Int) -> Bool? { var publicKeyParameters: [String: AnyObject] = [ String(kSecAttrAccessible): kSecAttrAccessibleAlways, ] var privateKeyParameters: [String: AnyObject] = [ String(kSecAttrAccessible): kSecAttrAccessibleAlways, ] if((self.keyTag) != nil){ privateKeyParameters[String(kSecAttrIsPermanent)] = kCFBooleanTrue privateKeyParameters[String(kSecAttrApplicationTag)] = self.privateKeyTag as AnyObject publicKeyParameters[String(kSecAttrIsPermanent)] = kCFBooleanTrue publicKeyParameters[String(kSecAttrApplicationTag)] = self.publicKeyTag as AnyObject } #if !arch(i386) && !arch(x86_64) //This only works for Secure Enclave consistign of 256 bit key, note, the signatureType is irrelavent for this check if keyAlgorithm.type == KeyAlgorithm.ec(signatureType: .sha1).type{ let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleAlwaysThisDeviceOnly, .privateKeyUsage, nil)! // Ignore error privateKeyParameters[String(kSecAttrAccessControl)] = access } #endif //Define what type of keys to be generated here var parameters: [String: AnyObject] = [ String(kSecReturnRef): kCFBooleanTrue, kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject, kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject, ] parameters[String(kSecAttrKeySizeInBits)] = keySize as AnyObject if #available(iOS 10, *) { parameters[String(kSecAttrKeyType)] = keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions parameters[String(kSecAttrKeyType)] = keyAlgorithm.secKeyAttrTypeiOS9 } #if !arch(i386) && !arch(x86_64) //iOS only allows EC 256 keys to be secured in enclave. This will attempt to allow any EC key in the enclave, assuming iOS will do it outside of the enclave if it doesn't like the key size, note: the signatureType is irrelavent for this check if keyAlgorithm.type == KeyAlgorithm.ec(signatureType: .sha1).type{ parameters[String(kSecAttrTokenID)] = kSecAttrTokenIDSecureEnclave } #endif // TODO: Fix for when not set keytag and dont use keychain if #available(iOS 10.0, *) { var error: Unmanaged<CFError>? self.privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) if self.privateKey == nil { print("Error occured: keys weren't created") return nil } self.publicKey = SecKeyCopyPublicKey(self.privateKey!) } else { // Fallback on earlier versions let result = SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey) if result != errSecSuccess{ print("Error occured: \(result)") return nil } } guard self.publicKey != nil else { print( "Error in setUp(). PublicKey shouldn't be nil") return nil } guard self.privateKey != nil else{ print("Error in setUp(). PrivateKey shouldn't be nil") return nil } return true } public func generateEC() -> Bool? { self.keyAlgorithm = KeyAlgorithm.ec(signatureType: .sha256) // ios support 256 return self.generate(keySize: 256); } public func generateCSR(CN: String?, withAlgorithm: String) -> String? { self.setAlgorithm(algorithm: withAlgorithm) // self.privateKey = self.getPrivateKeyChain(tag: self.privateKeyTag!) self.publicKeyBits = self.getPublicKeyChainData(tag: self.publicKeyTag!) var csrString: String? let csrBlock: SecKeyPerformBlock = { privateKey in let csr = CertificateSigningRequest(commonName: CN, organizationName: nil, organizationUnitName: nil, countryName: nil, stateOrProvinceName: nil, localityName: nil, keyAlgorithm: self.keyAlgorithm) csrString = csr.buildCSRAndReturnString(self.publicKeyBits!, privateKey: privateKey) } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: csrBlock) } else { csrBlock(self.privateKey!); } return csrString } private func getPublicKeyChainData(tag : String) -> Data? { //Ask keychain to provide the publicKey in bits var query: [String: AnyObject] = [ String(kSecClass): kSecClassKey, String(kSecAttrApplicationTag): self.publicKeyTag as AnyObject, String(kSecReturnData): kCFBooleanTrue ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } var tempPublicKeyBits:AnyObject? let result = SecItemCopyMatching(query as CFDictionary, &tempPublicKeyBits) switch result { case errSecSuccess: guard let keyBits = tempPublicKeyBits as? Data else { print("error in: convert to publicKeyBits") return nil } return keyBits default: print("error in: convert to publicKeyBits") return nil } } private func setAlgorithm(algorithm: String) -> Void { switch algorithm { case "SHA256withRSA": self.keyAlgorithm = .rsa(signatureType: .sha256) case "SHA512withRSA": self.keyAlgorithm = .rsa(signatureType: .sha512) case "SHA1withRSA": self.keyAlgorithm = .rsa(signatureType: .sha1) case "SHA256withECDSA": self.keyAlgorithm = .ec(signatureType: .sha256) case "SHA512withECDSA": self.keyAlgorithm = .ec(signatureType: .sha512) case "SHA1withECDSA": self.keyAlgorithm = .ec(signatureType: .sha1) default: self.keyAlgorithm = .rsa(signatureType: .sha1) } } public func deletePrivateKey(){ var query: [String: AnyObject] = [ String(kSecClass) : kSecClassKey, String(kSecAttrApplicationTag): self.privateKeyTag as AnyObject, String(kSecReturnRef) : true as AnyObject ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } let result = SecItemDelete(query as CFDictionary) if result != errSecSuccess{ print("Error delete private key: \(result)") // return nil } } public func encodedPublicKeyRSA() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKeyRSA(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKeyRSA(key: self.publicKey!) } public func encodedPublicKeyDER() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKeyDER(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKeyDER(key: self.publicKey!) } public func encodedPublicKey() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKey(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKey(key: self.publicKey!) } public func encodedPrivateKeyRSA() -> String? { if ((self.keyTag) != nil) { var encodedPrivateKey: String? self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in encodedPrivateKey = self.externalRepresentationForPrivateKeyRSA(key: privateKey) } return encodedPrivateKey; } if(self.privateKey == nil) { return nil } return self.externalRepresentationForPrivateKeyRSA(key: self.privateKey!) } public func encodedPrivateKeyDER() -> String? { if ((self.keyTag) != nil) { var encodedPrivateKey: String? self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in encodedPrivateKey = self.externalRepresentationForPrivateKeyDER(key: privateKey) } return encodedPrivateKey; } if(self.privateKey == nil) { return nil } return self.externalRepresentationForPrivateKeyDER(key: self.privateKey!) } public func setPublicKey(publicKey: String) -> Bool? { guard let publicKeyStr = RSAECFormatter.stripHeaders(pemString: publicKey) else { return false } let query: [String: AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeyClass): kSecAttrKeyClassPublic, ] print(publicKeyStr, "publicKeyStrpublicKeyStr") var error: Unmanaged<CFError>? guard let data = Data(base64Encoded: publicKeyStr, options: .ignoreUnknownCharacters) else { return false } print(data, "datadatadata") if #available(iOS 10.0, *) { guard let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, &error) else { return false } self.publicKey = key return true } else { // Fallback on earlier versions } return false } public func setPrivateKey(privateKey: String) -> Bool? { guard let privateKeyStr = RSAECFormatter.stripHeaders(pemString: privateKey) else { return nil } let query: [String: AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeyClass): kSecAttrKeyClassPrivate, ] var error: Unmanaged<CFError>? guard let data = Data(base64Encoded: privateKeyStr, options: .ignoreUnknownCharacters) else { return nil } if #available(iOS 10.0, *) { guard let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, &error) else { return nil } self.privateKey = key return true } else { // Fallback on earlier versions } return nil } public func encrypt64(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } let encrypted = self._encrypt(data: data) return encrypted?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } public func encrypt(message: String) -> String? { guard let data = message.data(using: .utf8) else { return nil } let encrypted = self._encrypt(data: data) return encrypted?.base64EncodedString(options: .lineLength64Characters) } public func _encrypt(data: Data) -> Data? { var cipherText: Data? // Closures let encryptor:SecKeyPerformBlock = { publicKey in if #available(iOS 10.0, *) { let canEncrypt = SecKeyIsAlgorithmSupported(publicKey, .encrypt, .rsaEncryptionPKCS1) if(canEncrypt){ var error: Unmanaged<CFError>? cipherText = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? } } else { // Fallback on earlier versions }; } if ((self.keyTag) != nil) { self.performWithPublicKeyTag(tag: self.publicKeyTag!, block: encryptor) } else { encryptor(self.publicKey!); } return cipherText; } public func decrypt64(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } let decrypted = self._decrypt(data: data) return decrypted?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } public func decrypt(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } let decrypted = self._decrypt(data: data) if (decrypted == nil) { return nil } return String(data: decrypted!, encoding: String.Encoding.utf8) } private func _decrypt(data: Data) -> Data? { var clearText: Data? let decryptor: SecKeyPerformBlock = {privateKey in if #available(iOS 10.0, *) { let canEncrypt = SecKeyIsAlgorithmSupported(privateKey, .decrypt, .rsaEncryptionPKCS1) if(canEncrypt){ var error: Unmanaged<CFError>? clearText = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? } } else { // Fallback on earlier versions }; } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: decryptor) } else { decryptor(self.privateKey!); } return clearText } public func sign64(b64message: String, withAlgorithm: String) -> String? { guard let data = Data(base64Encoded: b64message, options: .ignoreUnknownCharacters) else { return nil } let encodedSignature = self._sign(messageBytes: data, withAlgorithm: withAlgorithm, withEncodeOption: .lineLength64Characters) return encodedSignature } public func sign(message: String, withAlgorithm: String, withEncodeOption: NSData.Base64EncodingOptions) -> String? { guard let data = message.data(using: .utf8) else { return nil } let encodedSignature = self._sign(messageBytes: data, withAlgorithm: withAlgorithm, withEncodeOption: withEncodeOption) return encodedSignature } private func _sign(messageBytes: Data, withAlgorithm: String, withEncodeOption: NSData.Base64EncodingOptions) -> String? { self.setAlgorithm(algorithm: withAlgorithm) var encodedSignature: String? let signer: SecKeyPerformBlock = { privateKey in if #available(iOS 11, *) { // Build signature - step 1: SHA1 hash // Build signature - step 2: Sign hash // var signature: Data? = nil var error: Unmanaged<CFError>? let signature = SecKeyCreateSignature(privateKey, self.keyAlgorithm.signatureAlgorithm, messageBytes as CFData, &error) as Data? if error != nil{ print("Error in creating signature: \(error!.takeRetainedValue())") } encodedSignature = signature!.base64EncodedString(options: withEncodeOption) } else { // TODO: fix and test // Fallback on earlier versions // Build signature - step 1: SHA1 hash var signature = [UInt8](repeating: 0, count: self.keyAlgorithm.availableKeySizes.last!) var signatureLen:Int = signature.count var messageDataBytes = [UInt8](repeating: 0, count: messageBytes.count) messageBytes.copyBytes(to: &messageDataBytes, count: messageBytes.count) var digest = [UInt8](repeating: 0, count: self.keyAlgorithm.digestLength) let padding = self.keyAlgorithm.padding switch self.keyAlgorithm { case .rsa(signatureType: .sha1), .ec(signatureType: .sha1): var SHA1 = CC_SHA1_CTX() CC_SHA1_Init(&SHA1) CC_SHA1_Update(&SHA1, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA1_Final(&digest, &SHA1) case .rsa(signatureType: .sha256), .ec(signatureType: .sha256): var SHA256 = CC_SHA256_CTX() CC_SHA256_Init(&SHA256) CC_SHA256_Update(&SHA256, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA256_Final(&digest, &SHA256) case .rsa(signatureType: .sha512), .ec(signatureType: .sha512): var SHA512 = CC_SHA512_CTX() CC_SHA512_Init(&SHA512) CC_SHA512_Update(&SHA512, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA512_Final(&digest, &SHA512) } // Build signature - step 2: Sign hash let result = SecKeyRawSign(privateKey, padding, digest, digest.count, &signature, &signatureLen) if result != errSecSuccess{ print("Error signing: \(result)") return } var signData = Data() let zero:UInt8 = 0 signData.append(zero) signData.append(signature, count: signatureLen) encodedSignature = signData.base64EncodedString(options: withEncodeOption) } } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: signer) } else { signer(self.privateKey!); } return encodedSignature } public func verify64(encodedSignature: String, withMessage: String, withAlgorithm: String) -> Bool? { guard let messageBytes = Data(base64Encoded: encodedSignature, options: .ignoreUnknownCharacters) else { return nil } guard let signatureBytes = Data(base64Encoded: withMessage, options: .ignoreUnknownCharacters) else { return nil } return self._verify(signatureBytes: signatureBytes, withMessage: messageBytes, withAlgorithm: withAlgorithm) } public func verify(encodedSignature: String, withMessage: String, withAlgorithm: String) -> Bool? { guard let messageBytes = withMessage.data(using: .utf8) else { return nil } guard let signatureBytes = Data(base64Encoded: encodedSignature, options: .ignoreUnknownCharacters) else { return nil } return self._verify(signatureBytes:signatureBytes , withMessage: messageBytes, withAlgorithm: withAlgorithm) } private func _verify(signatureBytes: Data, withMessage: Data, withAlgorithm: String) -> Bool? { var result = false self.setAlgorithm(algorithm: withAlgorithm) // Closures let verifier: SecKeyPerformBlock = { publicKey in if #available(iOS 10.0, *) { var error: Unmanaged<CFError>? result = SecKeyVerifySignature(publicKey, self.keyAlgorithm.signatureAlgorithm, withMessage as CFData, signatureBytes as CFData, &error) } else { // Fallback on earlier versions } } if ((self.keyTag) != nil) { self.performWithPublicKeyTag(tag: self.publicKeyTag!, block: verifier) } else { verifier(self.publicKey!); } return result } private func performWithPrivateKeyTag(keyTag: String, block: SecKeyPerformBlock){ var query: [String: AnyObject] = [ String(kSecClass) : kSecClassKey, String(kSecAttrApplicationTag): keyTag as AnyObject, String(kSecReturnRef) : true as AnyObject ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } var result : AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) if status == errSecSuccess { print("\(keyTag) Key existed!") block((result as! SecKey?)!) } } private func performWithPublicKeyTag(tag: String, block: SecKeyPerformBlock){ self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in if #available(iOS 10.0, *) { let publicKey = SecKeyCopyPublicKey(privateKey) block(publicKey!) } else { // Fallback on earlier versions } } } private func externalRepresentationForPublicKeyRSA(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPublicKeyRSA(publicKeyData: data) } private func externalRepresentationForPublicKey(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPublicKey(publicKeyData: data) } private func externalRepresentationForPublicKeyDER(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } let convertedData = RSAKeyEncoding().convertToX509EncodedKey(data) return RSAECFormatter.PEMFormattedPublicKey(publicKeyData: convertedData) } private func externalRepresentationForPrivateKeyRSA(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPrivateKeyRSA(privateKeyData: data) } private func externalRepresentationForPrivateKeyDER(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } let convertedData = RSAKeyEncoding().convertToX509EncodedKey(data) return RSAECFormatter.PEMFormattedPrivateKey(privateKeyData: convertedData) } private func externalRepresentationForPrivateKey(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPrivateKey(privateKeyData: data) } private func dataForKey(key: SecKey) -> Data? { var error: Unmanaged<CFError>? var keyData: Data? if #available(iOS 10.0, *) { keyData = SecKeyCopyExternalRepresentation(key, &error) as Data? } else { // Fallback on earlier versions } if (keyData == nil) { print("error in dataForKey") return nil } return keyData; } }
mit
183dd383ab2aae80bbf8314af43a4b64
40.021242
250
0.592631
5.308733
false
false
false
false
00buggy00/SwiftOpenGLTutorials
SwiftOpenGLRefactor/GraphicSceneObjects.swift
1
29599
// // GraphicSceneObjects.swift // SwiftOpenGLRefactor // // Created by Myles Schultz on 1/19/18. // Copyright © 2018 MyKo. All rights reserved. // import Foundation import Quartz import OpenGL.GL3 func glLogCall(file: String, line: Int) -> Bool { var error = GLenum(GL_NO_ERROR) repeat { error = glGetError() switch error { case GLenum(GL_INVALID_ENUM): print("\(file), line: \(line), ERROR: invalid Enum") return false case GLenum(GL_INVALID_VALUE): print("\(file), line: \(line), ERROR: invalid value passed") return false case GLenum(GL_INVALID_OPERATION): print("\(file), line: \(line), ERROR: invalid operation attempted") return false case GLenum(GL_INVALID_FRAMEBUFFER_OPERATION): print("\(file), line: \(line), ERROR: invalid framebuffer operation attempted") return false case GLenum(GL_OUT_OF_MEMORY): print("\(file), line: \(line), ERROR: out of memory") return false default: return true } } while error != GLenum(GL_NO_ERROR) } func glCall<T>(_ function: @autoclosure () -> T, file: String = #file, line: Int = #line) -> T { while glGetError() != GL_NO_ERROR {} let result = function() assert(glLogCall(file: file, line: line)) return result } protocol OpenGLObject { var id: GLuint { get set } func bind() func unbind() mutating func delete() } struct Vertex { var position: Float3 var normal: Float3 var textureCoordinate: Float2 var color: Float3 } struct VertexBufferObject: OpenGLObject { var id: GLuint = 0 let type: GLenum = GLenum(GL_ARRAY_BUFFER) var vertexCount: Int32 { return Int32(data.count) } var data: [Vertex] = [] mutating func load(_ data: [Vertex]) { self.data = data glCall(glGenBuffers(1, &id)) bind() glCall(glBufferData(GLenum(GL_ARRAY_BUFFER), data.count * MemoryLayout<Vertex>.size, data, GLenum(GL_STATIC_DRAW))) } func bind() { glCall(glBindBuffer(type, id)) } func unbind() { glCall(glBindBuffer(type, id)) } mutating func delete() { glCall(glDeleteBuffers(1, &id)) } } struct VertexArrayObject: OpenGLObject { var id: GLuint = 0 mutating func layoutVertexPattern() { glCall(glGenVertexArrays(1, &id)) bind() glCall(glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 0))) glCall(glEnableVertexAttribArray(0)) glCall(glVertexAttribPointer(1, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 12))) glCall(glEnableVertexAttribArray(1)) glCall(glVertexAttribPointer(2, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 24))) glCall(glEnableVertexAttribArray(2)) glCall(glVertexAttribPointer(3, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern:32))) glCall(glEnableVertexAttribArray(3)) } func bind() { glCall(glBindVertexArray(id)) } func unbind() { glCall(glBindVertexArray(id)) } mutating func delete() { glCall(glDeleteVertexArrays(1, &id)) } } enum TextureSlot: GLint { case texture1 = 33984 } struct TextureBufferObject: OpenGLObject { var id: GLuint = 0 var textureSlot: GLint = TextureSlot.texture1.rawValue mutating func loadTexture(named name: String) { guard let textureData = NSImage(named: NSImage.Name(rawValue: name))?.tiffRepresentation else { Swift.print("Image name not located in Image Asset Catalog") return } glCall(glGenTextures(1, &id)) bind() glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT)) glCall(glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT)) glCall(glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, 256, 256, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), (textureData as NSData).bytes)) } func bind() { glCall(glBindTexture(GLenum(GL_TEXTURE_2D), id)) } func unbind() { glCall(glBindTexture(GLenum(GL_TEXTURE_2D), 0)) } mutating func delete() { glCall(glDeleteTextures(1, &id)) } } enum ShaderType: UInt32 { case vertex = 35633 /* GL_VERTEX_SHADER */ case fragment = 35632 /* GL_FRAGMENT_SHADER */ } struct Shader: OpenGLObject { var id: GLuint = 0 mutating func create(withVertex vertexSource: String, andFragment fragmentSource: String) { id = glCall(glCreateProgram()) let vertex = compile(shaderType: .vertex, withSource: vertexSource) let fragment = compile(shaderType: .fragment, withSource: fragmentSource) link(vertexShader: vertex, fragmentShader: fragment) } func compile(shaderType type: ShaderType, withSource source: String) -> GLuint { let shader = glCall(glCreateShader(type.rawValue)) var pointerToShader = UnsafePointer<GLchar>(source.cString(using: String.Encoding.ascii)) glCall(glShaderSource(shader, 1, &pointerToShader, nil)) glCall(glCompileShader(shader)) var compiled: GLint = 0 glCall(glGetShaderiv(shader, GLbitfield(GL_COMPILE_STATUS), &compiled)) if compiled <= 0 { print("Could not compile shader type: \(type), getting log...") var logLength: GLint = 0 print("Log length: \(logLength)") glCall(glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &logLength)) if logLength > 0 { let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength)) glCall(glGetShaderInfoLog(shader, GLsizei(logLength), &logLength, cLog)) Swift.print("\n\t\(String.init(cString: cLog))") free(cLog) } } return shader } func link(vertexShader vertex: GLuint, fragmentShader fragment: GLuint) { glCall(glAttachShader(id, vertex)) glCall(glAttachShader(id, fragment)) glCall(glLinkProgram(id)) var linked: GLint = 0 glCall(glGetProgramiv(id, UInt32(GL_LINK_STATUS), &linked)) if linked <= 0 { Swift.print("Could not link, getting log") var logLength: GLint = 0 glCall(glGetProgramiv(id, UInt32(GL_INFO_LOG_LENGTH), &logLength)) Swift.print(" logLength = \(logLength)") if logLength > 0 { let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength)) glCall(glGetProgramInfoLog(id, GLsizei(logLength), &logLength, cLog)) Swift.print("log: \(String.init(cString:cLog))") free(cLog) } } glCall(glDeleteShader(vertex)) glCall(glDeleteShader(fragment)) } func setInitialUniforms(for scene: inout Scene) { // let location = glCall(glGetUniformLocation(id, "sample")) // glCall(glUniform1i(location, scene.tbo.textureSlot)) bind() scene.light.attach(toShader: self) scene.light.updateParameters(for: self) scene.camera.attach(toShader: self) scene.camera.updateParameters(for: self) } func bind() { glCall(glUseProgram(id)) } func unbind() { glCall(glUseProgram(0)) } func delete() { glCall(glDeleteProgram(id)) } } struct DisplayLink { let id: CVDisplayLink let displayLinkOutputCallback: CVDisplayLinkOutputCallback = {(displayLink: CVDisplayLink, inNow: UnsafePointer<CVTimeStamp>, inOutputTime: UnsafePointer<CVTimeStamp>, flagsIn: CVOptionFlags, flagsOut: UnsafeMutablePointer<CVOptionFlags>, displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn in // print("fps: \(Double(inNow.pointee.videoTimeScale) / Double(inNow.pointee.videoRefreshPeriod))") let view = unsafeBitCast(displayLinkContext, to: GraphicView.self) view.displayLink?.currentTime = Double(inNow.pointee.videoTime) / Double(inNow.pointee.videoTimeScale) let result = view.drawView() return result } var currentTime: Double = 0.0 { willSet { deltaTime = currentTime - newValue } } var deltaTime: Double = 0.0 init?(forView view: GraphicView) { var newID: CVDisplayLink? if CVDisplayLinkCreateWithActiveCGDisplays(&newID) == kCVReturnSuccess { self.id = newID! CVDisplayLinkSetOutputCallback(id, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(view).toOpaque())) } else { return nil } } func start() { CVDisplayLinkStart(id) } func stop() { CVDisplayLinkStop(id) } } struct Light { private enum Parameter: String { case color = "light.color" case position = "light.position" case ambientStrength = "light.ambient" case specularStrength = "light.specStrength" case specularHardness = "light.specHardness" } var color: [GLfloat] = [1.0, 1.0, 1.0] { didSet { parametersToUpdate.append(.color) } } var position: [GLfloat] = [0.0, 1.0, 0.5] { didSet { parametersToUpdate.append(.position) } } var ambietStrength: GLfloat = 0.25 { didSet { parametersToUpdate.append(.ambientStrength) } } var specularStrength: GLfloat = 3.0 { didSet { parametersToUpdate.append(.specularStrength) } } var specularHardness: GLfloat = 32 { didSet { parametersToUpdate.append(.specularHardness) } } private var shaderParameterLocations = [GLuint : [Parameter : Int32]]() private var parametersToUpdate: [Parameter] = [.color, .position, .ambientStrength, .specularStrength, .specularHardness] mutating func attach(toShader shader: Shader) { let shader = shader.id var parameterLocations = [Parameter : Int32]() parameterLocations[.color] = glCall(glGetUniformLocation(shader, Parameter.color.rawValue)) parameterLocations[.position] = glCall(glGetUniformLocation(shader, Parameter.position.rawValue)) parameterLocations[.ambientStrength] = glCall(glGetUniformLocation(shader, Parameter.ambientStrength.rawValue)) parameterLocations[.specularStrength] = glCall(glGetUniformLocation(shader, Parameter.specularStrength.rawValue)) parameterLocations[.specularHardness] = glCall(glGetUniformLocation(shader, Parameter.specularHardness.rawValue)) shaderParameterLocations[shader] = parameterLocations } mutating func updateParameters(for shader: Shader) { if let parameterLocations = shaderParameterLocations[shader.id] { for parameter in parametersToUpdate { switch parameter { case .color: if let location = parameterLocations[parameter] { glCall(glUniform3fv(location, 1, color)) } case .position: if let location = parameterLocations[parameter] { glCall(glUniform3fv(location, 1, position)) } case .ambientStrength: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, ambietStrength)) } case .specularStrength: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, specularStrength)) } case .specularHardness: if let location = parameterLocations[parameter] { glCall(glUniform1f(location, specularHardness)) } } } parametersToUpdate.removeAll() } } } struct Camera: Asset { private enum Parameter: String { case position = "view" case projection = "projection" } var name: String = "Camera" var position = FloatMatrix4() { didSet { parametersToUpdate.insert(.position) } } var projection = FloatMatrix4() { didSet { parametersToUpdate.insert(.projection) } } private var shaderParameterLocations = [GLuint : [Parameter : Int32]]() private var parametersToUpdate: Set<Parameter> = [.position, .projection] mutating func attach(toShader shader: Shader) { let shader = shader.id var parameterLocations = [Parameter : Int32]() parameterLocations[.position] = glCall(glGetUniformLocation(shader, Parameter.position.rawValue)) parameterLocations[.projection] = glCall(glGetUniformLocation(shader, Parameter.projection.rawValue)) shaderParameterLocations[shader] = parameterLocations } mutating func updateParameters(for shader: Shader) { if let parameterLocations = shaderParameterLocations[shader.id] { for parameter in parametersToUpdate { switch parameter { case .position: if let location = parameterLocations[parameter] { glCall(glUniformMatrix4fv(location, 1, GLboolean(GL_FALSE), position.columnMajorArray())) } case .projection: if let location = parameterLocations[parameter] { glCall(glUniformMatrix4fv(location, 1, GLboolean(GL_FALSE), projection.columnMajorArray())) } } } parametersToUpdate.removeAll() } } } struct Scene { var shader = Shader() var vao = VertexArrayObject() var vbo = VertexBufferObject() var tbo = TextureBufferObject() var light = Light() var camera = Camera() let data: [Vertex] = [ Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Front face 1 */ normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), /* Front face 2 */ normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: 0.0, z: 1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), /* Right face 1 */ normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Right face 2 */ normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Back face 1 */ normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), /* Back face 2 */ normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: 0.0, z: -1.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), /* Left face 1 */ normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Left face 2 */ normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: -1.0, y: 0.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Bottom face 1 */ normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 0.0), color: Float3(x: 0.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Bottom face 2 */ normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 1.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), normal: Float3(x: 0.0, y: -1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 0.0, z: 0.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Top face 1 */ normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 0.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Top face 2 */ normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 1.0, y: 1.0), color: Float3(x: 0.0, y: 1.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 1.0), color: Float3(x: 1.0, y: 0.0, z: 1.0)), Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), normal: Float3(x: 0.0, y: 1.0, z: 0.0), textureCoordinate: Float2(x: 0.0, y: 0.0), color: Float3(x: 1.0, y: 1.0, z: 1.0)) ] mutating func load(into view: GraphicView) { tbo.loadTexture(named: "Texture") vbo.load(data) vao.layoutVertexPattern() vao.unbind() camera.position = FloatMatrix4().translate(x: 0.0, y: 0.0, z: -5.0) // camera.projection = FloatMatrix4.orthographic(width: Float(view.bounds.size.width), height: Float(view.bounds.size.height)) camera.projection = FloatMatrix4.projection(aspect: Float(view.bounds.size.width / view.bounds.size.height)) let vertexSource = "#version 330 core \n" + "layout (location = 0) in vec3 position; \n" + "layout (location = 1) in vec3 normal; \n" + "layout (location = 2) in vec2 texturePosition; \n" + "layout (location = 3) in vec3 color; \n" + "out vec3 passPosition; \n" + "out vec3 passNormal; \n" + "out vec2 passTexturePosition; \n" + "out vec3 passColor; \n" + "uniform mat4 view; \n" + "uniform mat4 projection; \n" + "void main() \n" + "{ \n" + " gl_Position = projection * view * vec4(position, 1.0); \n" + " passPosition = position; \n" + " passNormal = normal; \n" + " passTexturePosition = texturePosition; \n" + " passColor = color; \n" + "} \n" let fragmentSource = "#version 330 core \n" + "uniform sampler2D sample; \n" + "uniform struct Light { \n" + " vec3 color; \n" + " vec3 position; \n" + " float ambient; \n" + " float specStrength; \n" + " float specHardness; \n" + "} light; \n" + "in vec3 passPosition; \n" + "in vec3 passNormal; \n" + "in vec2 passTexturePosition; \n" + "in vec3 passColor; \n" + "out vec4 outColor; \n" + "void main() \n" + "{ \n" + " vec3 normal = normalize(passNormal); \n" + " vec3 lightRay = normalize(light.position - passPosition); \n" + " float intensity = dot(normal, lightRay); \n" + " intensity = clamp(intensity, 0, 1); \n" + " vec3 viewer = normalize(vec3(0.0, 0.0, 0.2) - passPosition); \n" + " vec3 reflection = reflect(lightRay, normal); \n" + " float specular = pow(max(dot(viewer, reflection), 0.0), light.specHardness); \n" + " vec3 light = light.ambient + light.color * intensity + light.specStrength * specular * light.color; \n" + " vec3 surface = texture(sample, passTexturePosition).rgb * passColor; \n" + " vec3 rgb = surface * light; \n" + " outColor = vec4(rgb, 1.0); \n" + "} \n" shader.create(withVertex: vertexSource, andFragment: fragmentSource) shader.setInitialUniforms(for: &self) } mutating func update(with value: Float) { light.position = [sin(value), -5.0, 5.0] camera.position = FloatMatrix4().translate(x: 0.0, y: 0.0, z: -5.0).rotateYAxis(value).rotateXAxis(-0.5) } mutating func draw(with renderer: Renderer) { shader.bind() vao.bind() light.updateParameters(for: shader) camera.updateParameters(for: shader) renderer.render(vbo.vertexCount, as: .triangles) vao.unbind() } mutating func delete() { vao.delete() vbo.delete() tbo.delete() shader.delete() } }
mit
46b4f850f98f9b1c25c34b5f908e7ea6
43.981763
303
0.48902
3.8519
false
false
false
false
zisko/swift
test/SILGen/retaining_globals.swift
1
2863
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/globals.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s // REQUIRES: objc_interop // This test makes sure loading from globals properly retains/releases loads from globals. // NSString was the only real problem, as the compiler treats NSString globals specially. // The rest of these are just hedges against future changes. // From header: // globalString: __strong NSString* // globalObject: __strong NSObject* // globalID: __strong id // globalArray: __strong NSArray* // globalConstArray: __strong NSArray *const func main() { Globals.sharedInstance() // Initialize globals (dispatch_once) // CHECK: global_addr @globalConstArray : $*Optional<NSArray> // CHECK: global_addr @globalArray : $*Optional<NSArray> // CHECK: global_addr @globalId : $*Optional<AnyObject> // CHECK: global_addr @globalObject : $*Optional<NSObject> // CHECK: global_addr @globalString : $*NSString // CHECK: [[globalString:%.*]] = load [copy] {{%.*}} : $*NSString // CHECK: [[bridgeStringFunc:%.*]] = function_ref @{{.*}} : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: [[wrappedString:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[globalString]] : $NSString // CHECK: [[stringMetaType:%.*]] = metatype $@thin String.Type // CHECK: [[bridgedString:%.*]] = apply [[bridgeStringFunc]]([[wrappedString]], [[stringMetaType]]) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String let string = globalString // Problematic case, wasn't being retained // CHECK: [[load_1:%.*]] = load [copy] {{%.*}} : $*Optional<NSObject> let object = globalObject // CHECK: [[load_2:%.*]] = load [copy] {{%.*}} : $*Optional<AnyObject> let id = globalId // CHECK: [[load_3:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let arr = globalArray // CHECK: [[load_4:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let constArr = globalConstArray // Make sure there's no more copies // CHECK-NOT: load [copy] print(string as Any) print(object as Any) print(id as Any) print(arr as Any) print(constArr as Any) // CHECK: [[PRINT_FUN:%.*]] = function_ref @$Ss5print_9separator10terminatoryypd_S2StF : $@convention(thin) (@owned Array<Any>, @owned String, @owned String) -> () // CHECK: apply [[PRINT_FUN]]({{.*}}) // CHECK: destroy_value [[load_4]] // CHECK: destroy_value [[load_3]] // CHECK: destroy_value [[load_2]] // CHECK: destroy_value [[load_1]] // CHECK: destroy_value [[bridgedString]] // Make sure there's no more destroys // CHECK-NOT: destroy_value // CHECK: } // end sil function '$S17retaining_globals4mainyyF' } main() main() // Used to crash here, due to use-after-free. main() main() main() main()
apache-2.0
91f4bfd07d6eed2940f96154029da559
37.689189
188
0.657352
3.718182
false
false
false
false
kildevaeld/DataRepresentation
Example/Tests/Tests.swift
1
1185
// https://github.com/Quick/Quick import Quick import Nimble import DataRepresentation 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
2d43bba850483adea110d05ad27c7ff1
22.58
63
0.368109
5.509346
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/SOLID.swift
2
6815
// // SOLID.swift // Neocom // // Created by Artem Shimanski on 24.08.2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures protocol Assembly { associatedtype View: Neocom.View // typealias Input = View.Input func instantiate(_ input: View.Input) -> Future<View> } extension Assembly where View.Input == Void { func instantiate() -> Future<View> { return instantiate(()) } } protocol View: class { associatedtype Presenter: Neocom.Presenter var presenter: Presenter! {get set} var unwinder: Unwinder? {get set} associatedtype Input = Void var input: Input? {get set} func prepareToRoute<T: View>(to view: T) -> Void } protocol Interactor: class { associatedtype Presenter: Neocom.Presenter var presenter: Presenter? {get set} init(presenter: Presenter) func configure() -> Void } protocol Presenter: class { associatedtype View: Neocom.View associatedtype Interactor: Neocom.Interactor var view: View? {get set} var interactor: Interactor! {get set} init(view: View) func configure() -> Void func viewWillAppear(_ animated: Bool) -> Void func viewDidAppear(_ animated: Bool) -> Void func viewWillDisappear(_ animated: Bool) -> Void func viewDidDisappear(_ animated: Bool) -> Void func applicationWillEnterForeground() -> Void func beginTask(totalUnitCount unitCount: Int64, indicator: ProgressTask.Indicator) -> ProgressTask func beginTask(totalUnitCount unitCount: Int64) -> ProgressTask } extension View { func prepareToRoute<T: View>(to view: T) -> Void { } } extension View where Input == Void { var input: Input? { get { return nil } set {} } } extension Presenter { func configure() -> Void { interactor.configure() } func viewWillAppear(_ animated: Bool) -> Void { } func viewDidAppear(_ animated: Bool) -> Void { } func viewWillDisappear(_ animated: Bool) -> Void { } func viewDidDisappear(_ animated: Bool) -> Void { } func applicationWillEnterForeground() { } } extension Presenter { func beginTask(totalUnitCount unitCount: Int64, indicator: ProgressTask.Indicator) -> ProgressTask { return ProgressTask(totalUnitCount: unitCount, indicator: indicator) } } extension Presenter where View: UIViewController { func beginTask(totalUnitCount unitCount: Int64) -> ProgressTask { return beginTask(totalUnitCount: unitCount, indicator: .progressBar(view!)) } } extension Presenter where View: UIView { func beginTask(totalUnitCount unitCount: Int64) -> ProgressTask { return beginTask(totalUnitCount: unitCount, indicator: .progressBar(view!)) } } extension Interactor { func configure() { } } protocol ContentProviderView: View where Presenter: ContentProviderPresenter { @discardableResult func present(_ content: Presenter.Presentation, animated: Bool) -> Future<Void> func fail(_ error: Error) -> Void } protocol ContentProviderPresenter: Presenter where View: ContentProviderView, Interactor: ContentProviderInteractor, Presentation == View.Presenter.Presentation { associatedtype Presentation var content: Interactor.Content? {get set} var presentation: Presentation? {get set} var loading: Future<Presentation>? {get set} func presentation(for content: Interactor.Content) -> Future<Presentation> func prepareForReload() } protocol ContentProviderInteractor: Interactor where Presenter: ContentProviderPresenter { associatedtype Content = Void func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> func isExpired(_ content: Content) -> Bool } extension ContentProviderPresenter { func prepareForReload() { } // @discardableResult func reload(cachePolicy: URLRequest.CachePolicy) -> Future<Presentation> { guard self.loading == nil else {return .init(.failure(NCError.reloadInProgress))} var task: ProgressTask! = beginTask(totalUnitCount: 2) let progress1 = task.performAsCurrent(withPendingUnitCount: 1) { Progress(totalUnitCount: 1)} let progress2 = task.performAsCurrent(withPendingUnitCount: 1) { Progress(totalUnitCount: 1)} prepareForReload() let loading = progress1.performAsCurrent(withPendingUnitCount: 1) { interactor.load(cachePolicy: cachePolicy).then(on: .main) { [weak self] content -> Future<Presentation> in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} return progress2.performAsCurrent(withPendingUnitCount: 1) { strongSelf.presentation(for: content).then(on: .main) { presentation -> Presentation in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} strongSelf.content = content strongSelf.presentation = presentation strongSelf.loading = nil return presentation } } }.catch(on: .main) { [weak self] _ in self?.loading = nil }.finally(on: .main) { task = nil } } if case .pending = loading.state { self.loading = loading } return loading } } extension ContentProviderPresenter where Interactor.Content == Void { var content: Void? { get { return ()} set {} } } extension ContentProviderInteractor where Content: ESIResultProtocol { func isExpired(_ content: Content) -> Bool { guard let expires = content.expires else {return true} return expires < Date() } } extension ContentProviderPresenter { func reloadIfNeeded() { if let content = content, presentation != nil, !interactor.isExpired(content) { return } else { let animated = presentation != nil reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self] presentation in self?.view?.present(presentation, animated: animated) }.catch(on: .main) { [weak self] error in self?.view?.fail(error) } } } func viewWillAppear(_ animated: Bool) -> Void { reloadIfNeeded() } func applicationWillEnterForeground() -> Void { reloadIfNeeded() } } extension ContentProviderInteractor where Content == Void { func load(cachePolicy: URLRequest.CachePolicy) -> Future<Void> { return .init(()) } func isExpired(_ content: Void) -> Bool { return false } } class MyV: TreeViewController<MyP, Void>, TreeView { func present(_ content: Void, animated: Bool) -> Future<Void> { fatalError() } } class MyP: TreePresenter { var view: MyV? var interactor: MyI! required init(view: MyV) { } var presentation: Void? var loading: Future<Void>? func presentation(for content: ()) -> Future<Void> { fatalError() } typealias Presentation = Void typealias View = MyV typealias Interactor = MyI } class MyI: TreeInteractor { var presenter: MyP? required init(presenter: MyP) { } typealias Presenter = MyP } class MyA: Assembly { func instantiate(_ input: View.Input) -> Future<MyV> { fatalError() } typealias View = MyV }
lgpl-2.1
959212f6218d2f890c180f50f5d8f029
24.143911
162
0.721162
3.920598
false
false
false
false
CarlosMChica/swift-dojos
SocialNetworkKata/SocialNetworkKataTest/doubles/ActionSpy.swift
1
341
class ActionSpy: Action { var executeCalled = false var executeInput = Input(input: "") let canExecute: Bool init(canExecute: Bool) { self.canExecute = canExecute } func canExecute(input: Input) -> Bool { return canExecute } func execute(input: Input) { executeCalled = true executeInput = input } }
apache-2.0
5970ba420dc0afcd74ed7e657e705ba1
14.5
41
0.656891
4.108434
false
false
false
false
PiXeL16/BudgetShare
BudgetShare/Services/ServiceProviders/LocalCurrencyServiceProvider.swift
1
1035
// // LocalCurrencyServiceProvider.swift // BudgetShare // // Created by Chris Jimenez on 7/17/17. // Copyright © 2017 Chris Jimenez. All rights reserved. // import Foundation class LocalCurrencyServiceProvider: CurrencyService { let currentLocale: Locale init (locale: Locale) { self.currentLocale = locale } convenience init() { self.init(locale: Locale.current) } func getCurrencies() -> [Currency] { let currencies = Locale.isoCurrencyCodes.map { (currencyCode) -> Currency in let currencyName = (currentLocale as NSLocale).displayName(forKey: .currencyCode, value: currencyCode) let currencySymbol = (currentLocale as NSLocale).displayName(forKey: .currencySymbol, value: currencyCode) let currency = Currency(code: currencyCode, symbol: currencySymbol ?? "", displayName: currencyName ?? currencyCode) return currency } return currencies } }
mit
e311b3ae45cd21a6dc4de67595c4052e
27.722222
128
0.636364
5.248731
false
false
false
false
oliverkulpakko/ATMs
ATMs/View/Controllers/MapViewController.swift
1
3801
// // MapViewController.swift // ATMs // // Created by Oliver Kulpakko on 5.12.2017. // Copyright © 2017 East Studios. All rights reserved. // import UIKit import MapKit import PullUpController import StoreKit import GoogleMobileAds class MapViewController: UIViewController { // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.requestLocation() #if DEBUG adBannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716" #else adBannerView.adUnitID = "ca-app-pub-2929799728547191/6214864662" #endif adBannerView.adSize = kGADAdSizeBanner adBannerView.rootViewController = self adBannerView.load(GADRequest()) if #available(iOS 10.3, *) { checkReviewStatus() } if let atmsViewController = storyboard?.instantiateViewController(withIdentifier: "ATMsViewController") as? ATMsViewController { self.atmsViewController = atmsViewController atmsViewController.delegate = self addPullUpController(atmsViewController, initialStickyPointOffset: 100, animated: false) if #available(iOS 11.0, *) { atmsViewController.setupTrackingButton(mapView: mapView) } else { // TODO: Fallback on earlier versions } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapMap)) mapView.addGestureRecognizer(tapGestureRecognizer) } RemoteService.shared.fetchATMs(completion: { result in switch result { case .success(let atms): self.atms = atms case .failure(let error): self.presentError(error) } }) } @objc func didTapMap() { atmsViewController?.dismiss() } @available(iOS 10.3, *) func checkReviewStatus() { if AnalyticsStore.appLaunchCount > 2 && !UserDefaults.standard.bool(forKey: "AskedForRating") { RateHelper.showRatingPrompt() UserDefaults.standard.set(true, forKey: "AskedForRating") } } // MARK: Stored Properties var atmsViewController: ATMsViewController? var locationManager = CLLocationManager() var atms = [ATM]() { didSet { mapView.addAnnotations(atms) atmsViewController?.atms = atms } } // MARK: IBOutlets @IBOutlet var statusBarBlurView: UIVisualEffectView! @IBOutlet var adBannerView: GADBannerView! @IBOutlet var mapView: MKMapView! } extension MapViewController: ATMsViewControllerDelegate { func didSelectATM(_ atm: ATM, in atmsViewController: ATMsViewController) { atmsViewController.dismiss() mapView.zoomTo(atm, animated: true) analytics.logAction("OpenATM", data1: atm.name) } } extension MapViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } mapView.zoomToCoordinate(location.coordinate, animated: true) atmsViewController?.location = location } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { presentError(error) } } extension MapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard !(annotation is MKUserLocation) else { return nil } guard let atm = annotation as? ATM else { return nil } if #available(iOS 11.0, *) { let annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "ATM") annotationView.markerTintColor = atm.modelColor() annotationView.glyphText = atm.modelFormatted() return annotationView } else { let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "ATM") annotationView.pinTintColor = atm.modelColor() return annotationView } } }
mit
9d70491c2319c35aead4e88e62fe71c9
25.027397
130
0.743684
4.139434
false
false
false
false
kstaring/swift
test/Constraints/optional.swift
1
3449
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop func markUsed<T>(_ t: T) {} class A { @objc func do_a() {} @objc(do_b_2:) func do_b(_ x: Int) {} @objc func do_b(_ x: Float) {} @objc func do_c(x: Int) {} @objc func do_c(y: Int) {} } func test0(_ a: AnyObject) { a.do_a?() a.do_b?(1) a.do_b?(5.0) a.do_c?(1) // expected-error {{cannot invoke value of function type with argument list '(Int)'}} a.do_c?(x: 1) } func test1(_ a: A) { a?.do_a() // expected-error {{cannot use optional chaining on non-optional value of type 'A'}} {{4-5=}} a!.do_a() // expected-error {{cannot force unwrap value of non-optional type 'A'}} {{4-5=}} // Produce a specialized diagnostic here? a.do_a?() // expected-error {{cannot use optional chaining on non-optional value of type '() -> ()'}} {{9-10=}} } // <rdar://problem/15508756> extension Optional { func bind<U>(_ f: (Wrapped) -> U?) -> U? { switch self { case .some(let x): return f(x) case .none: return .none } } } var c: String? = Optional<Int>(1) .bind {(x: Int) in markUsed("\(x)!"); return "two" } func test4() { func foo() -> Int { return 0 } func takes_optfn(_ f : () -> Int?) -> Int? { return f() } _ = takes_optfn(foo) func takes_objoptfn(_ f : () -> AnyObject?) -> AnyObject? { return f() } func objFoo() -> AnyObject { return A() } _ = takes_objoptfn(objFoo) // okay func objBar() -> A { return A() } _ = takes_objoptfn(objBar) // okay } func test5() -> Int? { return nil } func test6<T>(_ x : T) { // FIXME: this code should work; T could be Int? or Int?? // or something like that at runtime. rdar://16374053 let y = x as? Int? // expected-error {{cannot downcast from 'T' to a more optional type 'Int?'}} } class B : A { } func test7(_ x : A) { let y = x as? B? // expected-error{{cannot downcast from 'A' to a more optional type 'B?'}} } func test8(_ x : AnyObject?) { let _ : A = x as! A } // Partial ordering with optionals func test9_helper<T>(_ x: T) -> Int { } func test9_helper<T>(_ x: T?) -> Double { } func test9(_ i: Int, io: Int?) { let result = test9_helper(i) var _: Int = result let result2 = test9_helper(io) let _: Double = result2 } protocol P { } func test10_helper<T : P>(_ x: T) -> Int { } func test10_helper<T : P>(_ x: T?) -> Double { } extension Int : P { } func test10(_ i: Int, io: Int?) { let result = test10_helper(i) var _: Int = result let result2 = test10_helper(io) var _: Double = result2 } var z: Int? = nil z = z ?? 3 var fo: Float? = 3.14159 func voidOptional(_ handler: () -> ()?) {} func testVoidOptional() { let noop: () -> Void = {} voidOptional(noop) let optNoop: (()?) -> ()? = { return $0 } voidOptional(optNoop) } func testTernaryWithNil(b: Bool, s: String, i: Int) { let t1 = b ? s : nil let _: Double = t1 // expected-error{{value of type 'String?'}} let t2 = b ? nil : i let _: Double = t2 // expected-error{{value of type 'Int?'}} let t3 = b ? "hello" : nil let _: Double = t3 // expected-error{{value of type 'String?'}} let t4 = b ? nil : 1 let _: Double = t4 // expected-error{{value of type 'Int?'}} } // inference with IUOs infix operator ++++ protocol PPPP { static func ++++(x: Self, y: Self) -> Bool } func compare<T: PPPP>(v: T, u: T!) -> Bool { return v ++++ u } func sr2752(x: String?, y: String?) { _ = x.map { xx in y.map { _ in "" } ?? "\(xx)" } }
apache-2.0
44b459f2019ce0048a932e100e4bde86
22.147651
113
0.56973
2.898319
false
true
false
false
swillsea/DailyDiary
DailyDiary/DayByDayVC.swift
1
4551
// // DayByDayVC.swift // Quotidian // // Created by Sam on 5/9/16. // Copyright © 2016 Sam Willsea, Pei Xiong, and Michael Merrill. All rights reserved. // import UIKit import CoreData class DayByDayVC: UIViewController, UIScrollViewDelegate { var resultsArray : [NSManagedObject]! var selectedEntry: Entry! var index:NSInteger! @IBOutlet var timeTextField: UITextField! @IBOutlet var imageView: UIImageView! @IBOutlet var textView: UITextView! var moc: NSManagedObjectContext! @IBOutlet weak var cardView: UIView! @IBOutlet weak var timeLabelTopConstraint: NSLayoutConstraint! @IBOutlet weak var wordCountLabelTopConstraint: NSLayoutConstraint! @IBOutlet weak var timeTextLabel: UILabel! @IBOutlet weak var wordNumberLabel: UILabel! //MARK: Appearance override func viewDidLoad() { super.viewDidLoad() self.styleNavBar() self.prefersStatusBarHidden() self.cardView.layer.cornerRadius = 14 self.cardView.clipsToBounds = true if self.resultsArray.count != 0 { self.selectedEntry = resultsArray[self.index] as! Entry self.showDiaryWithEntry(self.selectedEntry) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation:UIStatusBarAnimation.None) self.showDiaryWithEntry(self.selectedEntry) } func styleNavBar() { self.navigationController?.setNavigationBarHidden(true, animated: true) } override func prefersStatusBarHidden() -> Bool { return true } func showDiaryWithEntry(entry:Entry) { let dateFormat = NSDateFormatter() dateFormat.dateStyle = .MediumStyle self.timeTextField.text = dateFormat.stringFromDate(entry.date!) if selectedEntry.imageData != nil { self.imageView.image = UIImage(data:entry.imageData!) self.timeLabelTopConstraint.constant = 13 self.wordCountLabelTopConstraint.constant = 13 } else { self.imageView.image = nil self.timeLabelTopConstraint.constant = 13-self.imageView.frame.height self.wordCountLabelTopConstraint.constant = 13-self.imageView.frame.height } self.textView.text = entry.text self.textView.setContentOffset(CGPointMake(0.0, 0.0), animated: false) self.wordNumberLabel.text = selectedEntry.text!.asWordCountString() self.timeTextLabel.text = self.selectedEntry.date?.time() } //MARK: Moving through Entries func goBackOneEntry(){ if self.index == self.resultsArray.count-1 { } else { self.selectedEntry = resultsArray[self.index+1] as! Entry self.showDiaryWithEntry(self.selectedEntry) self.index = self.index + 1 } } func goForwardOneEntry(){ if self.index == 0 { } else { self.selectedEntry = resultsArray[self.index-1] as! Entry self.showDiaryWithEntry(self.selectedEntry) self.index = self.index - 1 } } @IBAction func onLeftButtonPressed(sender: UIButton) { goForwardOneEntry() } @IBAction func onRightButtonPressed(sender: UIButton) { goBackOneEntry() } //Allows us to override UITextView gesture recognition so entries are swipeable when swipes occur over text func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @IBAction func onSwipeRight(sender: UISwipeGestureRecognizer) { textView.scrollEnabled = false goBackOneEntry() textView.scrollEnabled = true } @IBAction func onSwipeLeft(sender: UISwipeGestureRecognizer) { textView.scrollEnabled = false goForwardOneEntry() textView.scrollEnabled = true } //MARK: Navigation @IBAction func onDismissButtonPressed(sender: UIButton) { self.navigationController?.popViewControllerAnimated(true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destVC = segue.destinationViewController as! AddOrEditVC // since we're going to a navigation controller destVC.moc = self.moc destVC.entryBeingEdited = self.selectedEntry } }
mit
9162a5ea0f7d75adb4a4d4371af47ed7
33.210526
172
0.671648
5.100897
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatRoomModule/View/JCChatRoomInfoCell.swift
1
2158
// // JCChatRoomInfoTableViewCell.swift // JChat // // Created by Allan on 2019/4/25. // Copyright © 2019 HXHG. All rights reserved. // import UIKit class JCChatRoomInfoCell: JCTableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code _init() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: UITableViewCell.CellStyle.value1, reuseIdentifier: reuseIdentifier) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } private func _init(){ self.accessoryType = .disclosureIndicator } override func prepareForReuse() { super.prepareForReuse() for view in self.contentView.subviews { if view.isKind(of: UIImageView.self) { view.removeFromSuperview() } } } public func bindImages(users: [JMSGUser]?) { let startX = UIScreen.main.bounds.width - 25 let paddingX: CGFloat = 5 let width: CGFloat = 40 let y: CGFloat = self.contentView.centerY - width/2 var end = users?.count ?? 0 if end > 5 { //最多取5个管理员头像展示 end = 5 } for index in 0..<end { let i : CGFloat = CGFloat(index + 1) let user = users?[end-index-1] let x = startX - (paddingX + width)*i let imageView = UIImageView.init(frame: CGRect.init(x: x, y: y, width: width, height: width)) self.contentView.addSubview(imageView) user?.thumbAvatarData { (data, id, error) in if let data = data { let image = UIImage(data: data) imageView.image = image } else { imageView.image = UIImage.loadImage("com_icon_user_50") } } } } }
mit
dab48bce7caf00f6e2fca62fd77a1d45
29.5
105
0.56534
4.457203
false
false
false
false
qq456cvb/DeepLearningKitForiOS
DeepLearningKitForiOS/DeepLearningKitForiOS/DeepNetwork+JSON.swift
1
704
// // DeepNetwork+JSON.swift // MemkiteMetal // // Created by Amund Tveit & Torb Morland on 12/12/15. // Copyright © 2015 Memkite. All rights reserved. // import Foundation public extension DeepNetwork { func loadJSONFile(_ filename: String) -> NSDictionary? { print(" ==> loadJSONFile(filename=\(filename)") do { let bundle = Bundle.main let path = bundle.path(forResource: filename, ofType: "json")! let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) print(" <== loadJSONFile") return try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as? NSDictionary } catch _ { return nil } } }
apache-2.0
73d1fda3ef5071dffe9537f0b82b6d1b
26.038462
107
0.647226
4.111111
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Reader/View/ReaderModeStyleViewController.swift
1
13448
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import Shared // MARK: - ReaderModeStyleViewControllerDelegate protocol ReaderModeStyleViewControllerDelegate: AnyObject { // isUsingUserDefinedColor should be false by default unless we need to override the default color func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle, isUsingUserDefinedColor: Bool) } // MARK: - ReaderModeStyleViewController class ReaderModeStyleViewController: UIViewController, Themeable { // UI views private var fontTypeButtons: [ReaderModeFontTypeButton]! private var fontSizeLabel: ReaderModeFontSizeLabel! private var fontSizeButtons: [ReaderModeFontSizeButton]! private var themeButtons: [ReaderModeThemeButton]! private var separatorLines = [UIView.build(), UIView.build(), UIView.build()] private var fontTypeRow: UIView! private var fontSizeRow: UIView! private var brightnessRow: UIView! private lazy var slider: UISlider = .build { slider in slider.accessibilityLabel = .ReaderModeStyleBrightnessAccessibilityLabel slider.addTarget(self, action: #selector(self.changeBrightness), for: .valueChanged) } // Keeps user-defined reader color until reader mode is closed or reloaded private var isUsingUserDefinedColor = false private var viewModel: ReaderModeStyleViewModel! var delegate: ReaderModeStyleViewControllerDelegate? var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol init(viewModel: ReaderModeStyleViewModel, notificationCenter: NotificationProtocol = NotificationCenter.default, themeManager: ThemeManager = AppContainer.shared.resolve()) { self.viewModel = viewModel self.notificationCenter = notificationCenter self.themeManager = themeManager super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Our preferred content size has a fixed width and height based on the rows + padding preferredContentSize = CGSize(width: ReaderModeStyleViewModel.Width, height: ReaderModeStyleViewModel.Height) // Font type row fontTypeRow = .build() view.addSubview(fontTypeRow) NSLayoutConstraint.activate([ fontTypeRow.topAnchor.constraint(equalTo: view.topAnchor, constant: viewModel.fontTypeOffset), fontTypeRow.leftAnchor.constraint(equalTo: view.leftAnchor), fontTypeRow.rightAnchor.constraint(equalTo: view.rightAnchor), fontTypeRow.heightAnchor.constraint(equalToConstant: ReaderModeStyleViewModel.RowHeight), ]) fontTypeButtons = [ ReaderModeFontTypeButton(fontType: ReaderModeFontType.sansSerif), ReaderModeFontTypeButton(fontType: ReaderModeFontType.serif) ] setupButtons(fontTypeButtons, inRow: fontTypeRow, action: #selector(changeFontType)) view.addSubview(separatorLines[0]) makeSeparatorView(fromView: separatorLines[0], topConstraint: fontTypeRow) // Font size row fontSizeRow = .build() view.addSubview(fontSizeRow) NSLayoutConstraint.activate([ fontSizeRow.topAnchor.constraint(equalTo: separatorLines[0].bottomAnchor), fontSizeRow.leftAnchor.constraint(equalTo: view.leftAnchor), fontSizeRow.rightAnchor.constraint(equalTo: view.rightAnchor), fontSizeRow.heightAnchor.constraint(equalToConstant: ReaderModeStyleViewModel.RowHeight), ]) fontSizeLabel = .build() fontSizeRow.addSubview(fontSizeLabel) NSLayoutConstraint.activate([ fontSizeLabel.centerXAnchor.constraint(equalTo: fontSizeRow.centerXAnchor), fontSizeLabel.centerYAnchor.constraint(equalTo: fontSizeRow.centerYAnchor), ]) fontSizeButtons = [ ReaderModeFontSizeButton(fontSizeAction: FontSizeAction.smaller), ReaderModeFontSizeButton(fontSizeAction: FontSizeAction.reset), ReaderModeFontSizeButton(fontSizeAction: FontSizeAction.bigger) ] setupButtons(fontSizeButtons, inRow: fontSizeRow, action: #selector(changeFontSize)) view.addSubview(separatorLines[1]) makeSeparatorView(fromView: separatorLines[1], topConstraint: fontSizeRow) // Theme row let themeRow: UIView = .build() view.addSubview(themeRow) NSLayoutConstraint.activate([ themeRow.topAnchor.constraint(equalTo: separatorLines[1].bottomAnchor), themeRow.leftAnchor.constraint(equalTo: view.leftAnchor), themeRow.rightAnchor.constraint(equalTo: view.rightAnchor), themeRow.heightAnchor.constraint(equalToConstant: ReaderModeStyleViewModel.RowHeight) ]) // These UIButtons represent the ReaderModeTheme (Light/Sepia/Dark) // they don't follow the App Theme themeButtons = [ ReaderModeThemeButton(readerModeTheme: ReaderModeTheme.light), ReaderModeThemeButton(readerModeTheme: ReaderModeTheme.sepia), ReaderModeThemeButton(readerModeTheme: ReaderModeTheme.dark) ] setupButtons(themeButtons, inRow: themeRow, action: #selector(changeTheme)) view.addSubview(separatorLines[2]) makeSeparatorView(fromView: separatorLines[2], topConstraint: themeRow) // Brightness row brightnessRow = .build() view.addSubview(brightnessRow) NSLayoutConstraint.activate([ brightnessRow.topAnchor.constraint(equalTo: separatorLines[2].bottomAnchor), brightnessRow.leftAnchor.constraint(equalTo: view.leftAnchor), brightnessRow.rightAnchor.constraint(equalTo: view.rightAnchor), brightnessRow.heightAnchor.constraint(equalToConstant: ReaderModeStyleViewModel.RowHeight), brightnessRow.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: viewModel.brightnessRowOffset), ]) brightnessRow.addSubview(slider) NSLayoutConstraint.activate([ slider.centerXAnchor.constraint(equalTo: brightnessRow.centerXAnchor), slider.centerYAnchor.constraint(equalTo: brightnessRow.centerYAnchor), slider.widthAnchor.constraint(equalToConstant: CGFloat(ReaderModeStyleViewModel.BrightnessSliderWidth)) ]) let brightnessMinImageView: UIImageView = .build { imageView in imageView.image = UIImage(named: "brightnessMin") } brightnessRow.addSubview(brightnessMinImageView) NSLayoutConstraint.activate([ brightnessMinImageView.centerYAnchor.constraint(equalTo: slider.centerYAnchor), brightnessMinImageView.rightAnchor.constraint(equalTo: slider.leftAnchor, constant: -CGFloat(ReaderModeStyleViewModel.BrightnessIconOffset)) ]) let brightnessMaxImageView: UIImageView = .build { imageView in imageView.image = UIImage(named: "brightnessMax") } brightnessRow.addSubview(brightnessMaxImageView) NSLayoutConstraint.activate([ brightnessMaxImageView.centerYAnchor.constraint(equalTo: slider.centerYAnchor), brightnessMaxImageView.leftAnchor.constraint(equalTo: slider.rightAnchor, constant: CGFloat(ReaderModeStyleViewModel.BrightnessIconOffset)) ]) selectFontType(viewModel.readerModeStyle.fontType) updateFontSizeButtons() selectTheme(viewModel.readerModeStyle.theme) slider.value = Float(UIScreen.main.brightness) listenForThemeChange() applyTheme() } // MARK: - Applying Theme func applyTheme() { let theme = themeManager.currentTheme popoverPresentationController?.backgroundColor = theme.colors.layer1 slider.tintColor = theme.colors.actionPrimary // Set background color to container views [fontTypeRow, fontSizeRow, brightnessRow].forEach { view in view?.backgroundColor = theme.colors.layer1 } fontSizeLabel.textColor = theme.colors.textPrimary fontTypeButtons.forEach { button in button.setTitleColor(theme.colors.textPrimary, for: .selected) button.setTitleColor(theme.colors.textDisabled, for: []) } fontSizeButtons.forEach { button in button.setTitleColor(theme.colors.textPrimary, for: .normal) button.setTitleColor(theme.colors.textPrimary, for: .disabled) } separatorLines.forEach { line in line.backgroundColor = theme.colors.borderPrimary } } func applyTheme(_ preferences: Prefs, contentScript: TabContentScript) { guard let readerPreferences = preferences.dictionaryForKey(ReaderModeProfileKeyStyle), let readerMode = contentScript as? ReaderMode, var style = ReaderModeStyle(dict: readerPreferences) else { return } style.ensurePreferredColorThemeIfNeeded() readerMode.style = style } private func makeSeparatorView(fromView: UIView, topConstraint: UIView) { NSLayoutConstraint.activate([ fromView.topAnchor.constraint(equalTo: topConstraint.bottomAnchor), fromView.leftAnchor.constraint(equalTo: view.leftAnchor), fromView.rightAnchor.constraint(equalTo: view.rightAnchor), fromView.heightAnchor.constraint(equalToConstant: CGFloat(ReaderModeStyleViewModel.SeparatorLineThickness)) ]) } /// Setup constraints for a row of buttons. Left to right. They are all given the same width. private func setupButtons(_ buttons: [UIButton], inRow row: UIView, action: Selector) { for (idx, button) in buttons.enumerated() { row.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: action, for: .touchUpInside) NSLayoutConstraint.activate([ button.topAnchor.constraint(equalTo: row.topAnchor), button.leftAnchor.constraint(equalTo: idx == 0 ? row.leftAnchor : buttons[idx - 1].rightAnchor), button.bottomAnchor.constraint(equalTo: row.bottomAnchor), button.widthAnchor.constraint(equalToConstant: self.preferredContentSize.width / CGFloat(buttons.count)) ]) } } @objc func changeFontType(_ button: ReaderModeFontTypeButton) { selectFontType(button.fontType) delegate?.readerModeStyleViewController(self, didConfigureStyle: viewModel.readerModeStyle, isUsingUserDefinedColor: isUsingUserDefinedColor) } private func selectFontType(_ fontType: ReaderModeFontType) { viewModel.readerModeStyle.fontType = fontType for button in fontTypeButtons { button.isSelected = button.fontType.isSameFamily(fontType) } for button in themeButtons { button.fontType = fontType } fontSizeLabel.fontType = fontType } @objc func changeFontSize(_ button: ReaderModeFontSizeButton) { switch button.fontSizeAction { case .smaller: viewModel.readerModeStyle.fontSize = viewModel.readerModeStyle.fontSize.smaller() case .bigger: viewModel.readerModeStyle.fontSize = viewModel.readerModeStyle.fontSize.bigger() case .reset: viewModel.readerModeStyle.fontSize = ReaderModeFontSize.defaultSize } updateFontSizeButtons() delegate?.readerModeStyleViewController(self, didConfigureStyle: viewModel.readerModeStyle, isUsingUserDefinedColor: isUsingUserDefinedColor) } private func updateFontSizeButtons() { for button in fontSizeButtons { switch button.fontSizeAction { case .bigger: button.isEnabled = !viewModel.readerModeStyle.fontSize.isLargest() break case .smaller: button.isEnabled = !viewModel.readerModeStyle.fontSize.isSmallest() break case .reset: break } } } @objc func changeTheme(_ button: ReaderModeThemeButton) { selectTheme(button.readerModeTheme) isUsingUserDefinedColor = true delegate?.readerModeStyleViewController(self, didConfigureStyle: viewModel.readerModeStyle, isUsingUserDefinedColor: true) } private func selectTheme(_ theme: ReaderModeTheme) { viewModel.readerModeStyle.theme = theme } @objc func changeBrightness(_ slider: UISlider) { UIScreen.main.brightness = CGFloat(slider.value) } }
mpl-2.0
3d3b4398ed1c414b035d2226d7f22b32
41.025
152
0.68077
6.04133
false
false
false
false
masters3d/xswift
exercises/difference-of-squares/Sources/DifferenceOfSquaresExample.swift
1
487
struct Squares { var max = 1 init (_ max: Int) { if max > 0 { self.max = max } } var squareOfSums: Int { let numbers = Array(1...self.max) let sum = numbers.reduce(0, + ) return sum * sum } var sumOfSquares: Int { let numbers = Array(1...self.max) return numbers.map { return $0*$0 }.reduce(0, + ) } var differenceOfSquares: Int { return squareOfSums - sumOfSquares } }
mit
108389f78b1f26c505d82feac57053b8
18.48
57
0.505133
3.746154
false
false
false
false
brentdax/swift
validation-test/Evolution/Inputs/class_insert_superclass.swift
7
1156
#if BEFORE open class FirstMiddle { let x: String public init(x: String) { self.x = x } public func get() -> String { return x } } open class SecondMiddle { let x: String public init(x: String) { self.x = x } public func get() -> String { return x } } open class GenericMiddle<T> { let x: T public init(x: T) { self.x = x } public func get() -> T { return x } } #else // Insert concrete superclass open class Base { let x: String public init(t: String) { self.x = t } } open class FirstMiddle : Base { public init(x: String) { super.init(t: x) } public func get() -> String { return x } } // Insert generic superclass open class GenericBase<T> { let x: T public init(t: T) { self.x = t } } open class SecondMiddle : GenericBase<String> { public init(x: String) { super.init(t: x) } public func get() -> String { return x } } // Insert concrete superclass - class itself is generic open class GenericMiddle<T> : GenericBase<T> { public init(x: T) { super.init(t: x) } public func get() -> T { return x } } #endif
apache-2.0
f243de95ea0b8edd376fbd3fd8b926a5
11.703297
55
0.58218
3.107527
false
false
false
false
tardieu/swift
test/IRGen/objc_subclass.swift
3
19951
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s // REQUIRES: objc_interop // CHECK: [[SGIZMO:C13objc_subclass10SwiftGizmo]] = type // CHECK: [[TYPE:%swift.type]] = type // CHECK: [[INT:%Si]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }> // CHECK: [[OBJC_CLASS:%objc_class]] = type // CHECK: [[OPAQUE:%swift.opaque]] = type // CHECK: [[GIZMO:%CSo5Gizmo]] = type opaque // CHECK: [[OBJC:%objc_object]] = type opaque // CHECK-32: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i32 12, align [[WORD_SIZE_IN_BYTES:4]] // CHECK-64: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i64 16, align [[WORD_SIZE_IN_BYTES:8]] // CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) } // CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00" // CHECK: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer // CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00" // CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00" // CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00" // CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00" // CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00" // CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00" // CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00" // CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00" // CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00" // CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 129, // CHECK-32: i32 20, // CHECK-32: i32 20, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 129, // CHECK-64: i32 40, // CHECK-64: i32 40, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 12, // CHECK-32: i32 11, // CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%1* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast ({{(i8|i1)}} (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*) // CHECK-32: }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 11, // CHECK-64: [11 x { i8*, i8*, i8* }] [{ // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2]]*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE1:.*]]* ([[OPAQUE0:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5:.*]]* ([[OPAQUE6:.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE10:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ({{(i8|i1)}} ([[OPAQUE11:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE12:%.*]]*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5]]* ([[OPAQUE6]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*) // CHECK-64: }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 20, // CHECK-32: i32 1, // CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } { // CHECK-32: i32* @_T013objc_subclass10SwiftGizmoC1xSivWvd, // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i32 0, i32 0), // CHECK-32: i32 2, // CHECK-32: i32 4 }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 32, // CHECK-64: i32 1, // CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } { // CHECK-64: i64* @_T013objc_subclass10SwiftGizmoC1xSivWvd, // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0), // CHECK-64: i32 3, // CHECK-64: i32 8 }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 132, // CHECK-32: i32 12, // CHECK-32: i32 16, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 132, // CHECK-64: i32 16, // CHECK-64: i32 24, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}} // CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo // CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00" // CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, i32, [5 x { i8*, i8*, i8* }] } { // CHECK-32: i32 12, // CHECK-32: i32 5, // CHECK-32: [5 x { i8*, i8*, i8* }] [ // CHECK-32: { // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*, %0*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*, i32)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*) // CHECK-32: } // CHECK-32: ] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 5, // CHECK-64: [5 x { i8*, i8*, i8* }] [ // CHECK-64: { // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE13:%.*]]* ([[OPAQUE14:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE15:%.*]]*, i8*, [[OPAQUE16:%.*]]*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE18:%.*]]* ([[OPAQUE19:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE20:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*) // CHECK-64: } // CHECK-64: ] } // CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass10SwiftGizmoCN to i8*), i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_classlist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]] // CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_nlclslist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]] import Foundation import gizmo @requires_stored_property_inits class SwiftGizmo : Gizmo { var x = Int() func getX() -> Int { return x } override func duplicate() -> Gizmo { return SwiftGizmo() } override init() { super.init(bellsOn:0) } init(int i: Int, string str : String) { super.init(bellsOn:i) } deinit { var x = 10 } var enabled: Bool { @objc(isEnabled) get { return true } @objc(setIsEnabled:) set { } } } class GenericGizmo<T> : Gizmo { func foo() {} var x : Int { return 0 } var array : [T] = [] } // CHECK: define hidden [[LLVM_PTRSIZE_INT]] @_T013objc_subclass12GenericGizmoC1xSifg( var sg = SwiftGizmo() sg.duplicate() @objc_non_lazy_realization class SwiftGizmo2 : Gizmo { var sg : SwiftGizmo override init() { sg = SwiftGizmo() super.init() } deinit { } }
apache-2.0
13db3d3cd642b720a4820287c96b69ca
58.555224
347
0.599669
2.762531
false
false
false
false
Peterrkang/SpotMe
SpotMe/SpotMe/ChatVC.swift
1
6562
// // ChatVC.swift // SpotMe // // Created by Peter Kang on 11/1/16. // Copyright © 2016 Peter Kang. All rights reserved. // import UIKit import FirebaseDatabase import SwiftKeychainWrapper class ChatVC: UICollectionViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { private let _userID: String? = KeychainWrapper.standard.string(forKey: KEY_UID) private var _convo: Convo! private var messages = [Message]() var convo: Convo { get { return _convo } set { _convo = newValue } } var toUser: String { if _userID == convo.user1 { return convo.user2 } else { return convo.user1 } } var fromUser: String { if _userID == convo.user1 { return convo.user1 } else { return convo.user2 } } lazy var inputTextField: UITextField = { let textField = UITextField() textField.placeholder = "Enter Message..." textField.translatesAutoresizingMaskIntoConstraints = false textField.delegate = self return textField }() var tableView: UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() override func viewDidLoad() { super.viewDidLoad() setupComponents() tableView.delegate = self tableView.dataSource = self observeMessage() } func setupComponents(){ let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(containerView) containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true containerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true view.addSubview(tableView) tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true tableView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: containerView.topAnchor).isActive = true tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true let sendButton = UIButton(type: .system) sendButton.setTitle("Send", for: .normal) sendButton.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(sendButton) sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside) sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true containerView.addSubview(inputTextField) inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true let seperatorLineView = UIView() seperatorLineView.backgroundColor = UIColor.lightGray seperatorLineView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(seperatorLineView) seperatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true seperatorLineView.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true seperatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true seperatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true seperatorLineView.bottomAnchor.constraint(equalTo: containerView.topAnchor).isActive = true } func handleSend(){ let timestamp: String = "\(NSDate())" let ref = DataService.instance.convosRef.child(convo.id) let childRef = ref.childByAutoId() let values = ["text": inputTextField.text!, "toUser": toUser, "fromUser": fromUser, "timestamp": timestamp] childRef.updateChildValues(values) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { handleSend() textField.text = "" return true } func observeMessage() { let ref = DataService.instance.convosRef.child(convo.id) ref.observe(.childAdded, with: { (snapshot: FIRDataSnapshot) in if let dict = snapshot.value as? Dictionary<String, AnyObject>{ if let text = dict["text"] as? String { if let fromUser = dict["fromUser"] as? String { if let timestamp = dict["timestamp"] as? String { if let toUser = dict["toUser"] as? String { let message = Message(toUser: toUser, fromUser: fromUser, text: text, timestamp: timestamp) self.messages.append(message) } } } } } self.tableView.reloadData() }, withCancel: nil) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId") let message = messages[indexPath.row] cell.textLabel?.text = message.text return cell } }
mit
fbbb43557e7a8314785e76e0de9e465e
36.706897
123
0.63725
5.710183
false
false
false
false
exyte/Macaw
Source/platform/macOS/MBezierPath+Extension_macOS.swift
1
5729
// // MBezierPath+Extension_macOS.swift // Macaw // // Created by Daniil Manin on 8/17/17. // Copyright © 2017 Exyte. All rights reserved. // import Foundation #if os(OSX) import AppKit public struct MRectCorner: OptionSet { public let rawValue: UInt public static let none = MRectCorner([]) public static let topLeft = MRectCorner(rawValue: 1 << 0) public static let topRight = MRectCorner(rawValue: 1 << 1) public static let bottomLeft = MRectCorner(rawValue: 1 << 2) public static let bottomRight = MRectCorner(rawValue: 1 << 3) public static var allCorners: MRectCorner { return [.topLeft, .topRight, .bottomLeft, .bottomRight] } public init(rawValue: UInt) { self.rawValue = rawValue } } extension MBezierPath { public var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< self.elementCount { let type = self.element(at: i, associatedPoints: &points) switch type { case .moveTo: path.move(to: CGPoint(x: points[0].x, y: points[0].y)) case .lineTo: path.addLine(to: CGPoint(x: points[0].x, y: points[0].y)) case .curveTo: path.addCurve( to: CGPoint(x: points[2].x, y: points[2].y), control1: CGPoint(x: points[0].x, y: points[0].y), control2: CGPoint(x: points[1].x, y: points[1].y)) case .closePath: path.closeSubpath() @unknown default: fatalError("Type of element undefined") } } return path } public convenience init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { self.init() self.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) } public convenience init(roundedRect rect: NSRect, byRoundingCorners corners: MRectCorner, cornerRadii: NSSize) { self.init() let kappa: CGFloat = 1.0 - 0.552228474 let topLeft = rect.origin let topRight = NSPoint(x: rect.maxX, y: rect.minY) let bottomRight = NSPoint(x: rect.maxX, y: rect.maxY) let bottomLeft = NSPoint(x: rect.minX, y: rect.maxY) if corners.contains(.topLeft) { move(to: CGPoint(x: topLeft.x + cornerRadii.width, y: topLeft.y)) } else { move(to: topLeft) } if corners.contains(.topRight) { line(to: CGPoint(x: topRight.x - cornerRadii.width, y: topRight.y)) curve(to: CGPoint(x: topRight.x, y: topRight.y + cornerRadii.height), controlPoint1: CGPoint(x: topRight.x - cornerRadii.width * kappa, y: topRight.y), controlPoint2: CGPoint(x: topRight.x, y: topRight.y + cornerRadii.height * kappa)) } else { line(to: topRight) } if corners.contains(.bottomRight) { line(to: CGPoint(x: bottomRight.x, y: bottomRight.y - cornerRadii.height)) curve(to: CGPoint(x: bottomRight.x - cornerRadii.width, y: bottomRight.y), controlPoint1: CGPoint(x: bottomRight.x, y: bottomRight.y - cornerRadii.height * kappa), controlPoint2: CGPoint(x: bottomRight.x - cornerRadii.width * kappa, y: bottomRight.y)) } else { line(to: bottomRight) } if corners.contains(.bottomLeft) { line(to: CGPoint(x: bottomLeft.x + cornerRadii.width, y: bottomLeft.y)) curve(to: CGPoint(x: bottomLeft.x, y: bottomLeft.y - cornerRadii.height), controlPoint1: CGPoint(x: bottomLeft.x + cornerRadii.width * kappa, y: bottomLeft.y), controlPoint2: CGPoint(x: bottomLeft.x, y: bottomLeft.y - cornerRadii.height * kappa)) } else { line(to: bottomLeft) } if corners.contains(.topLeft) { line(to: CGPoint(x: topLeft.x, y: topLeft.y + cornerRadii.height)) curve(to: CGPoint(x: topLeft.x + cornerRadii.width, y: topLeft.y), controlPoint1: CGPoint(x: topLeft.x, y: topLeft.y + cornerRadii.height * kappa), controlPoint2: CGPoint(x: topLeft.x + cornerRadii.width * kappa, y: topLeft.y)) } else { line(to: topLeft) } close() } func addLine(to: NSPoint) { self.line(to: to) } func addCurve(to: NSPoint, controlPoint1: NSPoint, controlPoint2: NSPoint) { self.curve(to: to, controlPoint1: controlPoint1, controlPoint2: controlPoint2) } func addQuadCurve(to: NSPoint, controlPoint: NSPoint) { let QP0 = self.currentPoint let CP3 = to let CP1 = CGPoint( x: QP0.x + ((2.0 / 3.0) * (controlPoint.x - QP0.x)), y: QP0.y + ((2.0 / 3.0) * (controlPoint.y - QP0.y)) ) let CP2 = CGPoint( x: to.x + (2.0 / 3.0) * (controlPoint.x - to.x), y: to.y + (2.0 / 3.0) * (controlPoint.y - to.y) ) self.addCurve(to: CP3, controlPoint1: CP1, controlPoint2: CP2) } func addArc(withCenter: NSPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { let startAngleRadian = ((startAngle) * (180.0 / .pi)) let endAngleRadian = ((endAngle) * (180.0 / .pi)) self.appendArc(withCenter: withCenter, radius: radius, startAngle: startAngleRadian, endAngle: endAngleRadian, clockwise: !clockwise) } func addPath(path: NSBezierPath!) { self.append(path) } } #endif
mit
cba23bf0cc085ad3763b2e36ff4c91dd
33.095238
141
0.585894
3.950345
false
false
false
false
puyanLiu/LPYFramework
第三方框架改造/Toast-Swift-master/Demo/AppDelegate.swift
1
1969
// // AppDelegate.swift // Toast-Swift // // Copyright (c) 2015 Charles Scalesse. // // 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { let viewController = ViewController(style: .plain) let navigationController = UINavigationController(rootViewController: viewController) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() UINavigationBar.appearance().barTintColor = UIColor.blue UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] return true } }
apache-2.0
a660a75c8ae520f685063efdba472ac5
42.755556
151
0.742509
4.959698
false
false
false
false
eBardX/XestiMonitors
Sources/Core/UIKit/Application/ApplicationStateMonitor.swift
1
5424
// // ApplicationStateMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2016-11-23. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) || os(tvOS) import Foundation import UIKit /// /// An `ApplicationStateMonitor` instance monitors the app for changes to /// its runtime state. /// public class ApplicationStateMonitor: BaseNotificationMonitor { /// /// Encapsulates changes to the runtime state of the app. /// public enum Event { /// /// The app has entered the active state. /// case didBecomeActive /// /// The app has entered the background state. /// case didEnterBackground /// /// The app has finished launching. /// case didFinishLaunching([AnyHashable: Any]?) /// /// The app is about to leave the background state. /// case willEnterForeground /// /// The app is about to leave the active state. /// case willResignActive /// /// The app is about to terminate. /// case willTerminate } /// /// Specifies which events to monitor. /// public struct Options: OptionSet { /// /// Monitor `didBecomeActive` events. /// public static let didBecomeActive = Options(rawValue: 1 << 0) /// /// Monitor `didEnterBackground` events. /// public static let didEnterBackground = Options(rawValue: 1 << 1) /// /// Monitor `didFinishLaunching` events. /// public static let didFinishLaunching = Options(rawValue: 1 << 2) /// /// Monitor `willEnterForeground` events. /// public static let willEnterForeground = Options(rawValue: 1 << 3) /// /// Monitor `willResignActive` events. /// public static let willResignActive = Options(rawValue: 1 << 4) /// /// Monitor `willTerminate` events. /// public static let willTerminate = Options(rawValue: 1 << 5) /// /// Monitor all events. /// public static let all: Options = [.didBecomeActive, .didEnterBackground, .didFinishLaunching, .willEnterForeground, .willResignActive, .willTerminate] /// :nodoc: public init(rawValue: UInt) { self.rawValue = rawValue } /// :nodoc: public let rawValue: UInt } /// /// Initializes a new `ApplicationStateMonitor`. /// /// - Parameters: /// - options: The options that specify which events to monitor. /// By default, all events are monitored. /// - queue: The operation queue on which the handler executes. /// By default, the main operation queue is used. /// - handler: The handler to call when the app changes its /// runtime state or is about to change its runtime /// state. /// public init(options: Options = .all, queue: OperationQueue = .main, handler: @escaping (Event) -> Void) { self.application = ApplicationInjector.inject() self.handler = handler self.options = options super.init(queue: queue) } /// /// The runtime state of the app. /// public var state: UIApplicationState { return application.applicationState } private let application: ApplicationProtocol private let handler: (Event) -> Void private let options: Options override public func addNotificationObservers() { super.addNotificationObservers() if options.contains(.didBecomeActive) { observe(.UIApplicationDidBecomeActive, object: application) { [unowned self] _ in self.handler(.didBecomeActive) } } if options.contains(.didEnterBackground) { observe(.UIApplicationDidEnterBackground, object: application) { [unowned self] _ in self.handler(.didEnterBackground) } } if options.contains(.didFinishLaunching) { observe(.UIApplicationDidFinishLaunching, object: application) { [unowned self] in self.handler(.didFinishLaunching($0.userInfo)) } } if options.contains(.willEnterForeground) { observe(.UIApplicationWillEnterForeground, object: application) { [unowned self] _ in self.handler(.willEnterForeground) } } if options.contains(.willResignActive) { observe(.UIApplicationWillResignActive, object: application) { [unowned self] _ in self.handler(.willResignActive) } } if options.contains(.willTerminate) { observe(.UIApplicationWillTerminate, object: application) { [unowned self] _ in self.handler(.willTerminate) } } } } #endif
mit
2a2443cf53de74a8ff05c0051e32908e
27.845745
74
0.529965
5.596491
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/Former/Former/RowFormers/SegmentedRowFormer.swift
2
2428
// // SegmentedRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 7/30/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol SegmentedFormableRow: FormableRow { func formSegmented() -> UISegmentedControl func formTitleLabel() -> UILabel? } open class SegmentedRowFormer<T: UITableViewCell> : BaseRowFormer<T>, Formable where T: SegmentedFormableRow { // MARK: Public open var segmentTitles = [String]() open var selectedIndex: Int = 0 open var titleDisabledColor: UIColor? = .lightGray required public init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } @discardableResult public final func onSegmentSelected(_ handler: @escaping ((Int, String) -> Void)) -> Self { onSegmentSelected = handler return self } open override func cellInitialized(_ cell: T) { super.cellInitialized(cell) cell.formSegmented().addTarget(self, action: #selector(SegmentedRowFormer.valueChanged(segment:)), for: .valueChanged) } open override func update() { super.update() cell.selectionStyle = .none let titleLabel = cell.formTitleLabel() let segment = cell.formSegmented() segment.removeAllSegments() for (index, title) in segmentTitles.enumerated() { segment.insertSegment(withTitle: title, at: index, animated: false) } segment.selectedSegmentIndex = selectedIndex segment.isEnabled = enabled if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } titleColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } titleLabel?.textColor = titleDisabledColor } } // MARK: Private private final var onSegmentSelected: ((Int, String) -> Void)? private final var titleColor: UIColor? @objc private dynamic func valueChanged(segment: UISegmentedControl) { if enabled { let index = segment.selectedSegmentIndex let selectedTitle = segment.titleForSegment(at: index)! selectedIndex = index onSegmentSelected?(selectedIndex, selectedTitle) } } }
mit
2044a66d68f4fc894ae3419885b8a2ac
30.934211
126
0.635764
5.045738
false
false
false
false
KennethTsang/NumberField
NumberField/Classes/FakeCursor.swift
1
1195
// // NumberFieldCursor.swift // Pods // // Created by Tsang Kenneth on 20/3/2017. // // import UIKit final class FakeCursor: UIView { var timer: Timer? override var intrinsicContentSize: CGSize { return CGSize(width: 2, height: UIView.noIntrinsicMetric) } override var isHidden: Bool { didSet { if isHidden { timer?.invalidate() } else { if (timer?.isValid ?? false) == false { alpha = 1 timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(flash), userInfo: nil, repeats: true) } } } } @objc func flash(timer: Timer) { self.alpha = self.alpha > 0 ? 0 : 1 } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { isHidden = true } override func layoutSubviews() { super.layoutSubviews() backgroundColor = tintColor } }
mit
916d04a7f55d9d4ab4649119ba94ac4d
21.12963
139
0.528033
4.578544
false
false
false
false
3lvis/CardStack
Source/CardStackLayout.swift
1
3790
import UIKit protocol CardStackLayoutDataSource: class { func cardStateAtIndexPath(indexPath: NSIndexPath) -> Int } class CardStackLayout: UICollectionViewLayout { static let BellowOffset = 45.0 static let BellowCellHeight = 7.0 static let ScaleFactor = 0.015 var visibleCellHeight: Double = 0.0 var actualCellHeight: Double = 0.0 weak var dataSource: CardStackLayoutDataSource? = nil override func collectionViewContentSize() -> CGSize { return self.collectionView!.bounds.size } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() let visibleIndexPaths = self.indexPathsOfItemsInRect(rect) for indexPath in visibleIndexPaths { let attribute = self.layoutAttributesForItemAtIndexPath(indexPath) attributes.append(attribute!) } return attributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) self.applyLayoutAttributes(attributes) return attributes } // MARK: Private func applyLayoutAttributes(attributes: UICollectionViewLayoutAttributes) { let cardState = self.dataSource!.cardStateAtIndexPath(attributes.indexPath) switch cardState { case CardState.Normal.rawValue: attributes.frame = self.computedFrame(attributes.indexPath, offset: attributes.indexPath.row, height: self.actualCellHeight) case CardState.Selected.rawValue: attributes.frame = self.computedFrame(attributes.indexPath, offset: 0, height: self.actualCellHeight) case CardState.Collapsed.rawValue: self.applyCollapsedAttributes(attributes) default: break } } func applyCollapsedAttributes(attributes: UICollectionViewLayoutAttributes) { let indexPath = attributes.indexPath let rowCount = Double(self.collectionView!.dataSource!.collectionView(self.collectionView!, numberOfItemsInSection: indexPath.section)) attributes.frame = self.computedFrame(indexPath, offset: indexPath.row, height: 50.0) var transform = attributes.transform3D let yTarget = Double(self.collectionView!.bounds.height) - CardStackLayout.BellowOffset + (CardStackLayout.BellowCellHeight * Double(indexPath.row)) let yOffset = yTarget - Double(attributes.frame.minY) transform = CATransform3DTranslate(transform, CGFloat(0.0), CGFloat(yOffset), CGFloat(0.0)) let sx = 1.0 - ((rowCount - Double(indexPath.row)) * CardStackLayout.ScaleFactor) transform = CATransform3DScale(transform, CGFloat(sx), CGFloat(1.0), CGFloat(1.0)) attributes.transform3D = transform } func indexPathsOfItemsInRect(rect: CGRect) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() var sectionsCount = 0 if let sections = self.collectionView?.numberOfSections() { sectionsCount = sections } for section in 0..<sectionsCount { var rowsCount = 0 if let rows = self.collectionView?.numberOfItemsInSection(section) { rowsCount = rows } for row in 0..<rowsCount { indexPaths.append(NSIndexPath(forRow: row, inSection: section)) } } return indexPaths } func computedFrame(indexPath: NSIndexPath, offset: Int, height: Double) -> CGRect { return CGRect(x: 0.0, y: self.visibleCellHeight * Double(offset), width: Double(self.collectionView!.bounds.width), height: height) } }
mit
1d22b0cf27d5a44e29e785e6a1b184c0
40.195652
156
0.694195
5.234807
false
false
false
false
kinyong/KYWeiboDemo-Swfit
AYWeibo/AYWeibo/QorumLogs.swift
2
12871
// // QorumLogs.swift // Qorum // // Created by Goktug Yilmaz on 27/08/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) || os(tvOS) import UIKit #endif /// Debug error level private let kLogDebug : String = "Debug"; /// Info error level private let kLogInfo : String = "Info"; /// Warning error level private let kLogWarning : String = "Warning"; /// Error error level private let kLogError : String = "Error"; public struct QorumLogs { /// While enabled QorumOnlineLogs does not work public static var enabled = false /// 1 to 4 public static var minimumLogLevelShown = 1 /// Change the array element with another UIColor. 0 is info gray, 5 is purple, rest are log levels public static var colorsForLogLevels: [QLColor] = [ QLColor(r: 120, g: 120, b: 120), //0 QLColor(r: 0, g: 180, b: 180), //1 QLColor(r: 0, g: 150, b: 0), //2 QLColor(r: 255, g: 190, b: 0), //3 QLColor(r: 255, g: 0, b: 0), //4 QLColor(r: 160, g: 32, b: 240)] //5 private static var showFiles = [String]() //========================================================================================================== // MARK: - Public Methods //========================================================================================================== /// Ignores all logs from other files public static func onlyShowTheseFiles(fileNames: Any...) { minimumLogLevelShown = 1 let showFiles = fileNames.map {fileName in return fileName as? String ?? { let classString: String = { if let obj: AnyObject = fileName as? AnyObject { let classString = String(obj.dynamicType) return classString.ns.pathExtension } else { return String(fileName) } }() return classString }() } self.showFiles = showFiles print(ColorLog.colorizeString("QorumLogs: Only Showing: \(showFiles)", colorId: 5)) } /// Ignores all logs from other files public static func onlyShowThisFile(fileName: Any) { onlyShowTheseFiles(fileName) } /// Test to see if its working public static func test() { let oldDebugLevel = minimumLogLevelShown minimumLogLevelShown = 1 QL1(kLogDebug) QL2(kLogInfo) QL3(kLogWarning) QL4(kLogError) minimumLogLevelShown = oldDebugLevel } //========================================================================================================== // MARK: - Private Methods //========================================================================================================== private static func shouldPrintLine(level level: Int, fileName: String) -> Bool { if !QorumLogs.enabled { return false } else if QorumLogs.minimumLogLevelShown <= level { return QorumLogs.shouldShowFile(fileName) } else { return false } } private static func shouldShowFile(fileName: String) -> Bool { return QorumLogs.showFiles.isEmpty || QorumLogs.showFiles.contains(fileName) } } /// Debug error level private let kOnlineLogDebug : String = "1Debug"; /// Info error level private let kOnlineLogInfo : String = "2Info"; /// Warning error level private let kOnlineLogWarning : String = "3Warning"; /// Error error level private let kOnlineLogError : String = "4Error"; public struct QorumOnlineLogs { private static let appVersion = versionAndBuild() private static var googleFormLink: String! private static var googleFormAppVersionField: String! private static var googleFormUserInfoField: String! private static var googleFormMethodInfoField: String! private static var googleFormErrorTextField: String! /// Online logs does not work while QorumLogs is enabled public static var enabled = false /// 1 to 4 public static var minimumLogLevelShown = 1 /// Empty dictionary, add extra info like user id, username here public static var extraInformation = [String: String]() //========================================================================================================== // MARK: - Public Methods //========================================================================================================== /// Test to see if its working public static func test() { let oldDebugLevel = minimumLogLevelShown minimumLogLevelShown = 1 QL1(kLogDebug) QL2(kLogInfo) QL3(kLogWarning) QL4(kLogError) minimumLogLevelShown = oldDebugLevel } /// Setup Google Form links public static func setupOnlineLogs(formLink formLink: String, versionField: String, userInfoField: String, methodInfoField: String, textField: String) { googleFormLink = formLink googleFormAppVersionField = versionField googleFormUserInfoField = userInfoField googleFormMethodInfoField = methodInfoField googleFormErrorTextField = textField } //========================================================================================================== // MARK: - Private Methods //========================================================================================================== private static func sendError<T>(classInformation classInformation: String, textObject: T, level: String) { var text = "" if let stringObject = textObject as? String { text = stringObject } else { let stringObject = String(textObject) text = stringObject } let versionLevel = (appVersion + " - " + level) let url = NSURL(string: googleFormLink) var postData = googleFormAppVersionField + "=" + versionLevel postData += "&" + googleFormUserInfoField + "=" + extraInformation.description postData += "&" + googleFormMethodInfoField + "=" + classInformation postData += "&" + googleFormErrorTextField + "=" + text let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding) #if os(OSX) if kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber10_10 { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) task.resume() } else { NSURLConnection(request: request, delegate: nil)?.start() } #elseif os(iOS) NSURLSession.sharedSession().dataTaskWithRequest(request).resume(); #endif let printText = "OnlineLogs: \(extraInformation.description) - \(versionLevel) - \(classInformation) - \(text)" print(" \(ColorLog.colorizeString(printText, colorId: 5))\n", terminator: "") } private static func shouldSendLine(level level: Int, fileName: String) -> Bool { if !QorumOnlineLogs.enabled { return false } else if QorumOnlineLogs.minimumLogLevelShown <= level { return QorumLogs.shouldShowFile(fileName) } else { return false } } } ///Detailed logs only used while debugging public func QL1<T>(debug: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(debug, file: file, function: function, line: line, level:1) } ///General information about app state public func QL2<T>(info: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(info,file: file,function: function,line: line,level:2) } ///Indicates possible error public func QL3<T>(warning: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(warning,file: file,function: function,line: line,level:3) } ///An unexpected error occured public func QL4<T>(error: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(error,file: file,function: function,line: line,level:4) } private func printLog<T>(informationPart: String, text: T, level: Int) { print(" \(ColorLog.colorizeString(informationPart, colorId: 0))", terminator: "") print(" \(ColorLog.colorizeString(text, colorId: level))\n", terminator: "") } ///===== public func QLShortLine(file: String = #file, _ function: String = #function, _ line: Int = #line) { let lineString = "======================================" QLineManager(lineString, file: file, function: function, line: line) } ///+++++ public func QLPlusLine(file: String = #file, _ function: String = #function, _ line: Int = #line) { let lineString = "+++++++++++++++++++++++++++++++++++++" QLineManager(lineString, file: file, function: function, line: line) } ///Print data with level private func QLManager<T>(debug: T, file: String, function: String, line: Int, level : Int){ let levelText : String; switch (level) { case 1: levelText = kOnlineLogDebug case 2: levelText = kOnlineLogInfo case 3: levelText = kOnlineLogWarning case 4: levelText = kOnlineLogError default: levelText = kOnlineLogDebug } let fileExtension = file.ns.lastPathComponent.ns.pathExtension let filename = file.ns.lastPathComponent.ns.stringByDeletingPathExtension if QorumLogs.shouldPrintLine(level: level, fileName: filename) { let informationPart: String informationPart = "\(filename).\(fileExtension):\(line) \(function):" printLog(informationPart, text: debug, level: level) } else if QorumOnlineLogs.shouldSendLine(level: level, fileName: filename) { let informationPart = "\(filename).\(function)[\(line)]" QorumOnlineLogs.sendError(classInformation: informationPart, textObject: debug, level: levelText) } } ///Print line private func QLineManager(lineString : String, file: String, function: String, line: Int){ let fileExtension = file.ns.lastPathComponent.ns.pathExtension let filename = file.ns.lastPathComponent.ns.stringByDeletingPathExtension if QorumLogs.shouldPrintLine(level: 2, fileName: filename) { let informationPart: String informationPart = "\(filename).\(fileExtension):\(line) \(function):" printLog(informationPart, text: lineString, level: 5) } } private struct ColorLog { private static let ESCAPE = "\u{001b}[" private static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color private static let RESET_BG = ESCAPE + "bg;" // Clear any background color private static let RESET = ESCAPE + ";" // Clear any foreground or background color static func colorizeString<T>(object: T, colorId: Int) -> String { return "\(ESCAPE)fg\(QorumLogs.colorsForLogLevels[colorId].redColor),\(QorumLogs.colorsForLogLevels[colorId].greenColor),\(QorumLogs.colorsForLogLevels[colorId].blueColor);\(object)\(RESET)" } } private func versionAndBuild() -> String { let version = NSBundle.mainBundle().infoDictionary? ["CFBundleShortVersionString"] as! String let build = NSBundle.mainBundle().infoDictionary? [kCFBundleVersionKey as String] as! String return version == build ? "v\(version)" : "v\(version)(\(build))" } private extension String { /// Qorum Extension var ns: NSString { return self as NSString } } ///Used in color settings for QorumLogs public class QLColor { #if os(OSX) var color: NSColor #elseif os(iOS) || os(tvOS) var color: UIColor #endif public init(r: CGFloat, g: CGFloat, b: CGFloat) { #if os(OSX) color = NSColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1) #elseif os(iOS) || os(tvOS) color = UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1) #endif } public convenience init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { self.init(r: red * 255, g: green * 255, b: blue * 255) } var redColor: Int { var r: CGFloat = 0 color.getRed(&r, green: nil, blue: nil, alpha: nil) return Int(r * 255) } var greenColor: Int { var g: CGFloat = 0 color.getRed(nil, green: &g, blue: nil, alpha: nil) return Int(g * 255) } var blueColor: Int { var b: CGFloat = 0 color.getRed(nil, green: nil, blue: &b, alpha: nil) return Int(b * 255) } }
apache-2.0
4ddb5adc013446d0495964b979c9e58a
34.952514
198
0.592961
4.7901
false
false
false
false