repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
galacemiguel/bluehacks2017
Project Civ-1/Project Civ/ProjectCoverViewCell.swift
1
4665
// // ProjectCoverViewCell.swift // Project Civ // // Created by Carlos Arcenas on 2/18/17. // Copyright © 2017 Rogue Three. All rights reserved. // import UIKit class ProjectCoverViewCell: UICollectionViewCell { static let commonInsets = UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15) static let nameFont = UIFont(name: "Tofino-Bold", size: 40)! static let locationFont = UIFont(name: "Tofino-Book", size: 20)! var delegate: ProjectCoverViewCellDelegate? static func cellSize(width: CGFloat, nameString: String, locationString: String) -> CGSize { let nameBounds = TextSize.size(nameString, font: ProjectCoverViewCell.nameFont, width: width, insets: UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)) let locationBounds = TextSize.size(locationString, font: ProjectCoverViewCell.locationFont, width: width, insets: ProjectCoverViewCell.commonInsets) return CGSize(width: width, height: nameBounds.height + locationBounds.height) } lazy var gradientLayer: CAGradientLayer! = { let layer = CAGradientLayer() layer.frame = self.bounds layer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor] layer.locations = [0.6, 1.0] return layer }() let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "hellohello.jpg") return imageView }() let nameLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.numberOfLines = 0 label.font = ProjectCoverViewCell.nameFont // label.textColor = UIColor(hex6: 0xE83151) label.textColor = UIColor.white return label }() let locationLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.numberOfLines = 0 label.font = ProjectCoverViewCell.locationFont label.textColor = UIColor(hex6: 0xDBD4D3) return label }() let closeButton: UIButton = { let button = UIButton() button.setTitle("X", for: .normal) button.titleLabel?.font = UIFont(name: "Tofino-Bold", size: 20)! button.titleLabel?.textColor = UIColor.blue button.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) return button }() let infoButton: UIButton = { let button = UIButton() button.setTitle("Info", for: .normal) button.titleLabel?.font = UIFont(name: "Tofino-Bold", size: 20)! button.titleLabel?.textColor = UIColor.blue button.addTarget(self, action: #selector(infoTapped), for: .touchUpInside) return button }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) imageView.layer.addSublayer(gradientLayer) contentView.addSubview(nameLabel) contentView.addSubview(locationLabel) contentView.addSubview(closeButton) contentView.addSubview(infoButton) clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = self.frame let locationLabelRect = TextSize.size(locationLabel.text!, font: ProjectCoverViewCell.locationFont, width: frame.width, insets: ProjectCoverViewCell.commonInsets) locationLabel.frame = UIEdgeInsetsInsetRect(locationLabelRect, UIEdgeInsets(top: 0, left: 15, bottom: 10, right: 15)) locationLabel.frame.origin.y = frame.height - locationLabelRect.size.height let nameLabelRect = TextSize.size(nameLabel.text!, font: ProjectCoverViewCell.nameFont, width: frame.width, insets: UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)) nameLabel.frame = UIEdgeInsetsInsetRect(nameLabelRect, UIEdgeInsets(top: 0, left: 15, bottom: 10, right: 15)) nameLabel.frame.origin.y = locationLabel.frame.origin.y - nameLabel.frame.height closeButton.frame = CGRect(x: 20, y: 20, width: 40, height: 40) infoButton.frame = CGRect(x: frame.width - 60, y: 20, width: 40, height: 40) } func closeTapped() { delegate?.closeTapped() } func infoTapped() { delegate?.infoTapped() } } protocol ProjectCoverViewCellDelegate { func closeTapped() func infoTapped() }
mit
eca12d6c1b360ab1426016deb054720b
34.603053
178
0.647084
4.493256
false
false
false
false
powerytg/Accented
Accented/Core/Storage/Models/CommentModel.swift
1
1543
// // CommentModel.swift // Accented // // Comment model for a photo // // Created by Tiangong You on 8/8/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit import SwiftyJSON class CommentModel: ModelBase { var dateFormatter = DateFormatter() var commentId : String! var userId : String! var commentedOnUserId : String! var body : String! var creationDate : Date? var user : UserModel! override init() { super.init() } init(json:JSON) { super.init() commentId = String(json["id"].int!) modelId = commentId commentedOnUserId = String(json["to_whom_user_id"].int!) userId = String(json["user_id"].int!) body = json["body"].string!.trimmingCharacters(in: .whitespaces) // Dates dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ" let createdAt = json["created_at"].string! creationDate = dateFormatter.date(from: createdAt) // User user = UserModel(json: json["user"]) StorageService.sharedInstance.putUserToCache(user) } override func copy(with zone: NSZone? = nil) -> Any { let clone = CommentModel() clone.commentId = self.commentId clone.modelId = self.modelId clone.commentedOnUserId = self.commentedOnUserId clone.userId = self.userId clone.creationDate = self.creationDate clone.user = self.user.copy() as! UserModel return clone } }
mit
f60af0c03e624d8056302b5a174d49b5
27.036364
72
0.610895
4.236264
false
false
false
false
jverdi/Gramophone
Source/Resources/RelationshipsAPI.swift
1
8855
// // Relationships.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import Result extension Client.API { fileprivate enum Relationships: Resource { case myFollows case myFollowers case myRequests case relationship(withUserID: String) func uri() -> String { switch self { case .myFollows: return "/v1/users/self/follows" case .myFollowers: return "/v1/users/self/followed-by" case .myRequests: return "/v1/users/self/requested-by" case .relationship(let userID): return "/v1/users/\(userID)/relationship" } } } } extension Client { fileprivate static let relationshipActionFollowValue = "follow" fileprivate static let relationshipActionUnfollowValue = "unfollow" fileprivate static let relationshipActionApproveValue = "approve" fileprivate static let relationshipActionIgnoreValue = "ignore" @discardableResult public func myFollows(completion: @escaping (APIResult<Array<User>>) -> Void) -> URLSessionDataTask? { if let error = validateScopes([Scope.followerList]) { completion(Result.failure(error)); return nil } return get(API.Relationships.myFollows, completion: completion) } @discardableResult public func myFollowers(completion: @escaping (APIResult<Array<User>>) -> Void) -> URLSessionDataTask? { if let error = validateScopes([Scope.followerList]) { completion(Result.failure(error)); return nil } return get(API.Relationships.myFollowers, completion: completion) } @discardableResult public func myRequests(completion: @escaping (APIResult<Array<User>>) -> Void) -> URLSessionDataTask? { if let error = validateScopes([Scope.followerList]) { completion(Result.failure(error)); return nil } return get(API.Relationships.myRequests, completion: completion) } @discardableResult public func relationship(withUserID ID: String, completion: @escaping (APIResult<IncomingRelationship>) -> Void) -> URLSessionDataTask? { if let error = validateScopes([Scope.followerList]) { completion(Result.failure(error)); return nil } return get(API.Relationships.relationship(withUserID: ID), completion: completion) } @discardableResult public func followUser(withID ID: String, completion: @escaping (APIResult<OutgoingRelationship>) -> Void) -> URLSessionDataTask? { guard hasValidAccessToken(accessToken) else { completion(Result.failure(APIError.authenticationRequired(responseError: nil))); return nil } if let error = validateScopes([Scope.relationships]) { completion(Result.failure(error)); return nil } let apiResource = API.Relationships.relationship(withUserID: ID) guard let url = resource(apiResource, options: nil, parameters: [ Param.accessToken.rawValue: accessToken! ]) else { completion(Result.failure(APIError.invalidURL(path: apiResource.uri()))); return nil } var request = URLRequest(url: url) request.httpMethod = "POST" let parameters = [ Param.relationshipAction.rawValue: Client.relationshipActionFollowValue ] if let queryItems = queryItems(options: nil, parameters: parameters), queryItems.count > 0 { var components = URLComponents() components.queryItems = queryItems if let postString = components.query { request.httpBody = postString.data(using: .utf8) } } return fetch(request: request, completion: completion) } @discardableResult public func unfollowUser(withID ID: String, completion: @escaping (APIResult<OutgoingRelationship>) -> Void) -> URLSessionDataTask? { guard hasValidAccessToken(accessToken) else { completion(Result.failure(APIError.authenticationRequired(responseError: nil))); return nil } if let error = validateScopes([Scope.relationships]) { completion(Result.failure(error)); return nil } let apiResource = API.Relationships.relationship(withUserID: ID) guard let url = resource(apiResource, options: nil, parameters: [ Param.accessToken.rawValue: accessToken! ]) else { completion(Result.failure(APIError.invalidURL(path: apiResource.uri()))); return nil } var request = URLRequest(url: url) request.httpMethod = "POST" let parameters = [ Param.relationshipAction.rawValue: Client.relationshipActionUnfollowValue ] if let queryItems = queryItems(options: nil, parameters: parameters), queryItems.count > 0 { var components = URLComponents() components.queryItems = queryItems if let postString = components.query { request.httpBody = postString.data(using: .utf8) } } return fetch(request: request, completion: completion) } @discardableResult public func approveUser(withID ID: String, completion: @escaping (APIResult<IncomingRelationship>) -> Void) -> URLSessionDataTask? { guard hasValidAccessToken(accessToken) else { completion(Result.failure(APIError.authenticationRequired(responseError: nil))); return nil } if let error = validateScopes([Scope.relationships]) { completion(Result.failure(error)); return nil } let apiResource = API.Relationships.relationship(withUserID: ID) guard let url = resource(apiResource, options: nil, parameters: [ Param.accessToken.rawValue: accessToken! ]) else { completion(Result.failure(APIError.invalidURL(path: apiResource.uri()))); return nil } var request = URLRequest(url: url) request.httpMethod = "POST" let parameters = [ Param.relationshipAction.rawValue: Client.relationshipActionApproveValue ] if let queryItems = queryItems(options: nil, parameters: parameters), queryItems.count > 0 { var components = URLComponents() components.queryItems = queryItems if let postString = components.query { request.httpBody = postString.data(using: .utf8) } } return fetch(request: request, completion: completion) } @discardableResult public func ignoreUser(withID ID: String, completion: @escaping (APIResult<IncomingRelationship>) -> Void) -> URLSessionDataTask? { guard hasValidAccessToken(accessToken) else { completion(Result.failure(APIError.authenticationRequired(responseError: nil))); return nil } if let error = validateScopes([Scope.relationships]) { completion(Result.failure(error)); return nil } let apiResource = API.Relationships.relationship(withUserID: ID) guard let url = resource(apiResource, options: nil, parameters: [ Param.accessToken.rawValue: accessToken! ]) else { completion(Result.failure(APIError.invalidURL(path: apiResource.uri()))); return nil } var request = URLRequest(url: url) request.httpMethod = "POST" let parameters = [ Param.relationshipAction.rawValue: Client.relationshipActionIgnoreValue ] if let queryItems = queryItems(options: nil, parameters: parameters), queryItems.count > 0 { var components = URLComponents() components.queryItems = queryItems if let postString = components.query { request.httpBody = postString.data(using: .utf8) } } return fetch(request: request, completion: completion) } }
mit
a661bc835d3a1436d07f7c7587f70d37
52.023952
147
0.680632
4.897677
false
false
false
false
sindanar/PDStrategy
Example/PDStrategy/PDStrategy/PageAndRefreshViewController.swift
1
3764
// // PageAndRefreshViewController.swift // PDStrategy // // Created by Pavel Deminov on 05/11/2017. // Copyright © 2017 Pavel Deminov. All rights reserved. // import UIKit class PageAndRefreshViewController: PDTableViewController { var currentPage = 0 var limit = 20 var allDataLoaded = false var pageIsLoading = false override func viewDidLoad() { super.viewDidLoad() refreshEnabled = true refresh() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func refresh() { allDataLoaded = false currentPage = 0 loadNextPage() } func loadNextPage() { weak var wSelf = self pageIsLoading = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(2 * Double(NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {() -> Void in guard let sSelf = wSelf else { return } if sSelf.currentPage == 0 { sSelf.dataSource?.setup() } guard let sectionInfo = sSelf.dataSource?.sections?.first as? PDSectionInfo else { return } var count = sectionInfo.items?.count if count == nil { count = 0 } var array = [PageAndResfreshModel]() for _ in 0..<sSelf.limit { let model = PageAndResfreshModel() model.title = "title \(String(count!))" model.value = "value \(String(count!))" count = count! + 1 array.append(model) // limit check if (count! > 64) { break } } if array.count < sSelf.limit { sSelf.allDataLoaded = true } sSelf.dataSource?.appendData(array) sSelf.currentPage += 1 sSelf.refreshControl?.endRefreshing() sSelf.pageIsLoading = false sSelf.tableView?.reloadData() }) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count = super.tableView(tableView, numberOfRowsInSection: section) if !allDataLoaded { count += 1 } return count } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard !allDataLoaded && !pageIsLoading else { return } if let sectionInfo = self.sectionInfo(forSection: indexPath.section), dataSource?.sections?.count == indexPath.section + 1, sectionInfo.items?.count == indexPath.row { if let loadingCell = cell as? LoadingCell { loadingCell.activityIndicator.startAnimating() } loadNextPage() } } override func cellIdentifier(for indexPath: IndexPath) -> String { let cellIdentifier = super.cellIdentifier(for: indexPath) guard !allDataLoaded && !pageIsLoading else { return cellIdentifier } if let sectionInfo = self.sectionInfo(forSection: indexPath.section), dataSource?.sections?.count == indexPath.section + 1, sectionInfo.items?.count == indexPath.row { return LoadingCell.reuseIdentifier() } return cellIdentifier } }
mit
ca7b09b03b3f935437ac6b83692c0d92
30.099174
149
0.545575
5.477438
false
false
false
false
kasei/kineo
Sources/Kineo/QuadStore/Graph.swift
1
6438
// // Graph.swift // Kineo // // Created by Gregory Todd Williams on 3/20/19. // import Foundation import SPARQLSyntax public protocol GraphProtocol { associatedtype VertexType var term: Term { get } func instancesOf(_ type: Term) throws -> [VertexType] func vertex(_ term: Term) -> VertexType func vertices() throws -> [VertexType] func extensionOf(_ predicate: Term) throws -> [(VertexType, VertexType)] } public protocol GraphVertexProtocol { associatedtype VertexType associatedtype GraphType var term: Term { get } var graph: GraphType { get } func listElements() throws -> [VertexType] func incoming(_ predicate: Term) throws -> [VertexType] func outgoing(_ predicate: Term) throws -> [VertexType] func incoming() throws -> Set<Term> func outgoing() throws -> Set<Term> func edges() throws -> [(Term, VertexType)] func graphs() throws -> [GraphType] } public enum GraphAPI { public struct GraphVertex<QS: QuadStoreProtocol>: GraphVertexProtocol { public typealias VertexType = GraphVertex<QS> public typealias GraphType = Graph<QS> var store: QS public var graph: Graph<QS> public var term: Term public func listElements() throws -> [GraphVertex<QS>] { let first = Term(iri: Namespace.rdf.first) let rest = Term(iri: Namespace.rdf.rest) let _nil = Term(iri: Namespace.rdf.nil) var head = self var values = [GraphVertex<QS>]() while head.term != _nil { values += try head.outgoing(first) guard let tail = try head.outgoing(rest).first else { break } head = tail } return values } public func incoming(_ predicate: Term) throws -> [GraphVertex<QS>] { var qp = QuadPattern.all qp.predicate = .bound(predicate) qp.object = .bound(term) qp.graph = .bound(graph.term) let q = try store.quads(matching: qp) return q.map { GraphVertex(store: store, graph: graph, term: $0.subject) } } public func outgoing(_ predicate: Term) throws -> [GraphVertex<QS>] { var qp = QuadPattern.all qp.subject = .bound(term) qp.predicate = .bound(predicate) qp.graph = .bound(graph.term) let q = try store.quads(matching: qp) return q.map { GraphVertex(store: store, graph: graph, term: $0.object) } } public func incoming() throws -> Set<Term> { var qp = QuadPattern.all qp.object = .bound(term) qp.graph = .bound(graph.term) let q = try store.quads(matching: qp) let props = Set(q.map { $0.predicate }) return props } public func outgoing() throws -> Set<Term> { var qp = QuadPattern.all qp.subject = .bound(term) qp.graph = .bound(graph.term) let q = try store.quads(matching: qp) let props = Set(q.map { $0.predicate }) return props } public func edges() throws -> [(Term, GraphVertex<QS>)] { var qp = QuadPattern.all qp.graph = .bound(graph.term) let q = try store.quads(matching: qp) let pairs = q.map { ($0.predicate, GraphVertex(store: store, graph: graph, term: $0.subject)) } return pairs } public func graphs() throws -> [Graph<QS>] { var outQp = QuadPattern.all outQp.subject = .bound(term) let oq = try store.quads(matching: outQp) let outV = Set(oq.map { $0.graph }) var inQp = QuadPattern.all inQp.object = .bound(term) let iq = try store.quads(matching: inQp) let inV = Set(iq.map { $0.graph }) let vertices = outV.union(inV) return vertices.map { Graph(store: store, term: $0) } } } public struct Graph<QS: QuadStoreProtocol>: GraphProtocol { public typealias VertexType = GraphVertex<QS> var store: QS public var term: Term public func instancesOf(_ type: Term) throws -> [VertexType] { var qp = QuadPattern.all qp.predicate = .bound(Term(iri: Namespace.rdf.type)) qp.object = .bound(type) qp.graph = .bound(term) let q = try store.quads(matching: qp) let subjects = q.map { GraphVertex(store: store, graph: self, term: $0.subject) } return subjects } public func vertex(_ term: Term) -> VertexType { return GraphVertex(store: store, graph: self, term: term) } public func vertices() throws -> [VertexType] { let vertices = store.graphTerms(in: term) return vertices.map { GraphVertex(store: store, graph: self, term: $0) } } public func extensionOf(_ predicate: Term) throws -> [(VertexType, VertexType)] { var qp = QuadPattern.all qp.predicate = .bound(predicate) qp.graph = .bound(term) let subjects = try store.quads(matching: qp).map { GraphVertex(store: store, graph: self, term: $0.subject) } let objects = try store.quads(matching: qp).map { GraphVertex(store: store, graph: self, term: $0.object) } let pairs = zip(subjects, objects) return Array(pairs) } } } extension GraphAPI.GraphVertex: Hashable { public static func == (lhs: GraphAPI.GraphVertex<QS>, rhs: GraphAPI.GraphVertex<QS>) -> Bool { return lhs.term == rhs.term && lhs.graph == rhs.graph } public func hash(into hasher: inout Hasher) { hasher.combine(term) hasher.combine(graph) } } extension GraphAPI.Graph: Hashable { public static func == (lhs: GraphAPI.Graph<QS>, rhs: GraphAPI.Graph<QS>) -> Bool { return lhs.term == rhs.term } public func hash(into hasher: inout Hasher) { hasher.combine(term) } } extension QuadStoreProtocol { public func graph(_ iri: Term) -> GraphAPI.Graph<Self> { return GraphAPI.Graph(store: self, term: iri) } }
mit
4da8087b3deecd6d7b4657245b25b4c9
33.8
121
0.560578
4.066961
false
false
false
false
rogerioth/OriginStamp-MacOS
OriginStamp-Mac/OriginStamp-Mac/APIViewController.swift
1
1687
// // APIViewController.swift // OriginStamp-Mac // // Created by Rogerio Hirooka on 8/17/16. // Copyright © 2016 Rogerio Hirooka. All rights reserved. // import Cocoa import Foundation class APIViewController : NSViewController { @IBOutlet weak var buttonAPIKey: NSButton! @IBOutlet weak var txtAPIKey: NSTextField! override func viewDidLoad() { super.viewDidLoad() let textColor = NSColor.blueColor() let colorTitle = NSMutableAttributedString(attributedString: buttonAPIKey.attributedTitle) let titleRange = NSMakeRange(0, colorTitle.length) colorTitle.addAttribute(NSForegroundColorAttributeName, value: textColor, range: titleRange) buttonAPIKey.attributedTitle = colorTitle let defaults = NSUserDefaults.standardUserDefaults() if let apiKey = defaults.stringForKey("APIKey") { txtAPIKey.stringValue = apiKey } else { txtAPIKey.stringValue = Constants.DefaultAPIKey } } @IBAction func tapAPIKey(sender: AnyObject) { if let checkURL = NSURL(string: "https://www.originstamp.org/developer") { if NSWorkspace.sharedWorkspace().openURL(checkURL) { AppDelegate.log.info("Openning external URL at \(checkURL)...") } } else { } } override func viewWillDisappear() { // saves the API Key to storage let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(txtAPIKey.stringValue, forKey: "APIKey") AppDelegate.log.info("Updating APIKey to: \(txtAPIKey.stringValue)") } }
gpl-3.0
967eaab5af6fb690de5475ccb04b48ce
28.086207
100
0.647094
5.047904
false
false
false
false
scyphi/swift
Stopwatch/Stopwatch/ViewController.swift
1
1002
// // ViewController.swift // Stopwatch // // Created by Pradyuman Vig on 3/19/15. // Copyright (c) 2015 Asuna. All rights reserved. // import UIKit class ViewController: UIViewController { var timer = NSTimer() var count = 0 func updateTime(){ count++ display.text = "\(count)" } @IBAction func pause(sender: AnyObject) { timer.invalidate() } @IBOutlet var display: UILabel! @IBAction func start(sender: AnyObject) { timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) } @IBAction func stop(sender: AnyObject) { timer.invalidate() count = 0 display.text = "0" } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
368cf06ec42166b67d42778c9e98445a
17.555556
133
0.605788
4.473214
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/NSRange.swift
1
8785
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSRange : Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(location) hasher.combine(length) } public static func==(lhs: NSRange, rhs: NSRange) -> Bool { return lhs.location == rhs.location && lhs.length == rhs.length } } extension NSRange : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "{\(location), \(length)}" } public var debugDescription: String { guard location != NSNotFound else { return "{NSNotFound, \(length)}" } return "{\(location), \(length)}" } } extension NSRange { public init?(_ string: __shared String) { var savedLocation = 0 if string.isEmpty { // fail early if the string is empty return nil } let scanner = Scanner(string: string) let digitSet = CharacterSet.decimalDigits let _ = scanner.scanUpToCharacters(from: digitSet, into: nil) if scanner.isAtEnd { // fail early if there are no decimal digits return nil } var location = 0 savedLocation = scanner.scanLocation guard scanner.scanInt(&location) else { return nil } if scanner.isAtEnd { // return early if there are no more characters after the first int in the string return nil } if scanner.scanString(".", into: nil) { scanner.scanLocation = savedLocation var double = 0.0 guard scanner.scanDouble(&double) else { return nil } guard let integral = Int(exactly: double) else { return nil } location = integral } let _ = scanner.scanUpToCharacters(from: digitSet, into: nil) if scanner.isAtEnd { // return early if there are no integer characters after the first int in the string return nil } var length = 0 savedLocation = scanner.scanLocation guard scanner.scanInt(&length) else { return nil } if !scanner.isAtEnd { if scanner.scanString(".", into: nil) { scanner.scanLocation = savedLocation var double = 0.0 guard scanner.scanDouble(&double) else { return nil } guard let integral = Int(exactly: double) else { return nil } length = integral } } self.init(location: location, length: length) } } extension NSRange { public var lowerBound: Int { return location } public var upperBound: Int { return location + length } public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) } public mutating func formUnion(_ other: NSRange) { self = union(other) } public func union(_ other: NSRange) -> NSRange { let max1 = location + length let max2 = other.location + other.length let maxend = (max1 < max2) ? max2 : max1 let minloc = location < other.location ? location : other.location return NSRange(location: minloc, length: maxend - minloc) } public func intersection(_ other: NSRange) -> NSRange? { let max1 = location + length let max2 = other.location + other.length let minend = (max1 < max2) ? max1 : max2 if other.location <= location && location < max2 { return NSRange(location: location, length: minend - location) } else if location <= other.location && other.location < max1 { return NSRange(location: other.location, length: minend - other.location); } return nil } } //===----------------------------------------------------------------------===// // Ranges //===----------------------------------------------------------------------===// extension NSRange { public init<R: RangeExpression>(_ region: R) where R.Bound: FixedWidthInteger { let r = region.relative(to: 0..<R.Bound.max) self.init(location: numericCast(r.lowerBound), length: numericCast(r.count)) } public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S) where R.Bound == S.Index { let r = region.relative(to: target) self.init(target._toUTF16Offsets(r)) } @available(swift, deprecated: 4, renamed: "Range.init(_:)") public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } } extension Range where Bound: BinaryInteger { public init?(_ range: NSRange) { guard range.location != NSNotFound else { return nil } self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound))) } } // This additional overload will mean Range.init(_:) defaults to Range<Int> when // no additional type context is provided: extension Range where Bound == Int { public init?(_ range: NSRange) { guard range.location != NSNotFound else { return nil } self.init(uncheckedBounds: (range.lowerBound, range.upperBound)) } } extension Range where Bound == String.Index { private init?<S: StringProtocol>( _ range: NSRange, _genericIn string: __shared S ) { // Corresponding stdlib version guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else { fatalError() } let u = string.utf16 guard range.location != NSNotFound, let start = u.index( u.startIndex, offsetBy: range.location, limitedBy: u.endIndex), let end = u.index( start, offsetBy: range.length, limitedBy: u.endIndex), let lowerBound = String.Index(start, within: string), let upperBound = String.Index(end, within: string) else { return nil } self = lowerBound..<upperBound } public init?(_ range: NSRange, in string: __shared String) { if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { // When building for an OS that has the new stuff that supports // the generic version available, we just use that. self.init(range, _genericIn: string) } else { // Need to have the old version available to support testing a just- // built standard library on 10.14. We may want to figure out a more // principled way to handle this in the future, but this should keep // local and PR testing working. let u = string.utf16 guard range.location != NSNotFound, let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex), let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex), let lowerBound = String.Index(start, within: string), let upperBound = String.Index(end, within: string) else { return nil } self = lowerBound..<upperBound } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public init?<S: StringProtocol>(_ range: NSRange, in string: __shared S) { self.init(range, _genericIn: string) } } extension NSRange : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["location": location, "length": length]) } } extension NSRange : _CustomPlaygroundQuickLookable { @available(*, deprecated, message: "NSRange.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: PlaygroundQuickLook { return .range(Int64(location), Int64(length)) } } extension NSRange : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let location = try container.decode(Int.self) let length = try container.decode(Int.self) self.init(location: location, length: length) } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.location) try container.encode(self.length) } }
apache-2.0
5bb2597440a66ee8348a2766ba8dd7eb
34.281124
117
0.599089
4.662951
false
false
false
false
wavecos/curso_ios_3
SuperMarioBook/SuperMarioBook/ViewControllers/DetailViewController.swift
1
1347
// // DetailViewController.swift // SuperMarioBook // // Created by onix on 11/8/14. // Copyright (c) 2014 tekhne. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var consoleLabel: UILabel! @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var notesLabel: UILabel! var character : Character? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if self.character != nil { self.title = self.character!.name self.photoView.image = self.character!.image self.consoleLabel.text = self.character!.console self.yearLabel.text = String(self.character!.year) self.notesLabel.text = self.character!.notes } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
fe21256afd4602b2aa1eda90e87fca09
24.903846
104
0.697105
4.535354
false
false
false
false
takev/DimensionsCAM
DimensionsCAM/FixedPoint.swift
1
4980
// DimensionsCAM - A multi-axis tool path generator for a milling machine // Copyright (C) 2015 Take Vos // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. protocol NumericOperationsType { func +(l: Self, r: Self) -> Self func -(l: Self, r: Self) -> Self func *(l: Self, r: Self) -> Self func /(l: Self, r: Self) -> Self } protocol ShiftOperationsType { func <<(l: Self, r: Self) -> Self func >>(l: Self, r: Self) -> Self } protocol NumericConvertible { init(_: Int64) init(_: Int) init(_: Double) var id: UInt64 { get } var toDouble: Double { get } } extension NumericConvertible { /// Get the lowest 21 bits of a signed scaled Q10 integer var id: UInt64 { switch self { case let x as Int64: return UInt64(bitPattern: x) & 0x1fffff; default: preconditionFailure("Can not cast to an id") } } var toDouble: Double { return Double(self) } } extension Int64: NumericOperationsType, ShiftOperationsType, NumericConvertible { } extension Double: NumericOperationsType, NumericConvertible { init(_ x: NumericConvertible) { switch x { case let value as Int64: self = Double(value) case let value as Double: self = value default: self = x.toDouble } } } protocol FixedPointQ { typealias IntElement: NumericOperationsType, BitwiseOperationsType, Comparable, ShiftOperationsType, IntegerLiteralConvertible, NumericConvertible, Hashable; static var fractionWidth: IntElement { get } static func scaleUp(x: Double) -> IntElement static func scaleUp(x: IntElement) -> IntElement static func scaleDown(x: IntElement) -> IntElement static func scaleDown(x: IntElement) -> Double } extension FixedPointQ { static func scaleUp(x: Double) -> IntElement { return IntElement(round(x * Double(1 << fractionWidth))) } static func scaleDown(x: IntElement) -> Double { return Double(x) / Double(1 << fractionWidth) } static func scaleUp(x: IntElement) -> IntElement { return x << fractionWidth } static func scaleDown(x : IntElement) -> IntElement { return (x >> fractionWidth) + ((x >> (fractionWidth - 1)) & 1) } } struct FixedPointQ53_10: FixedPointQ { typealias IntElement = Int64 static var fractionWidth: IntElement = 10 } struct FixedPoint<T: FixedPointQ> : NumericOperationsType, Comparable, NumericConvertible, Hashable, IntegerLiteralConvertible, FloatLiteralConvertible { let v: T.IntElement init(_ a: T.IntElement) { v = T.scaleUp(a) } init(_ a: Double) { v = T.scaleUp(a) } init(_ a: Int) { v = T.scaleUp(T.IntElement(a)) } init(_ a: Int64) { v = T.scaleUp(T.IntElement(a)) } init(raw: T.IntElement) { v = raw } init(integerLiteral value: IntegerLiteralType) { v = T.scaleUp(T.IntElement(value)) } init(floatLiteral value: FloatLiteralType) { v = T.scaleUp(value) } var hashValue: Int { return v.hashValue } var id: UInt64 { return v.id } var toDouble: Double { return T.scaleDown(v) } } func ==<T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> Bool { return lhs.v == rhs.v } func < <T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> Bool { return lhs.v < rhs.v } func <= <T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> Bool { return lhs.v <= rhs.v } func > <T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> Bool { return lhs.v > rhs.v } func >= <T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> Bool { return lhs.v >= rhs.v } func +<T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> FixedPoint<T> { return FixedPoint<T>(raw:lhs.v + rhs.v) } func -<T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> FixedPoint<T> { return FixedPoint<T>(raw:lhs.v - rhs.v) } func *<T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> FixedPoint<T> { return FixedPoint<T>(raw:T.scaleDown(lhs.v * rhs.v)) } func /<T: FixedPointQ>(lhs: FixedPoint<T>, rhs: FixedPoint<T>) -> FixedPoint<T> { return FixedPoint<T>(raw:T.scaleUp(lhs.v) / rhs.v) } typealias Fix10 = FixedPoint<FixedPointQ53_10>
gpl-3.0
538123d8727e24c3ac833a2cbfda803c
25.774194
161
0.637751
3.521924
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
11-WKWebProgressDemo/WKWebProgressDemo/BaseWebViewController.swift
1
12680
// // BaseWebViewController.swift // EnergyTaxi // // Created by Allison on 2017/5/23. // Copyright © 2017年 Allison. All rights reserved. // import UIKit import WebKit class BaseWebViewController: UIViewController { var webView: WKWebView? var progressView: UIProgressView? override func viewDidLoad() { super.viewDidLoad() //self.view.backgroundColor = UIColor.white // self.automaticallyAdjustsScrollViewInsets = false let configuration = WKWebViewConfiguration.init() // 设置偏好设置 configuration.preferences = WKPreferences.init() configuration.preferences.minimumFontSize = 16; configuration.preferences.javaScriptEnabled = true // 不能自动通过窗口打开 configuration.preferences.javaScriptCanOpenWindowsAutomatically = false // web内容处理池 configuration.processPool = WKProcessPool.init() // 通过JS与WebView交互 configuration.userContentController = WKUserContentController.init() // 注意:self会被强引用(像被某个单例请引用,释放webView也不能释放self),得调用下面的代码才行 // self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "AppModel") // 注册函数名,注入JS对象名称AppModel,JS调用改函数时WKScriptMessageHandler代理可接收到 configuration.userContentController.add(self as WKScriptMessageHandler, name: "AppModel") self.webView = WKWebView.init(frame: self.view.bounds, configuration: configuration) self.view.addSubview(self.webView!) self.webView?.allowsBackForwardNavigationGestures = true // 代理代理 self.webView?.navigationDelegate = self // 与webview UI 交互代理 self.webView?.uiDelegate = self // KVO self.webView?.addObserver(self, forKeyPath: "title", options: .new, context: nil) self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) self.progressView = UIProgressView.init(frame: CGRect(x:0, y:(self.navigationController?.navigationBar.bounds.height)!, width:self.view.frame.size.width, height:5)) self.navigationController?.navigationBar.addSubview(self.progressView!) self.progressView?.backgroundColor = UIColor.white self.progressView?.progressTintColor = UIColor.blue self.progressView?.trackTintColor = UIColor.lightGray let goFarward = UIBarButtonItem.init(title: "前进", style: .plain, target: self, action: #selector(BaseWebViewController.goFarward)) let goBack = UIBarButtonItem.init(title: "后退", style: .plain, target: self, action: #selector(BaseWebViewController.goBack)) self.navigationItem.rightBarButtonItems = [goBack,goFarward] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // let Url = Bundle.main.url(forResource: "test", withExtension: "html") let Url = URL.init(string: "https://github.com") let request = URLRequest.init(url: Url!) _ = self.webView?.load(request) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Swift调用JS self.webView?.evaluateJavaScript("callJsAlert()", completionHandler: { (response, error) in if (error == nil) { print(response ?? "") }else { print(error?.localizedDescription ?? "") } }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // 一定要调用,不然self会一直被强引用,就算释放webView也不能将self释放 self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "AppModel") self.progressView?.removeFromSuperview() self.webView?.stopLoading() } deinit { self.webView?.removeObserver(self, forKeyPath: "title") self.webView?.removeObserver(self, forKeyPath: "estimatedProgress") NSLog("\(self.classForCoder)%@已释放") } final func goFarward() { if (self.webView?.canGoForward == true) { _ = self.webView?.goForward() } } final func goBack() { if (self.webView?.canGoBack == true) { _ = self.webView?.goBack() } } // MARK - KVO override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "title" { self.navigationItem.title = self.webView?.title }else if keyPath == "estimatedProgress" { let estimatedProgress = Float((self.webView?.estimatedProgress)!) self.progressView?.setProgress(estimatedProgress, animated: true) //TLOG(estimatedProgress) }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension BaseWebViewController: WKNavigationDelegate{ // MARK: - WKNavigationDelegate /// 发送请求前决定是否跳转的代理 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { // let hostName = navigationAction.request.url?.host?.lowercased() // if (navigationAction.navigationType == WKNavigationType.linkActivated && hostName?.contains(".baidu.com") == false) { // UIApplication.shared.canOpenURL(navigationAction.request.url!) // decisionHandler(WKNavigationActionPolicy.cancel) // }else{ // self.progressView?.alpha = 1.0 decisionHandler(WKNavigationActionPolicy.allow) // } TLOG("") } /// 收到响应后,决定是否跳转的代理 func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { decisionHandler(WKNavigationResponsePolicy.allow) TLOG("") } /// 接收到服务器跳转请求的代理 func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { TLOG("") } /// 准备加载页面 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { self.progressView?.isHidden = false self.progressView?.alpha = 1.0 TLOG("") } /// 准备加载失败 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { weak var weakSelf = self UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: { guard let strongSelf = weakSelf else { return } strongSelf.progressView?.alpha = 0 }) { (finished) in guard let strongSelf = weakSelf else { return } strongSelf.progressView?.progress = 0 strongSelf.progressView?.isHidden = true } TLOG("") } /// 内容开始加载 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { TLOG("") } /// 加载完成 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { webView.evaluateJavaScript("showAlert('这是一个弹窗')") { (item, error) in if (error != nil) { TLOG(item) }else { TLOG(error?.localizedDescription) } } weak var weakSelf = self UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: { guard let strongSelf = weakSelf else { return } strongSelf.progressView?.alpha = 0 }) { (finished) in guard let strongSelf = weakSelf else { return } strongSelf.progressView?.progress = 0 strongSelf.progressView?.isHidden = true } TLOG("") } /// 加载失败 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { weak var weakSelf = self UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: { guard let strongSelf = weakSelf else { return } strongSelf.progressView?.alpha = 0 }) { (finished) in guard let strongSelf = weakSelf else { return } strongSelf.progressView?.progress = 0 strongSelf.progressView?.isHidden = true } TLOG("") } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) TLOG("") } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { TLOG("") } } extension BaseWebViewController: WKScriptMessageHandler{ // MARK - WKNavigationDelegate // JS调用swift注册的函数时回调,message包括JS传的数据 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name.isEqual("AppModel") { // NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull print(message.body) } } } extension BaseWebViewController: WKUIDelegate{ // MARK - WKUIDelegate // web已关闭 func webViewDidClose(_ webView: WKWebView) { TLOG("") } // 在JS端调用alert函数时(警告弹窗),会触发此代理方法。message :JS端传的数据 // 通过completionHandler()回调JS func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertVC = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in completionHandler() })) self.present(alertVC, animated: true, completion: nil) TLOG("") } // JS端调用confirm函数时(确认、取消弹窗),会触发此方法 // completionHandler(true)返回结果,message :JS端传的数据 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertVC = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in completionHandler(true) })) alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in completionHandler(false) })) self.present(alertVC, animated: true, completion: nil) TLOG(message) } // JS调用prompt函数(输入框)时回调,completionHandler回调结果 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertVC = UIAlertController.init(title: "TextInput", message: prompt, preferredStyle: .alert) alertVC.addTextField { (textField) in textField.textColor = UIColor.red textField.placeholder = "TextInput" } alertVC.addAction(UIAlertAction.init(title: "确定", style: .cancel, handler: { (action) in completionHandler(alertVC.textFields?.last?.text) })) self.present(alertVC, animated: true, completion: nil) TLOG(prompt) } }
mit
5672e7d2b6ef72ebfdae38c8ff97987e
34.66568
201
0.63061
5.086498
false
false
false
false
RiBj1993/CodeRoute
LoginForm/GOOGLEViewController.swift
1
3801
// // GOOGLEViewController.swift // LoginForm // // Created by SwiftR on 26/04/2017. // Copyright © 2017 vishalsonawane. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase import MobileCoreServices import Firebase import GoogleSignIn import FBSDKLoginKit import Firebase import FirebaseAuthUI import FirebaseGoogleAuthUI import FirebaseFacebookAuthUI import FirebaseAnalytics class GOOGLEViewController: UIViewController,UITextFieldDelegate , GIDSignInUIDelegate { let rootRef = FIRDatabase.database().reference() let storage = FIRStorage.storage() let ref: FIRDatabaseReference? = nil @IBOutlet weak var signn: GIDSignInButton! // @IBOutlet weak var signnnn: GIDSignInButton! override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().uiDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Handle your logic for siging with social media here /* @IBAction func connectWithFacebook(_ sender: AnyObject) { let facebookLogin = FBSDKLoginManager() print("Logging In") facebookLogin.logIn(withReadPermissions: ["email"], from: self, handler:{(facebookResult, facebookError) -> Void in if facebookError != nil { print("jhkjh") } else if (facebookResult?.isCancelled)! { print("Facebook login was cancelled.") } else { let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString) print("You’re inz 😉") FIRAuth.auth()?.signIn(with: credential) { (user, error) in self.performSegue(withIdentifier: "signF", sender: self ) if error == nil { self.performSegue(withIdentifier: "signF", sender: self ) } }} }); }*/ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } func signIn(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { print("failed to log into google: ", error) return } print("successfully logged into google ", user) guard let idToken = user.authentication.idToken else { return } guard let accessToken = user.authentication.accessToken else { return } let credentials = FIRGoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken) FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in if let error = error { print("Faild to create a firebase user with google account: ", error) return } guard let uid = user?.uid else { return } print("Successfully logged into firebase with google ", uid) self.performSegue(withIdentifier: "googleF", sender: self ) }) } @IBAction func connectWithGoogle(_ sender: GIDSignInButton) { print("nnnnnnnnnnnnnnnnnnnnn ") GIDSignIn.sharedInstance().signIn() print("vvvvvvvvvvvvvvvvv: ") } }
apache-2.0
9b22df227eae72285d6cb5a41def1b7f
32
124
0.610013
5.352609
false
false
false
false
moltin/ios-swift-example
MoltinSwiftExample/MoltinSwiftExample/ProductListTableViewController.swift
1
6356
// // ProductListTableViewController.swift // MoltinSwiftExample // // Created by Dylan McKee on 16/08/2015. // Copyright (c) 2015 Moltin. All rights reserved. // import UIKit import Moltin class ProductListTableViewController: UITableViewController { fileprivate let CELL_REUSE_IDENTIFIER = "ProductCell" fileprivate let LOAD_MORE_CELL_IDENTIFIER = "ProductsLoadMoreCell" fileprivate let PRODUCT_DETAIL_VIEW_SEGUE_IDENTIFIER = "productDetailSegue" fileprivate var products:NSMutableArray = NSMutableArray() fileprivate var paginationOffset:Int = 0 fileprivate var showLoadMore:Bool = true fileprivate let PAGINATION_LIMIT:Int = 3 fileprivate var selectedProductDict:NSDictionary? var collectionId:String? override func viewDidLoad() { super.viewDidLoad() loadProducts(true) } fileprivate func loadProducts(_ showLoadingAnimation: Bool){ assert(collectionId != nil, "Collection ID is required!") // Load in the next set of products... // Show loading if neccesary? if showLoadingAnimation { SwiftSpinner.show("Loading products") } Moltin.sharedInstance().product.listing(withParameters: ["collection": collectionId!, "limit": NSNumber(value: PAGINATION_LIMIT), "offset": paginationOffset], success: { (response) -> Void in // Let's use this response! SwiftSpinner.hide() if let newProducts:NSArray = response?["result"] as? NSArray { self.products.addObjects(from: newProducts as [AnyObject]) } let responseDictionary = NSDictionary(dictionary: response!) if let newOffset:NSNumber = responseDictionary.value(forKeyPath: "pagination.offsets.next") as? NSNumber { self.paginationOffset = newOffset.intValue } if let totalProducts:NSNumber = responseDictionary.value(forKeyPath: "pagination.total") as? NSNumber { // If we have all the products already, don't show the 'load more' button! if totalProducts.intValue >= self.products.count { self.showLoadMore = false } } self.tableView.reloadData() }) { (response, error) -> Void in // Something went wrong! SwiftSpinner.hide() AlertDialog.showAlert("Error", message: "Couldn't load products", viewController: self) print("Something went wrong...") print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if showLoadMore { return (products.count + 1) } return products.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (showLoadMore && (indexPath as NSIndexPath).row > (products.count - 1)) { // it's the last item - show a 'Load more' cell for pagination instead. let cell = tableView.dequeueReusableCell(withIdentifier: LOAD_MORE_CELL_IDENTIFIER, for: indexPath) as! ProductsLoadMoreTableViewCell return cell } let cell = tableView.dequeueReusableCell(withIdentifier: CELL_REUSE_IDENTIFIER, for: indexPath) as! ProductsListTableViewCell let row = (indexPath as NSIndexPath).row let product:NSDictionary = products.object(at: row) as! NSDictionary cell.configureWithProduct(product) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if (showLoadMore && (indexPath as NSIndexPath).row > (products.count - 1)) { // Load more products! loadProducts(false) return } // Push a product detail view controller for the selected product. let product:NSDictionary = products.object(at: (indexPath as NSIndexPath).row) as! NSDictionary selectedProductDict = product performSegue(withIdentifier: PRODUCT_DETAIL_VIEW_SEGUE_IDENTIFIER, sender: self) } override func tableView(_ _tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) { cell.separatorInset = UIEdgeInsets.zero } if cell.responds(to: #selector(setter: UIView.layoutMargins)) { cell.layoutMargins = UIEdgeInsets.zero } if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)) { cell.preservesSuperviewLayoutMargins = false } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. if segue.identifier == PRODUCT_DETAIL_VIEW_SEGUE_IDENTIFIER { // Set up product detail view let newViewController = segue.destination as! ProductDetailViewController newViewController.title = selectedProductDict!.value(forKey: "title") as? String newViewController.productDict = selectedProductDict } } }
mit
4cfd01b6383c133dffb4a5c6813be4da
33.73224
199
0.611076
5.580334
false
false
false
false
tombuildsstuff/swiftcity
SwiftCity/Entities/VCSRevision.swift
1
529
public struct VCSRevision { public let version: String public let vcsRootInstance: VCSRootInstance init?(dictionary: [String: AnyObject]) { guard let version = dictionary["version"] as? String, let instanceDictionary = dictionary["vcs-root-instance"] as? [String: AnyObject], let instance = VCSRootInstance(dictionary: instanceDictionary) else { return nil } self.version = version self.vcsRootInstance = instance } }
mit
8ca2c061582ad30f9ec903e8a4c8dda6
30.176471
93
0.620038
4.943925
false
false
false
false
FedeGens/WeePager
WeePager/BodyView.swift
1
8304
// // BodyView.swift // MyPager // // Created by Federico Gentile on 02/01/17. // Copyright © 2017 Federico Gentile. All rights reserved. // import UIKit @IBDesignable class BodyView: UIScrollView, UIScrollViewDelegate { private var initialPosition : Double! var viewControllers : [UIViewController] = [UIViewController]() var infiniteViewControllers : [UIViewController] = [UIViewController]() var menuReference: MenuView? var pagerReference: WeePager! init(frame: CGRect, viewControllers: [UIViewController], pagerReference: WeePager) { super.init(frame: frame) self.pagerReference = pagerReference self.isPagingEnabled = true self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.clipsToBounds = pagerReference.clipsToBounds self.isScrollEnabled = pagerReference.bodyScrollable self.bounces = pagerReference.bodyBounceable delegate = self self.viewControllers = viewControllers if pagerReference.loadAllPages { for elem in viewControllers { self.addSubview(elem.view) } } self.decelerationRate = UIScrollView.DecelerationRate.normal } internal func updateLayout() { //setup infiniteScroll guard !pagerReference.infiniteScroll else { updateLayoutInfiniteScroll() return } for elem in viewControllers { let index = viewControllers.firstIndex(of: elem)! elem.view.frame.size = self.frame.size elem.view.frame.origin.x = CGFloat(index)*self.frame.width } self.contentSize = CGSize(width: frame.width*CGFloat(viewControllers.count), height: 1.0) self.contentOffset.x = CGFloat(pagerReference.getPage()) * self.frame.width menuReference?.moveIndicator(offsetX: Double(self.contentOffset.x)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: Scroll Delegate func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { pagerReference.delegate?.pagerWillBeginMoving?(fromIndex: self.currentPage) } internal func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard !pagerReference.infiniteScroll else { pagerReference.didSetPage(index: pagerReference.getPage()) return } pagerReference.didSetPage(index: (self.currentPage < viewControllers.count) ? self.currentPage : viewControllers.count-1) } internal func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { guard !pagerReference.infiniteScroll else { pagerReference.didSetPage(index: pagerReference.getPage()) return } pagerReference.didSetPage(index: (self.currentPage < viewControllers.count) ? self.currentPage : viewControllers.count-1) } internal func scrollViewDidScroll(_ scrollView: UIScrollView) { if !pagerReference.infiniteScroll { pagerReference.isSettingPage(index: (self.currentHalfPage < viewControllers.count) ? self.currentHalfPage : viewControllers.count-1) menuReference?.moveIndicator(offsetX: Double(scrollView.contentOffset.x)) } else { pagerReference.isSettingPage(index: self.currentHalfPageInfinite) } pagerReference.delegate?.percentageScrolled?(percentage: Double(scrollView.contentOffset.x / (CGFloat(viewControllers.count-1) * self.frame.width))) } //MARK: Pages Management internal func moveToPage(index: Int, animated: Bool) { let myOffset = CGFloat(index)*frame.width setContentOffset(CGPoint(x: myOffset, y: 0), animated: animated) } private func createPageFromController(index: Int) { if index >= 0 && index < self.viewControllers.count && !self.viewControllers[index].view.isDescendant(of: self) { self.addSubview(self.viewControllers[index].view) } } internal func checkCreatedPages(index: Int) { guard !pagerReference.loadAllPages else{ return } DispatchQueue.main.async { for i in index-self.pagerReference.pagesOffLimit...index+self.pagerReference.pagesOffLimit { self.createPageFromController(index: i) } } } //MARK: Infinite Scroll func updateLayoutInfiniteScroll() { let selectedVC = viewControllers[pagerReference.getPage()] let halfCount = (viewControllers.count - 1)/2 var vcRightArr: [UIViewController] = [] var vcLeftArr: [UIViewController] = [] //rightArr if pagerReference.getPage() + halfCount < viewControllers.count { for i in 1...halfCount { vcRightArr.append(viewControllers[pagerReference.getPage()+i]) } } else { let diff = pagerReference.getPage() + halfCount - viewControllers.count for i in 1..<halfCount-diff { vcRightArr.append(viewControllers[pagerReference.getPage()+i]) } for i in 0...diff { vcRightArr.append(viewControllers[i]) } } //leftArr if pagerReference.getPage() - halfCount >= 0 { for i in 1...halfCount { vcLeftArr.append(viewControllers[pagerReference.getPage()-i]) } } else { let diff = pagerReference.getPage() - halfCount for i in (0..<pagerReference.getPage()).reversed() { vcLeftArr.append(viewControllers[i]) } for i in (viewControllers.count+diff..<viewControllers.count).reversed() { vcLeftArr.append(viewControllers[i]) } } infiniteViewControllers = vcLeftArr.reversed() + [selectedVC] + vcRightArr selectedVC.view.frame.size = self.frame.size selectedVC.view.frame.origin.x = 0 for elem in vcRightArr { let index = vcRightArr.firstIndex(of: elem)! + 1 elem.view.frame.size = self.frame.size elem.view.frame.origin.x = CGFloat(index)*self.frame.width } for elem in vcLeftArr.reversed() { let index = vcLeftArr.firstIndex(of: elem)! + 1 elem.view.frame.size = self.frame.size elem.view.frame.origin.x = -CGFloat(index)*self.frame.width } self.contentInset = UIEdgeInsets(top: 0, left: CGFloat(vcLeftArr.count)*self.frame.width, bottom: 0, right: 0) self.contentSize = CGSize(width: frame.width*CGFloat(vcRightArr.count), height: frame.height) self.contentOffset.x = 0 pagerReference.bodyOldIndex = 0 } internal func updateInfiniteViewControllersPosition(forward: Bool) { guard !forward else { let firstVc = infiniteViewControllers.remove(at: 0) firstVc.view.frame.origin.x = infiniteViewControllers.last!.view.frame.origin.x + self.frame.width infiniteViewControllers.append(firstVc) self.contentSize = CGSize(width: self.contentSize.width+self.frame.width, height: self.contentSize.height) return } let lastVc = infiniteViewControllers.remove(at: infiniteViewControllers.count-1) lastVc.view.frame.origin.x = infiniteViewControllers.first!.view.frame.origin.x - self.frame.width infiniteViewControllers.insert(lastVc, at: 0) self.contentInset = UIEdgeInsets(top: 0, left: self.contentInset.left+self.frame.width, bottom: 0, right: 0) } } internal extension BodyView { var currentPage:Int{ return Int(self.contentOffset.x/self.frame.width) } var currentHalfPage:Int { return Int((self.contentOffset.x+(0.5*self.frame.size.width))/self.frame.width) } var currentHalfPageInfinite:Int { if self.contentOffset.x < 0 { return Int((self.contentOffset.x+(-0.5*self.frame.size.width))/self.frame.width) } return Int((self.contentOffset.x+(0.5*self.frame.size.width))/self.frame.width) } }
mit
352136ad18b78ab00e6119407fb6e908
39.111111
156
0.64001
4.567107
false
false
false
false
bestwpw/LTJelloSwitch
Pod/Classes/LTJelloSwitch.swift
1
7472
// // LTJelloSwitch.swift // LTJelloSwitch // // Created by Lex Tang on 4/13/15. // Copyright (c) 2015 Lex Tang. All rights reserved. // import UIKit public protocol LTJelloSwitchDelegate { func jelloSwitchDidChange(jelloSwitch: LTJelloSwitch) } let kPullingThreshold: CGFloat = 40 @IBDesignable public class LTJelloSwitch: UIControl, UIScrollViewDelegate { @IBInspectable public var on: Bool = false { didSet { self.jelloView.jelloColor = on ? self.onColor : self.offColor self.onView.hidden = !on self.offView.hidden = on self.delegate?.jelloSwitchDidChange(self) } } @IBInspectable public var onColor: UIColor = UIColor.blueColor() @IBInspectable public var offColor: UIColor = UIColor.lightGrayColor() public var delegate: LTJelloSwitchDelegate? private var dragOffsetX: CGFloat = 0 { didSet { jelloView.dragOffsetX = dragOffsetX var jelloFrame = self.jelloView.frame if dragOffsetX > 0 { jelloFrame.origin.x = max(-76, -160 * sin(dragOffsetX / 100.0)) } else { jelloFrame.origin.x = min(30, 60 * sin(dragOffsetX / 100.0)) } jelloView.frame = jelloFrame if dragOffsetX > kPullingThreshold { showTriggerView(on) } else { self.triggerOffView.hidden = true self.triggerOnView.hidden = true self.triggerOffView.alpha = 0 self.triggerOnView.alpha = 0 } } } private lazy var scrollView: UIScrollView = { let s = UIScrollView(frame: self.bounds) s.contentSize = CGSizeMake(1, 0) s.backgroundColor = UIColor.clearColor() s.showsHorizontalScrollIndicator = false s.showsVerticalScrollIndicator = false s.bounces = true s.alwaysBounceHorizontal = true s.alwaysBounceVertical = false s.directionalLockEnabled = true self.addSubview(s) for view in self.subviews { if !view.isKindOfClass(UIScrollView.self) || view as! UIScrollView != s { view.removeFromSuperview() s.addSubview(view as! UIView) } } self.insertSubview(self.jelloView, belowSubview: s) return s }() private lazy var jelloView: LTJelloView = { let j = LTJelloView(frame: CGRectMake(0, 0, self.bounds.size.width + 300, self.bounds.size.height)) return j }() // MARK: - Views public lazy var onView: LTOnView = { let v = LTOnView() v.frame = CGRectMake(276, 2, 40, 40) self.jelloView.addSubview(v) return v }() public lazy var offView: LTOffView = { let v = LTOffView() v.frame = CGRectMake(276, 2, 40, 40) self.jelloView.addSubview(v) return v }() public lazy var pullingView: LTPullingView = { let v = LTPullingView() v.frame = CGRectMake(276, 2, 40, 40) self.jelloView.addSubview(v) return v }() public lazy var triggerOnView: LTTriggerOnView = { let v = LTTriggerOnView() v.frame = CGRectMake(306, 0, 40, 40) self.jelloView.addSubview(v) return v }() public lazy var triggerOffView: LTTriggerOffView = { let v = LTTriggerOffView() v.frame = CGRectMake(306, 0, 40, 40) self.jelloView.addSubview(v) return v }() public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) object_setClass(self, LTJelloSwitch.self) setup() } // MARK: - Initialize override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { self.clipsToBounds = true } // MARK: - KVO for contentOffset public override func willMoveToSuperview(newSuperview: UIView?) { if newSuperview != nil { scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) scrollView.delegate = self } } deinit { scrollView.delegate = nil scrollView.removeObserver(self, forKeyPath: "contentOffset") } public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if keyPath == "contentOffset" { if let newValue: AnyObject = change[NSKeyValueChangeNewKey] { let newOffset = newValue.CGPointValue() dragOffsetX = newOffset.x } } } // MARK: - Trigger view public func showTriggerView(show: Bool) { if !show { triggerOffView.layer.removeAllAnimations() if triggerOnView.alpha == 1 { return } if CGAffineTransformIsIdentity(triggerOnView.transform) { triggerOnView.transform = CGAffineTransformMakeScale(0.01, 0.01) } triggerOnView.hidden = false triggerOnView.alpha = 0 if !pullingView.hidden { UIView.animateWithDuration(0.16, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.triggerOnView.alpha = 1 self.triggerOnView.transform = CGAffineTransformIdentity }, completion: nil) } } else { triggerOnView.layer.removeAllAnimations() if triggerOffView.alpha == 1 { return } if CGAffineTransformIsIdentity(triggerOffView.transform) { triggerOffView.transform = CGAffineTransformMakeScale(0.01, 0.01) } triggerOffView.hidden = false triggerOffView.alpha = 0 if !pullingView.hidden { UIView.animateWithDuration(0.16, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.triggerOffView.alpha = 1 self.triggerOffView.transform = CGAffineTransformIdentity }, completion: nil) } } } // MARK: - ScrollView delegate public func scrollViewWillBeginDecelerating(scrollView: UIScrollView) { jelloView.dragging = false jelloView.startBouncing() if scrollView.contentOffset.x > kPullingThreshold { on = !on sendActionsForControlEvents(UIControlEvents.ValueChanged) } if on { onView.hidden = false } else { offView.hidden = false } pullingView.hidden = true } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { pullingView.hidden = false onView.hidden = true offView.hidden = true jelloView.dragging = true sendActionsForControlEvents(UIControlEvents.TouchDragEnter) } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { sendActionsForControlEvents(UIControlEvents.TouchDragExit) } }
mit
ac91f67260ac8a2a13d551a8bcce8c0d
29.876033
163
0.575616
4.88047
false
false
false
false
matsprea/omim
iphone/Maps/Bookmarks/Catalog/DownloadedBookmarksViewController.swift
1
6765
class DownloadedBookmarksViewController: MWMViewController { @IBOutlet var bottomView: UIView! @IBOutlet weak var noDataView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var bottomViewTitleLabel: UILabel! { didSet { bottomViewTitleLabel.text = L("guides_catalogue_title").uppercased() } } @IBOutlet weak var bottomViewDownloadButton: UIButton! { didSet { bottomViewDownloadButton.setTitle(L("download_guides").uppercased(), for: .normal) } } @IBOutlet weak var noDataViewDownloadButton: UIButton! { didSet { noDataViewDownloadButton.setTitle(L("download_guides").uppercased(), for: .normal) } } let dataSource = DownloadedBookmarksDataSource() override func viewDidLoad() { super.viewDidLoad() tableView.tableHeaderView = bottomView tableView.registerNib(cell: CatalogCategoryCell.self) tableView.registerNibForHeaderFooterView(BMCCategoriesHeader.self) checkInvalidSubscription { [weak self] deleted in if deleted { self?.reloadData() } } if #available(iOS 11, *) { return } // workaround for https://jira.mail.ru/browse/MAPSME-8101 reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadData() Statistics.logEvent(kStatGuidesShown, withParameters: [kStatServerIds : dataSource.guideIds], with: .realtime) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var f = bottomView.frame let s = bottomView.systemLayoutSizeFitting(CGSize(width: tableView.width, height: 1), withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow) f.size = s bottomView.frame = f tableView.refresh() } @IBAction func onDownloadBookmarks(_ sender: Any) { Statistics.logEvent(kStatCatalogOpen, withParameters: [kStatFrom: kStatDownloaded]) let webViewController = CatalogWebViewController.catalogFromAbsoluteUrl(nil, utm: .bookmarksPageCatalogButton) MapViewController.topViewController().navigationController?.pushViewController(webViewController, animated: true) } private func reloadData() { dataSource.reloadData() noDataView.isHidden = dataSource.categoriesCount > 0 tableView.reloadData() } private func setCategoryVisible(_ visible: Bool, at index: Int) { dataSource.setCategory(visible: visible, at: index) if let categoriesHeader = tableView.headerView(forSection: 0) as? BMCCategoriesHeader { categoriesHeader.isShowAll = dataSource.allCategoriesHidden } Statistics.logEvent(kStatBookmarkVisibilityChange, withParameters: [kStatFrom : kStatBookmarkList, kStatAction : visible ? kStatShow : kStatHide]) } private func deleteCategory(at index: Int) { guard index >= 0 && index < dataSource.categoriesCount else { assertionFailure() return } dataSource.deleteCategory(at: index) if dataSource.categoriesCount > 0 { tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic) } else { noDataView.isHidden = false tableView.reloadData() } } } extension DownloadedBookmarksViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.categoriesCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(cell: CatalogCategoryCell.self, indexPath: indexPath) cell.update(with: dataSource.category(at: indexPath.row), delegate: self) return cell } } extension DownloadedBookmarksViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 48 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(BMCCategoriesHeader.self) headerView.isShowAll = dataSource.allCategoriesHidden headerView.title = L("guides_groups_cached") headerView.delegate = self return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if (dataSource.isGuide(at: indexPath.row)) { Statistics.logEvent(kStatGuidesOpen, withParameters: [kStatServerId : dataSource.getServerId(at: indexPath.row)], with: .realtime) } let category = dataSource.category(at: indexPath.row) let bmViewController = BookmarksVC(category: category.categoryId) MapViewController.topViewController().navigationController?.pushViewController(bmViewController, animated: true) } } extension DownloadedBookmarksViewController: CatalogCategoryCellDelegate { func cell(_ cell: CatalogCategoryCell, didCheck visible: Bool) { if let indexPath = tableView.indexPath(for: cell) { setCategoryVisible(visible, at: indexPath.row) } } func cell(_ cell: CatalogCategoryCell, didPress moreButton: UIButton) { if let indexPath = tableView.indexPath(for: cell) { let category = dataSource.category(at: indexPath.row) let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if let ppc = actionSheet.popoverPresentationController { ppc.sourceView = moreButton ppc.sourceRect = moreButton.bounds } let showHide = L(category.isVisible ? "hide" : "show").capitalized actionSheet.addAction(UIAlertAction(title: showHide, style: .default, handler: { _ in self.setCategoryVisible(!category.isVisible, at: indexPath.row) self.tableView.reloadRows(at: [indexPath], with: .none) })) let delete = L("delete").capitalized let deleteAction = UIAlertAction(title: delete, style: .destructive, handler: { _ in self.deleteCategory(at: indexPath.row) }) actionSheet.addAction(deleteAction) let cancel = L("cancel").capitalized actionSheet.addAction(UIAlertAction(title: cancel, style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } } } extension DownloadedBookmarksViewController: BMCCategoriesHeaderDelegate { func visibilityAction(_ categoriesHeader: BMCCategoriesHeader) { dataSource.allCategoriesHidden = !dataSource.allCategoriesHidden tableView.reloadData() } }
apache-2.0
22ea80653f294e3ffe0077e2c139beb2
37.4375
119
0.702439
4.981591
false
false
false
false
dnsdesigner/BMBaseModal
Classes/BMBaseModal.swift
1
2725
// // BMBaseModal.swift // estudo Modal // // Created by Dennis de Oliveira on 23/01/15. // Copyright (c) 2015 Dennis de Oliveira. All rights reserved. // import UIKit class BMBaseModalOwner { let modalOwner: BMBaseModal init(modalOwner: BMBaseModal) { self.modalOwner = modalOwner //println("Init BaseModalOwner") } } class BMBaseModal: UIViewController { // Crio o arquivo que ficará responsável pelo objeto var baseModalOwner: BMBaseModalOwner! // Propriedades que virão da Xib var baseModalContentView: UIView = UIView(frame: CGRectMake(0, 0, 250, 250)) //Propriedades da classe var baseModalBackground:UIColor = UIColor.blackColor() var baseModalBackgroundAlpha: CGFloat = 0.5 required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } required override init() { super.init() // Adiciona a content view na view principal self.view.addSubview(self.baseModalContentView) // Inicializar Background self.view.frame = UIScreen.mainScreen().bounds self.view.backgroundColor = self.baseModalBackground.colorWithAlphaComponent(self.baseModalBackgroundAlpha) // Inicializar Content View self.baseModalContentView.center = self.view.center self.baseModalContentView.backgroundColor = UIColor.yellowColor() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } // #pragma mark - Métodos da classe func showModal() { // Adiciona a view principal na tela do app self.view.alpha = 0 let window = UIApplication.sharedApplication().keyWindow?.subviews.first as UIView window.addSubview(self.view) //view.frame = rv.bounds // Delego a propriedade deste objeto para a classe BaseModalViewOwner self.baseModalOwner = BMBaseModalOwner(modalOwner: self) // Adiciono um timer para fechar sozinho para teste NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("hideModal"), userInfo: nil, repeats: false) // Crio uma animação para apresentar a tela UIView.animateWithDuration(0.2, animations: { self.view.alpha = 1 }, completion: { finished in }) } func hideModal() { UIView.animateWithDuration(0.2, animations: { self.view.alpha = 0 }, completion: { finished in self.view.removeFromSuperview() }) } }
mit
99fa157dac3e87dc066483926c3a75d0
30.252874
129
0.641045
4.509121
false
false
false
false
DSanzh/GuideMe-iOS
Pods/EasyPeasy/EasyPeasy/Item.swift
1
6883
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif var easy_attributesReference: Int = 0 /** Typealias of a tuple grouping an array of `NSLayoutConstraints` to activate and another array of `NSLayoutConstraints` to deactivate */ typealias ActivationGroup = ([NSLayoutConstraint], [NSLayoutConstraint]) /** Protocol enclosing the objects a constraint will apply to */ public protocol Item: NSObjectProtocol { /// Array of constraints installed in the current `Item` var constraints: [NSLayoutConstraint] { get } /// Owning `UIView` for the current `Item`. The concept varies /// depending on the class conforming the protocol var owningView: View? { get } } public extension Item { /// Access to **EasyPeasy** `layout`, `reload` and `clear`operations public var easy: EasyPeasy { return EasyPeasy(item: self) } /** This method will trigger the recreation of the constraints created using *EasyPeasy* for the current view. `Condition` closures will be evaluated again */ @available(iOS, deprecated: 1.5.1, message: "Use easy.reload() instead") public func easy_reload() { self.reload() } /** Clears all the constraints applied with EasyPeasy to the current `UIView` */ @available(iOS, deprecated: 1.5.1, message: "Use easy.clear() instead") public func easy_clear() { self.clear() } } /** Internal extension that handles the storage and application of `Attributes` in an `Item` */ extension Item { /** This method will trigger the recreation of the constraints created using *EasyPeasy* for the current view. `Condition` closures will be evaluated again */ func reload() { var activateConstraints: [NSLayoutConstraint] = [] var deactivateConstraints: [NSLayoutConstraint] = [] for node in self.nodes.values { let activationGroup = node.reload() activateConstraints.append(contentsOf: activationGroup.0) deactivateConstraints.append(contentsOf: activationGroup.1) } // Activate/deactivate the resulting `NSLayoutConstraints` NSLayoutConstraint.deactivate(deactivateConstraints) NSLayoutConstraint.activate(activateConstraints) } /** Clears all the constraints applied with EasyPeasy to the current `UIView` */ func clear() { var deactivateConstraints: [NSLayoutConstraint] = [] for node in self.nodes.values { deactivateConstraints.append(contentsOf: node.clear()) } self.nodes = [:] // Deactivate the resulting `NSLayoutConstraints` NSLayoutConstraint.deactivate(deactivateConstraints) } } /** Internal extension that handles the storage and application of `Attributes` in an `Item` */ extension Item { /// Dictionary persisting the `Nodes` related with this `Item` var nodes: [String:Node] { get { if let nodes = objc_getAssociatedObject(self, &easy_attributesReference) as? [String:Node] { return nodes } let nodes: [String:Node] = [:] let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &easy_attributesReference, nodes, policy) return nodes } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &easy_attributesReference, newValue, policy) } } /** Applies the `Attributes` within the passed array to the current `Item` - parameter attributes: Array of `Attributes` to apply into the `Item` - returns the resulting `NSLayoutConstraints` */ func apply(attributes: [Attribute]) -> [NSLayoutConstraint] { // Before doing anything ensure that this item has translates autoresizing // mask into constraints disabled self.disableAutoresizingToConstraints() var layoutConstraints: [NSLayoutConstraint] = [] var activateConstraints: [NSLayoutConstraint] = [] var deactivateConstraints: [NSLayoutConstraint] = [] for attribute in attributes { if let compoundAttribute = attribute as? CompoundAttribute { layoutConstraints.append(contentsOf: self.apply(attributes: compoundAttribute.attributes)) continue } if let activationGroup = self.apply(attribute: attribute) { layoutConstraints.append(contentsOf: activationGroup.0) activateConstraints.append(contentsOf: activationGroup.0) deactivateConstraints.append(contentsOf: activationGroup.1) } } // Activate/deactivate the `NSLayoutConstraints` returned by the different `Nodes` NSLayoutConstraint.deactivate(deactivateConstraints) NSLayoutConstraint.activate(activateConstraints) return layoutConstraints } func apply(attribute: Attribute) -> ActivationGroup? { // Creates the `NSLayoutConstraint` of the `Attribute` holding // a reference to it from the `Attribute` objects attribute.createConstraints(for: self) // Checks the node correspoding to the `Attribute` and creates it // in case it doesn't exist let node = self.nodes[attribute.signature] ?? Node() // Set node self.nodes[attribute.signature] = node // Add the `Attribute` to the node and return the `NSLayoutConstraints` // to be activated/deactivated return node.add(attribute: attribute) } /** Sets `translatesAutoresizingMaskIntoConstraints` to `false` if the current `Item` implements it */ private func disableAutoresizingToConstraints() { #if os(iOS) || os(tvOS) (self as? UIView)?.translatesAutoresizingMaskIntoConstraints = false #else (self as? NSView)?.translatesAutoresizingMaskIntoConstraints = false #endif } }
mit
7a322a640e0c5c55470f8a575b41acd2
33.762626
106
0.645068
5.234221
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/expression/protocol_extension/main.swift
2
1552
// main.swift // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- public protocol Foo { func foo(_ x: Int) -> Int } struct FooishStruct : Foo { func foo(_ x: Int) -> Int { return x + FooishStruct.cvar } let x = 10 let y = "Hello world" static let cvar = 333 } class FooishClass : Foo { func foo(_ x: Int) -> Int { return x + FooishStruct.cvar } let x = 10 let y = "Hello world" static let cvar = 333 } enum FooishEnum : Int, Foo { case One = 1 case Two = 2 var x : Int {return 10} var y : String { return "Hello world"} func foo(_ x: Int) -> Int { return x + FooishEnum.cvar } static let cvar = 333 } extension Foo { public static func bar() { let local_var = 222 print("break here in static func \(local_var)") } public func baz() { let local_var = 111 print("break here in method \(local_var)") } } func main() { (FooishStruct()).baz() FooishStruct.bar() (FooishStruct()).baz() FooishStruct.bar() FooishEnum.One.baz() FooishEnum.bar() } main()
apache-2.0
d562a9f939939531f9e7f7db9e70fde5
17.046512
80
0.552191
3.669031
false
false
false
false
wiruzx/DSTU-FuzzyLogic
FuzzyLogic/GroupSelectViewController.swift
1
5062
// // GroupSelectViewController.swift // FuzzyLogic // // Created by Victor Shamanov on 3/18/15. // Copyright (c) 2015 Victor Shamanov. All rights reserved. // import UIKit private let verticalScale = 1.2 / Double(numberOfVerticalTicks) private let horizontalScale = 100.0 / Double(numberOfHorizontalTicks) private let numberOfVerticalTicks: Int32 = 6 private let numberOfHorizontalTicks: Int32 = 10 private let MinValue = 0.8 class GroupSelectViewController: UIViewController { // MARK:- Type declarations private enum Grade: Int { case Five, Four, Three, Two } private enum Operator: Int { case Or, And } // MARK:- Private properties private var onceToken: dispatch_once_t = 0 // MARK:- Public properties var studentsManager: StudentsManager! // MARK:- Outlets @IBOutlet private weak var gradesSegmentControl: UISegmentedControl! @IBOutlet private weak var operatorSegmentControl: UISegmentedControl! @IBOutlet private weak var notGradesSegmentControl: UISegmentedControl! @IBOutlet private weak var chartView: LineChart! // MARK:- View controller's overridings override func viewDidLoad() { super.viewDidLoad() configureLineChartView() updateGraphForCurrentState() } // MARK:- Actions @IBAction private func segmentControlValueChanged(sender: UISegmentedControl) { updateGraphForCurrentState() } @IBAction private func nextButtonPressed(sender: AnyObject) { let (grade, notGrade, op) = segmentValues() let gradeF = functionFromGrade(grade) let notGradeF = { 1 - self.functionFromGrade(notGrade)($0) } let predicate: Double -> Bool = { value in let first = gradeF(value) >= MinValue let second = { notGradeF(value) >= MinValue } switch op { case .Or: return first || second() case .And: return first && second() } } let studentListViewController = storyboard?.instantiateViewControllerWithIdentifier("ReadOnlyStudentListViewController") as! ReadOnlyStudentListViewController studentsManager .getStudents { predicate($0.points) } .onComplete { studentListViewController.students = $0 } navigationController?.pushViewController(studentListViewController, animated: true) } // MARK:- Private methods private func updateGraphForCurrentState() { let (grade, notGrade, op) = segmentValues() updateGraph(grade, notGrade: notGrade, op: op) } private func updateGraph(grade: Grade, notGrade: Grade, op: Operator) { let staticLine = Array(count: 11, repeatedValue: CGFloat(MinValue)) let gradeFunction = functionFromGrade(grade) let notGradeFunction = { 1 - self.functionFromGrade(notGrade)($0) } let line = Array(0...10).map { Double($0 * 10) } let firstLine = line.map(gradeFunction).map(toCGFloat) let secondLine = line.map(notGradeFunction).map(toCGFloat) chartView.clearAll() chartView.addLine(firstLine) chartView.addLine(secondLine) chartView.addLine(staticLine) } private func functionFromGrade(grade: Grade) -> Double -> Double { let f: Double -> Double switch grade { case .Five: f = five case .Four: f = four case .Three: f = three case .Two: f = two } return constrain(f) } // MARK:- Helper methods private func segmentValues() -> (grade: Grade, notGrade: Grade, op: Operator) { let grade = gradeFromSegment(gradesSegmentControl) ?? .Five let notGrade = gradeFromSegment(notGradesSegmentControl) ?? .Five let op = operatorFromSegment(operatorSegmentControl) ?? .Or return (grade, notGrade, op) } private func constrain(f: Double -> Double)(value: Double) -> Double { return min(max(0, f(value)), 1) } private func toCGFloat(doubleValue: Double) -> CGFloat { return CGFloat(doubleValue) } private func configureLineChartView() { chartView.area = false chartView.x.grid.count = 11 chartView.y.grid.count = 6 chartView.x.labels.values = Array(0...10).map { "\($0 * 10)" } } private func operatorFromSegment(segment: UISegmentedControl) -> Operator? { return segment.numberOfSegments == 2 ? Operator(rawValue: segment.selectedSegmentIndex) : nil } private func gradeFromSegment(segment: UISegmentedControl) -> Grade? { return segment.numberOfSegments == 4 ? Grade(rawValue: segment.selectedSegmentIndex) : nil } }
apache-2.0
402aee3ee210c38a8d7dc53063e3e0b2
28.952663
166
0.611418
4.948192
false
false
false
false
wisonlin/Swifter
Swifter/NSFileManager+Swifter.swift
1
4281
// // NSFileManager+Swifter.swift // Swifter // // Created by wison on 7/1/16. // Copyright © 2016 Finder Studio. All rights reserved. // import Foundation public enum FSFileType { case FSFileTypeUnknown case FSFileTypePic case FSFileTypeAudio case FSFileTypeVideo case FSFileTypeDoc case FSFileTypeZip case FSFileTypePDF case FSFileTypeFolder } extension NSFileManager { public class func fileTypeOf(filePath: NSURL) -> FSFileType { let typeDic = self.setUpFileTypeDictionary() if let fileExtension = filePath.pathExtension { if let fileType = typeDic[fileExtension] { return fileType } } return .FSFileTypeUnknown } public class func documentPath() -> String { return self.documentURL().absoluteString } public class func documentURL() -> NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) if urls.isEmpty { return NSURL() } else { return urls[0] } } public class func fileSizeStringOfURL(fileURL: NSURL) -> String { do { let values = try fileURL.resourceValuesForKeys([NSURLFileSizeKey]) if let fileSize = values[NSURLFileSizeKey] as? NSNumber { let filesizeString = NSByteCountFormatter.stringFromByteCount(fileSize.longLongValue, countStyle: .File) return filesizeString } } catch { return "" } return "" } public class func numberOfFilesInDirectory(directory: NSURL) -> Int { do { let paths = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: [.SkipsHiddenFiles]) return paths.count } catch { return 0 } } public class func isDirectory(filePath: NSURL) -> Bool { do { let values = try filePath.resourceValuesForKeys([NSURLIsDirectoryKey]) return (values[NSURLIsDirectoryKey]?.boolValue)! } catch { return false } } public class func isHidden(filePath: NSURL) -> Bool { do { let values = try filePath.resourceValuesForKeys([NSURLIsHiddenKey]) return (values[NSURLIsHiddenKey]?.boolValue)! } catch { return true } } class func setUpFileTypeDictionary() -> Dictionary<String, FSFileType>{ struct Static { static var onceToken: dispatch_once_t = 0 static var s_fileTypeDictionary: Dictionary<String, FSFileType>? } dispatch_once(&Static.onceToken, { Static.s_fileTypeDictionary = [ // doc "doc" : .FSFileTypeDoc, "xls" : .FSFileTypeDoc, "xlsx" : .FSFileTypeDoc, "txt" : .FSFileTypeDoc, "ppt" : .FSFileTypeDoc, "docx" : .FSFileTypeDoc, "pptx" : .FSFileTypeDoc, "rtf" : .FSFileTypeDoc, "htm" : .FSFileTypeDoc, "html" : .FSFileTypeDoc, // pic "jpg" : .FSFileTypePic, "jpeg" : .FSFileTypePic, "png" : .FSFileTypePic, "bmp" : .FSFileTypePic, "gif" : .FSFileTypePic, // pdf "pdf" : .FSFileTypePDF, // audio "mp3" : .FSFileTypeAudio, "wav" : .FSFileTypeAudio, "mid" : .FSFileTypeAudio, "midi" : .FSFileTypeAudio, "mp3pro": .FSFileTypeAudio, "wma" : .FSFileTypeAudio, "ape" : .FSFileTypeAudio, // video "mp4" : .FSFileTypeVideo, "m4v" : .FSFileTypeVideo, "mov" : .FSFileTypeVideo, "avi" : .FSFileTypeVideo, "flv" : .FSFileTypeVideo, "rmvb" : .FSFileTypeVideo, "asf" : .FSFileTypeVideo, "mpeg" : .FSFileTypeVideo, "mpg" : .FSFileTypeVideo, "rm" : .FSFileTypeVideo, "3gp" : .FSFileTypeVideo, "mkv" : .FSFileTypeVideo, "wmv" : .FSFileTypeVideo, "f4v" : .FSFileTypeVideo, "ts " : .FSFileTypeVideo, // zip "zip" : .FSFileTypeZip, "rar" : .FSFileTypeZip ] }) return Static.s_fileTypeDictionary! } }
mit
65a0f3c5b059b1b75ce1aa77205fdae7
27.918919
151
0.579206
3.479675
false
false
false
false
fabianpimminger/refresher
PullToRefreshDemo/PullToRefreshViewController.swift
5
4058
// // ViewController.swift // // Copyright (c) 2014 Josip Cavar // // 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 Refresher enum ExampleMode { case Default case Beat case Pacman case Custom } class PullToRefreshViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var exampleMode = ExampleMode.Default override func viewDidLoad() { super.viewDidLoad() switch exampleMode { case .Default: tableView.addPullToRefreshWithAction { NSOperationQueue().addOperationWithBlock { sleep(2) NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.stopPullToRefresh() } } } case .Beat: let beatAnimator = BeatAnimator(frame: CGRectMake(0, 0, 320, 80)) tableView.addPullToRefreshWithAction({ NSOperationQueue().addOperationWithBlock { sleep(2) NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.stopPullToRefresh() } } }, withAnimator: beatAnimator) case .Pacman: let pacmanAnimator = PacmanAnimator(frame: CGRectMake(0, 0, 320, 80)) tableView.addPullToRefreshWithAction({ NSOperationQueue().addOperationWithBlock { sleep(2) NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.stopPullToRefresh() } } }, withAnimator: pacmanAnimator) case .Custom: if let customSubview = NSBundle.mainBundle().loadNibNamed("CustomSubview", owner: self, options: nil).first as? CustomSubview { tableView.addPullToRefreshWithAction({ NSOperationQueue().addOperationWithBlock { sleep(2) NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.stopPullToRefresh() } } }, withAnimator: customSubview) } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.startPullToRefresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") cell.textLabel?.text = "Row " + String(indexPath.row + 1) return cell } }
mit
82ff641b6f02714a7b10206243c39024
37.283019
139
0.618531
5.780627
false
false
false
false
LeafPlayer/Leaf
Leaf/ViewController/IntroVC.swift
1
4853
// // IntroVC.swift // Leaf // // Created by lincolnlaw on 2017/10/27. // Copyright © 2017年 lincolnlaw. All rights reserved. // import Cocoa final class IntroWindowController: NSWindowController, Reslovable { static var resolveType: DI.ResloveType = .intro struct Constant { static let introRect = CGRect(x: 0, y: 0, width: 640, height: 400) } override init(window: NSWindow?) { super.init(window: window) } required init?(coder: NSCoder) { super.init(coder: coder) } convenience init() { let win = IntroWindow() self.init(window: win) DI.register(instance: self) } override func showWindow(_ sender: Any?) { window?.absCenter() window?.fadeIn() NSApp.activate(ignoringOtherApps: true) super.showWindow(sender) } } // private final class IntroWindow: NSWindow { override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) { super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag) } convenience init() { let rect = IntroWindowController.Constant.introRect self.init(contentRect: rect, styleMask: [.borderless, .miniaturizable, .closable, .fullSizeContentView, .unifiedTitleAndToolbar, .titled], backing: .buffered, defer: false) let vc = IntroViewController() contentViewController = vc isReleasedWhenClosed = false // key property for reopen window collectionBehavior = .fullScreenNone isMovableByWindowBackground = true isOpaque = false backgroundColor = .clear titlebarAppearsTransparent = true titleVisibility = .hidden minSize = rect.size appearance = NSAppearance(named: NSAppearance.Name.vibrantDark) setFrame(rect, display: false) } } private final class IntroViewController: NSViewController { public override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init() { self.init(nibName: nil, bundle: nil) } override func loadView() { let rect = IntroWindowController.Constant.introRect let effect = NSFlipVisualEffectView(frame: rect) effect.blendingMode = .behindWindow effect.maskImage = NSImage.maskImage(cornerRadius: 6) effect.state = .active effect.material = .dark effect.blendingMode = NSVisualEffectView.BlendingMode.behindWindow if #available(OSX 10.11, *) { effect.material = .ultraDark } view = effect } public override func viewDidLoad() { super.viewDidLoad() addIconAndVersion() addOpenActionItems() } private func addIconAndVersion() { let viewHeight = view.frame.height let bgWidth: CGFloat = 180 let bgView = NSFlipView(frame: CGRect(x: 0, y: 0, width: bgWidth, height: viewHeight)) bgView.wantsLayer = true bgView.layer?.backgroundColor = NSColor(red:0.13, green:0.13, blue:0.13, alpha:1.0).cgColor view.addSubview(bgView) let icon = CALayer() let length: CGFloat = 128 let x = (bgWidth - length) / 2 icon.frame = CGRect(x: x, y: 32, width: length, height: length) icon.contents = NSApp.applicationIconImage.cgImage(forProposedRect: nil, context: nil, hints: nil) bgView.layer?.addSublayer(icon) let name = Bundle.main.appName let textField = NSTextField.label(for: name, font: NSFont.boldSystemFont(ofSize: 16)) textField.frame = CGRect(x: x, y: 20 + icon.frame.maxY, width: length, height: 20) bgView.addSubview(textField) let versionBuild = Bundle.main.versionBuild let versionText = NSTextField.label(for: versionBuild, font: NSFont.systemFont(ofSize: NSFont.systemFontSize)) versionText.frame = CGRect(x: x, y: 4 + textField.frame.maxY, width: length, height: 20) bgView.addSubview(versionText) } private func addOpenActionItems() { } } private extension NSTextField { static func label(for text: String, font: NSFont) -> NSTextField { let textField = NSTextField() textField.stringValue = text textField.alignment = .center textField.textColor = NSColor.white textField.drawsBackground = false textField.font = font textField.isEditable = false textField.isSelectable = false textField.isBordered = false return textField } }
gpl-3.0
33da85a884c9fee69d4a24bb26a84b7f
33.892086
180
0.649691
4.524254
false
false
false
false
OscarSwanros/swift
test/Sema/string_to_substring_conversion.swift
21
2625
// RUN: %target-swift-frontend -typecheck -verify -fix-string-substring-conversion -swift-version 4 %s let s = "Hello" let ss = s[s.startIndex..<s.endIndex] // CTP_Initialization do { let s1: Substring = { return s }() // expected-error {{cannot convert value of type 'String' to specified type 'Substring'}} {{37-37=[]}} _ = s1 } // CTP_ReturnStmt do { func returnsASubstring() -> Substring { return s // expected-error {{cannot convert return expression of type 'String' to return type 'Substring'}} {{13-13=[]}} } } // CTP_ThrowStmt // Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError: // The conversion destination of throw is always ErrorType (at the moment) // if this ever expands, this should be a specific form like () is for // return. // CTP_EnumCaseRawValue // Substrings can't be raw values because they aren't literals. // CTP_DefaultParameter do { func foo(x: Substring = s) {} // expected-error {{default argument value of type 'String' cannot be converted to type 'Substring'}} {{28-28=[]}} } // CTP_CalleeResult do { func getString() -> String { return s } let gottenSubstring: Substring = getString() // expected-error {{cannot convert value of type 'String' to specified type 'Substring'}} {{47-47=[]}} _ = gottenSubstring } // CTP_CallArgument do { func takesASubstring(_ ss: Substring) {} takesASubstring(s) // expected-error {{cannot convert value of type 'String' to expected argument type 'Substring'}} {{20-20=[]}} } // CTP_ClosureResult do { [s].map { (x: String) -> Substring in x } // expected-error {{cannot convert value of type 'String' to closure result type 'Substring'}} {{42-42=[]}} } // CTP_ArrayElement do { let a: [Substring] = [ s ] // expected-error {{cannot convert value of type 'String' to expected element type 'Substring'}} {{27-27=[]}} _ = a } // CTP_DictionaryKey do { let d: [ Substring : Substring ] = [ s : ss ] // expected-error {{cannot convert value of type 'String' to expected dictionary key type 'Substring'}} {{41-41=[]}} _ = d } // CTP_DictionaryValue do { let d: [ Substring : Substring ] = [ ss : s ] // expected-error {{cannot convert value of type 'String' to expected dictionary value type 'Substring'}} {{46-46=[]}} _ = d } // CTP_CoerceOperand do { let s1: Substring = s as Substring // expected-error {{cannot convert value of type 'String' to type 'Substring' in coercion}} {{24-24=[]}} _ = s1 } // CTP_AssignSource do { let s1: Substring = s // expected-error {{cannot convert value of type 'String' to specified type 'Substring'}} {{24-24=[]}} _ = s1 }
apache-2.0
4286c2f0f485d7286bfcb9cafe37ae84
31.8125
166
0.670857
3.586066
false
false
false
false
aleph7/PlotKit
PlotKit/Views/HeatMapView.swift
1
4427
// Copyright © 2016 Venture Media Labs. All rights reserved. // // This file is part of PlotKit. The full PlotKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation /// HeatMapView draws continuous 3D data using a heat map. The data is provided by a value function that should return a `z` value for any `x, y` value pair inside the plot region. HeatMapView does not draw axes or any other plot decorations, use a `PlotView` for that. open class HeatMapView: DataView { public typealias ValueFunction = (_ x: Double, _ y: Double) -> Double /// The colo map determines the color to use for each value open var colorMap: ColorMap { didSet { needsDisplay = true } } /// The inverval of z values that the value function generates open var zInterval: ClosedRange<Double> { didSet { needsDisplay = true } } /// A function that maps from an `x, y` value pair to a `z` value open var valueFunction: ValueFunction? { didSet { needsDisplay = true } } public init() { colorMap = ViridisColorMap() zInterval = 0...1 super.init(frame: NSRect(x: 0, y: 0, width: 512, height: 512)) canDrawConcurrently = true } public required init?(coder: NSCoder) { colorMap = ViridisColorMap() zInterval = 0...1 super.init(coder: coder) canDrawConcurrently = true } public convenience init(valueFunction: @escaping ValueFunction) { self.init() self.valueFunction = valueFunction } open override func draw(_ rect: CGRect) { guard let valueFunction = valueFunction else { return } let scaleFactor = window?.screen?.backingScaleFactor ?? 1.0 let pixelsWide = Int(rect.width * scaleFactor) let pixelsHigh = Int(rect.height * scaleFactor) let bytesPerRow = pixelsWide * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: pixelsWide, height: pixelsHigh, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) guard let data = context?.data?.bindMemory(to: UInt8.self, capacity: bytesPerRow * pixelsHigh) else { return } let repXInterval = 0.0...Double(pixelsWide) let repYInterval = 0.0...Double(pixelsHigh) let rectXInterval = Double(rect.minX)...Double(rect.maxX) let rectYInterval = Double(rect.minY)...Double(rect.maxY) let boundsXInterval = Double(bounds.minX)...Double(bounds.maxX) let boundsYInterval = Double(bounds.minY)...Double(bounds.maxY) for yi in 0..<pixelsHigh { let yv = mapValue(Double(yi), fromInterval: repYInterval, toInterval: rectYInterval) let yb = mapValue(yv, fromInterval: rectYInterval, toInterval: boundsYInterval) let y = mapValue(yb, fromInterval: boundsYInterval, toInterval: yInterval) for xi in 0..<pixelsWide { let xv = mapValue(Double(xi), fromInterval: repXInterval, toInterval: rectXInterval) let xb = mapValue(xv, fromInterval: rectXInterval, toInterval: boundsXInterval) let x = mapValue(xb, fromInterval: boundsXInterval, toInterval: xInterval) let value = valueFunction(x, y) let normValue = mapValue(value, fromInterval: zInterval, toInterval: 0.0...1.0) let color = colorMap.colorForValue(normValue) data[xi * 4 + yi * bytesPerRow + 0] = UInt8(round(color.red * 255)) data[xi * 4 + yi * bytesPerRow + 1] = UInt8(round(color.green * 255)) data[xi * 4 + yi * bytesPerRow + 2] = UInt8(round(color.blue * 255)) data[xi * 4 + yi * bytesPerRow + 3] = UInt8(round(color.alpha * 255)) } } let image = context?.makeImage() NSGraphicsContext.current()?.cgContext.draw(image!, in: rect) } open override func pointAt(_ location: NSPoint) -> Point? { let point = convertViewPointToData(location) return Point(x: point.x, y: valueFunction?(point.x, point.y) ?? 0) } }
mit
4eb81923ef54c486a388bc263c61b4c6
40.754717
269
0.63014
4.259865
false
false
false
false
Lordxen/MagistralSwift
MagistralSwift/Magistral.swift
1
17509
// // magistral.swift // ios // // Created by rizarse on 22/07/16. // Copyright © 2016 magistral.io. All rights reserved. // import Foundation import SwiftMQTT import SwiftyJSON import Alamofire public class Magistral : IMagistral { private var pubKey : String, subKey : String, secretKey : String, cipher : String?; private var ssl : Bool?; private var active = false; private var host : String = "app.magistral.io"; private var mqtt : MqttClient?; private var settings : [String : [[String : String]]] = [ : ]; public typealias Connected = (Bool, Magistral) -> Void convenience init(pubKey : String, subKey : String, secretKey : String, connected : Connected?) { self.init(pubKey : pubKey, subKey : subKey, secretKey : secretKey, cipher : "", connected : connected); } public func setHost(host : String) { self.host = host; } public func setCipher(cipher: String) { self.cipher = cipher; } public required init(pubKey : String, subKey : String, secretKey : String, cipher : String, connected : Connected? ) { self.pubKey = pubKey; self.subKey = subKey; self.secretKey = secretKey; if (cipher != "") { self.cipher = cipher; } self.connectionPoints(callback: { token, settings in self.settings = settings; self.initMqtt(token: token, connected: { status, magistral in connected!(status, magistral); }) }); } private func initMqtt(token : String, connected : Connected?) { mqtt = MqttClient(host: self.host, port: 8883, clientID: "magistral.mqtt.gw." + token, cleanSession: false, keepAlive: 30, useSSL: true) mqtt?.username = self.pubKey + "|" + self.subKey; mqtt?.password = self.secretKey mqtt?.lastWillMessage = MQTTPubMsg(topic: "presence/" + self.pubKey + "/" + token, payload: Data(bytes: [0]), retain: true, QoS: MQTTQoS.atLeastOnce); mqtt?.delegate = mqtt; mqtt?.addMessageListener({ ref, message in if let groupListeners = self.lstMap[message.topic()] { for (group, listener) in groupListeners { let baseURL = "https://" + self.host + "/api/magistral/data/read" let user = self.pubKey + "|" + self.subKey; var params : Parameters = [ : ] params["group"] = group as AnyObject?; params["topic"] = message.topic() as AnyObject?; params["channel"] = message.channel() as AnyObject?; params["index"] = String(message.index()) as AnyObject?; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: params, user: user, password : self.secretKey, onCompletion: { json, err in do { let messages = try JsonConverter.sharedInstance.handleMessageEvent(json: json); for m in messages { listener(m, nil) } } catch { let eve = Message(topic: "null", channel: 0, msg: [], index: 0, timestamp: 0) listener(eve, MagistralException.conversionError) } }) } } }); mqtt?.connect(completion: { mqtt_connected, error in if (mqtt_connected) { self.mqtt?.subscribe(to: "exceptions", delivering: .atLeastOnce, completion: nil) self.mqtt?.publish(Data([1]), in: "presence/" + self.pubKey + "/" + token, delivering: .atLeastOnce, retain: true, completion: nil) self.active = true connected!(self.active, self); } }, disconnect: { session in if (self.active) { print("Connection dropped -> reconnection in 5 sec.") DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) { session.connect(completion: nil); } } }, socketerr: { session in if (self.active) { print("Socket error") } }) } private func connectionPoints(callback : @escaping (_ token : String, _ settings : [ String : [[String : String]] ]) -> Void) { let baseURL = "https://" + self.host + "/api/magistral/net/connectionPoints" let user = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: [:], user: user, password : self.secretKey, onCompletion: { json, err in let cps : (String, [ String : [[String : String]] ]) = JsonConverter.sharedInstance.connectionPoints(json: json); callback(cps.0, cps.1) }) } // PUBLISH public func publish(_ topic : String, msg : [UInt8], callback : io.magistral.client.pub.Callback?) throws { try self.publish(topic, channel: -1, msg: msg, callback: callback); } public func publish(_ topic : String, channel : Int, msg : [UInt8], callback : io.magistral.client.pub.Callback?) throws { mqtt?.publish(topic, channel: channel, msg: msg, callback: { ack, error in callback?(ack, error); }) } // SUBSCRIBE private var lstMap : [ String : [String : io.magistral.client.sub.NetworkListener]] = [ : ]; public func subscribe(_ topic : String, listener : @escaping io.magistral.client.sub.NetworkListener, callback : io.magistral.client.sub.Callback?) throws { try self.subscribe(topic, group : "default", channel : -1, listener : listener, callback: callback); } public func subscribe(_ topic : String, channel : Int, listener : @escaping io.magistral.client.sub.NetworkListener, callback : io.magistral.client.sub.Callback?) throws { try self.subscribe(topic, group : "default", channel : channel, listener : listener, callback: callback); } public func subscribe(_ topic : String, group : String, listener : @escaping io.magistral.client.sub.NetworkListener, callback : io.magistral.client.sub.Callback?) throws { try self.subscribe(topic, group : group, channel : -1, listener : listener, callback: callback); } public func subscribe(_ topic : String, group : String, channel : Int, listener : @escaping io.magistral.client.sub.NetworkListener, callback : io.magistral.client.sub.Callback?) throws { let ch = (channel < -1) ? -1 : channel; self.mqtt?.subscribe(topic, channel: ch, group: group, qos: .atLeastOnce, callback : { meta, err in callback?(meta, err) }) if let listenerGroups = self.lstMap[topic] { if listenerGroups[group] == nil { self.lstMap[topic]![group] = listener; } } else { self.lstMap[topic] = [ group : listener ] } } public func unsubscribe(_ topic : String, callback : io.magistral.client.sub.Callback?) throws { self.mqtt?.unsubscribe(topic, callback: { meta, err in callback?(io.magistral.client.sub.SubMeta(topic: meta.topic(), channel: meta.channel(), group: meta.group(), endPoints: meta.endPoints()), err); }) } public func unsubscribe(_ topic : String, channel : Int, callback : io.magistral.client.sub.Callback?) throws { self.mqtt?.unsubscribe(topic, callback: { meta, err in callback?(io.magistral.client.sub.SubMeta(topic: meta.topic(), channel: meta.channel(), group: meta.group(), endPoints: meta.endPoints()), err); }) } // TOPICS public func topics(_ callback : @escaping io.magistral.client.topics.Callback) throws { try permissions({ perms, err in var topics : [io.magistral.client.topics.TopicMeta] = [] for p in perms { topics.append(io.magistral.client.topics.TopicMeta(topic: p.topic(), channels: p.channels())) } callback(topics, err == nil ? nil : MagistralException.fetchTopicsError); }); } public func topic(_ topic : String, callback : @escaping io.magistral.client.topics.Callback) throws { try permissions(topic, callback: { perms, err in var topics : [io.magistral.client.topics.TopicMeta] = []; for p in perms { topics.append(io.magistral.client.topics.TopicMeta(topic: p.topic(), channels: p.channels())) } callback(topics, err == nil ? nil : MagistralException.fetchTopicsError); }); } // ACCESS CONTROL public func permissions(_ callback : @escaping io.magistral.client.perm.Callback) throws { let baseURL = "https://" + self.host + "/api/magistral/net/permissions" let user = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: [:], user: user, password : self.secretKey, onCompletion: { json, err in do { let permissions : [io.magistral.client.perm.PermMeta] = try JsonConverter.sharedInstance.handle(json: json); callback(permissions, err == nil ? nil : MagistralException.historyInvocationError); } catch MagistralException.historyInvocationError { } catch { } }) } public func permissions(_ topic: String, callback : @escaping io.magistral.client.perm.Callback) throws { let baseURL = "https://" + self.host + "/api/magistral/net/permissions" var params : Parameters = [ : ] params["topic"] = topic; let user = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: params, user: user, password : self.secretKey, onCompletion: { json, err in do { let permissions : [io.magistral.client.perm.PermMeta] = try JsonConverter.sharedInstance.handle(json: json); callback(permissions, err == nil ? nil : MagistralException.permissionFetchError); } catch { } }) } // PERMISSIONS - GRANT public func grant(_ user: String, topic: String, read: Bool, write: Bool, callback : io.magistral.client.perm.Callback?) throws { try self.grant(user, topic: topic, channel: -1, read: read, write: write, ttl: -1, callback: callback); } public func grant(_ user: String, topic: String, read: Bool, write: Bool, ttl: Int, callback : io.magistral.client.perm.Callback?) throws { try self.grant(user, topic: topic, channel: -1, read: read, write: write, ttl: ttl, callback: callback); } public func grant(_ user: String, topic: String, channel: Int, read: Bool, write: Bool, callback : io.magistral.client.perm.Callback?) throws { try self.grant(user, topic: topic, channel: channel, read: read, write: write, ttl: -1, callback: callback); } public func grant(_ user: String, topic: String, channel: Int, read: Bool, write: Bool, ttl: Int, callback : io.magistral.client.perm.Callback?) throws { let baseURL = "https://" + self.host + "/api/magistral/net/grant" var params : Parameters = [ : ] params["user"] = user; params["topic"] = topic; if (channel > -1) { params["channel"] = channel; } params["read"] = String(read); params["write"] = String(write); if (ttl > -1) { params["ttl"] = ttl; } let auth = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPPutRequestText(baseURL, parameters: params, user: auth, password : self.secretKey, onCompletion: { text, err in if (callback != nil && err == nil) { let baseURL = "https://" + self.host + "/api/magistral/net/user_permissions" RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: [ "userName" : user], user: auth, password : self.secretKey, onCompletion: { json, err in do { let permissions : [io.magistral.client.perm.PermMeta] = try JsonConverter.sharedInstance.handle(json: json); callback?(permissions, err == nil ? nil : MagistralException.permissionFetchError); } catch { } }) } }) } // PERMISSIONS - REVOKE public func revoke(_ user: String, topic: String, callback : io.magistral.client.perm.Callback?) throws { try revoke(user, topic: topic, channel: -1, callback: callback); } public func revoke(_ user: String, topic: String, channel: Int, callback : io.magistral.client.perm.Callback?) throws { let baseURL = "https://" + self.host + "/api/magistral/net/revoke" var params : Parameters = [ : ] params["user"] = user; params["topic"] = topic; if (channel > -1) { params["channel"] = channel; } let auth = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPDeleteRequestText(baseURL, parameters: params, user: auth, password: self.secretKey) { text, err in if (callback != nil && err == nil) { let baseURL = "https://" + self.host + "/api/magistral/net/user_permissions" RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: [ "userName" : user], user: auth, password : self.secretKey, onCompletion: { json, err in do { let permissions : [io.magistral.client.perm.PermMeta] = try JsonConverter.sharedInstance.handle(json: json); callback?(permissions, err == nil ? nil : MagistralException.permissionFetchError); } catch { } }) } } } // HISTORY public func history(_ topic: String, channel: Int, count: Int, callback : @escaping io.magistral.client.data.Callback) throws { try self.history(topic, channel: channel, start: UInt64(0), count: count, callback: callback) } public func history(_ topic: String, channel: Int, start: UInt64, count: Int, callback : @escaping io.magistral.client.data.Callback) throws { let baseURL = "https://" + self.host + "/api/magistral/data/history" var params : Parameters = [ : ] params["topic"] = topic; params["channel"] = channel; params["count"] = count; if (start > 0) { params["start"] = start } let user = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: params, user: user, password : self.secretKey, onCompletion: { json, err in do { let history : io.magistral.client.data.History = try JsonConverter.sharedInstance.handle(json: json); callback(history, err == nil ? nil : MagistralException.historyInvocationError); } catch MagistralException.historyInvocationError { let history = io.magistral.client.data.History(messages: [Message]()); callback(history, MagistralException.historyInvocationError) } catch { } }) } public func history(_ topic: String, channel: Int, start: UInt64, end: UInt64, callback : @escaping io.magistral.client.data.Callback) throws { let baseURL = "https://" + self.host + "/api/magistral/data/historyForPeriod" var params : Parameters = [ : ] params["topic"] = topic; params["channel"] = channel; params["start"] = start; params["end"] = end; let user = self.pubKey + "|" + self.subKey; RestApiManager.sharedInstance.makeHTTPGetRequest(path: baseURL, parameters: params, user: user, password : self.secretKey, onCompletion: { json, err in do { let history : io.magistral.client.data.History = try JsonConverter.sharedInstance.handle(json: json); callback(history, err == nil ? nil : MagistralException.historyInvocationError); } catch MagistralException.historyInvocationError { let history = io.magistral.client.data.History(messages: [Message]()); callback(history, MagistralException.historyInvocationError) } catch { } }) } public func close() { mqtt?.disconnect(); self.active = false; } }
mit
c1163a8cc912438a96c4f8dd068b0c77
42.22963
191
0.565684
4.355224
false
false
false
false
worthbak/ChatLog
ChatLog/ChatLog/MainView/MainViewController.swift
1
5724
// // MainViewController.swift // ChatLog // // Created by David Baker on 3/3/16. // Copyright © 2016 Worth Baker. All rights reserved. // import UIKit // MARK: - Constants / Protocols private let CalendarViewHeight: CGFloat = 80 private let PlusButtonDimension: CGFloat = 60 protocol MainViewControllerDelegate: class { func provideChatsForDate(date: NSDate) -> [Chat] func newChatButtonTappedWithDate(date: NSDate) } // MARK: - MainViewController class MainViewController: UIViewController { weak var delegate: MainViewControllerDelegate? // MARK: Lazily-loaded UI Elements private lazy var calendarViewController: CalendarViewController = { let dateVC = CalendarViewController() dateVC.delegate = self self.setUpChildViewController(dateVC) return dateVC }() private lazy var chatTableViewController: ChatTableViewController = { let chatVC = ChatTableViewController() self.setUpChildViewController(chatVC) return chatVC }() private lazy var plusButton: PlusButton = { let button = PlusButton(type: .System) button.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(button) // customize the button's tap action to call our delegate method button.tapActionClosure = { [unowned self] _ in self.delegate?.newChatButtonTappedWithDate(self.calendarViewController.selectedDate) } return button }() // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "ChatLog" // Set navBar appearance self.navigationController?.navigationBar.barTintColor = CLBlue self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent self.navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : CLWhite, NSFontAttributeName : UIFont.systemFontOfSize(20) ] // add constraints for the child view controllers MainViewController.createConstraintsForCalendarViewController(self.calendarViewController, withParentViewController: self) MainViewController.createConstraintsForChatTableViewController(self.chatTableViewController, withParentViewController: self, withTopAnchor: self.calendarViewController.bottomLayoutGuide.bottomAnchor) // add the plus button constraints MainViewController.createConstraintsForPlusButton(self.plusButton, withParentViewController: self) // load the initial displayed data self.reloadChatData() } /// Sets the currently selected date and reloads all chat data func setSelectedDate(date: NSDate, andReloadData reload: Bool = true) { self.calendarViewController.selectedDate = date if reload { self.reloadChatData() } } /// Reloads/resets the data in both the calendar view and chat table view. func reloadChatData() { self.calendarViewController.constructDates() let chats = self.delegate?.provideChatsForDate(self.calendarViewController.selectedDate) self.chatTableViewController.chatsForDisplay = chats ?? [Chat]() self.chatTableViewController.tableView.reloadData() } private func setUpChildViewController(childVC: UIViewController) { childVC.view.translatesAutoresizingMaskIntoConstraints = false self.addChildViewController(childVC) self.view.addSubview(childVC.view) childVC.didMoveToParentViewController(self) } } // MARK: - CalendarViewControllerDelegate extension MainViewController: CalendarViewControllerDelegate { func provideChatsForDate(date: NSDate) -> [Chat] { if let chats = self.delegate?.provideChatsForDate(date) { return chats } else { fatalError("there is no delegate for the main view controller; this is not allowed") } } func dateTapped(date: NSDate) { self.reloadChatData() } } // MARK: - Layout Generation // Static, standalone functions for adding view constraints extension MainViewController { static func createConstraintsForCalendarViewController(calendarVC: CalendarViewController, withParentViewController parentVC: UIViewController, withCalendarHeight height: CGFloat = CalendarViewHeight) { calendarVC.view.topAnchor.constraintEqualToAnchor(parentVC.topLayoutGuide.bottomAnchor).active = true calendarVC.view.leadingAnchor.constraintEqualToAnchor(parentVC.view.leadingAnchor).active = true calendarVC.view.trailingAnchor.constraintEqualToAnchor(parentVC.view.trailingAnchor).active = true calendarVC.view.heightAnchor.constraintEqualToConstant(height).active = true } static func createConstraintsForChatTableViewController(chatVC: ChatTableViewController, withParentViewController parentVC: UIViewController, withTopAnchor topAnchor: NSLayoutAnchor) { chatVC.view.topAnchor.constraintEqualToAnchor(topAnchor).active = true chatVC.view.leadingAnchor.constraintEqualToAnchor(parentVC.view.leadingAnchor).active = true chatVC.view.trailingAnchor.constraintEqualToAnchor(parentVC.view.trailingAnchor).active = true chatVC.view.bottomAnchor.constraintEqualToAnchor(parentVC.bottomLayoutGuide.bottomAnchor).active = true } static func createConstraintsForPlusButton(plusButton: PlusButton, withParentViewController parentVC: UIViewController, withButtonDimension dimension: CGFloat = PlusButtonDimension) { plusButton.heightAnchor.constraintEqualToConstant(dimension).active = true plusButton.widthAnchor.constraintEqualToConstant(dimension).active = true plusButton.centerXAnchor.constraintEqualToAnchor(parentVC.view.centerXAnchor).active = true plusButton.bottomAnchor.constraintEqualToAnchor(parentVC.bottomLayoutGuide.bottomAnchor, constant: -8.0).active = true } }
gpl-3.0
4d92e0cc7f871f1a83c99f5181e103b6
39.878571
204
0.779486
5.299074
false
false
false
false
tvolkert/plugins
packages/shared_preferences/shared_preferences_macos/macos/Classes/SharedPreferencesPlugin.swift
1
1960
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import Foundation public class SharedPreferencesPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel( name: "plugins.flutter.io/shared_preferences", binaryMessenger: registrar.messenger) let instance = SharedPreferencesPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getAll": result(getAllPrefs()) case "setBool", "setInt", "setDouble", "setString", "setStringList": let arguments = call.arguments as! [String: Any] let key = arguments["key"] as! String UserDefaults.standard.set(arguments["value"], forKey: key) result(true) case "commit": // UserDefaults does not need to be synchronized. result(true) case "remove": let arguments = call.arguments as! [String: Any] let key = arguments["key"] as! String UserDefaults.standard.removeObject(forKey: key) result(true) case "clear": let defaults = UserDefaults.standard for (key, _) in getAllPrefs() { defaults.removeObject(forKey: key) } result(true) default: result(FlutterMethodNotImplemented) } } } /// Returns all preferences stored by this plugin. private func getAllPrefs() -> [String: Any] { var filteredPrefs: [String: Any] = [:] if let appDomain = Bundle.main.bundleIdentifier, let prefs = UserDefaults.standard.persistentDomain(forName: appDomain) { for (key, value) in prefs where key.hasPrefix("flutter.") { filteredPrefs[key] = value } } return filteredPrefs }
bsd-3-clause
26deec2c931d74a24bb6543389813910
31.131148
82
0.677551
4.404494
false
false
false
false
xiajinchun/NimbleNinja
NimbleNinja/GameScene.swift
1
4848
// // GameScene.swift // NimbleNinja // // Created by Jinchun Xia on 15/4/14. // Copyright (c) 2015 TEAM. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var movingGround: NNMovingGround! var hero: NNHero! var cloudGenerator: NNCloudGenerator! var wallGenerator: NNWallGenerator! var isStarted = false var isGameOver = false override func didMoveToView(view: SKView) { /* Setup your scene here */ backgroundColor = UIColor(red: 159.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0) /* add ground */ addMovingGround() /* add hero */ addHero() /* add cloud generator */ addCloudGenerator() /* add wall generator */ addWallGenerator() /* add start label */ addTapToStartLabel() /* add physics world */ addPhysicsWorld() } func addMovingGround() { movingGround = NNMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight)) movingGround.position = CGPointMake(0, view!.frame.size.height / 2) self.addChild(movingGround) } func addHero() { hero = NNHero() hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height / 2 + hero.frame.size.height / 2) self.addChild(hero) hero.breath() } func addCloudGenerator() { cloudGenerator = NNCloudGenerator(color: UIColor.clearColor(), size: view!.frame.size) cloudGenerator.position = view!.center cloudGenerator.zPosition = -10 addChild(cloudGenerator) cloudGenerator.populate(7) cloudGenerator.startGeneratingWithSpawnTime(5) } func addWallGenerator() { wallGenerator = NNWallGenerator(color: UIColor.clearColor(), size: view!.frame.size) wallGenerator.position = view!.center addChild(wallGenerator) } func addTapToStartLabel() { let tapToStartLabel = SKLabelNode(text: "Tap to start!") tapToStartLabel.name = "tapToStartLabel" tapToStartLabel.position.x = view!.center.x tapToStartLabel.position.y = view!.center.y + 40 tapToStartLabel.fontName = "Helvetice" tapToStartLabel.fontColor = UIColor.blackColor() tapToStartLabel.fontSize = 22.0 addChild(tapToStartLabel) tapToStartLabel.runAction(blinkAnimation()) } func addPhysicsWorld() { physicsWorld.contactDelegate = self } // MARK: - Game Lifecycle func start() { isStarted = true /* find the ndoe by named "tapToStartLabel" and then remove it from parent node */ let tapToStartLabel = childNodeWithName("tapToStartLabel") tapToStartLabel?.removeFromParent() hero.stop() hero.startRuning() movingGround.start() wallGenerator.startGeneratingWallsEvery(1) } func gameOver() { isGameOver = true // stop everthing hero.fail() wallGenerator.stopWalls() movingGround.stop() hero.stop() // create game over label let gameOverLabel = SKLabelNode(text: "Game Over!") gameOverLabel.fontColor = UIColor.blackColor() gameOverLabel.fontName = "Helvetice" gameOverLabel.position.x = view!.center.x gameOverLabel.position.y = view!.center.y + 40 gameOverLabel.fontSize = 22.0 addChild(gameOverLabel) gameOverLabel.runAction(blinkAnimation()) } func restart() { cloudGenerator.stopGenerating() let newScene = GameScene(size: view!.bounds.size) newScene.scaleMode = SKSceneScaleMode.AspectFill view!.presentScene(newScene) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { /* Called when a touch begins */ if isGameOver { restart() } else if !isStarted { start() } else { hero.flip() } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } // MARK: - SKPhysiscContactDeleagte func didBeginContact(contact: SKPhysicsContact) { if !isGameOver{ gameOver() } } // MARK: - Animation func blinkAnimation() -> SKAction { let duration = 0.4 let fadeOut = SKAction.fadeAlphaTo(0.0, duration: duration) let fadeIn = SKAction.fadeAlphaTo(1.0, duration: duration) let blink = SKAction.sequence([fadeOut, fadeIn]) return SKAction.repeatActionForever(blink) } }
mit
64c0725056ffe065b60c53cd99ea9155
28.567073
130
0.603135
4.577904
false
false
false
false
joshdholtz/Few.swift
Few-iOS/Input.swift
1
4450
// // Input.swift // Few // // Created by Coen Wessels on 14-03-15. // Copyright (c) 2015 Josh Abernathy. All rights reserved. // import UIKit final internal class InputDelegate: NSObject, UITextFieldDelegate { var shouldReturn: (UITextField -> Bool)? func textFieldShouldReturn(textField: UITextField) -> Bool { return shouldReturn?(textField) ?? true } } public class Input: Element { public var text: String? public var textColor: UIColor? public var font: UIFont? public var initialText: String? public var placeholder: String? public var enabled: Bool public var secure: Bool public var borderStyle: UITextBorderStyle public var keyboardType: UIKeyboardType public var returnKeyType: UIReturnKeyType public var autocorrectionType: UITextAutocorrectionType public var autocapitalizationType: UITextAutocapitalizationType private var actionTrampoline = TargetActionTrampolineWithSender<UITextField>() private var inputDelegate = InputDelegate() public init(text: String? = nil, textColor: UIColor? = nil, font: UIFont? = nil, initialText: String? = nil, placeholder: String? = nil, enabled: Bool = true, secure: Bool = false, borderStyle: UITextBorderStyle = .None, keyboardType: UIKeyboardType = .Default, returnKeyType: UIReturnKeyType = .Default, autocorrectionType: UITextAutocorrectionType = .Default, autocapitalizationType: UITextAutocapitalizationType = .Sentences, shouldReturn: String -> Bool = { _ in true }, textChanged: String -> () = { _ in }) { self.text = text self.textColor = textColor self.font = font self.initialText = initialText self.placeholder = placeholder self.enabled = enabled self.secure = secure self.borderStyle = borderStyle self.keyboardType = keyboardType self.returnKeyType = returnKeyType self.autocorrectionType = autocorrectionType self.autocapitalizationType = autocapitalizationType actionTrampoline.action = { textField in textChanged(textField.text) } inputDelegate.shouldReturn = { textField in shouldReturn(textField.text) } super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 23)) } // MARK: Element public override func applyDiff(old: Element, realizedSelf: RealizedElement?) { super.applyDiff(old, realizedSelf: realizedSelf) if let textField = realizedSelf?.view as? UITextField { if let oldInput = old as? Input { let newTrampoline = oldInput.actionTrampoline newTrampoline.action = actionTrampoline.action // Make sure the newest action is used actionTrampoline = newTrampoline } textField.delegate = inputDelegate if placeholder != textField.placeholder { textField.placeholder = placeholder } if let text = text where text != textField.text { textField.text = text } if enabled != textField.enabled { textField.enabled = enabled } if secure != textField.secureTextEntry { textField.secureTextEntry = secure } if let font = font where font != textField.font { textField.font = font } if let color = textColor where color != textField.textColor { textField.textColor = color } if borderStyle != textField.borderStyle { textField.borderStyle = borderStyle } if keyboardType != textField.keyboardType { textField.keyboardType = keyboardType } if returnKeyType != textField.returnKeyType { textField.returnKeyType = returnKeyType } if autocorrectionType != textField.autocorrectionType { textField.autocorrectionType = autocorrectionType } if autocapitalizationType != textField.autocapitalizationType { textField.autocapitalizationType = autocapitalizationType } } } public override func createView() -> ViewType { let field = UITextField(frame: frame) field.addTarget(actionTrampoline.target, action: actionTrampoline.selector, forControlEvents: .EditingChanged) field.delegate = inputDelegate field.alpha = alpha field.hidden = hidden field.enabled = enabled field.placeholder = placeholder field.secureTextEntry = secure field.text = text ?? initialText ?? "" field.borderStyle = borderStyle field.keyboardType = keyboardType field.returnKeyType = returnKeyType field.autocorrectionType = autocorrectionType field.autocapitalizationType = autocapitalizationType if let font = font { field.font = font } if let color = textColor { field.textColor = color } return field } }
mit
a94a85d2deecab41dc7349a763b1d2b8
30.338028
515
0.736404
4.432271
false
false
false
false
nifti/CinchKit
CinchKitTests/CinchClient+NotificationsTests.swift
1
5536
// // CinchClient+NotificationsTests.swift // CinchKit // // Created by Ryan Fitzgerald on 5/12/15. // Copyright (c) 2015 cinch. All rights reserved. // import Foundation import Quick import Nimble import CinchKit import Nocilla class CinchClientNotificationsSpec: QuickSpec { override func spec() { describe("fetch notifications") { let client = CinchClient() beforeEach { LSNocilla.sharedInstance().start() LSNocilla.sharedInstance().clearStubs() } afterEach { LSNocilla.sharedInstance().clearStubs() LSNocilla.sharedInstance().stop() } it("should fetch notifications") { let data = CinchKitTestsHelper.loadJsonData("fetchNotifications") let urlStr = "http://notification-service-vpxjdpudmk.elasticbeanstalk.com/accounts/72d25ff9-1d37-4814-b2bd-bc149c222220/notifications" let url = NSURL(string: urlStr)! stubRequest("GET", urlStr).andReturn(200).withHeader("Content-Type", "application/json").withBody(data) waitUntil(timeout: 5) { done in client.fetchNotifications(atURL: url, queue: nil) { (response, error) in expect(error).to(beNil()) expect(response).notTo(beNil()) expect(response!.nextLink).notTo(beNil()) expect(response!.notifications).notTo(beEmpty()) expect(response!.notifications?.count).to(equal(6)) var note = response!.notifications![0] expect(note.senderAccount).notTo(beNil()) expect(note.recipientAccount).notTo(beNil()) expect(note.resourcePoll).notTo(beNil()) expect(note.resourceAccount).to(beNil()) expect(note.resourceCategory).to(beNil()) expect(note.action).to(equal("voted")) expect(note.extraCandidate!.id).to(equal("0278e2ed-5d8e-4556-88ef-c9e075524857:YES")) note = response!.notifications![1] expect(note.senderAccount).notTo(beNil()) expect(note.recipientAccount).notTo(beNil()) expect(note.resourcePoll).notTo(beNil()) expect(note.resourceAccount).to(beNil()) expect(note.resourceCategory).to(beNil()) expect(note.action).to(equal("created")) note = response!.notifications![2] expect(note.senderAccount).notTo(beNil()) expect(note.recipientAccount).notTo(beNil()) expect(note.resourcePoll).to(beNil()) expect(note.resourceAccount).notTo(beNil()) expect(note.resourceCategory).to(beNil()) expect(note.action).to(equal("following")) note = response!.notifications![5] expect(note.senderAccount).notTo(beNil()) expect(note.recipientAccount).notTo(beNil()) expect(note.resourcePoll).to(beNil()) expect(note.resourceAccount).to(beNil()) expect(note.resourceCategory).notTo(beNil()) expect(note.action).to(equal("following")) done() } } } } describe("sending notifications") { let c = CinchClient() CinchKitTestsHelper.setTestUserSession(c) let n = ApiResource(id: "notifications", href: NSURL(string: "http://notification-service-vpxjdpudmk.elasticbeanstalk.com/notifications")!, title: "Send notifications") c.rootResources = ["notifications" : n] it("should send notification") { waitUntil(timeout: 5) { done in c.refreshSession { (account, error) in let params = [ "recipientId": CinchKitTestsHelper.getTestUserId(), "recipientType": "account", "resourceId": CinchKitTestsHelper.getTestUserId(), "resourceType": "account", "action": "shared" ] c.sendNotification(params, queue: nil, completionHandler: { (response, error) -> () in expect(error).to(beNil()) done() }) } } } } describe("updating device token") { let c = CinchClient() let d = ApiResource(id: "deviceToken", href: NSURL(string: "http://notification-service-vpxjdpudmk.elasticbeanstalk.com/devicetokens")!, title: "Device token") c.rootResources = ["deviceToken" : d] it("should update device token") { waitUntil(timeout: 5) { done in c.updateDeviceToken("1111111111", accountId: "2222222222", queue: nil, completionHandler: { (_, error) -> () in expect(error).to(beNil()) done() }) } } } } }
mit
ff70603813ef657adeaa6cf974da1054
40.631579
180
0.50578
5.169001
false
true
false
false
ahoppen/swift
test/IRGen/conditional-dead-strip-ir.swift
9
2057
// Tests that with -conditional-runtime-records, IRGen marks class, struct, // enum, protocol, and protocol conformance records as conditionally removable // via !llvm.used.conditional metadata. // RUN: %target-build-swift -Xfrontend -conditional-runtime-records -Xfrontend -disable-objc-interop %s -emit-ir -o - | %FileCheck %s public protocol TheProtocol { } public class Class: TheProtocol { } public struct Struct { } public enum Enum { } // CHECK: @llvm.{{(compiler.)?}}used = appending global [ // CHECK-SAME: @"$s4main11TheProtocolHr" // CHECK-SAME: @"$s4main5ClassCAA11TheProtocolAAHc" // CHECK-SAME: @"$s4main5ClassCHn" // CHECK-SAME: @"$s4main6StructVHn" // CHECK-SAME: @"$s4main4EnumOHn" // CHECK-SAME: ], section "llvm.metadata" // CHECK: !llvm.used.conditional = !{[[M1:!.*]], [[M2:!.*]], [[M3:!.*]], [[M4:!.*]], [[C1:!.*]], [[C2:!.*]], [[C3:!.*]], [[C4:!.*]], [[C5:!.*]]} // CHECK-DAG: [[M1]] = !{{{.*}} @"$s4main11TheProtocol_pMF", i32 0, [[M1A:!.*]]} // CHECK-DAG: [[M1A]] = {{.*}} @"$s4main11TheProtocolMp" // CHECK-DAG: [[M2]] = !{{{.*}} @"$s4main5ClassCMF", i32 0, [[M2A:!.*]]} // CHECK-DAG: [[M2A]] = {{.*}} @"$s4main5ClassCMn" // CHECK-DAG: [[M3]] = !{{{.*}} @"$s4main6StructVMF", i32 0, [[M3A:!.*]]} // CHECK-DAG: [[M3A]] = {{.*}} @"$s4main6StructVMn" // CHECK-DAG: [[M4]] = !{{{.*}} @"$s4main4EnumOMF", i32 0, [[M4A:!.*]]} // CHECK-DAG: [[M4A]] = {{.*}} @"$s4main4EnumOMn" // CHECK-DAG: [[C1]] = !{{{.*}} @"$s4main11TheProtocolHr", i32 0, [[C1A:!.*]]} // CHECK-DAG: [[C1A]] = {{.*}} @"$s4main11TheProtocolMp"} // CHECK-DAG: [[C2]] = !{{{.*}} @"$s4main5ClassCAA11TheProtocolAAHc", i32 1, [[C2A:!.*]]} // CHECK-DAG: [[C2A]] = {{.*}} @"$s4main11TheProtocolMp", {{.*}} @"$s4main5ClassCMn"} // CHECK-DAG: [[C3]] = !{{{.*}} @"$s4main5ClassCHn", i32 0, [[M2A:!.*]]} // CHECK-DAG: [[C4]] = !{{{.*}} @"$s4main6StructVHn", i32 0, [[M3A:!.*]]} // CHECK-DAG: [[C5]] = !{{{.*}} @"$s4main4EnumOHn", i32 0, [[M4A:!.*]]}
apache-2.0
6929e645d6eb6bf80a1d6bbda7b50e84
41.854167
149
0.53087
2.654194
false
false
false
false
kylebrowning/waterwheel.swift
Sources/iOS/Views/waterwheelLoginViewController.swift
1
7347
// // waterwheelLoginViewController.swift // // import UIKit extension UIViewController { } open class waterwheelLoginViewController: UIViewController { open let usernameField: UITextField = { let usernameField = UITextField() usernameField.autocorrectionType = .no usernameField.attributedPlaceholder = NSAttributedString(string: "Email") usernameField.translatesAutoresizingMaskIntoConstraints = false usernameField.backgroundColor = UIColor.lightGray usernameField.textAlignment = .center usernameField.placeholder = "Username" usernameField.isHidden = true return usernameField }() open let passwordField: UITextField = { let passwordField = UITextField() passwordField.isSecureTextEntry = true passwordField.autocorrectionType = .no passwordField.attributedPlaceholder = NSAttributedString(string: "Password") passwordField.backgroundColor = UIColor.lightGray passwordField.textAlignment = .center passwordField.translatesAutoresizingMaskIntoConstraints = false passwordField.placeholder = "password" passwordField.isHidden = true passwordField.returnKeyType = .go return passwordField }() open var submitButton: waterwheelAuthButton = { let submitButton = waterwheelAuthButton() submitButton.translatesAutoresizingMaskIntoConstraints = false submitButton.backgroundColor = UIColor.darkGray return submitButton }() open var cancelButton: UIButton = { let cancelButton = UIButton() cancelButton.translatesAutoresizingMaskIntoConstraints = false cancelButton.backgroundColor = UIColor.gray cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside) cancelButton.setTitle("Cancel", for: UIControlState()) return cancelButton }() /** Provide a closure for when a Login Request is completed. */ open var loginRequestCompleted: (_ success: Bool, _ error: NSError?) -> Void = { _ in } /** Provide a closure for when a Logout Request is completed. */ open var logoutRequestCompleted: (_ success: Bool, _ error: NSError?) -> Void = { _ in } /** Provide a cancel button closure. */ open var cancelButtonHit: () -> Void = { _ in } override open func viewDidLoad() { super.viewDidLoad() configure(isInit:true) } /** Overridden viewDidAppear where decide if were logged in or not. - parameter animated: Is the view animated */ override open func viewDidAppear(_ animated: Bool) { self.configure(isInit:false) } /** Configure this viewcontrollers view based on auth state. */ open func configure(isInit: Bool) { if isInit { self.view.backgroundColor = UIColor.white // Incase of logout or login, we attach to the notification Center for the purpose of seeing requests. NotificationCenter.default.addObserver( self, selector: #selector(configure), name: NSNotification.Name(rawValue: waterwheelNotifications.waterwheelDidFinishRequest.rawValue), object: nil) submitButton.didPressLogin = { self.loginAction() } submitButton.didPressLogout = { (success, error) in self.logoutAction(success, error: error) } self.view.addSubview(usernameField) self.view.addSubview(passwordField) self.view.addSubview(submitButton) self.view.addSubview(cancelButton) } if !waterwheel.isLoggedIn() { self.showAnonymousSubviews() } else { // We do nothing because our waterwheelAuthButton will handle its own state } } /** Layout the Anonymous Subviews. */ open func layoutSubviews() { self.layoutLoginField() self.layoutPasswordField() self.layoutSubmitButton() self.layoutCancelButton() } /** Lays out the login field. */ open func layoutLoginField() { usernameField.constrainEqual(.leadingMargin, to: view) usernameField.constrainEqual(.trailingMargin, to: view) usernameField.constrainEqual(.top, to: view, .top, multiplier: 1.0, constant: 44) usernameField.heightAnchor.constraint(equalToConstant: 50.0).isActive = true } /** Lays out the password field. */ open func layoutPasswordField() { passwordField.constrainEqual(.leadingMargin, to: view) passwordField.constrainEqual(.trailingMargin, to: view) passwordField.constrainEqual(.bottomMargin, to: usernameField, .bottomMargin, multiplier: 1.0, constant: 55) passwordField.heightAnchor.constraint(equalToConstant: 50.0).isActive = true } /** Lays out the Submit Button */ open func layoutSubmitButton() { submitButton.constrainEqual(.leadingMargin, to: view) submitButton.constrainEqual(.trailingMargin, to: view) submitButton.constrainEqual(.bottomMargin, to: passwordField, .bottomMargin, multiplier: 1.0, constant: 55) submitButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true } /** Lays out the Anonymous Button */ open func layoutCancelButton() { cancelButton.constrainEqual(.leadingMargin, to: view) cancelButton.constrainEqual(.trailingMargin, to: view) cancelButton.constrainEqual(.bottomMargin, to: submitButton, .bottomMargin, multiplier: 1.0, constant: 55) cancelButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true } /** Remove anonymous subviews. */ open func hideAnonymousSubviews() { usernameField.isHidden = true passwordField.isHidden = true cancelButton.isHidden = true } /** Add Anonymous subviews. */ open func showAnonymousSubviews() { self.layoutSubviews() usernameField.isHidden = false passwordField.isHidden = false cancelButton.isHidden = false } /** Public Login Action function for the login button that runs our closure. */ open func loginAction() { waterwheel.login(username: usernameField.text!, password: passwordField.text!) { (success, _, _, error) in if (success) { self.hideAnonymousSubviews() } else { print("failed to login") } self.loginRequestCompleted(success, error) } } /** Public Logout action that runs our closure. - parameter success: success or failure - parameter error: if error happened. */ open func logoutAction(_ success: Bool, error: NSError?) { if (success) { self.showAnonymousSubviews() } else { print("failed to logout") } self.logoutRequestCompleted(success, error) } open func cancelAction() { self.cancelButtonHit() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
12e54bb2693e7621125923ddf2fc87a4
32.094595
116
0.646114
5.335512
false
false
false
false
hirohisa/RxSwift
RxCocoa/RxCocoa/Common/RxCocoa.swift
4
3657
// // RxCocoa.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif #if os(iOS) import UIKit #endif public enum RxCocoaError : Int { case Unknown = 0 case NetworkError = 1 case InvalidOperation = 2 case KeyPathInvalid = 3 } let defaultHeight: CGFloat = -1 public let RxCocoaErrorDomain = "RxCocoaError" public let RxCocoaErrorHTTPResponseKey = "RxCocoaErrorHTTPResponseKey" func rxError(errorCode: RxCocoaError, message: String) -> NSError { return NSError(domain: RxCocoaErrorDomain, code: errorCode.rawValue, userInfo: [NSLocalizedDescriptionKey: message]) } #if !RELEASE public func _rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError { return rxError(errorCode, message, userInfo) } #endif func rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError { var resultInfo: [NSObject: AnyObject] = [:] resultInfo[NSLocalizedDescriptionKey] = message for k in userInfo.allKeys { resultInfo[k as! NSObject] = userInfo[k as! NSCopying] } return NSError(domain: RxCocoaErrorDomain, code: Int(errorCode.rawValue), userInfo: resultInfo) } func handleVoidObserverResult(result: RxResult<Void>) { handleObserverResult(result) } func bindingErrorToInterface(error: ErrorType) { #if DEBUG rxFatalError("Binding error to UI: \(error)") #endif } // There are certain kinds of errors that shouldn't be silenced, but it could be weird to crash the app because of them. // DEBUG -> crash the app // RELEASE -> log to console func rxPossiblyFatalError(error: String) { #if DEBUG rxFatalError(error) #else println("[RxSwift]: \(error)") #endif } func rxAbstractMethodWithMessage<T>(message: String) -> T { return rxFatalErrorAndDontReturn(message) } func rxAbstractMethod<T>() -> T { return rxFatalErrorAndDontReturn("Abstract method") } func handleObserverResult<T>(result: RxResult<T>) { switch result { case .Failure(let error): print("Error happened \(error)") rxFatalError("Error '\(error)' happened while "); default: break } } // workaround for Swift compiler bug, cheers compiler team :) func castOptionalOrFatalError<T>(value: AnyObject?) -> T? { if value == nil { return nil } let v: T = castOrFatalError(value) return v } func castOrFatalError<T>(value: AnyObject!, message: String) -> T { let result: RxResult<T> = castOrFail(value) if result.isFailure { rxFatalError(message) } return result.get() } func castOrFatalError<T>(value: AnyObject!) -> T { let result: RxResult<T> = castOrFail(value) if result.isFailure { rxFatalError("Failure converting from \(value) to \(T.self)") } return result.get() } // Error messages { let dataSourceNotSet = "DataSource not set" let delegateNotSet = "Delegate not set" // } func rxFatalErrorAndDontReturn<T>(lastMessage: String) -> T { rxFatalError(lastMessage) return (nil as T!)! } #if !RX_NO_MODULE func rxFatalError(lastMessage: String) { // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. fatalError(lastMessage) } extension NSObject { func rx_synchronized<T>(@noescape action: () -> T) -> T { objc_sync_enter(self) let result = action() objc_sync_exit(self) return result } } func removingObserverFailed() { rxFatalError("Removing observer for key failed") } #endif
mit
bd9ceffbb6ec1fa81c8351242da2d96f
23.543624
120
0.691277
3.992358
false
false
false
false
itouch2/LeetCode
LeetCode/MergeSortedArray.swift
1
1212
// // MergeSortedArray.swift // LeetCode // // Created by You Tu on 2017/9/10. // Copyright © 2017年 You Tu. All rights reserved. // /* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ import Cocoa class MergeSortedArray: NSObject { func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { var i = 0, j = 0 var results: [Int] = [] while i < m && j < n { if nums1[i] <= nums2[j] { results.append(nums1[i]) i += 1 } else { results.append(nums2[j]) j += 1 } } let remained: [Int] = i >= m ? nums2 : nums1 var remainedIndex = i >= m ? j : i let remainedCount = i >= m ? n : m while remainedIndex < remainedCount { results.append(remained[remainedIndex]) remainedIndex += 1 } nums1 = results } }
mit
1c7889ffe9ce420218a399e168529bd5
27.116279
204
0.539289
3.789969
false
false
false
false
vadymmarkov/Mentions
Example/MentionsDemo/MentionsDemo/Sources/AppDelegate.swift
1
734
import UIKit import Mentions @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var navigationController: UINavigationController = { [unowned self] in let controller = UINavigationController(rootViewController: self.viewController) return controller }() lazy var viewController: ViewController = { let controller = ViewController() return controller }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = navigationController window?.makeKeyAndVisible() return true } }
mit
0effbb15d9214320cee26771b826b58e
27.230769
125
0.757493
5.919355
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/Cells/BasicMessageCell.swift
1
4045
// // BasicMessageCell.swift // Rocket.Chat // // Created by Filipe Alvarenga on 23/09/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import RocketChatViewController final class BasicMessageCell: BaseMessageCell, SizingCell { static let identifier = String(describing: BasicMessageCell.self) // MARK: SizingCell static let sizingCell: UICollectionViewCell & ChatCell = { guard let cell = BasicMessageCell.instantiateFromNib() else { return BasicMessageCell() } return cell }() @IBOutlet weak var avatarContainerView: UIView! { didSet { avatarContainerView.layer.cornerRadius = 4 avatarView.frame = avatarContainerView.bounds avatarContainerView.addSubview(avatarView) } } @IBOutlet weak var username: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var statusView: UIImageView! @IBOutlet weak var text: RCTextView! @IBOutlet weak var readReceiptButton: UIButton! @IBOutlet weak var textHeightConstraint: NSLayoutConstraint! @IBOutlet weak var textLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var textTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var readReceiptWidthConstraint: NSLayoutConstraint! @IBOutlet weak var readReceiptTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var avatarWidthConstraint: NSLayoutConstraint! @IBOutlet weak var avatarLeadingConstraint: NSLayoutConstraint! var textWidth: CGFloat { return messageWidth - textLeadingConstraint.constant - textTrailingConstraint.constant - readReceiptWidthConstraint.constant - readReceiptTrailingConstraint.constant - avatarWidthConstraint.constant - avatarLeadingConstraint.constant - layoutMargins.left - layoutMargins.right } override var delegate: ChatMessageCellProtocol? { didSet { text.delegate = delegate } } var initialTextHeightConstant: CGFloat = 0 override func awakeFromNib() { super.awakeFromNib() initialTextHeightConstant = textHeightConstraint.constant insertGesturesIfNeeded(with: username) } override func configure(completeRendering: Bool) { configure( with: avatarView, date: date, status: statusView, and: username, completeRendering: completeRendering ) configure(readReceipt: readReceiptButton) updateText() } func updateText() { guard let viewModel = viewModel?.base as? BasicMessageChatItem, let message = viewModel.message else { return } if let messageText = MessageTextCacheManager.shared.message(for: message, with: theme) { if message.temporary { messageText.setFontColor(MessageTextFontAttributes.systemFontColor(for: theme)) } else if message.failed { messageText.setFontColor(MessageTextFontAttributes.failedFontColor(for: theme)) } text.message = messageText let maxSize = CGSize( width: textWidth, height: .greatestFiniteMagnitude ) textHeightConstraint.constant = text.textView.sizeThatFits( maxSize ).height } } override func prepareForReuse() { super.prepareForReuse() username.text = "" date.text = "" text.message = nil avatarView.prepareForReuse() textHeightConstraint.constant = initialTextHeightConstant } } // MARK: Theming extension BasicMessageCell { override func applyTheme() { super.applyTheme() let theme = self.theme ?? .light date.textColor = theme.auxiliaryText username.textColor = theme.titleText updateText() } }
mit
5e203d0d57f9ceecc5162228541a5543
28.093525
96
0.644906
5.601108
false
false
false
false
frootloops/swift
test/NameBinding/Dependencies/private-subscript.swift
1
832
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps struct Wrapper { fileprivate subscript() -> InterestingType { fatalError() } } // CHECK-OLD: sil_global @_T04main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @_T04main1x{{[^ ]+}} : $Double public var x = Wrapper()[] + 0 // CHECK-DEPS-LABEL: depends-top-level: // CHECK-DEPS: - "InterestingType"
apache-2.0
34b1944a475df0e2d800ff24b4e7ece1
51
203
0.709135
3.175573
false
false
false
false
phelgo/Stevia
Stevia/Stevia.swift
1
869
import Foundation // MARK: - Closures func *(count: Int, closure: () -> ()) { for _ in 1...count { closure() } } // MARK: - Comparison operators infix operator ⩵ { precedence 130 } func ⩵<T:Equatable>(left: T, right: T) -> Bool { return left == right } infix operator ≠ { precedence 130 } func ≠<T:Equatable>(left: T, right: T) -> Bool { return left != right } infix operator ≤ { precedence 130 } func ≤<T:Comparable>(left: T, right: T) -> Bool { return left <= right } infix operator ≥ { precedence 130 } func ≥<T:Comparable>(left: T, right: T) -> Bool { return left >= right } // MARK: - Arrays public func +<Element>(left: [Element], right: Element) -> Array<Element> { return left + [right] } public func +<Element>(left: Element, right: [Element]) -> Array<Element> { return [left] + right }
mit
0d437d048f39cb8c053f7ced69c874b6
17.148936
75
0.602579
3.206767
false
false
false
false
mojidabckuu/content
Content/Classes/Base/ViewDelegate.swift
1
4103
// // ViewDelegate.swift // Contents // // Created by Vlad Gorbenko on 9/5/16. // Copyright © 2016 Vlad Gorbenko. All rights reserved. // import UIKit public protocol Scrollable {} extension Scrollable { var scrollView: UIScrollView { return self as! UIScrollView } } public protocol ViewDelegate: Scrollable { var contentDelegate: AnyObject? { get set } var contentDataSource: AnyObject? { get set } var isScrollEnabled: Bool { get set } // When try to confiorm contentOffset gives a crash on reload. func set(contentOffset: CGPoint) func reloadData() } public enum ContentScrollPosition { case none case top case middle case bottom case centeredVertically case left case centeredHorizontally case right var tableScroll: UITableViewScrollPosition { switch self { case .top: return UITableViewScrollPosition.top case .middle, .centeredVertically: return UITableViewScrollPosition.middle case .bottom: return UITableViewScrollPosition.bottom default: return UITableViewScrollPosition.none } } var collectionScroll: UICollectionViewScrollPosition { switch self { case .middle, .centeredVertically: return UICollectionViewScrollPosition.centeredVertically case .bottom: return UICollectionViewScrollPosition.bottom case .left: return UICollectionViewScrollPosition.left case .centeredHorizontally: return UICollectionViewScrollPosition.centeredHorizontally case .right: return UICollectionViewScrollPosition.right default: return UICollectionViewScrollPosition.top } } } open class BaseDelegate<Model: Equatable, View: ViewDelegate, Cell: ContentCell>: NSObject where View: UIView { open weak var content: Content<Model, View, Cell>! open var selectedItem: Model? open var selectedItems: [Model]? open var visibleItem: Model? open var visibleItems: [Model]? public override init() { super.init() } init(content: Content<Model, View, Cell>) { self.content = content super.init() } // Setup open func setup() {} // Select open func select(model: Model?, animated: Bool, scrollPosition: ContentScrollPosition) {} open func select(models: [Model]?, animated: Bool, scrollPosition: ContentScrollPosition) {} open func deselect(model: Model?, animated: Bool) {} open func deselect(models: [Model]?, animated: Bool) {} //Scroll open func scroll(to model: Model?, at: ContentScrollPosition, animated: Bool) {} open func scroll(to models: [Model]?, at: ContentScrollPosition, animated: Bool) {} open func scrollToBottom() {} open func scrollToTop() {} public typealias Completion = (() -> ()) // open func insert(_ models: [Model], index: Int, animated: Bool, completion: Completion? = nil) {} open func delete(_ models: [Model]) { } open func reload() { self.content.view.reloadData() } open func reload(_ models: [Model], animated: Bool) {} open func update(_ block: () -> (), completion: (() -> ())? = nil) { block() } open func move(from: Int, to: Int) {} open func indexPaths(_ models: [Model]) -> [IndexPath] { var indexPaths: [IndexPath] = [] for model in models { if let index = self.content.relation.index(of: model) { let indexPath = IndexPath(row: Int(index), section: 0) indexPaths.append(indexPath) } } return indexPaths } // open func registerCell(_ reuseIdentifier: String, `class`: AnyClass) { self.registerCell(reuseIdentifier, cell: `class`) } open func registerCell(_ reuseIdentifier: String, cell: AnyClass?) {} open func registerCell(_ reuseIdentifier: String, nib: UINib) {} open func dequeu(at indexPath: IndexPath) -> Cell? { return nil } open func indexPath(_ cell: Cell) -> IndexPath? { return nil } }
mit
59cf4e2320c2023cdb790d71003e0b30
30.79845
111
0.650902
4.889154
false
false
false
false
bfolder/Sweather
Example/Example/ViewController.swift
1
1844
// // ViewController.swift // Example // // Created by Heiko Dreyer on 08/12/14. // Copyright (c) 2014 boxedfolder.com. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var activityIndicatorView: UIActivityIndicatorView? @IBOutlet var textField: UITextField? @IBOutlet var textView: UITextView? var client: Sweather? override func viewDidLoad() { super.viewDidLoad() client = Sweather(apiKey: "ea42045886608526507915df6b33b290") activityIndicatorView?.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if !textField.text!.isEmpty { textView?.text = "" textField.resignFirstResponder() activityIndicatorView?.isHidden = false client?.currentWeather(textField.text!) { result in self.activityIndicatorView?.isHidden = true switch result { case .Error(_, let error): self.textView?.text = "Some error occured. Try again." print("Error: \(error)") case .success(_, let dictionary): self.textView?.text = "Received data: \(dictionary)" // Get temperature for city this way if let city = dictionary?["name"] as? String, let dict = dictionary?["main"] as? NSDictionary, let temperature = dict["temp"] as? Int { print("City: \(city) Temperature: \(temperature)") } } } return true } return false } }
mit
5cb92204ee3735cd6f0d6d4383ab2150
33.148148
114
0.558568
5.570997
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaPtpMessageInConfirm.swift
1
1122
import Foundation final class MVitaPtpMessageInConfirm:MVitaPtpMessageIn { let code:MVitaPtpCommand let transactionId:UInt32 override init?( header:MVitaPtpMessageInHeader, data:Data) { let codeSize:Int = MemoryLayout<UInt16>.size let transactionSize:Int = MemoryLayout<UInt32>.size let expectedSize:Int = codeSize + transactionSize guard data.count >= expectedSize else { return nil } let subdataTransaction:Data = data.subdata( start:codeSize) guard let rawCode:UInt16 = data.valueFromBytes(), let transactionId:UInt32 = subdataTransaction.valueFromBytes() else { return nil } print("confirm code \(rawCode)") self.transactionId = transactionId self.code = MVitaPtpMessageIn.factoryCommandCode( rawCode:rawCode) super.init( header:header, data:data) } }
mit
8d1c7e5f4901afe83f2787b08edf4ac7
23.391304
74
0.546346
5.054054
false
false
false
false
EyreFree/EFQRCode
Playgrounds/Generate/European SEPA Money Transfer + Watermark.playground/Contents.swift
1
2297
import EFQRCode import UIKit /*: # European Credit Transfer code + Watermark The code below generates a EPC QR code to initiate a SEPA credit transfer. Almost any European banking app can be used to scan this code and execute a money transfer. All settings are according to the [official spec](https://www.europeanpaymentscouncil.eu/sites/default/files/kb/file/2018-05/EPC069-12%20v2.1%20Quick%20Response%20Code%20-%20Guidelines%20to%20Enable%20the%20Data%20Capture%20for%20the%20Initiation%20of%20a%20SCT.pdf). See also [Wikipedia EPC QR Code](https://en.wikipedia.org/wiki/EPC_QR_code). Thie examples below create money transfer codes of €1 to the Belgian Red Cross. *** */ /*: Set up de content of the QR code - this can be any string. Note: In production code, you should abstract this data to a struct with some basic checks. For example - limit the size of the Remittance fields in order to not generate large QR codes (According to spec: "Maximum QR code version 13, equivalent to module size 69 or 331 byte payload") */ let belgianRedCrossEPC = """ BCD 002 1 SCT Red Cross of Belgium BE72000000001616 EUR1 https://github.com/EFPrefix/EFQRCode """ //: Generate a basic QR code. Scan this with a European banking app. if let tryImage = EFQRCode.generate( content: belgianRedCrossEPC, inputCorrectionLevel: .m // medium - 15% ECC ) { _ = tryImage // Click quickview or enable 'show result' on the right → } //: Make it fancy - add a **watermark** image. Mind that, while looking very cool, this may not be recognized as a QR code by some people. Also, these kinds of codes are more difficult to recognize by readers. Use with caution! let redcross = UIImage(named: "red-cross-logo.png")?.cgImage if let tryImage = EFQRCode.generate( content: belgianRedCrossEPC, watermark: redcross, inputCorrectionLevel: .m // medium - 15% ECC ) { _ = tryImage // Click quickview or enable 'show result' on the right → } //: Set `allowTransparent` to `false` in order to get a different style. if let tryImage = EFQRCode.generate( content: belgianRedCrossEPC, watermark: redcross, inputCorrectionLevel: .m, // medium - 15% ECC allowTransparent: false ) { _ = tryImage // Click quickview or enable 'show result' on the right → }
mit
f4a452a6575988989dc40934750ea924
37.79661
345
0.736129
3.559876
false
false
false
false
kevinmlong/realm-cocoa
RealmSwift/Object.swift
1
11096
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** In Realm you define your model classes by subclassing `Object` and adding properties to be persisted. You then instantiate and use your custom subclasses instead of using the RLMObject class directly. ```swift class Dog: Object { dynamic var name: String = "" dynamic var adopted: Bool = false let siblings = List<Dog> } ``` ### Supported property types - `String` - `Int` - `Float` - `Double` - `Bool` - `NSDate` - `NSData` - `Object` subclasses for to-one relationships - `List<T: Object>` for to-many relationships ### Querying You can gets `Results` of an Object subclass via tha `objects(_:)` free function or the `objects(_:)` instance method on `Realm`. ### Relationships See our [Cocoa guide](http://realm.io/docs/cocoa) for more details. */ public class Object: RLMObjectBase, Equatable, Printable { // MARK: Initializers /** Initialize a standalone (unpersisted) Object. Call `add(_:)` on a `Realm` to add standalone objects to a realm. :see: Realm().add(_:) */ public required override init() { super.init() } /** Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`. Call `add(_:)` on a `Realm` to add standalone objects to a realm. :param: value The value used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. */ public init(value: AnyObject) { super.init(value: value, schema: RLMSchema.sharedSchema()) } // MARK: Properties /// The `Realm` this object belongs to, or `nil` if the object /// does not belong to a realm (the object is standalone). public var realm: Realm? { if let rlmReam = RLMObjectBaseRealm(self) { return Realm(rlmReam) } return nil } /// The `ObjectSchema` which lists the persisted properties for this object. public var objectSchema: ObjectSchema { return ObjectSchema(RLMObjectBaseObjectSchema(self)) } /// Indicates if an object can no longer be accessed. public override var invalidated: Bool { return super.invalidated } /// Returns a human-readable description of this object. public override var description: String { return super.description } // MARK: Object customization /** Override to designate a property as the primary key for an `Object` subclass. Only properties of type String and Int can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set which incurs some overhead. Indexes are created automatically for primary key properties. :returns: Name of the property designated as the primary key, or `nil` if the model has no primary key. */ public class func primaryKey() -> String? { return nil } /** Override to return an array of property names to ignore. These properties will not be persisted and are treated as transient. :returns: `Array` of property names to ignore. */ public class func ignoredProperties() -> [String] { return [] } /** Return an array of property names for properties which should be indexed. Only supported for string and int properties. :returns: `Array` of property names to index. */ public class func indexedProperties() -> [String] { return [] } // MARK: Inverse Relationships /** Get an `Array` of objects of type `className` which have this object as the given property value. This can be used to get the inverse relationship value for `Object` and `List` properties. :param: className The type of object on which the relationship to query is defined. :param: property The name of the property which defines the relationship. :returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property. */ public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] { return RLMObjectBaseLinkingObjectsOfClass(self, T.className(), propertyName) as! [T] } // MARK: Private functions // FIXME: None of these functions should be exposed in the public interface. /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) } /** Returns the value for the property identified by the given key. :param: key The name of one of the receiver's properties. :returns: The value for the property identified by `key`. */ public override func valueForKey(key: String) -> AnyObject? { if let list = listProperty(key) { return list } return super.valueForKey(key) } /** Sets the property of the receiver specified by the given key to the given value. :param: value The value for the property identified by `key`. :param: key The name of one of the receiver's properties. */ public override func setValue(value: AnyObject?, forKey key: String) { if let list = listProperty(key) { if let value = value as? NSFastEnumeration { list._rlmArray.removeAllObjects() list._rlmArray.addObjects(value) } return } super.setValue(value, forKey: key) } /// Returns or sets the value of the property with the given name. public subscript(key: String) -> AnyObject? { get { if let list = listProperty(key) { return list } return RLMObjectBaseObjectForKeyedSubscript(self, key) } set(value) { if let list = listProperty(key) { if let value = value as? NSFastEnumeration { list._rlmArray.removeAllObjects() list._rlmArray.addObjects(value) } return } RLMObjectBaseSetObjectForKeyedSubscript(self, key, value) } } // Helper for getting a list property for the given key private func listProperty(key: String) -> RLMListBase? { if let prop = RLMObjectBaseObjectSchema(self)?[key] { if prop.type == .Array { return object_getIvar(self, prop.swiftListIvar) as! RLMListBase? } } return nil } } // MARK: Equatable /// Returns whether both objects are equal. /// Objects are considered equal when they are both from the same Realm /// and point to the same underlying object in the database. public func == <T: Object>(lhs: T, rhs: T) -> Bool { return RLMObjectBaseAreEqual(lhs, rhs) } /// Object interface which allows untyped getters and setters for Objects. public final class DynamicObject : Object { private var listProperties = [String: List<DynamicObject>]() // Override to create List<DynamicObject> on access private override func listProperty(key: String) -> RLMListBase? { if let prop = RLMObjectBaseObjectSchema(self)?[key] { if prop.type == .Array { if let list = listProperties[key] { return list } let list = List<DynamicObject>() listProperties[key] = list return list } } return nil } /// :nodoc: public override func valueForUndefinedKey(key: String) -> AnyObject? { return self[key] } /// :nodoc: public override func setValue(value: AnyObject?, forUndefinedKey key: String) { self[key] = value } @objc private class func shouldPersistToRealm() -> Bool { return false; } } /// :nodoc: /// Internal class. Do not use directly. public class ObjectUtil: NSObject { @objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.ignoredProperties() as NSArray? } return nil } @objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.indexedProperties() as NSArray? } return nil } // Get the names of all properties in the object which are of type List<> @objc private class func getGenericListPropertyNames(obj: AnyObject) -> NSArray { let reflection = reflect(obj) var properties = [String]() // Skip the first property (super): // super is an implicit property on Swift objects for i in 1..<reflection.count { let mirror = reflection[i].1 if mirror.valueType is RLMListBase.Type { properties.append(reflection[i].0) } } return properties } @objc private class func initializeListProperty(object: RLMObjectBase?, property: RLMProperty?, array: RLMArray?) { let list = (object as! Object)[property!.name]! as! RLMListBase list._rlmArray = array } @objc private class func getOptionalPropertyNames(object: AnyObject) -> NSArray { let reflection = reflect(object) var properties = [String]() // Skip the first property (super): // super is an implicit property on Swift objects for i in 1..<reflection.count { let mirror = reflection[i].1 if mirror.disposition == .Optional { properties.append(reflection[i].0) } } return properties } @objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? { return nil } }
apache-2.0
303925f48d19427a388ef2045c04711f
32.624242
126
0.634373
4.743908
false
false
false
false
OpenGenus/cosmos
code/sorting/src/insertion_sort/insertion_sort.swift
8
399
/* Part of Cosmos by OpenGenus Foundation */ // // insertion_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func insertionSort(_ array: inout [Int]) { for i in 1..<array.count { var j = Int(i) let key = array[j] while j >= 1 && key < array[j - 1] { array[j] = array[j - 1] j -= 1 } array[j] = key } }
gpl-3.0
26e1f76f67e8b082ec01ce2a9a8bc931
18.95
44
0.501253
3.192
false
false
false
false
sugar2010/Crust
Crust/TestModel.swift
2
640
// // TestModel.swift // Crust // // Created by Justin Spahr-Summers on 2014-06-23. // Copyright (c) 2014 Justin Spahr-Summers. All rights reserved. // import Foundation struct TestModel: Model { static let name = PropertyOf<String>("name") static let createdAt = PropertyOf<NSDate>("createdAt") static func describe() -> PropertyDescription[] { return [name, createdAt] } var properties: PropertyStorage mutating func testThings() { getProperty(self, TestModel.name) setProperty(&self, TestModel.name, "foobar") } } @infix func ==(lhs: TestModel, rhs: TestModel) -> Bool { return lhs.properties == rhs.properties }
mit
32083035e876a3342863555e148fd8cc
20.333333
65
0.709375
3.516484
false
true
false
false
the-blue-alliance/the-blue-alliance-ios
Frameworks/TBAUtils/Sources/Date/Date+TBA.swift
1
1661
import Foundation extension Date { public var year: Int { return Calendar.current.component(.year, from: self) } /** Determines if the reciver is between two given dates. */ public func isBetween(date date1: Date, andDate date2: Date) -> Bool { return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0 } public func startOfMonth(calendar: Calendar = Calendar.current) -> Date { return calendar.date(from: calendar.dateComponents([.year, .month], from: self))! } public func endOfMonth(calendar: Calendar = Calendar.current) -> Date { return calendar.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())! } /** 00:00:00am on the reciving date. */ public func startOfDay(calendar: Calendar = Calendar.current) -> Date { return calendar.date(bySettingHour: 0, minute: 0, second: 0, of: self)! } /** 11:59:59pm on the reciving date - used to inclusively match date in date logic */ public func endOfDay(calendar: Calendar = Calendar.current) -> Date { return calendar.date(bySettingHour: 23, minute: 59, second: 59, of: self)! } /** Find the next weekday after the current date. This method is not inclusive of the reciever. Ex: If reciever is a Monday, and we're looking for the next Monday, it will return reciever + 7, not reciever */ public func next(_ weekday: Weekday, calendar: Calendar = Calendar.current) -> Date { return calendar.nextDate(after: self, matching: DateComponents(weekday: weekday.rawValue), matchingPolicy: .strict)! } }
mit
c854eeeccd12dff35b646b9d6ba3322f
34.340426
160
0.659843
4.142145
false
false
false
false
goldenplan/Pattern-on-Swift
Decorator.playground/Contents.swift
1
1047
//: Playground - noun: a place where people can play // Decorator pattern import Cocoa class Component{ func operation(){ } } class ConcreteComponent: Component{ override func operation() { print("Concrete component") } } class Decorator: Component{ public var component: Component! override func operation() { if component != nil{ component.operation() } } } class ConcreteDecoratorA: Decorator{ let addedState = "Same State" override func operation() { super.operation() print(addedState) } } class ConcreteDecoratorB: Decorator{ func addBehavior(){ print("Behavior") } override func operation() { super.operation() addBehavior() } } let component = ConcreteComponent() let decoratorA = ConcreteDecoratorA() let decoratorB = ConcreteDecoratorB() decoratorA.component = component decoratorB.component = decoratorA decoratorB.operation()
mit
2e10f5bfeeba0e40f413e34876e6f7c2
12.253165
52
0.617001
4.695067
false
false
false
false
jakehirzel/swift-tip-calculator
CheckPlease/KeypadBehavior.swift
1
2601
// // KeypadBehavior.swift // CkPls // // Created by Jake Hirzel on 8/30/16. // Copyright © 2016 Jake Hirzel. All rights reserved. // import UIKit class KeypadBehavior { // A function for number key taps func keypadButtonTapped(_ button: UIButton, totalIn: String) -> String { // Limit to 8 characters (thousands + change) if totalIn.count >= 8 { return totalIn } // Otherwise append the button text, remove leading zero (if it exists), and move the decimal one place to the right else { // Assign and append var totalOut = totalIn totalOut += button.titleLabel!.text! // Check for leading zero let firstCharacter = totalOut[totalOut.startIndex] if firstCharacter == "0" { totalOut.removeFirst() } // Move decimal let decimalOldIndex = totalOut.index(totalOut.endIndex, offsetBy: -4 ) let decimalNewIndex = totalOut.index(totalOut.endIndex, offsetBy: -3 ) let thirdToLastCharacter = totalOut[decimalOldIndex] if thirdToLastCharacter == "." { totalOut.remove(at: decimalOldIndex) totalOut.insert(".", at: decimalNewIndex) } return totalOut } } // A function for delete key taps func deleteButtonTapped(_ button: UIButton, totalIn: String) -> String { // If it's $0.00, do nothing if totalIn == "0.00" { return totalIn } else { // Assign and remove last character var totalOut = totalIn totalOut.remove(at: totalOut.index(before: totalOut.endIndex)) // Add leading zeros if needed while totalOut.count < 4 { totalOut.insert("0", at: totalOut.startIndex) } // Move the decimal let decimalOldIndex = totalOut.index(totalOut.endIndex, offsetBy: -2 ) let decimalNewIndex = totalOut.index(totalOut.endIndex, offsetBy: -3 ) let secondToLastCharacter = totalOut[decimalOldIndex] if secondToLastCharacter == "." { totalOut.remove(at: decimalOldIndex) totalOut.insert(".", at: decimalNewIndex) } return totalOut } } }
mit
f7786fb3438c65f26b31310501981885
28.885057
124
0.520385
5.03876
false
false
false
false
CherishSmile/ZYBase
ZYBaseDemo/SubVCS/ScanVC.swift
1
3462
// // ScanVC.swift // ZYBase // // Created by Mzywx on 2017/2/24. // Copyright © 2017年 Mzywx. All rights reserved. // import UIKit class ScanVC: BaseDemoVC,UITableViewDelegate,UITableViewDataSource,LBXResultDelegate { fileprivate var scanTab : UITableView! fileprivate var scanArr : Array<String> = [] override func viewDidLoad() { super.viewDidLoad() scanArr = ["微信扫一扫","QQ扫一扫","支付宝扫一扫"] scanTab = creatTabView(self, .plain, { (make) in make.left.right.bottom.top.equalToSuperview() }) scanTab.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cellID") // Do any additional setup after loading the view. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return scanArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) cell.textLabel?.text = scanArr[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: WechatScan() case 1: QQScan() case 2: AlipayScan() default: break } } func WechatScan() { let scanVC = LBXScanViewController() scanVC.scanStyle = scanViewStyle(.wechat) scanVC.isOpenInterestRect = true scanVC.title = "微信扫一扫" scanVC.resultDelegate = self self.navigationController?.pushViewController(scanVC, animated: true) } func QQScan() { let scanVC = QQScanVC() scanVC.title = "QQ扫一扫" scanVC.resultDelegate = self scanVC.scanStyle = scanViewStyle(.qq) scanVC.isOpenInterestRect = true self.navigationController?.pushViewController(scanVC, animated: true) } func AlipayScan() { let scanVC = LBXScanViewController() scanVC.scanStyle = scanViewStyle(.aliPay) scanVC.isOpenInterestRect = true scanVC.title = "支付宝扫一扫" scanVC.resultDelegate = self self.navigationController?.pushViewController(scanVC, animated: true) } func LBXResultHandle(result: LBXScanResult) { if let url = result.strScanned { let webVC = ScanResultVC() webVC.isShowProgress = true webVC.isUseWebTitle = true webVC.webloadHtml(urlStr: url) self.navigationController?.pushViewController(webVC, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
661a9ace50993e3e3b73e1ce93bffff3
28.591304
106
0.616809
4.792958
false
false
false
false
TCA-Team/iOS
TUM Campus App/DataSources/CafeteriaDataSource.swift
1
3780
// // CafeteriaDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import MapKit class CafeteriaDataSource: NSObject, TUMDataSource, TUMInteractiveDataSource { let parent: CardViewController var manager: CafeteriaManager let cellType: AnyClass = CafeteriaCollectionViewCell.self var data: [Cafeteria] = [] var isEmpty: Bool { return data.isEmpty } var cardKey: CardKey { return manager.cardKey } let preferredHeight: CGFloat = 366.0 var menuDataSources: [MenuDataSource] = [] let distanceFormatter = MKDistanceFormatter() lazy var flowLayoutDelegate: ColumnsFlowLayoutDelegate = FixedColumnsFlowLayoutDelegate(delegate: self) init(parent: CardViewController, manager: CafeteriaManager) { self.parent = parent self.manager = manager self.distanceFormatter.unitStyle = .abbreviated super.init() } func refresh(group: DispatchGroup) { group.enter() manager.fetch().onSuccess(in: .main) { data in self.data = data.filter {$0.hasMenuToday}//$0.distance(self.manager.location) < 2500} self.menuDataSources = data.map { MenuDataSource(data: $0.getMenusForDate(.now)) } group.leave() } } func onShowMore() { let storyboard = UIStoryboard(name: "Cafeteria", bundle: nil) if let destination = storyboard.instantiateInitialViewController() as? CafeteriaViewController { destination.delegate = parent parent.navigationController?.pushViewController(destination, animated: true) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return min(data.count, 5) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseID, for: indexPath) as! CafeteriaCollectionViewCell let cafeteria = data[indexPath.row] let menuDataSource = menuDataSources[indexPath.row] let menu = cafeteria.getMenusForDate(.now) //TODO: display menu for tomorrow if today is over let menuTomorrow = cafeteria.getMenusForDate(.now + .aboutOneDay) // Display a placeholder label if no cafeteria data is available let isMenuEmpty = menuDataSource.data.isEmpty cell.placeholderLabel.isHidden = !isMenuEmpty cell.collectionView.isHidden = isMenuEmpty cell.collectionView.register(UINib(nibName: String(describing: menuDataSource.cellType), bundle: .main), forCellWithReuseIdentifier: menuDataSource.cellReuseID) cell.cafeteriaName.text = cafeteria.name cell.distanceLabel.text = distanceFormatter.string(fromDistance: cafeteria.distance(manager.location)) cell.collectionView.dataSource = menuDataSource cell.collectionView.delegate = menuDataSource.flowLayoutDelegate return cell } }
gpl-3.0
fc46202729ae920379870c034ad69402
40.086957
168
0.700794
4.719101
false
false
false
false
abarisain/skugga
Apple/macOS/skugga/Client/ClientUtils.swift
1
2145
// // ClientUtils.swift // Skugga // // Created by Arnaud Barisain-Monrose on 23/09/2017. // Copyright © 2017 NamelessDev. All rights reserved. // import Foundation enum APIClientError: Error, LocalizedError { case unknown case badURL case jsonParserError case httpError(code: Int) var errorDescription: String { switch(self) { case .unknown: return "Unknown" case .badURL: return "Bad URL" case .jsonParserError: return "JSON Parsing error" case .httpError: return "Bad HTTP Status Code: \(self.code)" } } var code: Int { switch(self) { case .unknown: return -1 case .badURL: return 1 case .jsonParserError: return 2 case .httpError: return 3 } } var nsError: NSError { return NSError(domain: "skugga.apiclient.error", code: self.code, userInfo: [NSLocalizedDescriptionKey: self.errorDescription ?? "Unknown"]) } } extension URL { init?(route: Route?) { self.init(string: Configuration.endpoint) self.appendPathComponent("1.0") if let route = route { self.appendPathComponent(route.rawValue) } } } extension URLRequest { init(route: Route?) throws { let url = URL(route: route) if let url = url { self.init(url: url) let secret = Configuration.secret if !secret.isEmpty { self.setValue(secret, forHTTPHeaderField: ClientConsts.SECRET_KEY_HEADER) } } else { throw APIClientError.badURL } } mutating func addSecret() { let secret = Configuration.secret if !secret.isEmpty { self.setValue(secret, forHTTPHeaderField: ClientConsts.SECRET_KEY_HEADER) } } } extension URLResponse { func httpError() -> APIClientError? { if let statusCode = (self as? HTTPURLResponse)?.statusCode, statusCode < 200 || statusCode > 299 { return APIClientError.httpError(code: statusCode) } return nil } }
apache-2.0
fb3605d8039dc4190964514b330f17a2
25.146341
148
0.589552
4.475992
false
false
false
false
KinoAndWorld/Meizhi-Swift
Meizhi-Swift/Scene/GallaryViewLayout.swift
1
2611
// // GallaryViewLayout.swift // Meizhi-Swift // // Created by kino on 14/11/26. // Copyright (c) 2014年 kino. All rights reserved. // import UIKit class GallaryViewLayout: UICollectionViewLayout { let kGallaryLayoutCellKind = "GallaryCell" var itemInsets:UIEdgeInsets = UIEdgeInsetsZero var itemSize:CGSize = CGSizeZero var interItemSpacingY:CGFloat = 0.0 var numberOfColumns:Int = 1 private var layoutInfo = NSDictionary() //MARK: Function override init() { super.init() initialize() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize(){ let mainWidth = UIApplication.sharedApplication().keyWindow?.bounds.width self.itemSize = CGSize(width: 150, height: 150) self.itemInsets = UIEdgeInsetsMake(0, 0, 0, 0) self.interItemSpacingY = 12.0 self.numberOfColumns = 2 } override func prepareLayout() { var newLayoutInfo = NSMutableDictionary() var cellLayoutInfo = NSMutableDictionary() let sectionCount = self.collectionView?.numberOfSections() var indexPath = NSIndexPath(forRow: 0, inSection: 0) for (var section = 0 ; section < sectionCount ; section++){ let itemCount = self.collectionView?.numberOfItemsInSection(section) for (var item = 0; item < itemCount ; item++){ indexPath = NSIndexPath(forRow: item, inSection: section) let itemAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) itemAttributes.frame = self.frameForAlbumPhotoAtIndexPath(indexPath) cellLayoutInfo[indexPath] = itemAttributes } } newLayoutInfo[kGallaryLayoutCellKind] = cellLayoutInfo self.layoutInfo = newLayoutInfo } //MARK: 计算布局 func frameForAlbumPhotoAtIndexPath(indexPath:NSIndexPath) -> CGRect{ //行数和列数 let row = indexPath.section / self.numberOfColumns let column = indexPath.row / self.numberOfColumns var spacingX:CGFloat = CGFloat(self.collectionView!.bounds.width) - CGFloat(self.itemInsets.left) - CGFloat(self.itemInsets.right) - (CGFloat(self.numberOfColumns) * CGFloat(self.itemSize.width)) return CGRectZero } }
apache-2.0
1ac4683f05af23ae2e94820945b6cc49
28.443182
102
0.602856
5.21328
false
false
false
false
kharrison/CodeExamples
Container/Container-SB/Container/MapViewController.swift
1
3556
// // MapViewController.swift // Container // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2017 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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 HOLDER 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 MapKit final class MapViewController: UIViewController { @IBOutlet private var mapView: MKMapView! /// The zoom level to use when setting the span /// of the map region to show. Default is 10 degrees. var zoom: CLLocationDegrees = 10.0 /// The coordinate to center the map on. Setting a new /// coordinate centers the map on a region spanned by /// the `zoom` level and drops a pin annotation at the /// coordinate. var coordinate: CLLocationCoordinate2D? { didSet { if let coordinate = coordinate { centerMap(coordinate) annotate(coordinate) } } } private func centerMap(_ coordinate: CLLocationCoordinate2D) { let span = MKCoordinateSpan.init(latitudeDelta: zoom, longitudeDelta: zoom) let region = MKCoordinateRegion(center: coordinate, span: span) mapView.setRegion(region, animated: true) } private func annotate(_ coordinate: CLLocationCoordinate2D) { let annotation = MKPointAnnotation() annotation.coordinate = coordinate mapView.addAnnotation(annotation) } } extension MapViewController: MKMapViewDelegate { private enum AnnotationView: String { case pin = "Pin" } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? MKPointAnnotation else { return nil } let identifier = AnnotationView.pin.rawValue guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView else { return MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) } annotationView.annotation = annotation return annotationView } }
bsd-3-clause
9d6a6063d8b4fa893bb82e19a5cd6f58
37.652174
131
0.715129
5.015515
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/DispatchQueue+ProcedureKit.swift
3
2607
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import Dispatch // MARK: - Queue public extension DispatchQueue { static var isMainDispatchQueue: Bool { return mainQueueScheduler.isScheduledQueue } static var `default`: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.default) } static var initiated: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) } static var interactive: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive) } static var utility: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.utility) } static var background: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.background) } static func concurrent(label: String, qos: DispatchQoS = .default, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil) -> DispatchQueue { return DispatchQueue(label: label, qos: qos, attributes: [.concurrent], autoreleaseFrequency: autoreleaseFrequency, target: target) } static func onMain<T>(execute work: () throws -> T) rethrows -> T { guard isMainDispatchQueue else { return try DispatchQueue.main.sync(execute: work) } return try work() } } internal extension QualityOfService { var qos: DispatchQoS { switch self { case .userInitiated: return DispatchQoS.userInitiated case .userInteractive: return DispatchQoS.userInteractive case .utility: return DispatchQoS.utility case .background: return DispatchQoS.background case .default: return DispatchQoS.default } } var qosClass: DispatchQoS.QoSClass { switch self { case .userInitiated: return .userInitiated case .userInteractive: return .userInteractive case .utility: return .utility case .background: return .background case .default: return .default } } } internal final class Scheduler { var key: DispatchSpecificKey<UInt8> var value: UInt8 = 1 init(queue: DispatchQueue) { key = DispatchSpecificKey() queue.setSpecific(key: key, value: value) } var isScheduledQueue: Bool { guard let retrieved = DispatchQueue.getSpecific(key: key) else { return false } return value == retrieved } } internal let mainQueueScheduler = Scheduler(queue: DispatchQueue.main)
mit
bf5e8e93f49100188e02dde326da93fc
28.280899
188
0.686493
5.070039
false
false
false
false
Mrwerdo/QuickShare
LibQuickShare/Sources/Core/FileMetadata.swift
1
5634
// // FileMetadata.swift // QuickShare // // Copyright (c) 2016 Andrew Thompson // // 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 Support import QSFcntl public typealias FIDType = UInt32 public struct FileMetadata { public var filename: String public var filesize: UInt64 public var checksumP1: UInt64 public var checksumP2: UInt64 public var numberOfPackets: UInt64 public var sizeOfPackets: UInt16 /// Read as 'File Identifier' public var fileID: FIDType // { get } /// Contains the location of the file in the file sysetm. /// Do not send this over the network! /// If nil, then the client should write the file to, for example, the /// downloads directory. public var originPath: String? } // File metadata should be packed in this form: // // File size : UInt64 // Checksum : UInt32 // Number of Packets : UInt64 // Size of Packets : UInt16 // Length : UInt16 // File ID : UInt32 // File Name : [UInt8] // extension FileMetadata : Encodable { public var length: UInt16 { let filenameLength = filename.utf8.count return 40 + UInt16(filenameLength) } public static var minimumLength: UInt16 { return 41 } public func fill(inout buff: [UInt8], offset: Int) { buff[offset +< 0...7] = filesize.bytes[0...7] buff[offset +< 8...15] = checksumP1.bytes[0...7] buff[offset +< 16...23] = checksumP2.bytes[0...7] buff[offset +< 24...31] = numberOfPackets.bytes[0...7] buff[offset +< 32...33] = sizeOfPackets.bytes[0...1] buff[offset +< 34...35] = length.bytes[0...1] buff[offset +< 36...39] = fileID.bytes[0...3] let filenameBuff = filename.utf8.map { $0 } let len = filenameBuff.count - 1 buff[offset +< 40...(40 + len)] = filenameBuff[0...len] } } extension FileMetadata : Decodable { public init?(buff: [UInt8]) { // Note: A buff with length 28 means that it has a filename of // length 1 byte/character guard buff.count > 40 else { return nil } let length = Int(UInt16(bytes: buff[34...35])) guard length == buff.count else { return nil } var cstring = buff[40..<length].map { Int8(bitPattern: $0) } + [0] guard let filename = String.fromCString(&cstring) else { return nil } self.filename = filename self.filesize = UInt64(bytes: buff[0...7]) self.checksumP1 = UInt64(bytes: buff[8...15]) self.checksumP2 = UInt64(bytes: buff[16...23]) self.numberOfPackets = UInt64(bytes: buff[24...31]) self.sizeOfPackets = UInt16(bytes: buff[32...33]) self.fileID = UInt32(bytes: buff[36...39]) } } extension File { public func md5Hash() throws -> String { var c = CC_MD5_CTX() CC_MD5_Init(&c) rewind(fp) while let data = try self.read(1024) { CC_MD5_Update(&c, data, CC_LONG(data.count)) } var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) CC_MD5_Final(&digest, &c) return digest.reduce("") { $0 + String(format: "%02x", $1) } } } extension FileMetadata { public init(path: String, filename: String) throws { let file = try File(path: path, mode: "r") let stats = try file.getStatistics() filesize = UInt64(stats.st_size) let sizeOfPackets: UInt64 = 4096 let remainder = filesize % sizeOfPackets numberOfPackets = (filesize / sizeOfPackets) + ((remainder != 0) ? 1 : 0) self.sizeOfPackets = UInt16(sizeOfPackets) let time = Darwin.time(nil) fileID = FIDType(truncatingBitPattern: time) (checksumP1, checksumP2) = try FileMetadata.calculateChecksum(file) self.filename = filename self.originPath = path } private static func calculateChecksum(file: File) throws -> (UInt64, UInt64) { let characters = try file.md5Hash().characters print("md5hash: characters=\(String(characters))") let middle = characters.startIndex.advancedBy(characters.count / 2) let part1 = String(characters[characters.startIndex..<middle]) let part2 = String(characters[middle..<characters.endIndex]) let cp1 = UInt64(part1, radix: 16)! let cp2 = UInt64(part2, radix: 16)! return (cp1, cp2) } }
mit
86c5d6a195087d5c4401b970c712187b
34.2125
82
0.619808
3.942617
false
false
false
false
joemcbride/outlander-osx
src/OutlanderTests/OutlanderScriptParserTester.swift
1
9127
// // OutlanderScriptParserTester.swift // Outlander // // Created by Joseph McBride on 11/7/15. // Copyright © 2015 Joe McBride. All rights reserved. // import Foundation import Quick import Nimble struct MessageTestContext<T: Message> { var context:ScriptContext var message:T } class OutlanderScriptParserTester : QuickSpec { func buildMessage<T: Message>(script:String, _ globalVars:[String:String]? = nil) -> MessageTestContext<T> { let parser = OutlanderScriptParser() let toMessage = TokenToMessage() let gameContext = GameContext() if globalVars != nil { for pair in globalVars! { gameContext.globalVars[pair.0] = pair.1 } } let context = ScriptContext([], context: gameContext, params: []) let tokens = parser.parseString(script) expect(tokens.count).to(equal(1)) let message = toMessage.toMessage(context, token: tokens[0]) return MessageTestContext(context: context, message: message as! T) } override func spec() { describe("parser") { beforeEach { } it("debug message") { let script = "debug 3" let ctx:MessageTestContext<DebugLevelMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("debug-level")) expect(ctx.message.level).to(equal(ScriptLogLevel.If)) } it("debug message - defaults to Actions") { let script = "debuglevel" let ctx:MessageTestContext<DebugLevelMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("debug-level")) expect(ctx.message.level).to(equal(ScriptLogLevel.Actions)) } it("echo message") { let script = "echo a message" let ctx:MessageTestContext<EchoMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("echo")) expect(ctx.message.message).to(equal("a message")) } it("eval message") { let script = "eval twoCount countsplit(%two, \"|\")" let ctx:MessageTestContext<EvalMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("eval")) expect(ctx.message.token.variable).to(equal("twoCount")) let funcToken = ctx.message.token.expression[1] as? FuncToken expect(funcToken != nil).to(equal(true)) expect(funcToken!.name).to(equal("countsplit")) expect(funcToken!.body[0].name).to(equal("globalvar")) expect(funcToken!.body[0].characters).to(equal("%two")) expect(funcToken!.body[3].name).to(equal("quoted-string")) expect(funcToken!.body[3].characters).to(equal("|")) } it("exit message") { let script = "exit" let ctx:MessageTestContext<ExitMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("exit")) } it("goto message") { let script = "goto $alabel one $two" let vars:[String:String] = ["alabel":"mylabel", "two":"three"] let ctx:MessageTestContext<GotoMessage> = self.buildMessage(script, vars) expect(ctx.message.name).to(equal("goto")) expect(ctx.message.label).to(equal("mylabel")) expect(ctx.message.params.count).to(equal(3)) expect(ctx.message.params[0]).to(equal("one three")) expect(ctx.message.params[1]).to(equal("one")) expect(ctx.message.params[2]).to(equal("three")) } it("matchwait message") { let script = "matchwait 3" let ctx:MessageTestContext<MatchwaitMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("matchwait")) expect(ctx.message.timeout).to(equal(3)) } it("matchwait message - default") { let script = "matchwait" let ctx:MessageTestContext<MatchwaitMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("matchwait")) expect(ctx.message.timeout).to(beNil()) } it("matchre message") { let script = "matchre one (two|three|four)" let ctx:MessageTestContext<MatchReMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("match")) expect(ctx.message.label).to(equal("one")) expect(ctx.message.value).to(equal("(two|three|four)")) } it("matchre with regex message") { let script = "matchre Done %material (\\s.*)?%item" let ctx:MessageTestContext<MatchReMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("match")) expect(ctx.message.label).to(equal("Done")) expect(ctx.message.value).to(equal("%material (\\s.*)?%item")) } it("math message - add") { let script = "math myvar add 2" let ctx:MessageTestContext<MathMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("math")) expect(ctx.message.variable).to(equal("myvar")) expect(ctx.message.operation).to(equal("add")) expect(ctx.message.number).to(equal(2)) } it("math message - subtract") { let script = "math myvar subtract 3" let ctx:MessageTestContext<MathMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("math")) expect(ctx.message.variable).to(equal("myvar")) expect(ctx.message.operation).to(equal("subtract")) expect(ctx.message.number).to(equal(3)) } it("pause message") { let script = "pause 0.5" let ctx:MessageTestContext<PauseMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("pause")) expect(ctx.message.seconds).to(equal(0.5)) } it("pause message - default to 1 second") { let script = "pause" let ctx:MessageTestContext<PauseMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("pause")) expect(ctx.message.seconds).to(equal(1)) } it("put message") { let script = "put #var something" let ctx:MessageTestContext<PutMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("put")) expect(ctx.message.message).to(equal("#var something")) } it("random message") { let script = "random 1 100" let ctx:MessageTestContext<RandomMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("random")) expect(ctx.message.min).to(equal(1)) expect(ctx.message.max).to(equal(100)) } it("save message") { let script = "save $something" let vars:[String:String] = ["something":"abcd"] let ctx:MessageTestContext<SaveMessage> = self.buildMessage(script, vars) expect(ctx.message.name).to(equal("save")) expect(ctx.message.text).to(equal("abcd")) } it("send message") { let script = "send echo $something" let vars:[String:String] = ["something":"abcd"] let ctx:MessageTestContext<SendMessage> = self.buildMessage(script, vars) expect(ctx.message.name).to(equal("send")) expect(ctx.message.message).to(equal("echo abcd")) } it("unar message") { let script = "unvar myvar" let ctx:MessageTestContext<UnVarMessage> = self.buildMessage(script) expect(ctx.message.name).to(equal("unvar")) expect(ctx.message.identifier).to(equal("myvar")) } } } }
mit
d79cbe12b8f552010cb63f6388f0f19f
39.202643
112
0.506903
4.606764
false
true
false
false
ngageoint/mage-ios
Mage/ColorPickerViewController.swift
1
13771
// // ColorPickerViewController.swift // MAGE // // Created by Daniel Barela on 5/18/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // // delete this class once ios13 support is dropped import Foundation @objc class ColorPickerViewController: UIViewController { var scheme: MDCContainerScheming?; var colorPreference: String? { didSet { if let color = UserDefaults.standard.color(forKey: colorPreference!) { textField.text = color.hex() textFieldPreviewTile.backgroundColor = color; } else { textField.text = nil; textFieldPreviewTile.backgroundColor = .clear; } } }; var tempColor: UIColor?; var preferenceTitle: String? { didSet { titleLabel.text = preferenceTitle; } } lazy var textFieldPreviewTile: UIView = { let textFieldPreviewTile = UIView(forAutoLayout: ()); textFieldPreviewTile.autoSetDimensions(to: CGSize(width: 24, height: 24)); textFieldPreviewTile.backgroundColor = UIColor(red: 0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) textFieldPreviewTile.layer.cornerRadius = 2; return textFieldPreviewTile }() lazy var textField: MDCFilledTextField = { let textField = MDCFilledTextField(forAutoLayout: ()); textField.delegate = self; textField.autocapitalizationType = .none; textField.accessibilityLabel = "hex color"; textField.label.text = "Hex Color"; textField.returnKeyType = .done textField.addTarget(self, action: #selector(textFieldDidEndEditing(_:)), for: .editingChanged) return textField; }() private lazy var actionButtonView: UIView = { let actionButtonView = UIView.newAutoLayout(); actionButtonView.addSubview(cancelButton); actionButtonView.addSubview(doneButton); doneButton.autoPinEdge(toSuperviewEdge: .right, withInset: 32); doneButton.autoPinEdge(.left, to: .right, of: cancelButton, withOffset: 16); cancelButton.autoAlignAxis(.horizontal, toSameAxisOf: doneButton); return actionButtonView; }() private lazy var doneButton: MDCButton = { let button = MDCButton(forAutoLayout: ()); button.accessibilityLabel = "done"; button.setTitle("Done", for: .normal); button.addTarget(self, action: #selector(colorSet), for: .touchUpInside); return button; }() private lazy var cancelButton: MDCButton = { let button = MDCButton(forAutoLayout: ()); button.accessibilityLabel = "cancel"; button.setTitle("Cancel", for: .normal); button.addTarget(self, action: #selector(cancelButtonPressed), for: .touchUpInside); return button; }(); func createTapGestureRecognizer() -> UITapGestureRecognizer { let tapGesture = UITapGestureRecognizer(target: self, action: #selector (self.colorPicked (_:))) return tapGesture; } let titleLabel = UILabel(forAutoLayout: ()); func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) { guard let containerScheme = containerScheme else { return } self.scheme = containerScheme; view.backgroundColor = self.scheme?.colorScheme.surfaceColor; doneButton.applyTextTheme(withScheme: containerScheme); cancelButton.applyTextTheme(withScheme: containerScheme); textField.applyTheme(withScheme: containerScheme); } override func viewDidLoad() { super.viewDidLoad() view.accessibilityIdentifier = "ColorPicker" view.accessibilityLabel = "ColorPicker" view.addSubview(titleLabel); titleLabel.autoAlignAxis(toSuperviewAxis: .vertical); titleLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 16); view.addSubview(textFieldPreviewTile); textFieldPreviewTile.autoPinEdge(toSuperviewEdge: .left, withInset: 32); view.addSubview(textField); textField.autoPinEdge(.left, to: .right, of: textFieldPreviewTile, withOffset: 16); textField.autoPinEdge(toSuperviewEdge: .right, withInset: 32); textField.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: 32); textFieldPreviewTile.autoAlignAxis(.horizontal, toSameAxisOf: textField) let colorsView = UIView(forAutoLayout: ()); view.addSubview(colorsView); colorsView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 32, bottom: 32, right: 32), excludingEdge: .top); colorsView.autoPinEdge(.top, to: .bottom, of: textField, withOffset: 32); let colorRow1 = UIView(forAutoLayout: ()); colorsView.addSubview(colorRow1); colorRow1.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .bottom); let blueView = UIView(forAutoLayout: ()); blueView.autoSetDimensions(to: CGSize(width: 75, height: 75)); blueView.backgroundColor = UIColor(red: 0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) blueView.layer.cornerRadius = 10; blueView.addGestureRecognizer(createTapGestureRecognizer()); let greenView = UIView(forAutoLayout: ()); greenView.autoSetDimensions(to: CGSize(width: 75, height: 75)); greenView.backgroundColor = UIColor(red: 52.0/255.0, green: 199.0/255.0, blue: 89.0/255.0, alpha: 1.0) greenView.layer.cornerRadius = 10; greenView.addGestureRecognizer(createTapGestureRecognizer()); let indigoView = UIView(forAutoLayout: ()); indigoView.autoSetDimensions(to: CGSize(width: 75, height: 75)); indigoView.backgroundColor = UIColor(red: 88.0/255.0, green: 86.0/255.0, blue: 214.0/255.0, alpha: 1.0) indigoView.layer.cornerRadius = 10; indigoView.addGestureRecognizer(createTapGestureRecognizer()); colorRow1.addSubview(blueView); colorRow1.addSubview(greenView); colorRow1.addSubview(indigoView); blueView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .right) greenView.autoPinEdge(toSuperviewEdge: .top); greenView.autoAlignAxis(toSuperviewAxis: .vertical); indigoView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .left); let colorRow2 = UIView(forAutoLayout: ()); colorsView.addSubview(colorRow2); colorRow2.autoPinEdge(toSuperviewEdge: .left); colorRow2.autoPinEdge(toSuperviewEdge: .right); colorRow2.autoPinEdge(.top, to: .bottom, of: colorRow1, withOffset: 32); let orangeView = UIView(forAutoLayout: ()); orangeView.autoSetDimensions(to: CGSize(width: 75, height: 75)); orangeView.backgroundColor = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0) orangeView.layer.cornerRadius = 10; orangeView.addGestureRecognizer(createTapGestureRecognizer()); let pinkView = UIView(forAutoLayout: ()); pinkView.autoSetDimensions(to: CGSize(width: 75, height: 75)); pinkView.backgroundColor = UIColor(red: 255.0/255.0, green: 45.0/255.0, blue: 95.0/255.0, alpha: 1.0) pinkView.layer.cornerRadius = 10; pinkView.addGestureRecognizer(createTapGestureRecognizer()); let purpleView = UIView(forAutoLayout: ()); purpleView.autoSetDimensions(to: CGSize(width: 75, height: 75)); purpleView.backgroundColor = UIColor(red: 175.0/255.0, green: 82.0/255.0, blue: 222.0/255.0, alpha: 1.0) purpleView.layer.cornerRadius = 10; purpleView.addGestureRecognizer(createTapGestureRecognizer()); colorRow2.addSubview(orangeView); colorRow2.addSubview(pinkView); colorRow2.addSubview(purpleView); orangeView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .right) pinkView.autoPinEdge(toSuperviewEdge: .top); pinkView.autoAlignAxis(toSuperviewAxis: .vertical); purpleView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .left); let colorRow3 = UIView(forAutoLayout: ()); colorsView.addSubview(colorRow3); colorRow3.autoPinEdge(toSuperviewEdge: .left); colorRow3.autoPinEdge(toSuperviewEdge: .right); colorRow3.autoPinEdge(.top, to: .bottom, of: colorRow2, withOffset: 32); let redView = UIView(forAutoLayout: ()); redView.autoSetDimensions(to: CGSize(width: 75, height: 75)); redView.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0) redView.layer.cornerRadius = 10; redView.addGestureRecognizer(createTapGestureRecognizer()); let tealView = UIView(forAutoLayout: ()); tealView.autoSetDimensions(to: CGSize(width: 75, height: 75)); tealView.backgroundColor = UIColor(red: 90.0/255.0, green: 200.0/255.0, blue: 250.0/255.0, alpha: 1.0) tealView.layer.cornerRadius = 10; tealView.addGestureRecognizer(createTapGestureRecognizer()); let yellowView = UIView(forAutoLayout: ()); yellowView.autoSetDimensions(to: CGSize(width: 75, height: 75)); yellowView.backgroundColor = UIColor(red: 255.0/255.0, green: 204.0/255.0, blue: 0.0/255.0, alpha: 1.0) yellowView.layer.cornerRadius = 10; yellowView.addGestureRecognizer(createTapGestureRecognizer()); colorRow3.addSubview(redView); colorRow3.addSubview(tealView); colorRow3.addSubview(yellowView); redView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .right) tealView.autoPinEdge(toSuperviewEdge: .top); tealView.autoAlignAxis(toSuperviewAxis: .vertical); yellowView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .left); let colorRow4 = UIView(forAutoLayout: ()); colorsView.addSubview(colorRow4); colorRow4.autoPinEdge(toSuperviewEdge: .left); colorRow4.autoPinEdge(toSuperviewEdge: .right); colorRow4.autoPinEdge(.top, to: .bottom, of: colorRow3, withOffset: 32); let lightGrayView = UIView(forAutoLayout: ()); lightGrayView.autoSetDimensions(to: CGSize(width: 75, height: 75)); lightGrayView.backgroundColor = UIColor(red: 224.0/255.0, green: 224.0/255.0, blue: 224.0/255.0, alpha: 1.0) lightGrayView.layer.cornerRadius = 10; lightGrayView.addGestureRecognizer(createTapGestureRecognizer()); let darkGrayView = UIView(forAutoLayout: ()); darkGrayView.autoSetDimensions(to: CGSize(width: 75, height: 75)); darkGrayView.backgroundColor = UIColor(red: 97.0/255.0, green: 97.0/255.0, blue: 97.0/255.0, alpha: 1.0) darkGrayView.layer.cornerRadius = 10; darkGrayView.addGestureRecognizer(createTapGestureRecognizer()); let blackView = UIView(forAutoLayout: ()); blackView.autoSetDimensions(to: CGSize(width: 75, height: 75)); blackView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) blackView.layer.cornerRadius = 10; blackView.addGestureRecognizer(createTapGestureRecognizer()); colorRow4.addSubview(lightGrayView); colorRow4.addSubview(darkGrayView); colorRow4.addSubview(blackView); lightGrayView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .right) darkGrayView.autoPinEdge(toSuperviewEdge: .top); darkGrayView.autoAlignAxis(toSuperviewAxis: .vertical); blackView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .left); view.addSubview(actionButtonView); actionButtonView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top); actionButtonView.autoPinEdge(.top, to: .bottom, of: blackView, withOffset: 32); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); applyTheme(withContainerScheme: scheme); } init(frame: CGRect) { super.init(nibName: nil, bundle: nil); } @objc convenience public init(containerScheme: MDCContainerScheming?) { self.init(frame: CGRect.zero); self.scheme = containerScheme; } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } @objc func cancelButtonPressed() { self.presentingViewController?.dismiss(animated: true, completion: nil); } @objc func colorSet() { if let colorPreference = colorPreference { UserDefaults.standard.set(tempColor, forKey: colorPreference) } self.presentingViewController?.dismiss(animated: true, completion: nil); } @objc func colorPicked(_ sender:UITapGestureRecognizer) { tempColor = sender.view?.backgroundColor; textFieldPreviewTile.backgroundColor = tempColor; textField.text = tempColor?.hex() } } extension ColorPickerViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { if let color: UIColor = UIColor(hex: textField.text ?? "") { textFieldPreviewTile.backgroundColor = color; tempColor = color; } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder(); return true; } }
apache-2.0
799d4e400e726caa76cde9048363f3db
43.85342
130
0.664851
4.772964
false
false
false
false
kandelvijaya/XcodeFormatter
XcodeFormatterTests/EmptyLineInsertionTests.swift
1
6449
// // EmptyLineInsertionTests.swift // Swinter // // Created by Vijaya Prakash Kandel on 9/20/16. // Copyright © 2016 Vijaya Prakash Kandel. All rights reserved. // import XCTest @testable import XcodeFormatter class LintLineTests: XCTestCase { let EMP = "\n" func testThat_SingleDeclaration_hasEmptyLineAboveAndBelow() { let input = ["class A {\n", "}\n"] let expected = [EMP, "class A {\n", EMP,"}\n",EMP] assertThat(inputCode: input, produces: expected) } func testhThat_SingleDeclarationWithMultipleEmptyLines_HasOnlyOneLineBeforeAndAfter() { let input = [EMP,EMP,EMP,"class A {\n",EMP,EMP,EMP, "}\n",EMP,EMP,EMP] let expected = [EMP, "class A {\n", EMP,"}\n",EMP] assertThat(inputCode: input, produces: expected) } func testThat_IncompleteCodeBlock_IsNotCorrectedAtAll() { let input = ["class A {\n", "let a: Int"] let expected = input assertThat(inputCode: input, produces: expected) } func testThat_CodeBlockCompleteOnSameLine_IsNotCorrectedAtAll() { let input = ["class A { } \n"] let expected = input assertThat(inputCode: input, produces: expected) } func testThat_ClassCodeBlock_IsCorrected() { let input = ["class A {\n", "}\n"] let expected = [EMP, "class A {\n", EMP ,"}\n",EMP] assertThat(inputCode: input, produces: expected) } func testThat_StructCodeBlock_IsCorrected() { let input = ["struct A {\n", "}\n"] let expected = [EMP, "struct A {\n", EMP,"}\n", EMP] assertThat(inputCode: input, produces: expected) } func testThat_ProtocolCodeBlock_IsCorrected() { let input = ["protocol A {\n", "func doThat()\n", "}\n"] let expected = [EMP, "protocol A {\n",EMP, "func doThat()\n" ,EMP,"}\n",EMP] assertThat(inputCode: input, produces: expected) } func testThat_ExtensionCodeBlock_IsCorrected() { let input = ["extension A{\n", "func doThat(){}\n", "}\n"] let expected = [EMP, "extension A{\n",EMP, "func doThat(){}\n" ,EMP,"}\n",EMP] assertThat(inputCode: input, produces: expected) } func testThat_EnumCodeBlock_IsCorrected() { let input = ["enum A{\n", "case .a, .b\n", "}\n"] let expected = [EMP, "enum A{\n", EMP, "case .a, .b\n" ,EMP,"}\n", EMP] assertThat(inputCode: input, produces: expected) } //Failure Case func testThat_FucntionBlock_doesNotGetEmptyLinesInsideTheBlock() { let input = ["func do() {\n","someMagic()" ,"}\n"] let expected = [EMP,"func do() {\n","someMagic()" ,"}\n" ] assertThat(inputCode: input, produces: expected) } func testThat_IfBlock_doesNotGetEmptyLines() { let input = ["if do() {\n","someMagic()" ,"} else {\n", "then clause here \n", "}\n"] let expected = input assertThat(inputCode: input, produces: expected) } //Complex cases //NOTE: Shall we put a empty Line at the end of the file if there is none explicitly like in the test case above that // ends with a single liner protocol. func testThat_MultipleTypesInSingleFile_AreCorrectedProperly() { let input = ["final class A {\n"," \n", " let a: Int\n","}\n", "final class B {\n", " let b: Int\n", "}\n", "protocol A { }\n"] let expected = [EMP,"final class A {\n"," \n", " let a: Int\n", EMP,"}\n", EMP,"final class B {\n", EMP, " let b: Int\n", EMP, "}\n", EMP, "protocol A { }\n"] assertThat(inputCode: input, produces: expected) } //NOTE: Shall we preserve the indentation spaces. CTRL + I will bring back this magic. func testThat_MultipleTypesWithMultipleMixedSpaces_WillBeCorrected() { let input = ["final class A {\n",EMP, EMP," \n", " let a: Int\n", EMP, EMP,EMP,"}\n", EMP, EMP,EMP, "final class B {\n", " let b: Int\n", "}\n",EMP, EMP,EMP,EMP, "protocol A { }\n"] let expected = [EMP,"final class A {\n","\n", " let a: Int\n", EMP,"}\n", EMP,"final class B {\n", EMP, " let b: Int\n", EMP, "}\n", EMP, "protocol A { }\n"] assertThat(inputCode: input, produces: expected) } func testThat_EmptyLineIsInsertedAboveFunctionWithoutEmptyLine() { let input = ["func dothis(){}\n"] let expected = [EMP, "func dothis(){}\n"] assertThat(inputCode: input, produces: expected) } func testThat_TwoFunctionsWithoutEmptyLineInBetween_AreSeparatedByOneEmptyLine() { let input = ["func do(){}\n", "func doThat(){}\n"] let expected = [EMP,"func do(){}\n",EMP, "func doThat(){}\n"] assertThat(inputCode: input, produces: expected) } func testThat_CommentAndClassDeclaration_AreNotSeparatedWhileInsertingEmptyLines() { let input = [EMP,"//this is comment \n", "class A { \n", EMP,"}\n", EMP] let expected = input assertThat(inputCode: input, produces: expected) } func testThat_CommentAndClassDeclaration_AreProperlyCorrected() { let input = ["//this is comment \n", "class A { \n", EMP,"}\n", EMP] let expected = [EMP] + input assertThat(inputCode: input, produces: expected) } func assertThat_CommentAndTypes_AreProperlyCorrected() { let input = [EMP, EMP, "//Comment\n", "struct A {\n", "something \n", "}\n", EMP] let expected = Array(input.dropFirst()) assertThat(inputCode: input, produces: expected) } func testThat_CommentAndTypesInComplexStructure_AreProperlyCorrected() { let input = ["let a: Int\n", " //Comment\n", "struct A {\n", "something \n", "}\n", EMP] let expected = ["let a: Int\n", EMP, " //Comment\n", "struct A {\n", EMP, "something \n", EMP, "}\n", EMP] assertThat(inputCode: input, produces: expected) } func testThat_DeclarationInsideStringQuotes_AreNotTouched() { let input = ["\" class A { \" \n", "\"}\" \n"] let expected = input assertThat(inputCode: input, produces: expected) } //MARK:- tester func assertThat(inputCode input: [String], produces expected: [String]) { let mutableInput = NSMutableArray(array: input) LintLine().ensureProperEmptyLines(in: mutableInput) let output = mutableInput.copy() as! [String] XCTAssertEqual(expected, output) } }
mit
e072e5bc8a932e64d38cc3503ec0be6e
39.810127
198
0.596774
3.695129
false
true
false
false
peterlafferty/LuasLife
LuasLifeKit/Route.swift
1
821
// // Route.swift // LuasLife // // Created by Peter Lafferty on 02/03/2016. // Copyright © 2016 Peter Lafferty. All rights reserved. // import Foundation import Decodable public struct Route { public let id: Int public let origin: Stop public let destination: Stop public let stops: [Stop] public init(id: Int, origin: Stop, destination: Stop, stops: [Stop]) { self.id = id self.origin = origin self.destination = destination self.stops = stops } } extension Route: Decodable { public static func decode(_ j: Any) throws -> Route { do { return try Route( id: j => "id", origin: j => "from", destination: j => "to", stops: j => "stops" ) } } }
mit
14997b02eeb3285c717c9e42e4339e63
21.162162
74
0.543902
4
false
false
false
false
ReduxKit/ReduxKitBond
ReduxKitBondTests/Mocks.swift
1
735
// // Mocks.swift // ReduxKitBond // // Created by Karl Bowden on 20/12/2015. // Copyright © 2015 ReduxKit. All rights reserved. // import ReduxKit struct State { let count: Int } struct IncrementAction: StandardAction { let meta: Any? let error: Bool let rawPayload: Int init(payload: Int? = nil, meta: Any? = nil, error: Bool = false) { self.rawPayload = payload ?? 1 self.meta = meta self.error = error } } func reducer(state: State? = nil, action: Action) -> State { let count = state?.count ?? 0 switch action { case let action as IncrementAction: return State(count: count + action.rawPayload) default: return State(count: count) } }
mit
fb96a37e1af91ba07cfb70bc02566d8a
19.388889
70
0.618529
3.563107
false
false
false
false
zigdanis/Interactive-Transitioning
InteractiveTransitioning/Views/RoundedImageView.swift
1
11177
// // RoundedView.swift // InteractiveTransitioning // // Created by Danis Ziganshin on 24/07/16. // Copyright © 2016 Zigdanis. All rights reserved. // import UIKit enum ReSizeAction { case Expand case Collapse } @IBDesignable class RoundedImageView: UIImageView, CAAnimationDelegate { private let maskLayer = CAShapeLayer() private let borderCircle = CAShapeLayer() var expandedRect: CGRect? = nil var animationCompletion: (()->())? var expandingMultiplier = 1/20.0 convenience init() { self.init(image: nil) } override convenience init(frame: CGRect) { self.init(image: UIImage(named: "close-winter")) } override init(image: UIImage?) { super.init(image: image) setupViewBehaviour() addRoundingLayers() } required init?(coder: NSCoder) { super.init(coder:coder) setupViewBehaviour() addRoundingLayers() } func setupViewBehaviour() { clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false contentMode = .scaleAspectFill } override public func layoutSubviews() { updateRoundedLayers(for: expandedRect) super.layoutSubviews() } override func prepareForInterfaceBuilder() { updateRoundedLayers() super.prepareForInterfaceBuilder() } //MARK: - Logic private func addRoundingLayers() { borderCircle.borderColor = UIColor.white.cgColor borderCircle.borderWidth = 2 layer.addSublayer(borderCircle) maskLayer.fillColor = UIColor.white.cgColor maskLayer.lineWidth = 0 layer.mask = maskLayer updateRoundedLayers() } private func updateRoundedLayers(for rect: CGRect? = nil) { let aBounds = rect ?? bounds let minSide = min(aBounds.width, aBounds.height) let x = aBounds.midX - minSide/2 let y = aBounds.midY - minSide/2 let squareInCenter = CGRect(x: x, y: y, width: minSide, height: minSide) borderCircle.frame = squareInCenter borderCircle.cornerRadius = minSide / 2 let arcPath = CGPath(ellipseIn: squareInCenter, transform: nil) maskLayer.path = arcPath maskLayer.bounds = aBounds maskLayer.position = CGPoint(x: aBounds.midX, y: aBounds.midY) } //MARK: - Public private func setup(animation: CAKeyframeAnimation, with options:UIViewAnimationOptions, duration: TimeInterval, action: ReSizeAction) { let timingFunc = mediaTimingFunction(for: options) let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let timingFunctions = action == .Expand ? [ timingFunc, linear] : [ linear, timingFunc] let fullDuration = duration + duration * expandingMultiplier let intermediate = action == .Expand ? NSNumber(value: duration / fullDuration) : NSNumber(value: 1 - duration / fullDuration) let keyTimes = [NSNumber(value: 0), intermediate, NSNumber(value: 1)] animation.timingFunctions = timingFunctions animation.keyTimes = keyTimes animation.duration = fullDuration } private func enableBoundsAnim(action: ReSizeAction, squareInitial: CGRect, squareDestination: CGRect, squareResized: CGRect) -> CAKeyframeAnimation { let boundsAnimation = CAKeyframeAnimation(keyPath: "bounds") let boundsAnimationFromValue = NSValue(cgRect: squareInitial) let boundsAnimationToValue = NSValue(cgRect: squareDestination) let boundsAnimationExValue = NSValue(cgRect: squareResized) if action == .Expand { boundsAnimation.values = [ boundsAnimationFromValue, boundsAnimationToValue, boundsAnimationExValue ] } else { boundsAnimation.values = [ boundsAnimationExValue, boundsAnimationFromValue, boundsAnimationToValue ] } maskLayer.bounds = action == .Expand ? squareResized : squareDestination // destination return boundsAnimation } private func enablePositionAnim(action: ReSizeAction, initial: CGRect, destination: CGRect, resized: CGRect) -> CAKeyframeAnimation { let positionAnimation = CAKeyframeAnimation(keyPath: "position") let fromPosition = CGPoint(x: initial.midX, y: initial.midY) let toPosition = CGPoint(x: destination.midX, y: destination.midY) let exPosition = CGPoint(x: resized.midX, y: resized.midY) if action == .Expand { positionAnimation.values = [ NSValue(cgPoint: fromPosition), NSValue(cgPoint: toPosition), NSValue(cgPoint: exPosition) ] } else { positionAnimation.values = [ NSValue(cgPoint: exPosition) , NSValue(cgPoint: fromPosition), NSValue(cgPoint: toPosition) ] } maskLayer.position = toPosition return positionAnimation } private func enableCornersAnim(action: ReSizeAction, minInitialSide: CGFloat, minDestinationSide: CGFloat, minExpandedSide: CGFloat) -> CAKeyframeAnimation { let cornersAnimation = CAKeyframeAnimation(keyPath: "cornerRadius") if action == .Expand { cornersAnimation.values = [ minInitialSide / 2, minDestinationSide / 2, minExpandedSide / 2 ] } else { cornersAnimation.values = [ minExpandedSide / 2, minInitialSide / 2, minDestinationSide / 2 ] } borderCircle.cornerRadius = action == .Expand ? minExpandedSide / 2 : minDestinationSide / 2 return cornersAnimation } private func enablePathAnim(action: ReSizeAction, squareInitial: CGRect, squareDestination: CGRect, squareResized: CGRect) -> CAKeyframeAnimation { let pathAnimation = CAKeyframeAnimation(keyPath: "path") let fromPath = CGPath(ellipseIn: squareInitial, transform: nil) let toPath = CGPath(ellipseIn: squareDestination, transform: nil) let exPath = CGPath(ellipseIn: squareResized, transform: nil) if action == .Expand { pathAnimation.values = [ fromPath, toPath, exPath ] } else { pathAnimation.values = [ exPath, fromPath, toPath ] } maskLayer.path = action == .Expand ? exPath : toPath return pathAnimation } func animateImageViewWith(action: ReSizeAction, initial: CGRect, destination: CGRect, duration: TimeInterval, options: UIViewAnimationOptions = []) { let minInitialSide = min(initial.width, initial.height) let minDestinationSide = min(destination.width, destination.height) let squareInitial = CGRect(x: 0, y: 0, width: minInitialSide, height: minInitialSide) let x = destination.midX - minDestinationSide/2 let y = destination.midY - minDestinationSide/2 let squareDestination = CGRect(x: x, y: y, width: minDestinationSide, height: minDestinationSide) let squareResized = containingCircleRect(for: action == .Expand ? destination : initial) let minExpandedSide = squareResized.size.width let fullDuration = duration + duration * expandingMultiplier let boundsAnimation = enableBoundsAnim(action: action, squareInitial: squareInitial, squareDestination: squareDestination, squareResized: squareResized) setup(animation: boundsAnimation, with: options, duration: duration, action: action) let positionAnimation = enablePositionAnim(action: action, initial: initial, destination: destination, resized: squareResized) setup(animation: positionAnimation, with: options, duration: duration, action: action) let cornersAnimation = enableCornersAnim(action: action, minInitialSide: minInitialSide, minDestinationSide: minDestinationSide, minExpandedSide: minExpandedSide) setup(animation: cornersAnimation, with: options, duration: duration, action: action) let pathAnimation = enablePathAnim(action: action, squareInitial: squareInitial, squareDestination: squareDestination, squareResized: squareResized) setup(animation: pathAnimation, with: options, duration: duration, action: action) let borderGroup = CAAnimationGroup() borderGroup.duration = fullDuration borderGroup.animations = [boundsAnimation, positionAnimation, cornersAnimation] let maskGroup = CAAnimationGroup() maskGroup.delegate = self maskGroup.duration = fullDuration maskGroup.animations = [boundsAnimation, positionAnimation, pathAnimation] borderCircle.add(borderGroup, forKey: "Resizing border") maskLayer.add(maskGroup, forKey: "Resizing circle mask") if action == .Expand { expandedRect = squareResized } else { expandedRect = nil } } //MARK: - CAAnimation Delegate func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { animationCompletion?() } //MARK: - Helpers private func setupOptionsForAnimation(animation: CAAnimationGroup, options: UIViewAnimationOptions) { animation.timingFunction = self.mediaTimingFunction(for: options) if options.contains(.autoreverse) { animation.autoreverses = true } if options.contains(.repeat) { animation.repeatCount = MAXFLOAT } } private func mediaTimingFunction(for options: UIViewAnimationOptions) -> CAMediaTimingFunction { var functionName = kCAMediaTimingFunctionLinear if options.contains(.curveLinear) { functionName = kCAMediaTimingFunctionLinear } else if options.contains(.curveEaseIn) { functionName = kCAMediaTimingFunctionEaseIn } else if options.contains(.curveEaseOut) { functionName = kCAMediaTimingFunctionEaseOut } else if options.contains(.curveEaseInOut) { functionName = kCAMediaTimingFunctionEaseInEaseOut } return CAMediaTimingFunction(name: functionName) } private func containingCircleRect(for rect: CGRect) -> CGRect { let height = rect.height let width = rect.width let diameter = sqrt((height * height) + (width * width)) let newX = rect.origin.x - (diameter - width) / 2 let newY = rect.origin.y - (diameter - height) / 2 let containerRect = CGRect(x: newX, y: newY, width: diameter, height: diameter) return containerRect } }
mit
829408a512253b19ebb9ea4ac7e6e7fa
42.150579
170
0.6352
5.316841
false
false
false
false
matsuda/MuddlerKit
Example/Example/AppDelegate.swift
1
4972
// // AppDelegate.swift // Example // // Created by Kosuke Matsuda on 2015/12/28. // Copyright © 2015年 Kosuke Matsuda. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Log("Log test") application.mk.applicationIconBadgeNumberSafely(0) applicationWillRegisterForRemoteNotifications(application: application) print("camelCased :", "camel case".mk.camelCased()) print("pascalCased :", "pascal case".mk.pascalCased()) print("randomAlphanumericString :", String.mk.randomAlphanumericString(8)) print("repeatedString :", String.mk.repeatedString(text: "r", length: 5, isNotEmpty: false)) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. application.mk.applicationIconBadgeNumberSafely(0) applicationWillRegisterForRemoteNotifications(application: application) } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate { func initialSetup() { self.window?.rootViewController?.peelViewController() self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() } } /// MARK: - APNs extension AppDelegate { func applicationWillRegisterForRemoteNotifications(application: UIApplication) { application.mk.activateUserNotificationSettings() } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { #if DEBUG NSLog("notificationSettings >>> %@", notificationSettings) #endif let types = notificationSettings.types if types.rawValue == 0 { } else { application.registerForRemoteNotifications() } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { #if DEBUG #if (arch(arm) || arch(arm64)) && os(iOS) NSLog("error >>> \(error)") #endif // stored directory with simulator #if (arch(i386) || arch(x86_64)) && os(iOS) let nsError = error as NSError if nsError.domain == NSCocoaErrorDomain && nsError.code == 3010 { let token = "iostestdummydevicetoken" if let deviceToken = token.data(using: String.Encoding.utf8) { self.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } } #endif #endif } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { #if DEBUG Log("deviceToken [NSData] >>> \(deviceToken)") #endif guard let token = String(deviceToken: deviceToken) else { return } Log("deviceToken [String] >>> \(token)") #if DEBUG let queue = DispatchQueue.global() queue.async { do { let dir = NSTemporaryDirectory() let path = (dir as NSString).appendingPathComponent("devicetoken.txt") try token.write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch {} } #endif } }
mit
4bdd4f315c467d53dca550acb6f64419
40.756303
285
0.70638
5.371892
false
false
false
false
tomerciucran/space-game
spacegame/MainMenuView.swift
1
1773
// // MainMenuView.swift // spacegame // // Created by Tomer Ciucran on 1/21/16. // Copyright © 2016 Tomer Ciucran. All rights reserved. // import UIKit protocol MainMenuDelegate: class { func play() func rate() func rankings() } class MainMenuView: UIView { var delegate:MainMenuDelegate? let userDefaults = UserDefaults.standard @IBOutlet weak var muteButton: UIButton! @IBOutlet var view: UIView! @IBOutlet weak var versionLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) Bundle.main.loadNibNamed("MainMenuView", owner: self, options: nil) view.frame = frame let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as AnyObject? let version = nsObject as! String versionLabel.text = "v\(version)" addSubview(view) let mute = userDefaults.bool(forKey: muteKey) muteButton.isSelected = mute } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func playButtonTapped(_ sender: AnyObject) { delegate?.play() } @IBAction func rateButtonTapped(_ sender: AnyObject) { delegate?.rate() } @IBAction func rankingsButtonTapped(_ sender: AnyObject) { delegate?.rankings() } @IBAction func muteButtonTapped(_ sender: UIButton) { sender.isSelected = !sender.isSelected userDefaults.set(sender.isSelected, forKey: muteKey) if sender.isSelected { MusicPlayer.sharedInstance.setVolume(value: 0.0) } else { MusicPlayer.sharedInstance.setVolume(value: 1.0) } } }
mit
ae13125cee281f70c200a59b86d9f723
25.848485
106
0.630926
4.508906
false
false
false
false
Jnosh/swift
stdlib/public/core/BidirectionalCollection.swift
2
12345
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements, with bidirectional /// index traversal. /// /// In most cases, it's best to ignore this protocol and use the /// `BidirectionalCollection` protocol instead, because it has a more complete /// interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead") public typealias BidirectionalIndexable = _BidirectionalIndexable public protocol _BidirectionalIndexable : _Indexable { // FIXME(ABI)#22 (Recursive Protocol Constraints): there is no reason for this protocol // to exist apart from missing compiler features that we emulate with it. // rdar://problem/20531108 // // This protocol is almost an implementation detail of the standard // library. /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) } /// A collection that supports backward as well as forward traversal. /// /// Bidirectional collections offer traversal backward from any valid index, /// not including a collection's `startIndex`. Bidirectional collections can /// therefore offer additional operations, such as a `last` property that /// provides efficient access to the last element and a `reversed()` method /// that presents the elements in reverse order. In addition, bidirectional /// collections have more efficient implementations of some sequence and /// collection methods, such as `suffix(_:)`. /// /// Conforming to the BidirectionalCollection Protocol /// ================================================== /// /// To add `BidirectionalProtocol` conformance to your custom types, implement /// the `index(before:)` method in addition to the requirements of the /// `Collection` protocol. /// /// Indices that are moved forward and backward in a bidirectional collection /// move by the same amount in each direction. That is, for any index `i` into /// a bidirectional collection `c`: /// /// - If `i >= c.startIndex && i < c.endIndex`, /// `c.index(before: c.index(after: i)) == i`. /// - If `i > c.startIndex && i <= c.endIndex` /// `c.index(after: c.index(before: i)) == i`. public protocol BidirectionalCollection : _BidirectionalIndexable, Collection // FIXME(ABI) (Revert Where Clauses): Restore these // where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection { // TODO: swift-3-indexing-model - replaces functionality in BidirectionalIndex /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) /// A sequence that can represent a contiguous subrange of the collection's /// elements. associatedtype SubSequence // FIXME(ABI) (Revert Where Clauses): Remove these conformances : _BidirectionalIndexable, Collection = BidirectionalSlice<Self> /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices // FIXME(ABI) (Revert Where Clauses): Remove these conformances : _BidirectionalIndexable, Collection = DefaultBidirectionalIndices<Self> /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } // TODO: swift-3-indexing-model: tests. /// The last element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let lastNumber = numbers.last { /// print(lastNumber) /// } /// // Prints "50" /// /// - Complexity: O(1) var last: Element? { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence { get } } /// Default implementation for bidirectional collections. extension _BidirectionalIndexable { @inline(__always) public func formIndex(before i: inout Index) { i = index(before: i) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { if n >= 0 { return _advanceForward(i, by: n) } var i = i for _ in stride(from: 0, to: n, by: -1) { formIndex(before: &i) } return i } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { if n >= 0 { return _advanceForward(i, by: n, limitedBy: limit) } var i = i for _ in stride(from: 0, to: n, by: -1) { if i == limit { return nil } formIndex(before: &i) } return i } public func distance(from start: Index, to end: Index) -> IndexDistance { var start = start var count: IndexDistance = 0 if start < end { while start != end { count += 1 as IndexDistance formIndex(after: &start) } } else if start > end { while start != end { count -= 1 as IndexDistance formIndex(before: &start) } } return count } } /// Supply the default "slicing" `subscript` for `BidirectionalCollection` /// models that accept the default associated `SubSequence`, /// `BidirectionalSlice<Self>`. extension BidirectionalCollection where SubSequence == BidirectionalSlice<Self> { public subscript(bounds: Range<Index>) -> BidirectionalSlice<Self> { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return BidirectionalSlice(base: self, bounds: bounds) } } extension BidirectionalCollection where SubSequence == Self { /// Removes and returns the last element of the collection. /// /// You can use `popLast()` to remove the last element of a collection that /// might be empty. The `removeLast()` method must be used only on a /// nonempty collection. /// /// - Returns: The last element of the collection if the collection has one /// or more elements; otherwise, `nil`. /// /// - Complexity: O(1). /// - SeeAlso: `removeLast()` public mutating func popLast() -> Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. To remove the last element of a /// collection that might be empty, use the `popLast()` method instead. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) /// - SeeAlso: `popLast()` @discardableResult public mutating func removeLast() -> Element { let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes the given number of elements from the end of the collection. /// /// - Parameter n: The number of elements to remove. `n` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))] } } extension BidirectionalCollection { /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off `n` elements from the end. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop. public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let end = index( endIndex, offsetBy: numericCast(-n), limitedBy: startIndex) ?? startIndex return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains the entire collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is equal to `maxLength`. public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = index( endIndex, offsetBy: numericCast(-maxLength), limitedBy: startIndex) ?? startIndex return self[start..<endIndex] } }
apache-2.0
419f5d528616a70dff0c289fdcd03ecb
35.961078
116
0.647874
4.319454
false
false
false
false
frajaona/LiFXSwiftKit
Pods/socks/Sources/SocksCore/Bytes.swift
1
1715
// // Bytes.swift // Socks // // Created by Honza Dvorsky on 3/20/16. // // #if os(Linux) import Glibc #else import Darwin #endif // Buffer capacity is the same as the maximum UDP packet size public let BufferCapacity = 65_507 class Bytes { let rawBytes: UnsafeMutablePointer<UInt8> let capacity: Int init(capacity: Int = BufferCapacity) { self.rawBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity + 1) //add null strings terminator at location 'capacity' //so that whatever we receive, we always terminate properly when converting to a string? //otherwise we might overread and read garbage, potentially opening a security hole. self.rawBytes[capacity] = UInt8(0) self.capacity = capacity } deinit { free(self.rawBytes) } var characters: [UInt8] { var data = [UInt8](repeating: 0, count: self.capacity) memcpy(&data, self.rawBytes, data.count) return data } func toString() throws -> String { return try self.characters.toString() } } extension Collection where Iterator.Element == UInt8 { public func toString() throws -> String { var utf = UTF8() var gen = self.makeIterator() var chars = String.UnicodeScalarView() while true { switch utf.decode(&gen) { case .emptyInput: //we're done return String(chars) case .error: //error, can't describe what however throw SocksError(.unparsableBytes) case .scalarValue(let unicodeScalar): chars.append(unicodeScalar) } } } }
apache-2.0
a327fe8fca5baf2b08f62a71b85e0faf
24.597015
96
0.605831
4.375
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Costello Reverb Operation.xcplaygroundpage/Contents.swift
2
937
//: ## Costello Reverb Operation //: import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) var player = try AKAudioPlayer(file: file) player.looping = true let effect = AKOperationEffect(player) { player, _ in return player.reverberateWithCostello( feedback: AKOperation.sineWave(frequency: 0.1).scale(minimum: 0.5, maximum: 0.97), cutoffFrequency: 10000) } AudioKit.output = effect AudioKit.start() player.play() //: User Interface class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Costello Reverb Operation") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: processingPlaygroundFiles)) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
e71b2fe2392a37acbebc140a54eaa823
25.055556
90
0.710779
4.805128
false
false
false
false
maxbritto/cours-ios11-swift4
Niveau_avance/Objectif 3/Notifications/Notifications/ViewController.swift
1
1811
// // ViewController.swift // Notifications // // Created by Maxime Britto on 15/01/2018. // Copyright © 2018 Maxime Britto. All rights reserved. // import UIKit import UserNotifications class ViewController: UIViewController { @IBAction func requestAuthorization() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in print("Response : \(granted)") } } @IBAction func scheduleNotification() { let content = UNMutableNotificationContent() content.title = "Super notification" content.body = "Ceci est une super notif, vous devriez lancer l'app pour en savoir plus!" content.userInfo["id-objet"] = 525 content.categoryIdentifier = "cat1" content.sound = UNNotificationSound.default() content.badge = 1 if let imageUrl = Bundle.main.url(forResource: "logo", withExtension: "png"), let attachment = try? UNNotificationAttachment(identifier: "logo", url: imageUrl, options: nil) { content.attachments = [attachment] } let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false) let request = UNNotificationRequest(identifier: "maNotif", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. UIApplication.shared.applicationIconBadgeNumber = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
0d0034126e400f262c22122926ec6fb0
33.150943
118
0.661326
5.08427
false
false
false
false
ifeherva/HSTracker
HSTracker/Hearthstone/Secrets/SecretsManager.swift
1
12512
// // SecretsManager.swift // HSTracker // // Created by Benjamin Michotte on 25/10/17. // Copyright © 2017 Benjamin Michotte. All rights reserved. // import Foundation import AwaitKit class SecretsManager { let avengeDelay: Double = 50 private var _avengeDeathRattleCount = 0 private var _awaitingAvenge = false private var _lastCompetitiveSpiritCheck = 0 private var game: Game private(set) var secrets: [Secret] = [] var onChanged: (([Card]) -> Void)? init(game: Game) { self.game = game } private var freeSpaceOnBoard: Bool { return game.opponentMinionCount < 7 } private var freeSpaceInHand: Bool { return game.opponentHandCount < 10 } private var handleAction: Bool { return hasActiveSecrets } private var hasActiveSecrets: Bool { return secrets.count > 0 } func exclude(cardId: String, invokeCallback: Bool = true) { if cardId.isBlank { return } secrets.forEach { $0.exclude(cardId: cardId) } if invokeCallback { onChanged?(getSecretList()) } } func exclude(cardIds: [String]) { cardIds.enumerated().forEach { exclude(cardId: $1, invokeCallback: $0 == cardIds.count - 1) } } func reset() { _avengeDeathRattleCount = 0 _awaitingAvenge = false _lastCompetitiveSpiritCheck = 0 secrets.removeAll() } @discardableResult func newSecret(entity: Entity) -> Bool { if !entity.isSecret || !entity.has(tag: .class) { return false } if entity.hasCardId { exclude(cardId: entity.cardId) } do { try secrets.append(Secret(entity: entity)) logger.info("new secret : \(entity)") onChanged?(getSecretList()) return true } catch { logger.error("\(error)") return false } } @discardableResult func removeSecret(entity: Entity) -> Bool { guard let secret = secrets.first(where: { $0.entity.id == entity.id }) else { logger.info("Secret not found \(entity)") return false } handleFastCombat(entity: entity) secrets.remove(secret) if secret.entity.hasCardId { exclude(cardId: secret.entity.cardId, invokeCallback: false) } onChanged?(getSecretList()) return true } func toggle(cardId: String) { let excluded = secrets.any { $0.isExcluded(cardId: cardId) } if excluded { secrets.forEach { $0.include(cardId: cardId) } } else { exclude(cardId: cardId, invokeCallback: false) } } func getSecretList() -> [Card] { let wildSets = CardSet.wildSets() let gameMode = game.currentGameType let format = game.currentFormat let opponentEntities = game.opponent.revealedEntities.filter { $0.id < 68 && $0.isSecret && $0.hasCardId } let gameModeHasCardLimit = [GameType.gt_casual, GameType.gt_ranked, GameType.gt_vs_friend, GameType.gt_vs_ai].contains(gameMode) let createdSecrets = secrets .filter { $0.entity.info.created } .flatMap { $0.excluded } .filter { !$0.value } .map { $0.key } .unique() let hasPlayedTwoOf: ((_ cardId: String) -> Bool) = { cardId in opponentEntities.filter { $0.cardId == cardId && !$0.info.created }.count >= 2 } let adjustCount: ((_ cardId: String, _ count: Int) -> Int) = { cardId, count in gameModeHasCardLimit && hasPlayedTwoOf(cardId) && !createdSecrets.contains(cardId) ? 0 : count } var cards: [Card] = secrets.flatMap { $0.excluded } .group { $0.key } .flatMap { let card = Cards.by(cardId: $0.key) card?.count = adjustCount($0.key, $0.value.filter({ !$0.value }).count) return card } if format == .standard || gameMode == .gt_arena { cards = cards.filter { !wildSets.contains($0.set ?? .invalid) } } if gameMode == .gt_arena { cards = cards.filter { !CardIds.Secrets.arenaExcludes.contains($0.id) } } return cards.filter { $0.count > 0 } } func handleAttack(attacker: Entity, defender: Entity, fastOnly: Bool = false) { guard handleAction else { return } if attacker[.controller] == defender[.controller] { return } var exclude: [String] = [] if freeSpaceOnBoard { exclude.append(CardIds.Secrets.Paladin.NobleSacrifice) } if defender.isHero { if !fastOnly { if freeSpaceOnBoard { exclude.append(CardIds.Secrets.Hunter.BearTrap) } exclude.append(CardIds.Secrets.Mage.IceBarrier) } if freeSpaceOnBoard { exclude.append(CardIds.Secrets.Hunter.WanderingMonster) } exclude.append(CardIds.Secrets.Hunter.ExplosiveTrap) if game.isMinionInPlay { exclude.append(CardIds.Secrets.Hunter.Misdirection) } if attacker.isMinion && game.playerMinionCount > 1 { exclude.append(CardIds.Secrets.Rogue.SuddenBetrayal) } if attacker.isMinion { exclude.append(CardIds.Secrets.Mage.Vaporize) exclude.append(CardIds.Secrets.Hunter.FreezingTrap) } } else { if !fastOnly && freeSpaceOnBoard { exclude.append(CardIds.Secrets.Hunter.SnakeTrap) exclude.append(CardIds.Secrets.Hunter.VenomstrikeTrap) } if attacker.isMinion { exclude.append(CardIds.Secrets.Hunter.FreezingTrap) } } self.exclude(cardIds: exclude) } func handleFastCombat(entity: Entity) { guard handleAction else { return } if !entity.hasCardId || game.proposedAttacker == 0 || game.proposedDefender == 0 { return } if !CardIds.Secrets.fastCombat.contains(entity.cardId) { return } if let attacker = game.entities[game.proposedAttacker], let defender = game.entities[game.proposedDefender] { handleAttack(attacker: attacker, defender: defender, fastOnly: true) } } func handleMinionPlayed() { guard handleAction else { return } var exclude: [String] = [] //Hidden cache will only trigger if the opponent has a minion in hand. //We might not know this for certain - requires additional tracking logic. //TODO: _game.SecretsManager.SetZero(Hunter.HiddenCache); exclude.append(CardIds.Secrets.Hunter.Snipe) exclude.append(CardIds.Secrets.Mage.ExplosiveRunes) exclude.append(CardIds.Secrets.Mage.PotionOfPolymorph) exclude.append(CardIds.Secrets.Paladin.Repentance) if freeSpaceOnBoard { exclude.append(CardIds.Secrets.Mage.MirrorEntity) } if freeSpaceInHand { exclude.append(CardIds.Secrets.Mage.FrozenClone) } self.exclude(cardIds: exclude) } func handleMinionDeath(entity: Entity) { guard handleAction else { return } var exclude: [String] = [] if freeSpaceInHand { exclude.append(CardIds.Secrets.Mage.Duplicate) exclude.append(CardIds.Secrets.Paladin.GetawayKodo) exclude.append(CardIds.Secrets.Rogue.CheatDeath) } var numDeathrattleMinions = 0 if entity.isActiveDeathrattle { if let count = CardIds.DeathrattleSummonCardIds[entity.cardId] { numDeathrattleMinions = count } else if entity.cardId == CardIds.Collectible.Neutral.Stalagg && game.opponent.graveyard.any({ $0.cardId == CardIds.Collectible.Neutral.Feugen }) || entity.cardId == CardIds.Collectible.Neutral.Feugen && game.opponent.graveyard.any({ $0.cardId == CardIds.Collectible.Neutral.Stalagg }) { numDeathrattleMinions = 1 } if game.entities.map({ $0.value }).any({ $0.cardId == CardIds.NonCollectible.Druid.SouloftheForest_SoulOfTheForestEnchantment && $0[.attached] == entity.id }) { numDeathrattleMinions += 1 } if game.entities.map({ $0.value }).any({ $0.cardId == CardIds.NonCollectible.Shaman.AncestralSpirit_AncestralSpiritEnchantment && $0[.attached] == entity.id }) { numDeathrattleMinions += 1 } } if let opponentEntity = game.opponentEntity, opponentEntity.has(tag: .extra_deathrattles) { numDeathrattleMinions *= opponentEntity[.extra_deathrattles] + 1 } handleAvengeAsync(deathRattleCount: numDeathrattleMinions) // redemption never triggers if a deathrattle effect fills up the board // effigy can trigger ahead of the deathrattle effect, but only if effigy was played before the deathrattle minion if game.opponentMinionCount < 7 - numDeathrattleMinions { exclude.append(CardIds.Secrets.Paladin.Redemption) } // TODO: break ties when Effigy + Deathrattle played on the same turn exclude.append(CardIds.Secrets.Mage.Effigy) self.exclude(cardIds: exclude) } func handleAvengeAsync(deathRattleCount: Int) { guard handleAction else { return } _avengeDeathRattleCount += deathRattleCount if _awaitingAvenge { return } _awaitingAvenge = true if game.opponentMinionCount != 0 { do { try await { Thread.sleep(forTimeInterval: self.avengeDelay) } if game.opponentMinionCount - _avengeDeathRattleCount > 0 { exclude(cardId: CardIds.Secrets.Paladin.Avenge) } } catch { logger.error("\(error)") } } _awaitingAvenge = false _avengeDeathRattleCount = 0 } func handleOpponentDamage(entity: Entity) { guard handleAction else { return } if entity.isHero && entity.isControlled(by: game.opponent.id) { exclude(cardId: CardIds.Secrets.Paladin.EyeForAnEye) exclude(cardId: CardIds.Secrets.Rogue.Evasion) } } func handleTurnsInPlayChange(entity: Entity, turn: Int) { guard handleAction else { return } if turn <= _lastCompetitiveSpiritCheck || !entity.isMinion || !entity.isControlled(by: game.opponent.id) || !(game.opponentEntity?.isCurrentPlayer ?? false) { return } _lastCompetitiveSpiritCheck = turn exclude(cardId: CardIds.Secrets.Paladin.CompetitiveSpirit) } func handleCardPlayed(entity: Entity) { guard handleAction else { return } var exclude: [String] = [] if entity.isSpell { exclude.append(CardIds.Secrets.Mage.Counterspell) if game.opponentHandCount < 10 { exclude.append(CardIds.Secrets.Mage.ManaBind) } if game.opponentMinionCount < 7 { // CARD_TARGET is set after ZONE, wait for 50ms gametime before checking do { try await { Thread.sleep(forTimeInterval: 0.2) } if let target = game.entities[entity[.card_target]], entity.has(tag: .card_target), target.isMinion { exclude.append(CardIds.Secrets.Mage.Spellbender) } exclude.append(CardIds.Secrets.Hunter.CatTrick) } catch { logger.error("\(error)") } } } else if entity.isMinion && game.playerMinionCount > 3 { exclude.append(CardIds.Secrets.Paladin.SacredTrial) } self.exclude(cardIds: exclude) } func handleHeroPower() { guard handleAction else { return } exclude(cardId: CardIds.Secrets.Hunter.DartTrap) } }
mit
13fa2e4aa5f0f554d7c4b70d8f0e8aad
32.722372
138
0.577492
4.710467
false
false
false
false
TENDIGI/Obsidian-iOS-SDK
Obsidian-iOS-SDK/Pagination.swift
1
1288
// // Pagination.swift // ObsidianSDK // // Created by Nick Lee on 7/1/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation /// The Pagination struct dictates how result sets will be chunked by the server public struct Pagination { // MARK: Properties /// A large limit, used for queries in which "all" records should be returned. public static let BigLimit = 99999 /// The desired page of results public let page: Int /// The desired number of results per page public let limit: Int // MARK: Configuring Pagination /** Constructs a new Pagination object - parameter page: The desired page of results - parameter limit: The desired number of results per page - returns: A new Pagination object */ public init(page: Int = Constants.Pagination.InitialPage, limit: Int = Constants.Pagination.DefaultLimit) { self.page = max(page, Constants.Pagination.InitialPage) self.limit = limit } } /// :nodoc: extension Pagination: Serializable { internal var serialized: ObsidianTypeConvertible { return [ Constants.Pagination.PageKey : page, Constants.Pagination.LimitKey : limit ] } }
mit
bc8f51925008851cae195f63d691cda5
24.254902
111
0.649068
4.487805
false
false
false
false
PoissonBallon/EasyRealm
EasyRealm/Classes/Delete.swift
1
3368
// // ER_Delete.swift // Pods // // Created by Allan Vialatte on 23/11/16. // // import Foundation import Realm import RealmSwift public enum EasyRealmDeleteMethod { case simple case cascade } public extension EasyRealmStatic where T:Object { public func deleteAll() throws { let realm = try Realm() try realm.write { realm.delete(realm.objects(self.baseType)) } } } public extension EasyRealm where T:Object { public func delete(with method:EasyRealmDeleteMethod = .simple) throws { switch method { case .simple: self.isManaged ? try managedSimpleDelete() : try unmanagedSimpleDelete() case .cascade: self.isManaged ? try managedCascadeDelete() : try unmanagedCascadeDelete() } } } //Normal Way fileprivate extension EasyRealm where T: Object { fileprivate func managedSimpleDelete() throws { guard let rq = EasyRealmQueue() else { throw EasyRealmError.RealmQueueCantBeCreate } let ref = ThreadSafeReference(to: self.base) try rq.queue.sync { guard let object = rq.realm.resolve(ref) else { throw EasyRealmError.ObjectCantBeResolved } try rq.realm.write { EasyRealm.simpleDelete(this: object, in: rq) } } } fileprivate func unmanagedSimpleDelete() throws { guard let rq = EasyRealmQueue() else { throw EasyRealmError.RealmQueueCantBeCreate } guard let key = T.primaryKey() else { throw EasyRealmError.ObjectCantBeResolved } try rq.queue.sync { let value = self.base.value(forKey: key) if let object = rq.realm.object(ofType: T.self, forPrimaryKey: value) { try rq.realm.write { EasyRealm.simpleDelete(this: object, in: rq) } } } } fileprivate static func simpleDelete(this object:Object, in queue:EasyRealmQueue) { queue.realm.delete(object) } } //Cascade Way fileprivate extension EasyRealm where T: Object { fileprivate func managedCascadeDelete() throws { guard let rq = EasyRealmQueue() else { throw EasyRealmError.RealmQueueCantBeCreate } let ref = ThreadSafeReference(to: self.base) try rq.queue.sync { guard let object = rq.realm.resolve(ref) else { throw EasyRealmError.ObjectCantBeResolved } try rq.realm.write { EasyRealm.cascadeDelete(this: object, in: rq) } } } fileprivate func unmanagedCascadeDelete() throws { guard let rq = EasyRealmQueue() else { throw EasyRealmError.RealmQueueCantBeCreate } guard let key = T.primaryKey() else { throw EasyRealmError.ObjectCantBeResolved } try rq.queue.sync { let value = self.base.value(forKey: key) if let object = rq.realm.object(ofType: T.self, forPrimaryKey: value) { try rq.realm.write { EasyRealm.cascadeDelete(this: object, in: rq) } } } } fileprivate static func cascadeDelete(this object:Object, in queue:EasyRealmQueue) { for property in object.objectSchema.properties { guard let value = object.value(forKey: property.name) else { continue } if let object = value as? Object { EasyRealm.cascadeDelete(this: object, in: queue) } if let list = value as? EasyRealmList { list.children().forEach { EasyRealm.cascadeDelete(this: $0, in: queue) } } } queue.realm.delete(object) } }
mit
3e01640af70ca1b481acacfa0163f794
26.606557
97
0.671318
3.925408
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/LineForm.swift
1
3395
// // LineForm.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath import ReformGraphics extension LineForm { public enum PointId : ExposedPointIdentifier { case start = 0 case end = 1 case center = 2 } } final public class LineForm : Form, Creatable { public static var stackSize : Int = 4 public let identifier : FormIdentifier public var drawingMode : DrawingMode = DrawingMode.draw public var name : String public init(id: FormIdentifier, name : String) { self.identifier = id self.name = name } var startPoint : WriteableRuntimePoint { get { return StaticPoint(formId: identifier, offset: 0) } } var endPoint : WriteableRuntimePoint { get { return StaticPoint(formId: identifier, offset: 2) } } public func initWithRuntime<R:Runtime>(_ runtime: R, min: Vec2d, max: Vec2d) { startPoint.setPositionFor(runtime, position: min) endPoint.setPositionFor(runtime, position: max) } public func getPoints() -> [ExposedPointIdentifier:LabeledPoint] { return [ PointId.start.rawValue:ExposedPoint(point: startPoint, name: "Start"), PointId.end.rawValue:ExposedPoint(point: endPoint, name: "End"), PointId.center.rawValue:ExposedPoint(point: CenterPoint(pointA: startPoint, pointB: endPoint), name: "Center"), ] } public var outline : Outline { get { return LineOutline(start: startPoint, end: endPoint) } } } extension LineForm { public var startAnchor : Anchor { return StaticPointAnchor(point: startPoint, name: "Start") } public var endAnchor : Anchor { return StaticPointAnchor(point: endPoint, name: "End") } } extension LineForm : Rotatable { public var rotator : Rotator { get { return BasicPointRotator(points: startPoint, endPoint) } } } extension LineForm : Translatable { public var translator : Translator { get { return BasicPointTranslator(points: startPoint, endPoint) } } } extension LineForm : Scalable { public var scaler : Scaler { get { return BasicPointScaler(points: startPoint, endPoint) } } } extension LineForm : Morphable { public enum AnchorId : AnchorIdentifier { case start = 0 case end = 1 } public func getAnchors() -> [AnchorIdentifier:Anchor] { return [ AnchorId.start.rawValue:startAnchor, AnchorId.end.rawValue:endAnchor, ] } } extension LineForm : Drawable { public func getPathFor<R:Runtime>(_ runtime: R) -> Path? { guard let start = startAnchor.getPositionFor(runtime), let end = endAnchor.getPositionFor(runtime) else { return nil } return Path(segments: .moveTo(start), .lineTo(end)) } public func getShapeFor<R:Runtime>(_ runtime: R) -> Shape? { guard let path = getPathFor(runtime) else { return nil } return Shape(area: .pathArea(path), background: .none, stroke: .solid(width: 1, color: ReformGraphics.Color(r:50, g:50, b:50, a: 255))) } }
mit
41bd95345501572fb4606227aa56e0d7
25.515625
143
0.612257
4.2425
false
false
false
false
sambhav7890/SSChartView
SSChartView/Classes/Helpers/ColorHelpers.swift
1
3076
// // ColorHelpers.swift // Pods // // Created by Sambhav Shah on 17/11/16. // // import UIKit enum DefaultColorType { case bar, line, barText, lineText, pieText func color() -> UIColor { switch self { case .bar: return UIColor(hex: "#4DC2AB") case .line: return UIColor(hex: "#FF0066") case .barText: return UIColor(hex: "#333333") case .lineText: return UIColor(hex: "#333333") case .pieText: return UIColor(hex: "#FFFFFF") } } static func pieColors(_ count: Int) -> [UIColor] { func randomArray(_ arr: [Int]) -> [Int] { if arr.count <= 0 { return [] } let randomIndex = Int(arc4random_uniform(UInt32(arr.count))) var tail = [Int]() for i in 0 ..< arr.count { if i != randomIndex { tail.append(arr[i]) } } return [arr[randomIndex]] + randomArray(tail) } let arr = Array(0 ..< count).map({ $0 }) let colors = arr.map({ UIColor(hue: CGFloat($0) / CGFloat(count), saturation: 0.9, brightness: 0.9, alpha: 1.0) }) return colors } } public extension UIColor { public static func colorGradientLocations(forColors colors: [Any]) -> [CGFloat] { let fractionCount = colors.count - 1 if fractionCount > 0 { let fraction = 1.0 / CGFloat(fractionCount) var colorLocations: [CGFloat] = [] var lastColor: CGFloat = 0.0 while lastColor <= 1.0 { colorLocations.append(lastColor) lastColor += fraction } return colorLocations } else { return [0.0] } } public convenience init(gray: Int = 1, _ alphaPercent: Int = 100) { let white = CGFloat(gray) / 255.0 let alphaVal = CGFloat(alphaPercent) / 100.0 self.init(white: white, alpha: alphaVal) } public convenience init(rgba: (Int, Int, Int, Float) = (0, 0, 0, 1.0)) { let red = CGFloat(rgba.0) / 255.0 let green = CGFloat(rgba.1) / 255.0 let blue = CGFloat(rgba.2) / 255.0 let alpha = CGFloat(rgba.3) self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(RGBInt: UInt64, alpha: Float = 1.0) { self.init( red: (((CGFloat)((RGBInt & 0xFF0000) >> 16)) / 255.0), green: (((CGFloat)((RGBInt & 0xFF00) >> 8)) / 255.0), blue: (((CGFloat)(RGBInt & 0xFF)) / 255.0), alpha: CGFloat(alpha) ) } public convenience init(hex: String) { let prefixCalculator: ((String) -> String) = { (str) -> String in for prefix in ["0x", "0X", "#"] { if str.hasPrefix(prefix) { return str.substring(from: str.characters.index(str.startIndex, offsetBy: prefix.characters.count)) } } return str } let prefixHex = prefixCalculator(hex) if prefixHex.characters.count != 6 && prefixHex.characters.count != 8 { self.init(white: 0.0, alpha: 1.0) return } let scanner = Scanner(string: prefixHex) var hexInt: UInt64 = 0 if !scanner.scanHexInt64(&hexInt) { self.init(white: 0.0, alpha: 1.0) return } switch prefixHex.characters.count { case 6: self.init(RGBInt: hexInt) case 8: self.init(RGBInt: hexInt >> 8, alpha: (((Float)(hexInt & 0xFF)) / 255.0)) case _: self.init(white: 0.0, alpha: 1.0) } } }
mit
90219f9e3fbc6ad7f62daa600af8b1f0
24.00813
116
0.626138
2.86406
false
false
false
false
brentdax/swift
stdlib/public/core/StringSwitch.swift
4
3928
//===----------------------------------------------------------------------===// // // 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 file contains compiler intrinsics for optimized string switch // implementations. All functions and types declared in this file are not // intended to be used by switch source directly. /// The compiler intrinsic which is called to lookup a string in a table /// of static string case values. @_semantics("findStringSwitchCase") public // COMPILER_INTRINSIC func _findStringSwitchCase( cases: [StaticString], string: String) -> Int { for (idx, s) in cases.enumerated() { if String(_builtinStringLiteral: s.utf8Start._rawValue, utf8CodeUnitCount: s._utf8CodeUnitCount, isASCII: s.isASCII._value) == string { return idx } } return -1 } @_fixed_layout // needs known size for static allocation public // used by COMPILER_INTRINSIC struct _OpaqueStringSwitchCache { var a: Builtin.Word var b: Builtin.Word } @usableFromInline // FIXME(sil-serialize-all) internal typealias _StringSwitchCache = Dictionary<String, Int> @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline // FIXME(sil-serialize-all) internal struct _StringSwitchContext { @inlinable // FIXME(sil-serialize-all) internal init( cases: [StaticString], cachePtr: UnsafeMutablePointer<_StringSwitchCache> ){ self.cases = cases self.cachePtr = cachePtr } @usableFromInline // FIXME(sil-serialize-all) internal let cases: [StaticString] @usableFromInline // FIXME(sil-serialize-all) internal let cachePtr: UnsafeMutablePointer<_StringSwitchCache> } /// The compiler intrinsic which is called to lookup a string in a table /// of static string case values. /// /// The first time this function is called, a cache is built and stored /// in \p cache. Consecutive calls use the cache for faster lookup. /// The \p cases array must not change between subsequent calls with the /// same \p cache. @_semantics("findStringSwitchCaseWithCache") public // COMPILER_INTRINSIC func _findStringSwitchCaseWithCache( cases: [StaticString], string: String, cache: inout _OpaqueStringSwitchCache) -> Int { return withUnsafeMutableBytes(of: &cache) { (bufPtr: UnsafeMutableRawBufferPointer) -> Int in let oncePtr = bufPtr.baseAddress! let cacheRawPtr = oncePtr + MemoryLayout<Builtin.Word>.stride let cachePtr = cacheRawPtr.bindMemory(to: _StringSwitchCache.self, capacity: 1) var context = _StringSwitchContext(cases: cases, cachePtr: cachePtr) withUnsafeMutablePointer(to: &context) { (context) -> () in Builtin.onceWithContext(oncePtr._rawValue, _createStringTableCache, context._rawValue) } let cache = cachePtr.pointee; if let idx = cache[string] { return idx } return -1 } } /// Builds the string switch case. @inlinable // FIXME(sil-serialize-all) internal func _createStringTableCache(_ cacheRawPtr: Builtin.RawPointer) { let context = UnsafePointer<_StringSwitchContext>(cacheRawPtr).pointee var cache = _StringSwitchCache() cache.reserveCapacity(context.cases.count) assert(MemoryLayout<_StringSwitchCache>.size <= MemoryLayout<Builtin.Word>.size) for (idx, s) in context.cases.enumerated() { let key = String(_builtinStringLiteral: s.utf8Start._rawValue, utf8CodeUnitCount: s._utf8CodeUnitCount, isASCII: s.isASCII._value) cache[key] = idx } context.cachePtr.initialize(to: cache) }
apache-2.0
44d6c336460dec701934fb2905ad6d32
34.071429
83
0.689155
4.307018
false
false
false
false
brentdax/swift
test/SILOptimizer/definite_init_failable_initializers_objc.swift
1
3419
// RUN: %target-swift-frontend -emit-sil -enable-sil-ownership -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s // FIXME: This needs more tests @objc protocol P3 { init?(p3: Int64) } extension P3 { // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc2P3PAAE3p3axSgs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Optional<Self> init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc2P3PAAE3p3bxs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Self init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } class LifetimeTracked { init(_: Int) {} } class FakeNSObject { @objc dynamic init() {} } class Cat : FakeNSObject { let x: LifetimeTracked // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc3CatC1n5afterACSgSi_Sbtcfc : $@convention(method) (Int, Bool, @owned Cat) -> @owned Optional<Cat> // CHECK: bb0(%0 : $Int, %1 : $Bool, %2 : $Cat): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $Cat // CHECK: store %2 to [[SELF_BOX]] : $*Cat // CHECK: [[FIELD_ADDR:%.*]] = ref_element_addr %2 : $Cat, #Cat.x // CHECK-NEXT: store {{%.*}} to [[FIELD_ADDR]] : $*LifetimeTracked // CHECK-NEXT: [[COND:%.*]] = struct_extract %1 : $Bool, #Bool._value // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: br bb3 // CHECK: bb2: // CHECK-NEXT: [[SUPER:%.*]] = upcast %2 : $Cat to $FakeNSObject // CHECK-NEXT: [[SUB:%.*]] = unchecked_ref_cast [[SUPER]] : $FakeNSObject to $Cat // CHECK-NEXT: [[SUPER_FN:%.*]] = objc_super_method [[SUB]] : $Cat, #FakeNSObject.init!initializer.1.foreign : (FakeNSObject.Type) -> () -> FakeNSObject, $@convention(objc_method) (@owned FakeNSObject) -> @owned FakeNSObject // CHECK-NEXT: [[NEW_SUPER_SELF:%.*]] = apply [[SUPER_FN]]([[SUPER]]) : $@convention(objc_method) (@owned FakeNSObject) -> @owned FakeNSObject // CHECK-NEXT: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SUPER_SELF]] : $FakeNSObject to $Cat // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] : $*Cat // TODO: Once we re-enable arbitrary take promotion, this retain and the associated destroy_addr will go away. // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[NEW_SELF]] : $Cat // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*Cat // CHECK-NEXT: br bb4([[RESULT]] : $Optional<Cat>) // CHECK: bb3: // CHECK-NEXT: [[FIELD_ADDR:%.*]] = ref_element_addr %2 : $Cat, #Cat.x // CHECK-NEXT: destroy_addr [[FIELD_ADDR]] : $*LifetimeTracked // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: dealloc_partial_ref %2 : $Cat, [[METATYPE]] : $@thick Cat.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*Cat // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br bb4([[RESULT]] : $Optional<Cat>) // CHECK: bb4([[RESULT:%.*]] : $Optional<Cat>): // CHECK-NEXT: return [[RESULT]] : $Optional<Cat> init?(n: Int, after: Bool) { self.x = LifetimeTracked(0) if after { return nil } super.init() } }
apache-2.0
0c94912e445dbe4bc4010fdb8bef78bf
43.402597
228
0.619187
3.189366
false
false
false
false
hash3r/quandoo_test
Quandoo_test/User.swift
1
1408
// // User.swift // Quandoo_test // // Created by Vladimir Gnatiuk on 11/9/16. // Copyright © 2016 Vladimir Gnatiuk. All rights reserved. // import Foundation import ObjectMapper struct User: Mappable { var userId: Int? var name: String? var username: String? var email: String? var street: String? var suite: String? var city: String? var zipcode: String? init?(map: Map) { } mutating func mapping(map: Map) { userId <- map["id"] name <- map["name"] username <- map["username"] email <- map["email"] street <- map["address.street"] suite <- map["address.suite"] city <- map["address.city"] zipcode <- map["address.zipcode"] } } extension User { /// Generate full address from details /// /// - Returns: Concatenated address details func fullAddress() -> String { var address = "" if let street = street { address += street } if let suite = suite { address = address.isEmpty == false ? address + ", " + suite : suite } if let city = city { address = address.isEmpty == false ? address + ", " + city : city } if let zipcode = zipcode { address = address.isEmpty == false ? address + ", " + zipcode : zipcode } return address } }
mit
11e157b1b4524bc22d3c78238d41b43f
22.847458
83
0.542289
4.162722
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/KillmailsPresenter.swift
2
5010
// // KillmailsPresenter.swift // Neocom // // Created by Artem Shimanski on 11/13/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController class KillmailsPresenter: ContentProviderPresenter { typealias View = KillmailsViewController typealias Interactor = KillmailsInteractor struct Presentation { var kills: [Section] var losses: [Section] } struct Section { var date: Date var rows: [Tree.Item.KillmailRow] } weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? required init(view: View) { self.view = view } func configure() { interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { let old = presentation if numberOfPages == nil { numberOfPages = content.value.pages } return DispatchQueue.global(qos: .utility).async { () -> Presentation in let calendar = Calendar(identifier: .gregorian) let characterID = Int(content.value.characterID) var rows = content.value.killmails .sorted{$0.killmailTime > $1.killmailTime} .map{ i -> Tree.Item.KillmailRow in let contactID = i.victim.characterID == characterID ? i.attackers.first.flatMap {$0.characterID ?? $0.corporationID ?? $0.allianceID} : i.victim.characterID let contact = contactID.flatMap{content.value.contacts?[Int64($0)]} return Tree.Item.KillmailRow(i, name: contact) } let i = rows.partition {$0.content.victim.characterID == characterID} let kills = Dictionary(grouping: rows[..<i], by: { (i) -> Date in let components = calendar.dateComponents([.year, .month, .day], from: i.content.killmailTime) return calendar.date(from: components) ?? i.content.killmailTime }).sorted {$0.key > $1.key} let losses = Dictionary(grouping: rows[i...], by: { (i) -> Date in let components = calendar.dateComponents([.year, .month, .day], from: i.content.killmailTime) return calendar.date(from: components) ?? i.content.killmailTime }).sorted {$0.key > $1.key} if var result = old { for i in kills { if let j = result.kills.upperBound(where: {$0.date <= i.key}).indices.first, result.kills[j].date == i.key { let killmailIDs = Set(result.kills[j].rows.map{$0.content.killmailID}) result.kills[j].rows.append(contentsOf: i.value.filter {!killmailIDs.contains($0.content.killmailID)}) } else { result.kills.append(Section(date: i.key, rows: i.value)) } } for i in losses { if let j = result.losses.upperBound(where: {$0.date <= i.key}).indices.first, result.losses[j].date == i.key { let killmailIDs = Set(result.losses[j].rows.map{$0.content.killmailID}) result.losses[j].rows.append(contentsOf: i.value.filter {!killmailIDs.contains($0.content.killmailID)}) } else { result.losses.append(Section(date: i.key, rows: i.value)) } } return result } else { return Presentation(kills: kills.map{Section(date: $0.key, rows: $0.value)}, losses: losses.map{Section(date: $0.key, rows: $0.value)}) } } } private var currentPage: Int? private var numberOfPages: Int? func prepareForReload() { self.presentation = nil self.currentPage = nil self.numberOfPages = nil } @discardableResult func fetchIfNeeded() -> Future<Void> { guard let numberOfPages = numberOfPages, self.loading == nil else {return .init(.failure(NCError.reloadInProgress))} let nextPage = (currentPage ?? 1) + 1 guard nextPage < numberOfPages else {return .init(.failure(NCError.isEndReached))} let loading = interactor.load(page: nextPage, cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self] content -> Future<Presentation> in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} return strongSelf.presentation(for: content).then(on: .main) { [weak self] presentation -> Future<Presentation> in guard let strongSelf = self, let view = strongSelf.view else {throw NCError.cancelled(type: type(of: self), function: #function)} strongSelf.presentation = presentation strongSelf.currentPage = nextPage strongSelf.loading = nil return view.present(presentation, animated: false).then {_ in presentation} } }.catch(on: .main) { [weak self] error in self?.loading = nil self?.currentPage = self?.numberOfPages } if case .pending = loading.state { self.loading = loading } return loading.then{_ in ()} } }
lgpl-2.1
acf411f9642675c1e6d595fb3dfe143a
33.784722
200
0.698343
3.560057
false
false
false
false
nbrady-techempower/FrameworkBenchmarks
frameworks/Swift/kitura/Sources/KueryPostgresORM/PostgresORM.swift
23
8463
/* * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Dispatch import LoggerAPI import SwiftKuery import SwiftKueryORM import KueryPostgres import TechEmpowerCommon // ORM conformance extension RandomRow: Model { public static var tableName: String { return "world" } } // ORM conformance extension Fortune: Model { public static var tableName: String { return "fortune" } } // Configure our ORM Database connection pool as dbConnPool created by KueryPostgres public func setupORM() { Database.default = Database(dbConnPool) } /// Get a list of Fortunes from the database. /// /// - Parameter callback: The callback that will be invoked once the DB query /// has completed and results are available, passing an /// optional [Fortune] (on success) or RequestError on /// failure. /// public func getFortunes(callback: @escaping ([Fortune]?, RequestError?) -> Void) -> Void { Fortune.findAll { (fortunes, err) in if let err = err { return callback(nil, err) } else { callback(fortunes, nil) } } } /// Get a random row (range 1 to 10,000) from the database. /// /// - Parameter callback: The callback that will be invoked once the DB query /// has completed and results are available, passing an /// optional RandomRow (on success) or RequestError on /// failure. /// public func getRandomRow(callback: @escaping (RandomRow?, RequestError?) -> Void) -> Void { // Select random row from database range let rnd = RandomRow.randomId RandomRow.find(id: rnd, callback) } /// Updates a row of World to a new value. /// /// - Parameter callback: The callback that will be invoked once the DB update /// has completed, passing an optional RequestError if the /// update failed. /// public func updateRow(id: Int, callback: @escaping (RequestError?) -> Void) -> Void { // Generate a random number for this row let row = RandomRow(id: id, randomNumber: RandomRow.randomValue) row.update(id: id) { (resultRow, err) in if let err = err { return callback(err) } else { callback(nil) } } } /// Get `count` random rows from the database, and pass the resulting array /// to a completion handler (or a RequestError, in the event that a row could /// not be retrieved). /// /// - Parameter count: The number of rows to retrieve /// - Parameter result: The intermediate result array being built /// - Parameter completion: The closure to invoke with the result array, or error /// public func getRandomRows(count: Int, result: [RandomRow] = [], completion: @escaping ([RandomRow]?, RequestError?) -> Void) { if count > 0 { // Select random row from database range RandomRow.find(id: RandomRow.randomId) { (resultRow, err) in if let resultRow = resultRow { var result = result result.append(resultRow) getRandomRows(count: count-1, result: result, completion: completion) } else { if let err = err { completion(nil, err) } else { fatalError("Unexpected: result and error both nil") } } } } else { completion(result, nil) } } /// A parallel version of `getRandomRows` that invokes each get in parallel, builds an /// array of results and waits for each get to complete before returning. /// /// - Parameter count: The number of rows to retrieve /// - Parameter completion: The closure to invoke with the result array, or error /// public func getRandomRowsParallel(count: Int, completion: @escaping ([RandomRow]?, RequestError?) -> Void) { var results: [RandomRow] = [] guard count > 0 else { return completion(results, nil) } // Used to protect result array from concurrent modification let updateLock = DispatchSemaphore(value: 1) // Execute each query. Each callback will append its result to `results` for _ in 1...count { RandomRow.find(id: RandomRow.randomId) { (resultRow, err) in guard let resultRow = resultRow else { Log.error("\(err ?? .internalServerError)") completion(nil, err ?? .internalServerError) return } updateLock.wait() results.append(resultRow) if results.count == count { completion(results, nil) } updateLock.signal() } } } /// Update and retrieve `count` random rows from the database, and pass the /// resulting array to a completion handler (or a RequestError, in the event /// that a row could not be retrieved or updated). /// /// - Parameter count: The number of rows to retrieve /// - Parameter result: The intermediate result array being built /// - Parameter completion: The closure to invoke with the result array, or error /// public func updateRandomRows(count: Int, result: [RandomRow] = [], completion: @escaping ([RandomRow]?, RequestError?) -> Void) { if count > 0 { // Select random row from database range RandomRow.find(id: RandomRow.randomId) { (resultRow, err) in if let resultRow = resultRow { var result = result let row = RandomRow(id: resultRow.id, randomNumber: RandomRow.randomValue) row.update(id: row.id) { (resultRow, err) in if let resultRow = resultRow { result.append(resultRow) updateRandomRows(count: count-1, result: result, completion: completion) } else { completion(nil, err) } } } else { if let err = err { completion(nil, err) } else { fatalError("Unexpected: result and error both nil") } } } } else { completion(result, nil) } } /// A parallel version of `updateRandomRows` that invokes each get/update operation /// in parallel, builds an array of results and waits for each get to complete before /// returning. /// /// - Parameter count: The number of rows to retrieve /// - Parameter completion: The closure to invoke with the result array, or error /// public func updateRandomRowsParallel(count: Int, completion: @escaping ([RandomRow]?, RequestError?) -> Void) { var results: [RandomRow] = [] guard count > 0 else { return completion(results, nil) } // Used to protect result array from concurrent modification let updateLock = DispatchSemaphore(value: 1) // Execute each query. Each callback will append its result to `results` for _ in 1...count { RandomRow.find(id: RandomRow.randomId) { (resultRow, err) in guard let resultRow = resultRow else { Log.error("\(err ?? .internalServerError)") completion(nil, err ?? .internalServerError) return } let row = RandomRow(id: resultRow.id, randomNumber: RandomRow.randomValue) row.update(id: row.id) { (resultRow, err) in if let resultRow = resultRow { updateLock.wait() results.append(resultRow) if results.count == count { completion(results, nil) } updateLock.signal() } else { Log.error("\(err ?? .internalServerError)") completion(nil, err ?? .internalServerError) return } } } } }
bsd-3-clause
b4eb59be51c243ae853868be84ac6c5a
36.950673
129
0.602151
4.569654
false
false
false
false
edx/edx-app-ios
Source/ValuePropComponentView.swift
1
9114
// // ValuePropMessageView.swift // edX // // Created by Muhammad Umer on 08/12/2020. // Copyright © 2020 edX. All rights reserved. // import Foundation protocol ValuePropMessageViewDelegate: AnyObject { func showValuePropDetailView() func didTapUpgradeCourse(upgradeView: ValuePropComponentView) } class ValuePropComponentView: UIView { typealias Environment = OEXStylesProvider & DataManagerProvider & OEXAnalyticsProvider weak var delegate: ValuePropMessageViewDelegate? private let imageSize: CGFloat = 20 private lazy var container = UIView() private lazy var titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() private lazy var messageLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() private lazy var upgradeButton: CourseUpgradeButtonView = { let upgradeButton = CourseUpgradeButtonView() upgradeButton.tapAction = { [weak self] in self?.upgradeCourse() } return upgradeButton }() private var showingMore: Bool = false private lazy var showMoreLessButton: UIButton = { let button = UIButton() button.setAttributedTitle(showMorelessButtonStyle.attributedString(withText: Strings.ValueProp.showMoreText).addUnderline(), for: .normal) button.oex_addAction({[weak self] (action) in self?.toggleInfoMessagesView() }, for: .touchUpInside) return button }() private let infoMessagesView = ValuePropMessagesView() private lazy var lockImageView = UIImageView() private lazy var titleStyle: OEXMutableTextStyle = { return OEXMutableTextStyle(weight: .bold, size: .small, color: environment.styles.neutralBlackT()) }() private lazy var messageStyle: OEXMutableTextStyle = { return OEXMutableTextStyle(weight: .normal, size: .base, color: environment.styles.neutralXXDark()) }() private lazy var showMorelessButtonStyle: OEXMutableTextStyle = { return OEXMutableTextStyle(weight: .normal, size: .small, color: environment.styles.neutralXXDark()) }() private lazy var course: OEXCourse? = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.course private lazy var pacing: String = { let selfPaced = course?.isSelfPaced ?? false return selfPaced ? "self" : "instructor" }() private let environment: Environment private var courseID: String private var blockID: String init(environment: Environment, courseID: String, blockID: CourseBlockID?) { self.environment = environment self.courseID = courseID self.blockID = blockID ?? "" super.init(frame: .zero) setupViews() setConstraints() setAccessibilityIdentifiers() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() container.addShadow(offset: CGSize(width: 0, height: 2), color: OEXStyles.shared().primaryDarkColor(), radius: 2, opacity: 0.35, cornerRadius: 5) } private func setupViews() { container.backgroundColor = environment.styles.neutralWhiteT() lockImageView.image = Icon.Closed.imageWithFontSize(size: imageSize).image(with: environment.styles.neutralBlackT()) titleLabel.attributedText = titleStyle.attributedString(withText: Strings.ValueProp.assignmentsAreLocked) let attributedMessage = messageStyle.attributedString(withText: Strings.ValueProp.upgradeToAccessGraded) messageLabel.attributedText = attributedMessage.setLineSpacing(8) container.addSubview(titleLabel) container.addSubview(messageLabel) container.addSubview(lockImageView) container.addSubview(showMoreLessButton) container.addSubview(infoMessagesView) container.addSubview(upgradeButton) addSubview(container) guard let course = course, let courseSku = UpgradeSKUManager.shared.courseSku(for: course) else { return } PaymentManager.shared.productPrice(courseSku) { [weak self] price in if let price = price { self?.upgradeButton.setPrice(price) } } } private func setConstraints() { container.snp.makeConstraints { make in make.top.equalTo(self) make.leading.equalTo(self).offset(StandardHorizontalMargin) make.trailing.equalTo(self).inset(StandardHorizontalMargin) make.bottom.equalTo(upgradeButton).offset(StandardVerticalMargin * 2) } lockImageView.snp.makeConstraints { make in make.top.equalTo(StandardVerticalMargin * 2) make.leading.equalTo(container).offset(StandardHorizontalMargin + 3) } titleLabel.snp.makeConstraints { make in make.centerY.equalTo(lockImageView) make.leading.equalTo(lockImageView).offset(imageSize+10) make.trailing.equalTo(container) make.width.equalTo(container) } messageLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(StandardVerticalMargin * 2) make.leading.equalTo(container).offset(StandardHorizontalMargin) make.trailing.equalTo(container).inset(StandardHorizontalMargin) } showMoreLessButton.snp.makeConstraints { make in make.top.equalTo(messageLabel.snp.bottom).offset(StandardVerticalMargin * 2) make.leading.equalTo(messageLabel) } infoMessagesView.snp.remakeConstraints { make in make.top.equalTo(showMoreLessButton.snp.bottom) make.leading.equalTo(container) make.trailing.equalTo(container) make.height.equalTo(0) } upgradeButton.snp.makeConstraints { make in make.leading.equalTo(container).offset(StandardHorizontalMargin) make.trailing.equalTo(container).inset(StandardHorizontalMargin) make.top.equalTo(infoMessagesView.snp.bottom).offset(StandardVerticalMargin * 3) make.height.equalTo(CourseUpgradeButtonView.height) } } private func setAccessibilityIdentifiers() { accessibilityIdentifier = "ValuePropMessageView:view" lockImageView.accessibilityIdentifier = "ValuePropMessageView:image-view-lock" titleLabel.accessibilityIdentifier = "ValuePropMessageView:label-title" messageLabel.accessibilityIdentifier = "ValuePropMessageView:label-message" showMoreLessButton.accessibilityIdentifier = "ValuePropMessageView:show-more-less-button" infoMessagesView.accessibilityIdentifier = "ValuePropMessageView:info-messages-view" upgradeButton.accessibilityIdentifier = "ValuePropMessageView:upgrade-button" } private func toggleInfoMessagesView() { let showingMore = self.showingMore let height = showingMore ? 0 : infoMessagesView.height() let title = showingMore ? Strings.ValueProp.showMoreText : Strings.ValueProp.showLessText self.showingMore = !showingMore trackShowMorelessAnalytics(showingMore: !showingMore) UIView.animate(withDuration: 0.3, animations: { [weak self] in guard let weakSelf = self else { return } weakSelf.showMoreLessButton.setAttributedTitle(weakSelf.showMorelessButtonStyle.attributedString(withText: title).addUnderline(), for: .normal) weakSelf.infoMessagesView.snp.remakeConstraints { make in make.top.equalTo(weakSelf.showMoreLessButton.snp.bottom).offset(StandardVerticalMargin * (showingMore ? 0 : 2)) make.leading.equalTo(weakSelf.container) make.trailing.equalTo(weakSelf.container) make.height.equalTo(height) } weakSelf.layoutIfNeeded() }) } private func upgradeCourse() { delegate?.didTapUpgradeCourse(upgradeView: self) environment.analytics.trackUpgradeNow(with: courseID, blockID: blockID, pacing: pacing) } private func trackShowMorelessAnalytics(showingMore: Bool) { let displayName = showingMore ? AnalyticsDisplayName.ValuePropShowMoreClicked : AnalyticsDisplayName.ValuePropShowLessClicked let eventName = showingMore ? AnalyticsEventName.ValuePropShowMoreClicked : AnalyticsEventName.ValuePropShowLessClicked environment.analytics.trackValuePropShowMoreless(with: displayName, eventName: eventName, courseID: courseID, blockID: blockID, pacing: pacing ) } func updateUpgradeButtonVisibility(visible: Bool) { upgradeButton.updateVisibility(visible: visible) } func startAnimating() { upgradeButton.startAnimating() } func stopAnimating() { upgradeButton.stopAnimating() } }
apache-2.0
aededad77ebe448d95af7cb51b8edfa9
38.969298
155
0.686602
5.246402
false
false
false
false
winslowdibona/TabDrawer
TabDrawer/Classes/TabBar.swift
1
3522
// // TabBar.swift // TabDrawer // // Created by Winslow DiBona on 4/22/16. // Copyright © 2016 expandshare. All rights reserved. // import UIKit public protocol TabBarDelegate { func selectedItem(item : TabBarItem) } public class TabBar: UIView { public var tabDrawerItems : [TabDrawerItem]! public var items : [TabBarItem] = [] public var delegate : TabBarDelegate! public var configuration : TabDrawerConfiguration! convenience public init(tabDrawerItems : [TabDrawerItem], delegate : TabBarDelegate, config : TabDrawerConfiguration?) { self.init(frame : CGRectZero) self.tabDrawerItems = tabDrawerItems self.delegate = delegate self.configuration = config ?? TabDrawerConfiguration.testConfiguration() backgroundColor = configuration.tabBarItemBackgroundColor for item in tabDrawerItems { items.append(TabBarItem(tabDrawerItem: item)) } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } public func setup() { for item in items { addSubview(item) } for i in 0..<items.count { if i == 0 { items[i] <- [ Left(0), Top(0), Bottom(0), Right(0).to(items[i+1], .Left), Width().like(items[i+1]) ] } else if i == items.count - 1 { items[i] <- [ Right(0), Top(0), Bottom(0) ] } else { items[i] <- [ Top(0), Bottom(0), Right(0).to(items[i+1], .Left), Width().like(items[i+1]) ] } } for item in items { item.setup() item.backgroundColor = configuration.tabBarItemBackgroundColor item.titleLabel.font = configuration.tabBarItemTextFont item.titleLabel.textColor = configuration.tabBarItemTextColor item.imageView.colorImage(configuration.tabBarItemIconColor!) item.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedItem(_:)))) } } public func tappedItem(sender : UITapGestureRecognizer) { var count : Int = 0 if let item = sender.view as? TabBarItem { for i in items { if i == item { i.backgroundColor = configuration.tabBarItemSelectedBackgroundColor i.titleLabel.textColor = configuration.tabBarItemSelectedTextColor i.imageView.colorImage(configuration.tabBarItemIconSelectedColor!) delegate.selectedItem(item) } else { i.backgroundColor = configuration.tabBarItemBackgroundColor i.titleLabel.textColor = configuration.tabBarItemTextColor i.imageView.colorImage(configuration.tabBarItemIconColor!) } count += 1 } } } public func setSelectedItem(index : Int) { for i in 0..<items.count { let item = items[i] if index == i { item.backgroundColor = configuration.tabBarItemSelectedBackgroundColor item.titleLabel.textColor = configuration.tabBarItemSelectedTextColor } else { item.backgroundColor = configuration.tabBarItemBackgroundColor item.titleLabel.textColor = configuration.tabBarItemTextColor } } } }
mit
f48eabc04f508c9f9265b0cd06e6f491
36.073684
124
0.597274
4.959155
false
true
false
false
Yatheesan/logTracker
logTracker/Classes/LoggerDelegate.swift
1
898
// // LoggerDelegate.swift // Pods // // Created by Yatheesan Chandreswaran on 3/29/17. // // import Foundation public enum LogLevel : Int { case TRACE = 0 case INFO = 1 case DEBUG = 2 case WARN = 3 case ERROR = 4 case SILENT = 5 } public protocol LoggerDelegate { var logLevel : LogLevel {get set} var isNill : Bool {get set} func trace(message: CVarArg..., function: String? , line: Int , file : String? ) func debug(message: CVarArg..., function: String? , line: Int , file : String? ) func info(message: CVarArg..., function: String? , line: Int , file : String? ) func warning(message: CVarArg..., function: String? , line: Int , file : String? ) func error(message: CVarArg..., function: String? , line: Int , file : String? ) func setLevel(level: LogLevel) }
mit
c93a6f155946231b74e0e0c44dca10c6
19.883721
86
0.584633
3.837607
false
false
false
false
alexbasson/swift-experiment
SwiftExperiment/Services/MovieService.swift
1
1055
import Foundation public class MovieService: MovieServiceInterface { public static let sharedInstance = MovieService(requestProvider: RequestProvider(), jsonClient: JSONClient()) let requestProvider: RequestProvider let jsonClient: JSONClientInterface public init(requestProvider: RequestProvider, jsonClient: JSONClientInterface) { self.requestProvider = requestProvider self.jsonClient = jsonClient } public func getMovies(closure: MovieServiceClosure) { if let request = requestProvider.getMoviesRequest() { jsonClient.sendRequest(request) { (json, error) in if let json = json, moviesJSON = json["movies"] as? [Dictionary<String, AnyObject>] { var movies: [Movie] = [] for movieJSON in moviesJSON { let movie = Movie(dict: movieJSON) movies.append(movie) } closure(movies: movies, error: nil) } else if let error = error { closure(movies: nil, error: error) } } } } }
mit
787de523f02b7b774717d4c073f3ef0a
31.96875
111
0.647393
4.83945
false
false
false
false
aolan/Cattle
CattleKit/CAProgressWidget.swift
1
8678
// // CAProgressWidget.swift // cattle // // Created by lawn on 15/11/5. // Copyright © 2015年 zodiac. All rights reserved. // import UIKit public class CAProgressWidget: UIView { // MARK: - Property /// 单例 static let sharedInstance = CAProgressWidget() /// 黑色背景圆角 static let blackViewRadius: CGFloat = 10.0 /// 黑色背景透明度 static let blackViewAlpha: CGFloat = 0.8 /// 黑色背景边长 let blackViewWH: CGFloat = 100.0 /// 标签高度 let labelHeight: CGFloat = 15.0 /// 间距 let margin: CGFloat = 10.0 /// 控件显示的最长时间 let timeout: Double = 20.0 /// 提示信息展示时间 let shortTimeout: Double = 2.0 /// 动画时间,秒为单位 let animateTime: Double = 0.2 lazy var label: UILabel? = { var tmpLbl = UILabel() tmpLbl.textColor = UIColor.whiteColor() tmpLbl.textAlignment = NSTextAlignment.Center tmpLbl.font = UIFont.systemFontOfSize(12) return tmpLbl }() lazy var detailLabel: UILabel? = { var tmpLbl = UILabel() tmpLbl.textColor = UIColor.whiteColor() tmpLbl.textAlignment = NSTextAlignment.Center tmpLbl.font = UIFont.systemFontOfSize(12) return tmpLbl }() lazy var blackView: UIView? = { var tmpView = UIView() tmpView.backgroundColor = UIColor.blackColor() tmpView.layer.cornerRadius = blackViewRadius tmpView.layer.masksToBounds = true tmpView.alpha = blackViewAlpha return tmpView }() var progressView: UIActivityIndicatorView? = { var tmpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) return tmpView }() // MARK: - Private Methods func dismissLoading(animated:NSNumber, didDissmiss: () -> Void) -> Void{ if superview == nil { return } if animated.boolValue{ UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() didDissmiss() } }else{ removeAllSubViews() removeFromSuperview() didDissmiss() } } func dismissLoading(animated: NSNumber) -> Void{ NSObject.cancelPreviousPerformRequestsWithTarget(self) if superview == nil { return } if animated.boolValue { UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() } }else{ removeAllSubViews() removeFromSuperview() } } func showLoading(inView: UIView?, text: String?, detailText: String?) { //如果已经显示了,先隐藏 if superview != nil{ dismissLoading(NSNumber(bool: false)) } //设置黑色背景和菊花 if inView != nil && blackView != nil && progressView != nil{ alpha = 0 frame = inView!.bounds backgroundColor = UIColor.clearColor() inView?.addSubview(self) blackView?.ca_size(CGSize(width: blackViewWH, height: blackViewWH)) blackView?.ca_center(inView!.ca_center()) addSubview(blackView!) progressView?.ca_center(inView!.ca_center()) addSubview(progressView!) //设置标题 if text != nil && label != nil{ progressView?.ca_addY(-margin) addSubview(label!) label?.frame = CGRect(x: blackView!.ca_minX(), y: progressView!.ca_maxY() + margin, width: blackView!.ca_width(), height: labelHeight) label?.text = text //设置描述 if detailText != nil && detailLabel != nil{ progressView?.ca_addY(-margin) label?.ca_addY(-margin) addSubview(detailLabel!) detailLabel?.frame = CGRect(x: blackView!.ca_minX(), y: label!.ca_maxY() + margin/2.0, width: blackView!.ca_width(), height: labelHeight) detailLabel?.text = detailText } } //显示 UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 1.0 }, completion: { (finished) -> Void in self.progressView?.startAnimating() self.performSelector(Selector("dismissLoading:"), withObject: NSNumber(bool: true), afterDelay: self.timeout) }) } } func dismissMessage(animated: NSNumber) -> Void{ NSObject.cancelPreviousPerformRequestsWithTarget(self) if animated.boolValue{ UIView.animateWithDuration(animateTime, animations: { () -> Void in self.ca_addY(20.0) self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() } }else{ removeAllSubViews() removeFromSuperview() } } func showMessage(inView: UIView?, text: String?) { //如果已经显示了,先隐藏 if superview != nil{ dismissMessage(NSNumber(bool: false)) } if inView != nil && text != nil && blackView != nil && label != nil{ alpha = 0 frame = inView!.bounds backgroundColor = UIColor.clearColor() inView?.addSubview(self) addSubview(blackView!) addSubview(label!) label?.text = text label?.numberOfLines = 2 let attributes = NSDictionary(object: label!.font, forKey: NSFontAttributeName) let size = label?.text?.boundingRectWithSize(CGSize(width: 200, height: 200), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: attributes as? [String : AnyObject], context: nil) label?.frame = CGRect(x: 0, y: 0, width: 200, height: (size?.height)! + 30) label?.ca_center(ca_center()) label?.ca_addY(-20.0) blackView!.frame = label!.frame //显示 UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 1.0 self.label?.ca_addY(20.0) self.blackView!.frame = self.label!.frame }, completion: { (finished) -> Void in self.performSelector(Selector("dismissMessage:"), withObject: NSNumber(bool: true), afterDelay: self.shortTimeout) }) } } // MARK: - Class Methods /** 展示加载框 - parameter inView: 父视图 */ class func loading(inView: UIView?) -> Void { sharedInstance.showLoading(inView, text: nil, detailText: nil) } /** 展示带标题的加载框 - parameter superView: 父视图 - parameter text: 标题内容 */ class func loading(inView: UIView?, text:String?) -> Void { sharedInstance.showLoading(inView, text: text, detailText: nil) } /** 展示带标题和描述的加载框 - parameter superView: 父视图 - parameter text: 标题内容 - parameter detailText: 描述内容 */ class func loading(inView: UIView?, text: String?, detailText: String?) -> Void{ sharedInstance.showLoading(inView, text: text, detailText: detailText) } /** 消息提示【几秒钟自动消失】 - parameter text: 提示信息 */ class func message(text:String?) -> Void{ let window: UIWindow? = UIApplication.sharedApplication().keyWindow sharedInstance.showMessage(window, text: text) } /** 隐藏加载框 */ class func dismiss(didDissmiss: () -> Void) -> Void { sharedInstance.dismissLoading(NSNumber(bool: true), didDissmiss: didDissmiss) } }
mit
3d353cb468d0c7e1ffe538eb1e57ded9
29.907407
206
0.533853
4.857392
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Reporters/EmojiReporter.swift
1
1292
import Foundation public struct EmojiReporter: Reporter { public static let identifier = "emoji" public static let isRealtime = false public var description: String { return "Reports violations in the format that's both fun and easy to read." } public static func generateReport(_ violations: [StyleViolation]) -> String { return violations .group(by: { $0.location.file ?? "Other" }) .sorted(by: { $0.key < $1.key }) .map(report).joined(separator: "\n") } private static func report(for file: String, with violations: [StyleViolation]) -> String { let lines = [file] + violations.sorted { lhs, rhs in guard lhs.severity == rhs.severity else { return lhs.severity > rhs.severity } return lhs.location > rhs.location }.map { violation in let emoji = (violation.severity == .error) ? "⛔️" : "⚠️" let lineString: String if let line = violation.location.line { lineString = "Line \(line): " } else { lineString = "" } return "\(emoji) \(lineString)\(violation.reason)" } return lines.joined(separator: "\n") } }
mit
937da56ae78aea78ea9591a114c5adb5
34.666667
95
0.558411
4.618705
false
false
false
false
ghodeaniket/CityList_IOS
CityList_IOS/CityList_IOS/CityManager.swift
1
2129
// // CityManager.swift // CityList_IOS // // Created by Aniket Ghode on 24/06/17. // Copyright © 2017 Aniket Ghode. All rights reserved. // import Foundation // Common access point for getting the cities information to display and search. // The reason I followed Monostate over Singleton because it solves the issue of singular nature of class which is transparent to user of this class. class CityManager { // private static cities which conforms to Monostate Design pattern since same cities vaiable will be available across the application life cycle private static var cities = [City] () private static var filteredCities = [City] () // Helper function to add City to cities array func addCity(city: City) { CityManager.cities.append(city) } // Helper methods for TableView DataSource func getCitiesCount(isFilterEnabled: Bool = false) -> Int { if isFilterEnabled { return CityManager.filteredCities.count } return CityManager.cities.count } func cityAtIndex(index: Int, isFilterEnabled: Bool = false) -> City { if isFilterEnabled { return CityManager.filteredCities[index] } return CityManager.cities[index] } // Helper function to filter list of cities based on whether city name starts with search string or not. func filterCityList(searchText: String) { let predicate = NSPredicate { (city, _) -> Bool in return (city as! City).name.hasPrefix(searchText) } CityManager.filteredCities = (CityManager.cities as NSArray).filtered(using: predicate) as! [City] print(CityManager.filteredCities.count) } // Helper function for unit testing to reset the 'System Under Test' func removeAllCities() { CityManager.cities.removeAll() CityManager.filteredCities.removeAll() } // Sort cities list by cities, country func sortCitiesList() { CityManager.cities.sort(by: { return $0.name < $1.name }) } }
apache-2.0
6bdd4befc6cb207f2c2859801d8985a6
30.294118
149
0.654135
4.537313
false
false
false
false
ZekeSnider/Jared
JaredFramework/Bodies.swift
1
816
// // Bodies.swift // JaredFramework // // Created by Zeke Snider on 2/3/19. // Copyright © 2019 Zeke Snider. All rights reserved. // import Foundation public protocol MessageBody: Codable {} public struct TextBody: MessageBody, Codable { public var message: String public init(_ message: String) { self.message = message } } public struct Attachment: Codable { public var id: Int? public var filePath: String public var mimeType: String? public var fileName: String? public var isSticker: Bool? public init(id: Int, filePath: String, mimeType: String, fileName: String, isSticker: Bool) { self.id = id self.filePath = filePath self.mimeType = mimeType self.fileName = fileName self.isSticker = isSticker } }
apache-2.0
7d1d0ad8055229064c3e5cb0da94ab5d
22.285714
97
0.653988
4.075
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/RedundantDiscardableLetRule.swift
2
4499
// // RedundantDiscardableLetRule.swift // SwiftLint // // Created by Marcelo Fabri on 01/25/17. // Copyright © 2017 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct RedundantDiscardableLetRule: CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "redundant_discardable_let", name: "Redundant Discardable Let", description: "Prefer `_ = foo()` over `let _ = foo()` when discarding a result from a function.", nonTriggeringExamples: [ "_ = foo()\n", "if let _ = foo() { }\n", "guard let _ = foo() else { return }\n", "let _: ExplicitType = foo()" ], triggeringExamples: [ "↓let _ = foo()\n", "if _ = foo() { ↓let _ = bar() }\n" ], corrections: [ "↓let _ = foo()\n": "_ = foo()\n", "if _ = foo() { ↓let _ = bar() }\n": "if _ = foo() { _ = bar() }\n" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(in: file).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "_") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } private func violationRanges(in file: File) -> [NSRange] { let contents = file.contents.bridge() return file.match(pattern: "let\\s+_\\b", with: [.keyword, .keyword]).filter { range in guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else { return false } return !isInBooleanCondition(byteOffset: byteRange.location, dictionary: file.structure.dictionary) && !hasExplicitType(utf16Range: range.location ..< range.location + range.length, fileContents: contents) } } private func isInBooleanCondition(byteOffset: Int, dictionary: [String: SourceKitRepresentable]) -> Bool { guard let offset = dictionary.offset, let byteRange = dictionary.length.map({ NSRange(location: offset, length: $0) }), NSLocationInRange(byteOffset, byteRange) else { return false } if let kind = dictionary.kind.flatMap(StatementKind.init), kind == .if || kind == .guard { let conditionKind = "source.lang.swift.structure.elem.condition_expr" for element in dictionary.elements where element.kind == conditionKind { guard let elementOffset = element.offset, let elementRange = element.length.map({ NSRange(location: elementOffset, length: $0) }), NSLocationInRange(byteOffset, elementRange) else { continue } return true } } for subDict in dictionary.substructure where isInBooleanCondition(byteOffset: byteOffset, dictionary: subDict) { return true } return false } private func hasExplicitType(utf16Range: Range<Int>, fileContents: NSString) -> Bool { guard utf16Range.upperBound != fileContents.length else { return false } let nextUTF16Unit = fileContents.substring(with: NSRange(location: utf16Range.upperBound, length: 1)) return nextUTF16Unit == ":" } }
mit
9d2c4545330262d489cd3bcd783bd986
37.706897
113
0.586192
4.812433
false
false
false
false
nicolastinkl/CardDeepLink
CardDeepLinkKit/CardDeepLinkKit/UIGitKit/Alamofire/ServerTrustPolicy.swift
1
13609
// ServerTrustPolicy.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. - parameter policies: A dictionary of all policies mapped to a particular host. - returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. By default, this method will return the policy that perfectly matches the given host. Subclasses could override this method and implement more complex mapping implementations such as wildcards. - parameter host: The host to use when searching for a matching policy. - returns: The server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. Applications are encouraged to always validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. By validating both the certificate chain and host, certificate pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. By validating both the certificate chain and host, public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `.cer` files. - returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) }.flatten()) for path in paths { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `*.cer` files. - returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. - parameter serverTrust: The server trust to evaluate. - parameter host: The host of the challenge protection space. - returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { /* var isValid = false var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType.unspecified let proceed = SecTrustResultType.proceed isValid = result == unspecified || result == proceed } return isValid */ return true } /* private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType(kSecTrustResultInvalid) let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType(kSecTrustResultUnspecified) let proceed = SecTrustResultType(kSecTrustResultProceed) isValid = result == unspecified || result == proceed } return isValid }*/ // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0) as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
bsd-2-clause
13823b1b60fefb7e9f806a2f7ecf398f
41.126935
121
0.656133
6.112758
false
false
false
false
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev
iOS/Pods/BluemixAppID/Source/BluemixAppID/internal/tokens/OAuthClientImpl.swift
2
1275
import Foundation internal class OAuthClientImpl: OAuthClient { private static let OAUTH_CLIENT = "oauth_client" private static let TYPE = "type" private static let NAME = "name" private static let SOFTWARE_ID = "software_id" private static let SOFTWARE_VERSION = "software_version" private static let DEVICE_ID = "device_id" private static let DEVICE_MODEL = "device_model" private static let DEVICE_OS = "device_os" internal var oauthClient: Dictionary<String, Any>? internal init?(with identityToken: IdentityToken) { self.oauthClient = identityToken.payload[OAuthClientImpl.OAUTH_CLIENT] as? Dictionary<String, Any> } var type: String? { return oauthClient?[OAuthClientImpl.TYPE] as? String } var name: String? { return oauthClient?[OAuthClientImpl.NAME] as? String } var softwareId: String? { return oauthClient?[OAuthClientImpl.SOFTWARE_ID] as? String } var softwareVersion: String? { return oauthClient?[OAuthClientImpl.SOFTWARE_VERSION] as? String } var deviceId: String? { return oauthClient?[OAuthClientImpl.DEVICE_ID] as? String } var deviceModel: String? { return oauthClient?[OAuthClientImpl.DEVICE_MODEL] as? String } var deviceOS: String? { return oauthClient?[OAuthClientImpl.DEVICE_OS] as? String } }
apache-2.0
f86a4e4e7eb6ff29f4e8e803ad2e1048
26.12766
100
0.747451
3.622159
false
false
false
false
petrmanek/revolver
Sources/Date.swift
1
3591
// // Date.swift // Revolver // // Created by Petr Mánek on 30.07.17. // Copyright © 2017 Petr Manek. All rights reserved. // #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C import struct Foundation.Date #elseif os(Linux) import Glibc import Foundation import Swift // Imported from: // https://gist.github.com/DonaldHays/8e5b2831313acfaea86b /// A `TimeInterval` represents a length of time in seconds. public typealias TimeInterval = Double /// A `Date` represents a single point in time. public struct Date: Hashable, Comparable, CustomStringConvertible { // MARK: - // MARK: Public Properties /// The time interval between January 1, 1970 at 0:00:00 UTC and the /// receiver. public var timeIntervalSince1970: TimeInterval /// The time interval between the current point in time and the receiver. public var timeIntervalSinceNow: TimeInterval { return timeIntervalSince(Date()) } public var description: String { return "<Date \(timeIntervalSince1970)>" } public var hashValue: Int { return timeIntervalSince1970.hashValue } // MARK: - // MARK: Lifecycle /// Creates a `Date` the represents the current point in time. public init() { var clock: clock_serv_t = clock_serv_t() var timeSpecBuffer: mach_timespec_t = mach_timespec_t(tv_sec: 0, tv_nsec: 0) host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock) clock_get_time(clock, &timeSpecBuffer) mach_port_deallocate(mach_task_self_, clock) timeIntervalSince1970 = Double(timeSpecBuffer.tv_sec) + Double(timeSpecBuffer.tv_nsec) * 0.000000001 } /// Creates a `Date` representing an interval of time after January 1, 1970 /// at 0:00:00 UTC. Provide a negative value to specify a point in time /// before the epoch. public init(timeIntervalSince1970: TimeInterval) { self.timeIntervalSince1970 = timeIntervalSince1970 } /// Creates a `Date` representing an interval of time after the current /// point in time. Provide a negative value to specify a point in time /// before the current point in time. public init(timeIntervalSinceNow: TimeInterval) { self.timeIntervalSince1970 = Date().timeIntervalSince1970 + timeIntervalSinceNow } // MARK: - // MARK: Public API /// Returns the time interval between the receiver and the specified date. /// The returned value will be positive if the receiver occurs after the /// specified date, and negative if it occurs before. public func timeIntervalSince(date: Date) -> TimeInterval { return timeIntervalSince1970 - date.timeIntervalSince1970 } } public func == (lhs: Date, rhs: Date) -> Bool { return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970 } public func < (lhs: Date, rhs: Date) -> Bool { return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970 } public func + (lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSince1970: lhs.timeIntervalSince1970 + rhs) } public func += (lhs: inout Date, rhs: TimeInterval) { lhs.timeIntervalSince1970 += rhs } public func - (lhs: Date, rhs: Date) -> TimeInterval { return lhs.timeIntervalSince(rhs) } public func - (lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSince1970: lhs.timeIntervalSince1970 - rhs) } public func -= (lhs: inout Date, rhs: TimeInterval) { lhs.timeIntervalSince1970 -= rhs } #endif
mit
80da7353289db4be803c25e762a6d019
30.208696
108
0.676233
4.232311
false
false
false
false
wokalski/Hourglass
Hourglass/Store.swift
1
2008
import RealmSwift import Foundation class Store { init(sideEffect: @escaping SideEffect) { self.sideEffect = sideEffect } let sideEffect: SideEffect // App identity lazy fileprivate(set) var state: State = State.initialState lazy fileprivate(set) var dataSource: DataSource = DataSource(store: self) fileprivate var timer: Timer? // Returns a function which can be used to dispatch actions var dispatch: Dispatch { get { return dispatcher(applicationReducer, storeChanged: { [weak self] state, action in self?.state = state self?.dataSource = DataSource(store: self) self?.sideEffect(state, action) })({ return self.state }) } } func startTimer(_ every: TimeInterval, do block: @escaping () -> Void) { let executor = BlockExecutor(block: block) timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: every, target: executor, selector: #selector(executor.execute), userInfo: nil, repeats: true) } func stopTimer() { timer?.invalidate() timer = nil } } class BlockExecutor { init(block: @escaping () -> Void) { self.block = block } let block: () -> Void @objc func execute() { block() } } extension DataSource { convenience init(store: Store?) { guard let store = store else { self.init(viewModels: [], dispatch: { _ in }) return } let tasks = Array(store.state.tasks.values) let viewModels = tasks.map { task -> TaskCellViewModel in return TaskCellViewModel(task: task, store: store) } self.init(viewModels: viewModels, dispatch: store.dispatch) } }
mit
91fad4b6a0eb6f2e0cdb4d98bf66291e
27.685714
94
0.539343
5.070707
false
false
false
false
makezwl/zhao
Nimble/Expression.swift
80
1402
import Foundation // Memoizes the given closure, only calling the passed // closure once; even if repeat calls to the returned closure internal func memoizedClosure<T>(closure: () -> T) -> (Bool) -> T { var cache: T? return ({ withoutCaching in if (withoutCaching || cache == nil) { cache = closure() } return cache! }) } public struct Expression<T> { internal let _expression: (Bool) -> T? internal let _withoutCaching: Bool public let location: SourceLocation public var cache: T? public init(expression: () -> T?, location: SourceLocation) { self._expression = memoizedClosure(expression) self.location = location self._withoutCaching = false } public init(memoizedExpression: (Bool) -> T?, location: SourceLocation, withoutCaching: Bool) { self._expression = memoizedExpression self.location = location self._withoutCaching = withoutCaching } public func cast<U>(block: (T?) -> U?) -> Expression<U> { return Expression<U>(expression: ({ block(self.evaluate()) }), location: self.location) } public func evaluate() -> T? { return self._expression(_withoutCaching) } public func withoutCaching() -> Expression<T> { return Expression(memoizedExpression: self._expression, location: location, withoutCaching: true) } }
apache-2.0
6a2dfc419f8918962e6ff6a7fe9d8d4a
30.863636
105
0.641227
4.566775
false
false
false
false
marcelvoss/WWDC15-Scholarship
Marcel Voss/Marcel Voss/MapViewer.swift
1
4273
// // MapViewer.swift // Marcel Voss // // Created by Marcel Voß on 18.04.15. // Copyright (c) 2015 Marcel Voß. All rights reserved. // import UIKit import MapKit class MapViewer: UIView { var mapView : MKMapView? var effectView = UIVisualEffectView() var aWindow : UIWindow? var closeButton = UIButton() var constraintY : NSLayoutConstraint? init() { super.init(frame: UIScreen.mainScreen().bounds) aWindow = UIApplication.sharedApplication().keyWindow! } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func show() { self.setupViews() UIView.animateWithDuration(0.4, animations: { () -> Void in self.effectView.alpha = 1 self.closeButton.alpha = 1 }) UIView.animateWithDuration(0.4, delay: 0.4, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.constraintY!.constant = 0 self.layoutIfNeeded() }) { (finished) -> Void in } } func hide() { UIView.animateWithDuration(0.4, animations: { () -> Void in self.effectView.alpha = 0 self.closeButton.alpha = 0 }) { (finished) -> Void in self.mapView!.delegate = nil; self.mapView!.removeFromSuperview(); self.mapView = nil; self.effectView.removeFromSuperview() self.removeFromSuperview() } UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.constraintY!.constant = self.frame.size.height self.layoutIfNeeded() }) { (finished) -> Void in self.mapView?.removeFromSuperview() } } func setupViews () { aWindow?.addSubview(self) let blur = UIBlurEffect(style: UIBlurEffectStyle.Dark) effectView = UIVisualEffectView(effect: blur) effectView.frame = self.frame effectView.alpha = 0 self.addSubview(effectView) closeButton.alpha = 0 closeButton.setTranslatesAutoresizingMaskIntoConstraints(false) closeButton.addTarget(self, action: "hide", forControlEvents: UIControlEvents.TouchUpInside) closeButton.setImage(UIImage(named: "CloseIcon"), forState: UIControlState.Normal) self.addSubview(closeButton) self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -20)) self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20)) // Map mapView?.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(mapView!) self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) constraintY = NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: self.frame.size.height) self.addConstraint(constraintY!) self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0)) var tap = UITapGestureRecognizer(target: self, action: "hide") effectView.addGestureRecognizer(tap) self.layoutIfNeeded() } }
unlicense
96c463a1ff2818953cbc099f818cb438
39.67619
232
0.65137
5.054438
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Me/MeViewController.swift
2
18204
import UIKit import CocoaLumberjack import WordPressShared import Gridicons class MeViewController: UITableViewController, UIViewControllerRestoration { static let restorationIdentifier = "WPMeRestorationID" var handler: ImmuTableViewHandler! static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { return WPTabBarController.sharedInstance().meViewController } // MARK: - Table View Controller override init(style: UITableViewStyle) { super.init(style: style) navigationItem.title = NSLocalizedString("Me", comment: "Me page title") // Need to use `super` to work around a Swift compiler bug // https://bugs.swift.org/browse/SR-3465 super.restorationIdentifier = MeViewController.restorationIdentifier restorationClass = type(of: self) clearsSelectionOnViewWillAppear = false } required convenience init() { self.init(style: .grouped) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(MeViewController.refreshModelWithNotification(_:)), name: NSNotification.Name.HelpshiftUnreadCountUpdated, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() // Preventing MultiTouch Scenarios view.isExclusiveTouch = true ImmuTable.registerRows([ NavigationItemRow.self, BadgeNavigationItemRow.self, ButtonRow.self, DestructiveButtonRow.self ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) WPStyleGuide.configureAutomaticHeightRows(for: tableView) NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.accountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) refreshAccountDetails() WPStyleGuide.configureColors(for: view, andTableView: tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) HelpshiftUtils.refreshUnreadNotificationCount() if splitViewControllerIsHorizontallyCompact { animateDeselectionInteractively() } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Required to update the tableview cell disclosure indicators reloadViewModel() } @objc fileprivate func accountDidChange() { reloadViewModel() // Reload the detail pane if the split view isn't compact if let splitViewController = splitViewController as? WPSplitViewController, let detailViewController = initialDetailViewControllerForSplitView(splitViewController), !splitViewControllerIsHorizontallyCompact { showDetailViewController(detailViewController, sender: self) } } @objc fileprivate func reloadViewModel() { let account = defaultAccount() let loggedIn = account != nil let badgeCount = HelpshiftUtils.isHelpshiftEnabled() ? HelpshiftUtils.unreadNotificationCount() : 0 // Warning: If you set the header view after the table model, the // table's top margin will be wrong. // // My guess is the table view adjusts the height of the first section // based on if there's a header or not. tableView.tableHeaderView = account.map { headerViewForAccount($0) } // After we've reloaded the view model we should maintain the current // table row selection, or if the split view we're in is not compact // then we'll just select the first item in the table. // First, we'll grab the appropriate index path so we can reselect it // after reloading the table let selectedIndexPath = tableView.indexPathForSelectedRow ?? IndexPath(row: 0, section: 0) // Then we'll reload the table view model (prompting a table reload) handler.viewModel = tableViewModel(loggedIn, helpshiftBadgeCount: badgeCount) if !splitViewControllerIsHorizontallyCompact { // And finally we'll reselect the selected row, if there is one tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none) } } fileprivate func headerViewForAccount(_ account: WPAccount) -> MeHeaderView { headerView.displayName = account.displayName headerView.username = account.username headerView.gravatarEmail = account.email return headerView } private var appSettingsRow: NavigationItemRow { let accessoryType: UITableViewCellAccessoryType = (splitViewControllerIsHorizontallyCompact) ? .disclosureIndicator : .none return NavigationItemRow( title: NSLocalizedString("App Settings", comment: "Link to App Settings section"), icon: Gridicon.iconOfType(.phone), accessoryType: accessoryType, action: pushAppSettings()) } fileprivate func tableViewModel(_ loggedIn: Bool, helpshiftBadgeCount: Int) -> ImmuTable { let accessoryType: UITableViewCellAccessoryType = (splitViewControllerIsHorizontallyCompact) ? .disclosureIndicator : .none let myProfile = NavigationItemRow( title: NSLocalizedString("My Profile", comment: "Link to My Profile section"), icon: Gridicon.iconOfType(.user), accessoryType: accessoryType, action: pushMyProfile()) let accountSettings = NavigationItemRow( title: NSLocalizedString("Account Settings", comment: "Link to Account Settings section"), icon: Gridicon.iconOfType(.cog), accessoryType: accessoryType, action: pushAccountSettings()) let notificationSettings = NavigationItemRow( title: NSLocalizedString("Notification Settings", comment: "Link to Notification Settings section"), icon: Gridicon.iconOfType(.bell), accessoryType: accessoryType, action: pushNotificationSettings()) let helpAndSupport = BadgeNavigationItemRow( title: NSLocalizedString("Help & Support", comment: "Link to Help section"), icon: Gridicon.iconOfType(.help), badgeCount: helpshiftBadgeCount, accessoryType: accessoryType, action: pushHelp()) let logIn = ButtonRow( title: NSLocalizedString("Log In", comment: "Label for logging in to WordPress.com account"), action: presentLogin()) let logOut = DestructiveButtonRow( title: NSLocalizedString("Log Out", comment: "Label for logging out from WordPress.com account"), action: confirmLogout(), accessibilityIdentifier: "logOutFromWPcomButton") let wordPressComAccount = NSLocalizedString("WordPress.com Account", comment: "WordPress.com sign-in/sign-out section header title") if loggedIn { return ImmuTable( sections: [ ImmuTableSection(rows: [ myProfile, accountSettings, appSettingsRow, notificationSettings ]), ImmuTableSection(rows: [ helpAndSupport ]), ImmuTableSection( headerText: wordPressComAccount, rows: [ logOut ]) ]) } else { // Logged out return ImmuTable( sections: [ ImmuTableSection(rows: [ appSettingsRow, ]), ImmuTableSection(rows: [ helpAndSupport ]), ImmuTableSection( headerText: wordPressComAccount, rows: [ logIn ]) ]) } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let isNewSelection = (indexPath != tableView.indexPathForSelectedRow) if isNewSelection { return indexPath } else { return nil } } // MARK: - Actions fileprivate func presentGravatarPicker() { WPAppAnalytics.track(.gravatarTapped) let pickerViewController = GravatarPickerViewController() pickerViewController.onCompletion = { [weak self] image in if let updatedGravatarImage = image { self?.uploadGravatarImage(updatedGravatarImage) } self?.dismiss(animated: true, completion: nil) } pickerViewController.modalPresentationStyle = .formSheet present(pickerViewController, animated: true, completion: nil) } fileprivate var myProfileViewController: UIViewController? { guard let account = self.defaultAccount() else { let error = "Tried to push My Profile without a default account. This shouldn't happen" assertionFailure(error) DDLogError(error) return nil } return MyProfileViewController(account: account) } fileprivate func pushMyProfile() -> ImmuTableAction { return { [unowned self] row in if let myProfileViewController = self.myProfileViewController { WPAppAnalytics.track(.openedMyProfile) self.showDetailViewController(myProfileViewController, sender: self) } } } fileprivate func pushAccountSettings() -> ImmuTableAction { return { [unowned self] row in if let account = self.defaultAccount() { WPAppAnalytics.track(.openedAccountSettings) guard let controller = AccountSettingsViewController(account: account) else { return } self.showDetailViewController(controller, sender: self) } } } func pushAppSettings() -> ImmuTableAction { return { [unowned self] row in WPAppAnalytics.track(.openedAppSettings) let controller = AppSettingsViewController() self.showDetailViewController(controller, sender: self) } } func pushNotificationSettings() -> ImmuTableAction { return { [unowned self] row in let controller = NotificationSettingsViewController() self.showDetailViewController(controller, sender: self) } } func pushHelp() -> ImmuTableAction { return { [unowned self] row in let controller = SupportViewController() self.showDetailViewController(controller, sender: self) } } fileprivate func presentLogin() -> ImmuTableAction { return { [unowned self] row in self.tableView.deselectSelectedRowWithAnimation(true) self.promptForLoginOrSignup() } } fileprivate func confirmLogout() -> ImmuTableAction { return { [unowned self] row in let format = NSLocalizedString("Logging out will remove all of @%@’s WordPress.com data from this device.", comment: "Label for logging out from WordPress.com account. The %@ is a placeholder for the user's screen name.") let title = String(format: format, self.defaultAccount()!.username) let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) let cancel = UIAlertAction( title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) let logOut = UIAlertAction( title: NSLocalizedString("Log Out", comment: "Button for confirming logging out from WordPress.com account"), style: .destructive, handler: { [unowned self] _ in self.logOut() }) alert.addAction(cancel) alert.addAction(logOut) self.present(alert, animated: true, completion: nil) self.tableView.deselectSelectedRowWithAnimation(true) } } /// Selects the App Settings row and pushes the App Settings view controller /// public func navigateToAppSettings() { let matchRow: ((ImmuTableRow) -> Bool) = { [weak self] row in if let row = row as? NavigationItemRow { return row.title == self?.appSettingsRow.title } return false } let sections = handler.viewModel.sections if let section = sections.index(where: { $0.rows.contains(where: matchRow) }), let row = sections[section].rows.index(where: matchRow) { let indexPath = IndexPath(row: row, section: section) tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle) handler.tableView(self.tableView, didSelectRowAt: indexPath) } } // MARK: - Notification observers func refreshModelWithNotification(_ notification: Foundation.Notification) { reloadViewModel() } // MARK: - Gravatar Helpers fileprivate func uploadGravatarImage(_ newGravatar: UIImage) { guard let account = defaultAccount() else { return } WPAppAnalytics.track(.gravatarUploaded) gravatarUploadInProgress = true headerView.overrideGravatarImage(newGravatar) let service = GravatarService() service.uploadImage(newGravatar, forAccount: account) { [weak self] error in DispatchQueue.main.async(execute: { self?.gravatarUploadInProgress = false self?.reloadViewModel() }) } } // MARK: - Helpers // FIXME: (@koke 2015-12-17) Not cool. Let's stop passing managed objects // and initializing stuff with safer values like userID fileprivate func defaultAccount() -> WPAccount? { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) let account = service.defaultWordPressComAccount() // Again, ! isn't cool, but let's keep it for now until we refactor the VC // initialization parameters. return account } fileprivate func refreshAccountDetails() { guard let account = defaultAccount() else { return } let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) service.updateUserDetails(for: account, success: { _ in }, failure: { _ in }) } fileprivate func logOut() { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) service.removeDefaultWordPressComAccount() } // MARK: - Private Properties fileprivate var gravatarUploadInProgress = false { didSet { headerView.showsActivityIndicator = gravatarUploadInProgress headerView.isUserInteractionEnabled = !gravatarUploadInProgress } } fileprivate lazy var headerView: MeHeaderView = { let headerView = MeHeaderView() headerView.onGravatarPress = { [weak self] in self?.presentGravatarPicker() } return headerView }() /// Shows an actionsheet with options to Log In or Create a WordPress site. /// This is a temporary stop-gap measure to preserve for users only logged /// into a self-hosted site the ability to create a WordPress.com account. /// fileprivate func promptForLoginOrSignup() { let controller = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet) controller.addActionWithTitle(NSLocalizedString("Log In", comment: "Button title. Tapping takes the user to the login form."), style: .default, handler: { (_) in SigninHelpers.showLoginForJustWPComFromPresenter(self) }) controller.addActionWithTitle(NSLocalizedString("Create a WordPress site", comment: "Button title. Tapping takes the user to a form where they can create a new WordPress site."), style: .default, handler: { (_) in let controller = SignupViewController.controller() let navController = NUXNavigationController(rootViewController: controller) self.present(navController, animated: true, completion: nil) }) controller.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Cancel")) controller.modalPresentationStyle = .popover present(controller, animated: true, completion: nil) if let presentationController = controller.popoverPresentationController, let cell = tableView.visibleCells.last { presentationController.permittedArrowDirections = .any presentationController.sourceView = cell presentationController.sourceRect = cell.bounds } } } extension MeViewController: WPSplitViewControllerDetailProvider { func initialDetailViewControllerForSplitView(_ splitView: WPSplitViewController) -> UIViewController? { // If we're not logged in yet, return app settings guard let _ = defaultAccount() else { return AppSettingsViewController() } return myProfileViewController } }
gpl-2.0
43b542c2dbb5def839a9e83c249b9b92
38.398268
233
0.63537
5.884901
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Community/ZSNotification.swift
1
5148
// // ZSNotification.swift // zhuishushenqi // // Created by yung on 2019/7/7. // Copyright © 2019 QS. All rights reserved. // import UIKit import HandyJSON enum MsgType:String,HandyJSONEnum { case none = "" case postPush = "post_push" case commentReply = "comment_reply" case commentLike = "comment_like" var image:UIImage? { switch self { case .postPush: return UIImage(named: "personal_icon_topic_14_14_14x14_") case .commentReply: return UIImage(named: "personal_icon_reply_14_14_14x14_") case .commentLike: return UIImage(named: "personal_icon_reply_14_14_14x14_") default: return nil } } } struct ZSNotification:HandyJSON { var _id:String = "" var type:MsgType = .postPush var post:ZSNotificationPost? var title:String = "" var trigger:ZSNotificationTrigger? var comment:ZSNotificationComment? var myComment:ZSNotificationMyComment? var deleted:Bool = false var created:String = "" } struct ZSNotificationPost:HandyJSON { var _id:String = "" var type:UserType = .normal var title:String = "" } struct ZSNotificationTrigger:HandyJSON { var _id:String = "" var avatar:String = "" var nickname:String = "" var type:UserType = .normal var lv:Int = 0 var gender:String = "" } struct ZSNotificationComment:HandyJSON { var _id:String = "" var content:String = "" var floor:Int = 0 } struct ZSNotificationMyComment:HandyJSON { var _id:String = "" var content:String = "" } //{ // "notifications": [{ // "_id": "5c9df5ba113ca53246a60349", // "type": "post_push", // "post": { // "_id": "5c9df54461465a4c4605170a", // "type": "normal", // "title": "【好消息】追书喜提晋江,各路大神文应有尽有,万本精品同步更新中!" // }, // "title": "【好消息】晋江掌阅好书来了!各路大神文应有尽有,万本精品同步更新中!", // "trigger": null, // "comment": null, // "myComment": null, // "deleted": false, // "created": "2019-03-29T10:38:50.298Z" // }, { // "_id": "5c4151669cb008ec1e0a730d", // "type": "comment_reply", // "post": { // "_id": "5c3fffd1b250154e3737ad54", // "type": "normal", // "title": "〔推书〕:读书人不得不看的三本优质网文!😉(含书评)" // }, // "user": "57ac9879c12b61e826bd7221", // "myComment": { // "_id": "5c4130cc18dd9c1c65086261", // "content": "可以\\n不错哟" // }, // "comment": { // "_id": "5c4151669cb008ec1e0a730c", // "content": "谢谢💓", // "floor": 26 // }, // "trigger": { // "_id": "57d9fa98d466c43c346612bf", // "avatar": "/avatar/5b/4c/5b4c8db957f7db769e251fff6681f68c", // "nickname": "ઇGodfatherଓ", // "type": "normal", // "lv": 10, // "gender": "female" // }, // "deleted": false, // "created": "2019-01-18T04:09:10.000Z" // }, { // "_id": "5be71c0b2b6cdd1000ef8bcc", // "type": "comment_reply", // "post": { // "_id": "5be29607474e10bd576ec1e4", // "type": "normal", // "title": "随便画画" // }, // "user": "57ac9879c12b61e826bd7221", // "myComment": { // "_id": "5be70b63d0074f1000171921", // "content": "测试下评论,没有做超链接的展示" // }, // "comment": { // "_id": "5be71c0b2b6cdd1000ef8bcb", // "content": "什么鬼◑▂◑◐▂◐", // "floor": 24 // }, // "trigger": { // "_id": "5addba11c127e26e7ef59051", // "avatar": "/avatar/d0/ee/d0ee266d66821762d950a8096aaa8548", // "nickname": "七月殇", // "type": "normal", // "lv": 7, // "gender": "male" // }, // "deleted": false, // "created": "2018-11-10T17:57:31.000Z" // }, { // "_id": "5be4237d7ccde0c779bbbc6d", // "type": "comment_reply", // "post": { // "_id": "5be29607474e10bd576ec1e4", // "type": "normal", // "title": "随便画画" // }, // "user": "57ac9879c12b61e826bd7221", // "myComment": { // "_id": "5be41fa3acc7d9350a427903", // "content": "试试" // }, // "comment": { // "_id": "5be4237d7ccde0c779bbbc6c", // "content": "什么", // "floor": 16 // }, // "trigger": { // "_id": "5addba11c127e26e7ef59051", // "avatar": "/avatar/d0/ee/d0ee266d66821762d950a8096aaa8548", // "nickname": "七月殇", // "type": "normal", // "lv": 7, // "gender": "male" // }, // "deleted": false, // "created": "2018-11-08T11:52:29.000Z" // }, { // "_id": "5bb1b0100e7abeaa7362fd86", // "type": "post_push", // "post": { // "_id": "5baf14726f660bbe4fe5dc36", // "type": "vote", // "title": "【活动】🇨🇳国庆七天乐:红歌大比拼,更多活动豪礼砸不停~【楼层奖励名单已出】" // }, // "title": "[有人@你]🇨🇳喜迎国庆🇨🇳追书七天福利送!最强攻略在这里!", // "trigger": null, // "comment": null, // "myComment": null, // "deleted": false, // "created": "2018-10-01T05:26:40.131Z" // }], // "ok": true //}
mit
98f6aa0817afb7c7c1c23d39b5529699
24.413978
69
0.549609
2.420379
false
false
false
false
society2012/HPZBTV
HPZBTV/HPZBTV/Classes/Home/Controller/HomeViewController.swift
1
3117
// // HomeViewController.swift // HPZBTV // // Created by hupeng on 17/3/21. // Copyright © 2017年 m.zintao. All rights reserved. // import UIKit fileprivate let kTitleViewH :CGFloat = 40 class HomeViewController: UIViewController { /// <#Description#> fileprivate lazy var pageTitleView : ZBPageTitleView = { let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigaitonBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = ZBPageTitleView(frame: titleFrame, titles: titles) titleView.backgroundColor = UIColor.orange titleView.delegate = self return titleView }() fileprivate lazy var pageContengView:PageContentView = {[weak self] in var childVCs = [UIViewController]() for _ in 0..<4{ let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVCs.append(vc) } let contentH = kScreenH - kStatusBarH - kNavigaitonBarH - kTitleViewH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigaitonBarH + kTitleViewH, width: kScreenW, height: contentH) let contentView = PageContentView(frame: contentFrame, childVCs: childVCs, parentViewController: self) return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() self.automaticallyAdjustsScrollViewInsets = false view.addSubview(self.pageTitleView) view.addSubview(pageContengView) pageContengView.delegate = self } } extension HomeViewController{ fileprivate func setupUI(){ setupnNavigationBar() } private func setupnNavigationBar(){ let logoItem = UIBarButtonItem(imageName: "logo") navigationItem.leftBarButtonItem = logoItem let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } extension HomeViewController:ZBPageTitleViewDelegate{ func pageTitleView(pageView: ZBPageTitleView, selectIndex index: Int) { print(index) self.pageContengView.setCurrentIndex(currentIndex: index) } } extension HomeViewController:PageContentViewDelegate{ func pageContentView(content: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { self.pageTitleView.setTitleViewProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
8a7a25694d3400be130f6363b9e1f0b5
30.612245
156
0.660426
4.886435
false
false
false
false
truemetal/vapor-2-heroku-auth-template
Sources/App/Controllers/UserController.swift
1
1586
import Vapor import Fluent import Crypto final class UserController { func index(_ req: Request) throws -> Future<[PublicUser]> { let user = try req.requireAuthenticated(User.self) return try User.query(on: req).filter(\.id != user.requireID()).all().map { try $0.map { try $0.public() } } } func me(_ req: Request) throws -> String { let user = try req.requireAuthenticated(User.self) return user.username } func login(_ req: Request) throws -> Future<AccessToken> { let user = try req.requireAuthenticated(User.self) let token = try AccessToken.create(userID: user.requireID()) return token.save(on: req) } func register(_ req: Request) throws -> Future<SignupResult> { return try req.content.decode(CreateUserRequest.self).flatMap { user in try User.register(username: user.username, password: user.password, on: req).flatMap { user in try AccessToken.create(userID: user.requireID()).save(on: req).map { token in try SignupResult(token: token.token, user: user.public()) } } } } func logout(_ req: Request) throws -> Future<HTTPStatus> { let user = try req.requireAuthenticated(User.self) return try user.tokens.query(on: req).delete().map { .ok } } } // MARK: Content fileprivate struct CreateUserRequest: Content { var username: String var password: String } struct SignupResult: Content { var token: String var user: PublicUser }
mit
6a9b97c52c784ca3023db0fb2c30c9b7
31.367347
116
0.624212
4.098191
false
false
false
false
mightydeveloper/swift
test/decl/func/complete_object_init.swift
9
4069
// RUN: %target-parse-verify-swift // --------------------------------------------------------------------------- // Declaration of complete object initializers and basic semantic checking // --------------------------------------------------------------------------- class A { convenience init(int i: Int) { // expected-note{{convenience initializer is declared here}} self.init(double: Double(i)) } convenience init(float f: Float) { self.init(double: Double(f)) } init(double d: Double) { } convenience init(crazy : A) { self.init(int: 42) } } class OtherA { init(double d: Double, negated: Bool) { // expected-error{{designated initializer for 'OtherA' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}}{{3-3=convenience }} self.init(double: negated ? -d : d) // expected-note{{delegation occurs here}} } init(double d: Double) { } } class DerivesA : A { init(int i: Int) { super.init(int: i) // expected-error{{must call a designated initializer of the superclass 'A'}} } convenience init(string: String) { super.init(double: 3.14159) // expected-error{{convenience initializer for 'DerivesA' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')}} } } struct S { convenience init(int i: Int) { // expected-error{{delegating initializers in structs are not marked with 'convenience'}} self.init(double: Double(i)) } init(double d: Double) { } } class DefaultInitComplete { convenience init() { self.init(string: "foo") } init(string: String) { } } class SubclassDefaultInitComplete : DefaultInitComplete { init() { } } // --------------------------------------------------------------------------- // Inheritance of initializers // --------------------------------------------------------------------------- // inherits convenience initializers class B1 : A { override init(double d: Double) { super.init(double: d) } } func testConstructB1(i: Int, f: Float, d: Double) { let b1a = B1(int: i) let b1b = B1(float: f) let b1c = B1(double: d) var b: B1 = b1a b = b1b b = b1c _ = b } // does not inherit convenience initializers class B2 : A { var s: String init() { s = "hello" super.init(double: 1.5) } } func testConstructB2(i: Int) { var b2a = B2() var b2b = B2(int: i) // expected-error{{extra argument 'int' in call}} var b2: B2 = b2a } // Initializer inheritance can satisfy the requirement for an // @required initializer within a subclass. class Ab1 { required init() { } } class Ab2 : Ab1 { var s: String // Subclasses can use this to satisfy the required initializer // requirement. required convenience init() { // expected-note{{'required' initializer is declared in superclass here}} self.init(string: "default") } init(string s: String) { self.s = s super.init() } } class Ab3 : Ab2 { override init(string s: String) { super.init(string: s) } } class Ab4 : Ab3 { init(int: Int) { super.init(string:"four") } // expected-error{{'required' initializer 'init()' must be provided by subclass of 'Ab2'}} func blah() { } } // Only complete object initializers are allowed in extensions class Extensible { } extension Extensible { init(int i: Int) { // expected-error{{designated initializer cannot be declared in an extension of 'Extensible'; did you mean this to be a convenience initializer?}}{{3-3=convenience }} self.init() } } // <rdar://problem/17785840> protocol Protocol { init(string: String) } class Parent: Protocol { required init(string: String) {} } class Child: Parent { convenience required init(string: String) { self.init(string: "") } } // overriding class Parent2 { init() { } convenience init(int: Int) { self.init() } } class Child2 : Parent2 { convenience init(int: Int) { self.init() } } func testOverride(int: Int) { Child2(int: int) // okay, picks Child2.init // expected-warning{{unused}} }
apache-2.0
5711e7083ec51b86b80a85bf0618c358
22.520231
205
0.608749
3.642793
false
false
false
false
natestedman/ReactiveCocoa
Sources/Tests/Swift/ActionSpec.swift
8
5279
// // ActionSpec.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-12-11. // Copyright (c) 2014 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa class ActionSpec: QuickSpec { override func spec() { describe("Action") { var action: Action<Int, String, NSError>! var enabled: MutableProperty<Bool>! var executionCount = 0 var values: [String] = [] var errors: [NSError] = [] var scheduler: TestScheduler! let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil) beforeEach { executionCount = 0 values = [] errors = [] enabled = MutableProperty(false) scheduler = TestScheduler() action = Action(enabledIf: enabled) { number in return SignalProducer { observer, disposable in executionCount++ if number % 2 == 0 { observer.sendNext("\(number)") observer.sendNext("\(number)\(number)") scheduler.schedule { observer.sendCompleted() } } else { scheduler.schedule { observer.sendFailed(testError) } } } } action.values.observeNext { values.append($0) } action.errors.observeNext { errors.append($0) } } it("should be disabled and not executing after initialization") { expect(action.enabled.value).to(beFalsy()) expect(action.executing.value).to(beFalsy()) } it("should error if executed while disabled") { var receivedError: ActionError<NSError>? action.apply(0).startWithFailed { receivedError = $0 } expect(receivedError).notTo(beNil()) if let error = receivedError { let expectedError = ActionError<NSError>.NotEnabled expect(error == expectedError).to(beTruthy()) } } it("should enable and disable based on the given property") { enabled.value = true expect(action.enabled.value).to(beTruthy()) expect(action.executing.value).to(beFalsy()) enabled.value = false expect(action.enabled.value).to(beFalsy()) expect(action.executing.value).to(beFalsy()) } describe("execution") { beforeEach { enabled.value = true } it("should execute successfully") { var receivedValue: String? action.apply(0).startWithNext { receivedValue = $0 } expect(executionCount).to(equal(1)) expect(action.executing.value).to(beTruthy()) expect(action.enabled.value).to(beFalsy()) expect(receivedValue).to(equal("00")) expect(values).to(equal([ "0", "00" ])) expect(errors).to(equal([])) scheduler.run() expect(action.executing.value).to(beFalsy()) expect(action.enabled.value).to(beTruthy()) expect(values).to(equal([ "0", "00" ])) expect(errors).to(equal([])) } it("should execute with an error") { var receivedError: ActionError<NSError>? action.apply(1).startWithFailed { receivedError = $0 } expect(executionCount).to(equal(1)) expect(action.executing.value).to(beTruthy()) expect(action.enabled.value).to(beFalsy()) scheduler.run() expect(action.executing.value).to(beFalsy()) expect(action.enabled.value).to(beTruthy()) expect(receivedError).notTo(beNil()) if let error = receivedError { let expectedError = ActionError<NSError>.ProducerError(testError) expect(error == expectedError).to(beTruthy()) } expect(values).to(equal([])) expect(errors).to(equal([ testError ])) } } } describe("CocoaAction") { var action: Action<Int, Int, NoError>! beforeEach { action = Action { value in SignalProducer(value: value + 1) } expect(action.enabled.value).to(beTruthy()) expect(action.unsafeCocoaAction.enabled).toEventually(beTruthy()) } #if os(OSX) it("should be compatible with AppKit") { let control = NSControl(frame: NSZeroRect) control.target = action.unsafeCocoaAction control.action = CocoaAction.selector control.performClick(nil) } #elseif os(iOS) it("should be compatible with UIKit") { let control = UIControl(frame: CGRectZero) control.addTarget(action.unsafeCocoaAction, action: CocoaAction.selector, forControlEvents: UIControlEvents.TouchDown) control.sendActionsForControlEvents(UIControlEvents.TouchDown) } #endif it("should generate KVO notifications for enabled") { var values: [Bool] = [] action.unsafeCocoaAction .rac_valuesForKeyPath("enabled", observer: nil) .toSignalProducer() .map { $0! as! Bool } .start(Observer(next: { values.append($0) })) expect(values).to(equal([ true ])) let result = action.apply(0).first() expect(result?.value).to(equal(1)) expect(values).toEventually(equal([ true, false, true ])) } it("should generate KVO notifications for executing") { var values: [Bool] = [] action.unsafeCocoaAction .rac_valuesForKeyPath("executing", observer: nil) .toSignalProducer() .map { $0! as! Bool } .start(Observer(next: { values.append($0) })) expect(values).to(equal([ false ])) let result = action.apply(0).first() expect(result?.value).to(equal(1)) expect(values).toEventually(equal([ false, true, false ])) } } } }
mit
afd13ee5b169172c4beb51b572dfaada
25.661616
123
0.649176
3.73338
false
false
false
false