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
aschwaighofer/swift
test/diagnostics/educational-notes.swift
1
3397
// RUN: not %target-swift-frontend -color-diagnostics -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace // RUN: not %target-swift-frontend -no-color-diagnostics -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace --check-prefix=NO-COLOR // RUN: not %target-swift-frontend -enable-experimental-diagnostic-formatting -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --check-prefix=CHECK-DESCRIPTIVE // A diagnostic with no educational notes let x = 1 + // CHECK:{{.*}}[0merror: expected expression after operator // CHECK-NOT: {{-+$}} // NO-COLOR:{{.*}}error: expected expression after operator // NO-COLOR-NOT: {{-+$}} // A diagnostic with an educational note using supported markdown features extension (Int, Int) {} // CHECK:{{.*}}[0merror: non-nominal type '(Int, Int)' cannot be extended // CHECK-NEXT:extension (Int, Int) {} // CHECK-NEXT:^ ~~~~~~~~~~ // CHECK-NEXT:Nominal Types // CHECK-NEXT:-------------- // CHECK-EMPTY: // CHECK-NEXT:Nominal types documentation content. This is a paragraph // CHECK-EMPTY: // CHECK-NEXT: blockquote // CHECK-NEXT: {{$}} // CHECK-NEXT: - item 1 // CHECK-NEXT: - item 2 // CHECK-NEXT: - item 3 // CHECK-NEXT: {{$}} // CHECK-NEXT: let x = 42 // CHECK-NEXT: if x > 0 { // CHECK-NEXT: print("positive") // CHECK-NEXT: } // CHECK-NEXT: {{$}} // CHECK-NEXT:Type 'MyClass' // CHECK-EMPTY: // CHECK-NEXT:[Swift](swift.org) // CHECK-EMPTY: // CHECK-NEXT:bold italics // CHECK-NEXT:-------------- // CHECK-NEXT:Header 1 // CHECK-NEXT:Header 3 // NO-COLOR:{{.*}}error: non-nominal type '(Int, Int)' cannot be extended // NO-COLOR-NEXT:extension (Int, Int) {} // NO-COLOR-NEXT:^ ~~~~~~~~~~ // NO-COLOR-NEXT:Nominal Types // NO-COLOR-NEXT:-------------- // NO-COLOR-EMPTY: // NO-COLOR-NEXT:Nominal types documentation content. This is a paragraph // NO-COLOR-EMPTY: // NO-COLOR-NEXT: blockquote // NO-COLOR-NEXT: {{$}} // NO-COLOR-NEXT: - item 1 // NO-COLOR-NEXT: - item 2 // NO-COLOR-NEXT: - item 3 // NO-COLOR-NEXT: {{$}} // NO-COLOR-NEXT: let x = 42 // NO-COLOR-NEXT: if x > 0 { // NO-COLOR-NEXT: print("positive") // NO-COLOR-NEXT: } // NO-COLOR-NEXT: {{$}} // NO-COLOR-NEXT:Type 'MyClass' // NO-COLOR-EMPTY: // NO-COLOR-NEXT:[Swift](swift.org) // NO-COLOR-EMPTY: // NO-COLOR-NEXT:bold italics // NO-COLOR-NEXT:-------------- // NO-COLOR-NEXT:Header 1 // NO-COLOR-NEXT:Header 3 // CHECK-DESCRIPTIVE: educational-notes.swift // CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note // CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {} // CHECK-DESCRIPTIVE-NEXT: | ^ error: expected expression after operator // CHECK-DESCRIPTIVE-NEXT: | // CHECK-DESCRIPTIVE: educational-notes.swift // CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note // CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {} // CHECK-DESCRIPTIVE-NEXT: | ~~~~~~~~~~ // CHECK-DESCRIPTIVE-NEXT: | ^ error: non-nominal type '(Int, Int)' cannot be extended // CHECK-DESCRIPTIVE-NEXT: | // CHECK-DESCRIPTIVE-NEXT: Nominal Types // CHECK-DESCRIPTIVE-NEXT: -------------
apache-2.0
c15905f936334f3ddf8a46a608ddd0a6
39.440476
224
0.648808
3.130876
false
false
false
false
sugar2010/arcgis-runtime-samples-ios
FindTaskSample/swift/FindTask/Controllers/ResultsViewController.swift
4
2695
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit class ResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView:UITableView! var results:[NSObject:AnyObject]! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Actions @IBAction func done(sender:AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } //MARK: - table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.results != nil ? self.results.count : 0) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reusableIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(reusableIdentifier) as! UITableViewCell //text is the key at the given indexPath let keyAtIndexPath = Array(self.results.keys)[indexPath.row] as! String cell.textLabel?.text = keyAtIndexPath //detail text is the value associated with the key above if let detailValue: AnyObject = self.results[keyAtIndexPath] { //figure out if the value is a NSDecimalNumber or NSString if detailValue is String { //value is a NSString, just set it cell.detailTextLabel?.text = detailValue as? String } else if detailValue is NSNumber { //value is a NSDecimalNumber, format the result as a double cell.detailTextLabel?.text = String(format: "%.2f", Double(detailValue as! NSNumber)) } else { //not a NSDecimalNumber or a NSString, cell.detailTextLabel?.text = "N/A" } } return cell } }
apache-2.0
1ac6f01eccea7d777de8079754e46988
32.6875
109
0.64564
5.284314
false
false
false
false
vrrathod/scrollableControl
slidingSegments/ViewController.swift
1
3363
// // ViewController.swift // slidingSegments // // Created by vr on 10/26/14. // Copyright (c) 2014 vr. All rights reserved. // import UIKit protocol CollectionViewScroller { func clickedOnButton( path:NSIndexPath ) -> Void; } class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, CollectionViewScroller{ @IBOutlet var swipeLeft: UISwipeGestureRecognizer! @IBOutlet var swipeRight: UISwipeGestureRecognizer! @IBOutlet weak var collectionView: UICollectionView! // MARK: variables let screenSize: CGRect = UIScreen.mainScreen().bounds var currentPath:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0); var items:[String] = ["item a","item b","item c","item d","item e","item f"]//,"item g","item h","item i","item j","item k","item l","item m","item n","item o","item p","item q","item r","item s","item t","item u","item v","item w","item x","item y","item z"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. println(currentPath) self.collectionView.dataSource = self; self.collectionView.delegate = self; self.collectionView.scrollEnabled = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// collection view ds func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell: LeagueCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("LeagueCell", forIndexPath: indexPath) as LeagueCollectionViewCell cell.btn.setTitle(items[indexPath.row], forState: UIControlState.Normal) cell.path = indexPath cell.deleagate = self return cell; } func clickedOnButton(path: NSIndexPath) { if( self.currentPath != path ) { self.currentPath = path } self.collectionView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true) } // content insets func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0.0, left: 100.0, bottom: 0.0, right: 100.0); } @IBAction func swipe(sender: UISwipeGestureRecognizer) { var currentRow = self.currentPath.row; if( sender == self.swipeLeft && currentRow < items.count - 1 ) { // go next var nextPath = self.currentPath.indexPathByRemovingLastIndex().indexPathByAddingIndex(currentRow + 1); clickedOnButton(nextPath); } else if ( sender == self.swipeRight && currentRow > 0 ) { var previousPath = currentPath.indexPathByRemovingLastIndex().indexPathByAddingIndex(currentRow - 1); clickedOnButton(previousPath); } } }
apache-2.0
80280c2fcf4ad3ab26a4722eb4aa8c05
39.518072
263
0.687481
5.072398
false
false
false
false
khoren93/SwiftHub
SwiftHub/Models/Repository.swift
1
10252
// // Repository.swift // SwiftHub // // Created by Khoren Markosyan on 6/30/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // // Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import ObjectMapper struct Repository: Mappable { var archived: Bool? var cloneUrl: String? var createdAt: Date? // Identifies the date and time when the object was created. var defaultBranch = "master" // The Ref name associated with the repository's default branch. var descriptionField: String? // The description of the repository. var fork: Bool? // Identifies if the repository is a fork. var forks: Int? // Identifies the total count of direct forked repositories var forksCount: Int? var fullname: String? // The repository's name with owner. var hasDownloads: Bool? var hasIssues: Bool? var hasPages: Bool? var hasProjects: Bool? var hasWiki: Bool? var homepage: String? // The repository's URL. var htmlUrl: String? var language: String? // The name of the current language. var languageColor: String? // The color defined for the current language. var languages: Languages? // A list containing a breakdown of the language composition of the repository. var license: License? var name: String? // The name of the repository. var networkCount: Int? var nodeId: String? var openIssues: Int? var openIssuesCount: Int? // Identifies the total count of issues that have been opened in the repository. var organization: User? var owner: User? // The User owner of the repository. var privateField: Bool? var pushedAt: String? var size: Int? // The number of kilobytes this repository occupies on disk. var sshUrl: String? var stargazersCount: Int? // Identifies the total count of items who have starred this starrable. var subscribersCount: Int? // Identifies the total count of users watching the repository var updatedAt: Date? // Identifies the date and time when the object was last updated. var url: String? // The HTTP URL for this repository var watchers: Int? var watchersCount: Int? var parentFullname: String? // The parent repository's name with owner, if this is a fork. var commitsCount: Int? // Identifies the total count of the commits var pullRequestsCount: Int? // Identifies the total count of a list of pull requests that have been opened in the repository. var branchesCount: Int? var releasesCount: Int? // Identifies the total count of releases which are dependent on this repository. var contributorsCount: Int? // Identifies the total count of Users that can be mentioned in the context of the repository. var viewerHasStarred: Bool? // Returns a boolean indicating whether the viewing user has starred this starrable. init?(map: Map) {} init() {} init(name: String?, fullname: String?, description: String?, language: String?, languageColor: String?, stargazers: Int?, viewerHasStarred: Bool?, ownerAvatarUrl: String?) { self.name = name self.fullname = fullname self.descriptionField = description self.language = language self.languageColor = languageColor self.stargazersCount = stargazers self.viewerHasStarred = viewerHasStarred owner = User() owner?.avatarUrl = ownerAvatarUrl } init(repo: TrendingRepository) { self.init(name: repo.name, fullname: repo.fullname, description: repo.descriptionField, language: repo.language, languageColor: repo.languageColor, stargazers: repo.stars, viewerHasStarred: nil, ownerAvatarUrl: repo.builtBy?.first?.avatar) } mutating func mapping(map: Map) { archived <- map["archived"] cloneUrl <- map["clone_url"] createdAt <- (map["created_at"], ISO8601DateTransform()) defaultBranch <- map["default_branch"] descriptionField <- map["description"] fork <- map["fork"] forks <- map["forks"] forksCount <- map["forks_count"] fullname <- map["full_name"] hasDownloads <- map["has_downloads"] hasIssues <- map["has_issues"] hasPages <- map["has_pages"] hasProjects <- map["has_projects"] hasWiki <- map["has_wiki"] homepage <- map["homepage"] htmlUrl <- map["html_url"] language <- map["language"] license <- map["license"] name <- map["name"] networkCount <- map["network_count"] nodeId <- map["node_id"] openIssues <- map["open_issues"] openIssuesCount <- map["open_issues_count"] organization <- map["organization"] owner <- map["owner"] privateField <- map["private"] pushedAt <- map["pushed_at"] size <- map["size"] sshUrl <- map["ssh_url"] stargazersCount <- map["stargazers_count"] subscribersCount <- map["subscribers_count"] updatedAt <- (map["updated_at"], ISO8601DateTransform()) url <- map["url"] watchers <- map["watchers"] watchersCount <- map["watchers_count"] parentFullname <- map["parent.full_name"] } func parentRepository() -> Repository? { guard let parentFullName = parentFullname else { return nil } var repository = Repository() repository.fullname = parentFullName return repository } } extension Repository { init(graph: RepositoryQuery.Data.Repository?) { self.init(name: graph?.name, fullname: graph?.nameWithOwner, description: graph?.description, language: graph?.primaryLanguage?.name, languageColor: graph?.primaryLanguage?.color, stargazers: graph?.stargazers.totalCount, viewerHasStarred: graph?.viewerHasStarred, ownerAvatarUrl: graph?.owner.avatarUrl) htmlUrl = graph?.url homepage = graph?.homepageUrl createdAt = graph?.createdAt.toISODate()?.date updatedAt = graph?.updatedAt.toISODate()?.date size = graph?.diskUsage fork = graph?.isFork parentFullname = graph?.parent?.nameWithOwner defaultBranch = graph?.defaultBranchRef?.name ?? "master" subscribersCount = graph?.watchers.totalCount forks = graph?.forks.totalCount openIssuesCount = graph?.issues.totalCount commitsCount = graph?.ref?.target.asCommit?.history.totalCount pullRequestsCount = graph?.pullRequests.totalCount releasesCount = graph?.releases.totalCount contributorsCount = graph?.mentionableUsers.totalCount owner?.login = graph?.owner.login owner?.type = graph?.owner.asOrganization != nil ? UserType.organization: UserType.user languages = Languages(graph: graph?.languages) if languages?.totalCount == 0 { languages = nil } } init(graph: SearchRepositoriesQuery.Data.Search.Node.AsRepository?) { self.init(name: graph?.name, fullname: graph?.nameWithOwner, description: graph?.description, language: graph?.primaryLanguage?.name, languageColor: graph?.primaryLanguage?.color, stargazers: graph?.stargazers.totalCount, viewerHasStarred: graph?.viewerHasStarred, ownerAvatarUrl: graph?.owner.avatarUrl) } init(graph: UserQuery.Data.User.PinnedItem.Node.AsRepository?) { self.init(name: graph?.name, fullname: graph?.nameWithOwner, description: graph?.description, language: graph?.primaryLanguage?.name, languageColor: graph?.primaryLanguage?.color, stargazers: graph?.stargazers.totalCount, viewerHasStarred: graph?.viewerHasStarred, ownerAvatarUrl: graph?.owner.avatarUrl) } init(graph: ViewerQuery.Data.Viewer.PinnedItem.Node.AsRepository?) { self.init(name: graph?.name, fullname: graph?.nameWithOwner, description: graph?.description, language: graph?.primaryLanguage?.name, languageColor: graph?.primaryLanguage?.color, stargazers: graph?.stargazers.totalCount, viewerHasStarred: graph?.viewerHasStarred, ownerAvatarUrl: graph?.owner.avatarUrl) } } extension Repository: Equatable { static func == (lhs: Repository, rhs: Repository) -> Bool { return lhs.fullname == rhs.fullname } } struct RepositorySearch: Mappable { var items: [Repository] = [] var totalCount: Int = 0 var incompleteResults: Bool = false var hasNextPage: Bool = false var endCursor: String? init?(map: Map) {} init() {} init(graph: SearchRepositoriesQuery.Data.Search) { if let repos = graph.nodes?.map({ Repository(graph: $0?.asRepository) }) { items = repos } totalCount = graph.repositoryCount hasNextPage = graph.pageInfo.hasNextPage endCursor = graph.pageInfo.endCursor } mutating func mapping(map: Map) { items <- map["items"] totalCount <- map["total_count"] incompleteResults <- map["incomplete_results"] hasNextPage = items.isNotEmpty } } struct TrendingRepository: Mappable { var author: String? var name: String? var url: String? var descriptionField: String? var language: String? var languageColor: String? var stars: Int? var forks: Int? var currentPeriodStars: Int? var builtBy: [TrendingUser]? var fullname: String? { return "\(author ?? "")/\(name ?? "")" } var avatarUrl: String? { return builtBy?.first?.avatar } init?(map: Map) {} init() {} mutating func mapping(map: Map) { author <- map["author"] name <- map["name"] url <- map["url"] descriptionField <- map["description"] language <- map["language"] languageColor <- map["languageColor"] stars <- map["stars"] forks <- map["forks"] currentPeriodStars <- map["currentPeriodStars"] builtBy <- map["builtBy"] } } extension TrendingRepository: Equatable { static func == (lhs: TrendingRepository, rhs: TrendingRepository) -> Bool { return lhs.fullname == rhs.fullname } }
mit
4dff8f314ece6ec3ad6623061e38d834
39.517787
177
0.656326
4.484252
false
false
false
false
pixelmaid/DynamicBrushes
swift/Palette-Knife/util/PathFunctions.swift
1
4844
// // PathFunctions.swift // DynamicBrushes // // Created by JENNIFER MARY JACOBS on 7/19/17. // Copyright © 2017 pixelmaid. All rights reserved. // import Foundation class PathFitter{ var points = [Point](); var closed = false; init(stroke:Stroke) { var segments = stroke.segments; // Copy over points from path and filter out adjacent duplicates. for i in 0..<segments.count{ //for (var i = 0, prev, l = segments.length; i < l; i++) { let point = segments[i].point; if (i<0 || !(segments[i-1].point == point)) { points.append(point.clone()); } } /* // We need to duplicate the first and last segment when simplifying a // closed path. if (closed) { points.unshift(points[points.length - 1]); points.push(points[1]); // The point previously at index 0 is now 1. } this.closed = closed;*/ } func addCurve(segments:[Segment], curve:[Point])->[Segment] { var prev = segments[segments.count - 1]; prev.setHandleOut(point: curve[1].sub(point: curve[0])); var s = Segment(point: curve[3]); s.setHandleIn(point: curve[2].sub(point:curve[3])); var nSegments = [Segment](); nSegments.append(contentsOf: segments); nSegments.append(s); return nSegments; } // Assign parameter values to digitized points // using relative distances between points. func chordLengthParameterize(first:Int, last:Int) ->[Float]{ var u = [Float](); u.append(0.0) for i in first + 1..<last-1 { u[i - first] = u[i - first - 1] + self.points[i].dist(point:self.points[i - 1]); } let m = last - first; for i in 0..<m-1 { u[i] /= u[m]; } return u; } func fit(error:Float)->[Segment] { var points = self.points; let length = points.count; var segments: [Segment]! if (length > 0) { // To support reducing paths with multiple points in the same place // to one segment: segments = [Segment(point: points[0])]; if (length > 1) { //self.fitCubic(segments:segments, error:error, first:0, last:length - 1, // Left Tangent //tan1:points[1].sub(point: points[0]), // Right Tangent // tan2:points[length - 2].sub(point: points[length - 1])); // Remove the duplicated segments for closed paths again. /*if (this.closed) { segments.shift(); segments.pop(); }*/ } } return segments; } // Fit a Bezier curve to a (sub)set of digitized points /*func fitCubic(segments:[Segment],error:Float,first:Int,last:Int,tan1:Point,tan2:Point)->[Segment]{ var points = self.points; // Use heuristic if region only has two points in it if (last - first == 1) { var pt1 = points[first], pt2 = points[last], dist = pt1.dist(point: pt2) / 3; var curve = [Point](); curve.append(pt1) curve.append(pt1.add(point: Point.normalize(vec:tan1,length:dist))) curve.append(pt2.add(point:Point.normalize(vec:tan2,length:dist))); curve.append(pt2) return self.addCurve(segments: segments,curve:curve); } // Parameterize points, and attempt to fit curve var uPrime = self.chordLengthParameterize(first: first, last: last); var maxError = MathUtil.max(v1: error, v2: error * error); var split:Int; var parametersInOrder = true; // Try 4 iterations for i in 0..<4 { var curve = self.generateBezier(first, last, uPrime, tan1, tan2); // Find max deviation of points to fitted curve var max = self.findMaxError(first, last, curve, uPrime); if (max.error < error && parametersInOrder) { self.addCurve(segments, curve); return; } split = max.index; // If error not too large, try reparameterization and iteration if (max.error >= maxError){ break; } parametersInOrder = this.reparameterize(first, last, uPrime, curve); maxError = max.error; } // Fitting failed -- split at max error point and fit recursively var tanCenter = points[split - 1].subtract(points[split + 1]); this.fitCubic(segments, error, first, split, tan1, tanCenter); this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2); }*/ }
mit
3ce421dbde55c8f786e3b7e26ee214b3
34.874074
104
0.543052
4.009106
false
false
false
false
Boilertalk/VaporFacebookBot
Sources/VaporFacebookBot/Send/FacebookSendButton.swift
1
7067
// // FacebookSendButton.swift // VaporFacebookBot // // Created by Koray Koska on 26/05/2017. // // import Foundation import Vapor public protocol FacebookSendButton: JSONConvertible { static var type: FacebookSendButtonType { get } } public enum FacebookSendButtonType: String { case webUrl = "web_url" case postback = "postback" case phoneNumber = "phone_number" case elementShare = "element_share" } public final class FacebookSendButtonHolder: JSONConvertible { public var button: FacebookSendButton public init(button: FacebookSendButton) { self.button = button } public convenience init(json: JSON) throws { guard let type = try FacebookSendButtonType(rawValue: json.get("type")), let buttonType = FacebookSendApi.shared.registeredButtonTypes[type] else { throw Abort(.badRequest, metadata: "type must be a valid FacebookSendButtonType for FacebookSendButtonHolder") } self.init(button: try buttonType.init(json: json)) } public func makeJSON() throws -> JSON { return try button.makeJSON(); } } public final class FacebookSendURLButton: FacebookSendButton { public static let type: FacebookSendButtonType = .webUrl public var title: String public var url: String public var webviewHeightRatio: FacebookSendWebviewHeightRatio? public var messengerExtensions: Bool? public var fallbackUrl: String? public var webviewShareButton: String? public init( title: String, url: String, webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil, messengerExtensions: Bool? = nil, fallbackUrl: String? = nil, webviewShareButton: String? = nil) { self.title = title self.url = url self.webviewHeightRatio = webviewHeightRatio self.messengerExtensions = messengerExtensions self.fallbackUrl = fallbackUrl self.webviewShareButton = webviewShareButton } public convenience init(json: JSON) throws { let title: String = try json.get("title") let url: String = try json.get("url") var webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil if let w = json["webview_height_ratio"]?.string { webviewHeightRatio = FacebookSendWebviewHeightRatio(rawValue: w) } let messengerExtensions = json["messenger_extensions"]?.bool let fallbackUrl = json["fallback_url"]?.string let webviewShareButton = json["webview_share_button"]?.string self.init(title: title, url: url, webviewHeightRatio: webviewHeightRatio, messengerExtensions: messengerExtensions, fallbackUrl: fallbackUrl, webviewShareButton: webviewShareButton) } public func makeJSON() throws -> JSON { var json = JSON() try json.set("type", type(of: self).type.rawValue) try json.set("title", title) try json.set("url", url) if let webviewHeightRatio = webviewHeightRatio { try json.set("webview_height_ratio", webviewHeightRatio.rawValue) } if let messengerExtensions = messengerExtensions { try json.set("messenger_extensions", messengerExtensions) } if let fallbackUrl = fallbackUrl { try json.set("fallback_url", fallbackUrl) } if let webviewShareButton = webviewShareButton { try json.set("webview_share_button", webviewShareButton) } return json } } public final class FacebookSendPostbackButton: FacebookSendButton { public static let type: FacebookSendButtonType = .postback public var title: String public var payload: String public init(title: String, payload: String) { self.title = title self.payload = payload } public convenience init(json: JSON) throws { let title: String = try json.get("title") let payload: String = try json.get("payload") self.init(title: title, payload: payload) } public func makeJSON() throws -> JSON { var json = JSON() try json.set("type", type(of: self).type.rawValue) try json.set("title", title) try json.set("payload", payload) return json } } public final class FacebookSendCallButton: FacebookSendButton { public static let type: FacebookSendButtonType = .phoneNumber public var title: String public var payload: String /** * Initializes a new instance of FacebookSendCallButton with the given title and payload attributes. * * - parameter title: The title of this button. 20 character limit. * - parameter payload: A valid phone number. Format must have "+" prefix followed by the country code, area code and local number. For example, +16505551234. */ public init(title: String, payload: String) { self.title = title self.payload = payload } public convenience init(json: JSON) throws { let title: String = try json.get("title") let payload: String = try json.get("payload") self.init(title: title, payload: payload) } public func makeJSON() throws -> JSON { var json = JSON() try json.set("type", type(of: self).type.rawValue) try json.set("title", title) try json.set("payload", payload) return json } } public final class FacebookSendShareButton: FacebookSendButton { public static let type: FacebookSendButtonType = .elementShare public var shareContents: FacebookSendAttachmentGenericTemplate? /** * Initializes a new instance of FacebookSendShareButton. * * Please use `shareContents` only if you know exactly what you are doing as there are some limitations * (like for example the maximum number of URL buttons, which is one as of now) which you must follow in order for * the request to work properly. * * See the documentation of `FacebookSendShareButton` for more details: https://developers.facebook.com/docs/messenger-platform/send-api-reference/share-button * * - parameter shareContents: The template which you want to share if it is different from the one this button is attached to. Defaults to nil. */ public init(shareContents: FacebookSendAttachmentGenericTemplate? = nil) { self.shareContents = shareContents } public convenience init(json: JSON) throws { var shareContents: FacebookSendAttachmentGenericTemplate? = nil if let j = json["share_contents"] { shareContents = try FacebookSendAttachmentGenericTemplate(json: j) } self.init(shareContents: shareContents) } public func makeJSON() throws -> JSON { var json = JSON() try json.set("type", type(of: self).type.rawValue) if let shareContents = shareContents { try json.set("share_contents", shareContents.makeJSON()) } return json } } // TODO: Buy Button, Login Button, Logout Button
mit
1b4f8c4cc92acec88dab3619950eb91b
30.690583
189
0.668601
4.60691
false
false
false
false
chenyunguiMilook/VisualDebugger
Sources/VisualDebugger/data/AffineRect.swift
1
2556
// // AffineRect.swift // VisualDebugger // // Created by chenyungui on 2018/3/19. // import Foundation #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif public struct AffineRect { public var v0: CGPoint // top left public var v1: CGPoint // top right public var v2: CGPoint // bottom right public var v3: CGPoint // bottom left public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.v0 = CGPoint(x: x, y: y) self.v1 = CGPoint(x: x+width, y: y) self.v2 = CGPoint(x: x+width, y: y+height) self.v3 = CGPoint(x: x, y: y+height) } public init(v0: CGPoint, v1: CGPoint, v2: CGPoint, v3: CGPoint) { self.v0 = v0 self.v1 = v1 self.v2 = v2 self.v3 = v3 } } extension AffineRect { public static let unit: AffineRect = AffineRect(x: 0, y: 0, width: 1, height: 1) public var bounds: CGRect { return [v0, v1, v2, v3].bounds } public var center: CGPoint { return calculateCenter(v0, v2) } public var angle: CGFloat { return calculateAngle(v0, v1) } public var width: CGFloat { return calculateDistance(v0, v1) } public var height: CGFloat { return calculateDistance(v0, v3) } } public func * (rect: AffineRect, t: CGAffineTransform) -> AffineRect { let v0 = rect.v0.applying(t) let v1 = rect.v1.applying(t) let v2 = rect.v2.applying(t) let v3 = rect.v3.applying(t) return AffineRect(v0: v0, v1: v1, v2: v2, v3: v3) } // MARK: - AffineRect extension AffineRect : Debuggable { public func debug(in coordinate: CoordinateSystem, color: AppColor?) { let rect = self * coordinate.matrix let shape = AppBezierPath() shape.move(to: rect.v0) shape.addLine(to: rect.v1) shape.addLine(to: rect.v2) shape.addLine(to: rect.v3) shape.close() let color = color ?? coordinate.getNextColor().withAlphaComponent(0.2) coordinate.addSublayer(CAShapeLayer(path: shape.cgPath, strokeColor: nil, fillColor: color, lineWidth: 0)) let xPath = AppBezierPath() xPath.move(to: rect.v0) xPath.addLine(to: rect.v1) coordinate.addSublayer(CAShapeLayer(path: xPath.cgPath, strokeColor: .red, fillColor: nil, lineWidth: 1)) let yPath = AppBezierPath() yPath.move(to: rect.v0) yPath.addLine(to: rect.v3) coordinate.addSublayer(CAShapeLayer(path: yPath.cgPath, strokeColor: .green, fillColor: nil, lineWidth: 1)) } }
mit
ca7921d93c8e0d2b08d5821470954344
30.95
115
0.624413
3.332464
false
false
false
false
tsaqib/samples
backgroundExtensionDemo/backgroundExtensionDemo/BackgroundExtension.swift
1
1603
// // BackgroundExtension.swift // backgroundExtensionTest // // Created by Tanzim Saqib on 10/27/15. // Copyright © 2015 Tanzim Saqib. All rights reserved. // import UIKit extension UIViewController { // Any Int value you want the views to be identified enum blurViewEnum: Int { case ID = -999 } func BlurExtraLight(imgView: UIImageView) { Blur(imgView, effectType: UIBlurEffectStyle.ExtraLight) } func BlurLight(imgView: UIImageView) { Blur(imgView, effectType: UIBlurEffectStyle.Light) } func BlurDark(imgView: UIImageView) { Blur(imgView, effectType: UIBlurEffectStyle.Dark) } func BlurReset() { for v in view.subviews { if (v.tag == blurViewEnum.ID.rawValue) { v.removeFromSuperview() } } } func Blur(imgView: UIImageView, effectType: UIBlurEffectStyle) { if !UIAccessibilityIsReduceTransparencyEnabled() { let effect = UIBlurEffect(style: effectType) let effectView = UIVisualEffectView(effect: effect) // Identify these created views with a tag for future reset effectView.tag = blurViewEnum.ID.rawValue effectView.frame = imgView.bounds // if you want the whole view to be blurred, // use view.bounds instead view.addSubview(effectView) } else { self.view.backgroundColor = UIColor.blackColor() } } }
mit
d7420fe6a37f0c62f3dd3d2aec0e1ade
25.716667
92
0.583645
4.959752
false
false
false
false
Aadeshp/APExpandingTextView
Example/APExpandingTextView/ViewController.swift
1
1130
// // ViewController.swift // APExpandingTextView // // Created by aadesh on 08/03/2015. // Copyright (c) 2015 aadesh. All rights reserved. // import UIKit import APExpandingTextView class ViewController: UIViewController, APExpandingTextViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var textView: APExpandingTextView = APExpandingTextView(frame: CGRectMake(self.view.frame.size.width / 2 - 100, 50, 200, 33)) textView.layer.borderColor = UIColor.blackColor().CGColor textView.layer.borderWidth = 1.0 textView.layer.cornerRadius = 5.0 textView._delegate = self self.view.addSubview(textView) } func textViewWillExpand(textView: APExpandingTextView!) { NSLog("WILL EXPAND") } func textViewDidExpand(textView: APExpandingTextView!) { NSLog("DID EXPAND") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3ce1bd86fb982a5bb7b9378d94759939
28.736842
133
0.676991
4.484127
false
false
false
false
dfortuna/theCraic3
theCraic3/Main/New Event/NewEventPicturesTableViewCell.swift
1
6695
// // NewEventPicturesTableViewCell.swift // theCraic3 // // Created by Denis Fortuna on 13/5/18. // Copyright © 2018 Denis. All rights reserved. // import UIKit protocol PicturesProtocol: class { func pictureAdded(sender: NewEventPicturesTableViewCell) } class NewEventPicturesTableViewCell: UITableViewCell { private var currentImageView: Int? private var eventStatus = EventStatus.creatingEvent var eventImages = [String : Data]() weak var delegate: PicturesProtocol? @IBOutlet weak var eventMainImage: UIImageView! @IBOutlet weak var eventImage2: UIImageView! @IBOutlet weak var eventImage3: UIImageView! @IBOutlet weak var eventImage4: UIImageView! @IBOutlet weak var eventImage5: UIImageView! @IBOutlet weak var eventImage6: UIImageView! func updateUI(eventStatus: EventStatus, eventPictures: [String:String]) { eventMainImage.layer.cornerRadius = 10 eventImage2.layer.cornerRadius = 10 eventImage3.layer.cornerRadius = 10 eventImage4.layer.cornerRadius = 10 eventImage5.layer.cornerRadius = 10 eventImage6.layer.cornerRadius = 10 addGesture() if eventStatus == .editingEvent { for (picPosition, picData) in eventPictures { if let eventImage = URL(string: picData) { DispatchQueue.global().async { guard let imagedata = try? Data(contentsOf: eventImage) else { return } DispatchQueue.main.async { switch picPosition { case "Pic_0": self.eventMainImage.image = UIImage(data: imagedata) self.eventMainImage.contentMode = .scaleAspectFill case "Pic_1": self.eventImage2.image = UIImage(data: imagedata) self.eventImage2.contentMode = .scaleAspectFill case "Pic_2": self.eventImage3.image = UIImage(data: imagedata) self.eventImage3.contentMode = .scaleAspectFill case "Pic_3": self.eventImage4.image = UIImage(data: imagedata) self.eventImage4.contentMode = .scaleAspectFill case "Pic_4": self.eventImage5.image = UIImage(data: imagedata) self.eventImage5.contentMode = .scaleAspectFill case "Pic_5": self.eventImage6.image = UIImage(data: imagedata) self.eventImage6.contentMode = .scaleAspectFill default: break } } } } } } } func addGesture() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.chooseEventImage)) eventMainImage.addGestureRecognizer(tapGesture) tapGesture.delegate = self eventMainImage.isUserInteractionEnabled = true eventImage2.addGestureRecognizer(tapGesture) eventImage3.addGestureRecognizer(tapGesture) eventImage4.addGestureRecognizer(tapGesture) eventImage5.addGestureRecognizer(tapGesture) eventImage6.addGestureRecognizer(tapGesture) } @objc func chooseEventImage(gestureRecognizer: UITapGestureRecognizer) { print("tappp") currentImageView = gestureRecognizer.view?.tag let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.present(picker, animated: true, completion: nil) } } extension NewEventPicturesTableViewCell: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let currentImage = currentImageView else { return } var selectedImageFromPicker: UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage { selectedImageFromPicker = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { selectedImageFromPicker = originalImage } if let newImage = selectedImageFromPicker { switch currentImage { case 0: eventMainImage.contentMode = .scaleAspectFill eventMainImage.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_0"] = uploadData } case 1: eventImage2.contentMode = .scaleAspectFill eventImage2.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_1"] = uploadData } case 2: eventImage3.contentMode = .scaleAspectFill eventImage3.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_2"] = uploadData } case 3: eventImage4.contentMode = .scaleAspectFill eventImage4.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_3"] = uploadData } case 4: eventImage5.contentMode = .scaleAspectFill eventImage5.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_4"] = uploadData } case 5: eventImage6.contentMode = .scaleAspectFill eventImage6.image = newImage if let uploadData = UIImagePNGRepresentation(newImage) { eventImages["Pic_5"] = uploadData } default: break } delegate?.pictureAdded(sender: self) } picker.dismiss(animated: true, completion: nil) } }
apache-2.0
27164dd558413abe5ffa5f665484bbe8
42.187097
119
0.567075
5.836094
false
false
false
false
Yoseob/Trevi
Trevi/Library/HttpProtocol.swift
1
14986
// // HttpProtocol.swift // Trevi // // Created by LeeYoseob on 2015. 12. 14.. // Copyright © 2015년 LeeYoseob. All rights reserved. // import Foundation public let CRLF = "\r\n" public let SP = " " public let HT = "\t" public let unreserved = "\\w\\-\\.\\_\\~" public let gen_delims = "\\:\\/\\?\\#\\[\\]\\@" public let sub_delims = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=" public var NewLine = "\r\n" public let HttpProtocol = "HTTP/1.1" public var Access_Control_Allow_Origin = "Access-Control-Allow-Origin" public var Accept_Patch = "Accept-Patch" public var Accept_Ranges = "Accept-Ranges" public var Age = "Age" public var Allow = "Allow" public var Cache_Control = "Cache-Control" public var Connection = "Connection" public var Content_Disposition = "Content-Disposition" public var Content_Encoding = "Content-Encoding" public var Content_Length = "Content-Length" public var Content_Language = "Content-Language" public var Content_Location = "Content-Location" public var Content_MD5 = "Content-MD5" public var Content_Range = "Content-Range" public var Content_Type = "Content-Type" public var Date = "Date" public var Expires = "Expires" public var Last_Modified = "Last-Modified" public var Link = "Link" public var Location = "Location" public var ETag = "ETag" public var Refresh = "Refresh" public var Strict_Transport_Security = "Strict-Transport-Security" public var Transfer_Encoding = "Transfer-Encoding" public var Upgrade = "Upgrade" public var Server = "Server" public enum HttpHeaderType: String { case Access_Control_Allow_Origin = "Access-Control-Allow-Origin" case Accept_Patch = "Accept-Patch" case Accept_Ranges = "Accept-Ranges" case Age = "Age" case Allow = "Allow" case Cache_Control = "Cache-Control" case Connection = "Connection" case Content_Disposition = "Content-Disposition" case Content_Encoding = "Content-Encoding" case Content_Length = "Content-Length" case Content_Language = "Content-Language" case Content_Location = "Content-Location" case Content_MD5 = "Content-MD5" case Content_Range = "Content-Range" case Content_Type = "Content-Type" case Date = "Date" case Expires = "Expires" case Last_Modified = "Last-Modified" case Link = "Link" case Location = "Location" case ETag = "ETag" case Refresh = "Refresh" case Strict_Transport_Security = "Strict-Transport-Security" case Transfer_Encoding = "Transfer-Encoding" case Upgrade = "Upgrade" case Server = "Server" public static let allValues = [ Access_Control_Allow_Origin, Accept_Patch, Accept_Ranges, Age, Allow, Cache_Control, Connection, Content_Disposition, Content_Encoding, Content_Length, Content_Language, Content_Location, Content_MD5, Content_Range, Content_Type, Date, Expires, Last_Modified, Link, Location, ETag, Refresh, Strict_Transport_Security, Transfer_Encoding, Upgrade, Server ] } public enum HTTPMethodType: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" case UNDEFINED = "UNDEFINED" case OPTIONS = "OPTIONS" } public enum StatusCode: Int { func statusString () -> String! { switch self { case .Continue: return "Continue" case .SwitchingProtocols: return "Switching Protocols" case .OK: return "OK" case .Created: return "Created" case .Accepted: return "Accepted" case .NonAuthoritativeInformation: return "Non-Authoritative Information" case .NoContent: return "No Content" case .ResetContent: return "Reset Content" case .MultipleChoices: return "Multiple Choices" case .MovedPermanently: return "Moved Permentantly" case .Found: return "Found" case .SeeOther: return "See Other" case .UseProxy: return "Use Proxy" case .BadRequest: return "Bad Request" case .Unauthorized: return "Unauthorized" case .Forbidden: return "Forbidden" case .NotFound: return "Not Found" case .InternalServerError: return "Internal Server Error" case .BadGateway: return "Bad Gateway" case .ServiceUnavailable: return "Service Unavailable" default: return nil } } case Continue = 100 case SwitchingProtocols = 101 case OK = 200 case Created = 201 case Accepted = 202 case NonAuthoritativeInformation = 203 case NoContent = 204 case ResetContent = 205 case MultipleChoices = 300 case MovedPermanently = 301 case Found = 302 case SeeOther = 303 case NotModified = 304 case UseProxy = 305 case BadRequest = 400 case Unauthorized = 401 case Forbidden = 403 case NotFound = 404 case MethodNotAllowed = 405 case NotAcceptable = 406 case RequestTimeout = 408 case InternalServerError = 500 case BadGateway = 502 case ServiceUnavailable = 503 } /* Content-type and mime-type */ public class Mime { class func type(key: String) -> String { var mType = [ "xfu":"application/x-www-form-urlencoded", "fdt":"multipart/form-data", "css":"text/css", "txt":"text/plain", "json":"application/json", "jpeg":"image/jpeg", "jpg":"image/jpeg", "png":"image/png", "html":"text/html", "mix":"multipart/mixed", "dig":"multipart/digest", "aln":"multipart/alternative", "aif":"audio/x-aiff", "aifc":"audio/x-aiff", "aiff":"audio/x-aiff", "asf":"video/x-ms-asf", "asr":"video/x-ms-asf", "asx":"video/x-ms-asf", "au":"audio/basic", "avi":"video/x-msvideo", "axs":"application/olescript", "bas":"text/plain", "bcpio":"application/x-bcpio", "bin":"application/octet-stream", "bmp":"image/bmp", "c":"text/plain", "cat":"application/vnd.ms-pkiseccat", "cdf":"application/x-netcdf", "cer":"application/x-x509-ca-cert", "class":"application/octet-stream", "clp":"application/x-msclip", "cmx":"image/x-cmx", "cod":"image/cis-cod", "cpio application/x-cpio":"undefined", "crd":"application/x-mscardfile", "crl":"application/pkix-crl", "crt":"application/x-x509-ca-cert", "csh":"application/x-csh", "dcr":"application/x-director", "der":"application/x-x509-ca-cert", "dir":"application/x-director", "dll":"application/x-msdownload", "dms":"application/octet-stream", "doc":"application/msword", "dot":"application/msword", "dvi":"application/x-dvi", "dxr":"application/x-director", "eps":"application/postscript", "etx":"text/x-setext", "evy":"application/envoy", "exe":"application/octet-stream", "fif":"application/fractals", "flr":"x-world/x-vrml", "gif":"image/gif", "gtar":"application/x-gtar", "gz":"application/x-gzip", "hdf":"application/x-hdf", "hlp":"application/winhlp", "hqx":"application/mac-binhex40", "hta":"application/hta", "htc":"text/x-component", "htt":"text/webviewhtml", "ico":"image/x-icon", "ief":"image/ief", "iii":"application/x-iphone", "ins":"application/x-internet-signup", "isp":"application/x-internet-signup", "jfif":"image/pipeg", "mny":"application/x-msmoney", "mht":"message/rfc822", "lsf":"video/x-la-asf", "mhtml":"message/rfc822", "mid":"audio/mid", "mov":"video/quicktime", "m3u":"audio/x-mpegurl", "movie":"video/x-sgi-movie", "mp2":"video/mpeg", "mp3":"audio/mpeg", "mpa":"video/mpeg", "mpe":"video/mpeg", "mpeg":"video/mpeg", "mpv2":"video/mpeg", "mpg":"video/mpeg", "mpp":"application/vnd.ms-project", "ms":"application/x-troff-ms", "msg":"application/vnd.ms-outlook", "mvb":"application/x-msmediaview", "nc":"application/x-netcdf", "nws":"message/rfc822", "acx":"application/internet-property-stream", "ai":"application/postscript", "js":"application/x-javascript", "latex":"application/x-latex", "lha":"application/octet-stream", "lzh":"application/octet-stream", "m13":"application/x-msmediaview", "m14":"application/x-msmediaview", "man":"application/x-troff-man", "mdb":"application/x-msaccess", "me":"application/x-troff-me", "pbm":"image/x-portable-bitmap", "pgm":"image/x-portable-graymap", "pnm":"image/x-portable-anymap", "ppm":"image/x-portable-pixmap", "qt":"video/quicktime", "ra":"audio/x-pn-realaudio", "ram":"audio/x-pn-realaudio", "ras":"image/x-cmu-raster", "rgb":"image/x-rgb", "rmi":"audio/mid", "rtx":"text/richtext", "sct":"text/scriptlet", "snd":"audio/basic", "z":"application/x-compress", "zip":"application/zip", "oda":"application/oda", "p10":"application/pkcs10", "p12":"application/x-pkcs12", "p7b":"application/x-pkcs7-certificates", "p7c":"application/x-pkcs7-mime", "p7m":"application/x-pkcs7-mime", "p7r":"application/x-pkcs7-certreqresp", "p7s":"application/x-pkcs7-signature", "pdf":"application/pdf", "pfx":"application/x-pkcs12", "pko":"application/ynd.ms-pkipko", "pma":"application/x-perfmon", "pmc":"application/x-perfmon", "pml":"application/x-perfmon", "pmr":"application/x-perfmon", "pmw":"application/x-perfmon", "pot":"application/vnd.ms-powerpoint", "pps":"application/vnd.ms-powerpoint", "ppt":"application/vnd.ms-powerpoint", "prf":"application/pics-rules", "ps":"application/postscript", "pub":"application/x-mspublisher", "roff":"application/x-troff", "rtf":"application/rtf", "scd":"application/x-msschedule", "setpay":"application/set-payment-initiation", "setreg":"application/set-registration-initiation", "sh":"application/x-sh", "shar":"application/x-shar", "sit":"application/x-stuffit", "spc":"application/x-pkcs7-certificates", "spl":"application/futuresplash", "src":"application/x-wais-source", "sst":"application/vnd.ms-pkicertstore", "stl":"application/vnd.ms-pkistl", "sv4cpio":"application/x-sv4cpio", "sv4crc":"application/x-sv4crc", "svg":"image/svg+xml", "swf":"application/x-shockwave-flash", "t":"application/x-troff", "tar":"application/x-tar", "tcl":"application/x-tcl", "tex":"application/x-tex", "texi":"application/x-texinfo", "texinfo":"application/x-texinfo", "tgz":"application/x-compressed", "wcm":"application/vnd.ms-works", "wdb":"application/vnd.ms-works", "wks":"application/vnd.ms-works", "wmf":"application/x-msmetafile", "wps":"application/vnd.ms-works", "wri":"application/x-mswrite", "xla":"application/vnd.ms-excel", "xlc":"application/vnd.ms-excel", "xlm":"application/vnd.ms-excel", "xls":"application/vnd.ms-excel", "xlt":"application/vnd.ms-excel", "xlw":"application/vnd.ms-excel", "tif":"image/tiff", "tiff":"image/tiff", "tr":"application/x-troff", "trm":"application/x-msterminal", "tsv":"text/tab-separated-values", "uls":"text/iuls", "ustar":"application/x-ustar", "vcf":"text/x-vcard", "vrml":"x-world/x-vrml", "wav":"audio/x-wav", "wrl":"x-world/x-vrml", "wrz":"x-world/x-vrml", "xaf":"x-world/x-vrml", "xbm":"image/x-xbitmap", "xof":"x-world/x-vrml", "xpm":"image/x-xpixmap", "xwd":"image/x-xwindowdump", ] if let t = mType[key] { return t } return "" } }
apache-2.0
e791d6962cfcfda38fb334ce5eed15b2
36.740554
81
0.488353
4.212258
false
false
false
false
dwestgate/AdScrubber
AdScrubber/ListUpdateStatus.swift
1
2375
// // ListUpdateStatus.swift // AdScrubber // // Created by David Westgate on 12/31/15. // Copyright © 2016 David Westgate // // 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 /// Used to signal the state of blacklist load operations enum ListUpdateStatus: String, Error { case UpdateSuccessful = "Ad Scrubber blocklist successfully updated" case NoUpdateRequired = "List already up-to-date" case NotHTTPS = "Error: link must be https" case InvalidURL = "Supplied URL is invalid" case ServerNotFound = "Unable to contact server" case NoSuchFile = "File not found" case UpdateRequired = "File is available - updating..." case ErrorDownloading = "File download interrupted" case UnexpectedDownloadError = "Unable to download file" case ErrorParsingFile = "Error parsing blocklist" case ErrorSavingToLocalFilesystem = "Unable to save downloaded file" case UnableToReplaceExistingBlockerlist = "Unable to replace existing blocklist" case ErrorSavingParsedFile = "Error saving parsed file" case TooManyEntries = "WARNING: blocklist size exceeds 50,000 entries. If Safari determines the size of the list will adversely impact performance it will ignore the new entries and continue using the rules from the last update." case InvalidJSON = "JSON file does not appear to be in valid Content Blocker format" }
mit
61b772a90e27825e06d17abd02e6dd5e
52.954545
231
0.772115
4.600775
false
false
false
false
CrowdShelf/ios
CrowdShelf/CrowdShelf/Handlers/KeyValueHandler.swift
1
3976
// // LocalDataHandler.swift // CrowdShelf // // Created by Øyvind Grimnes on 26/08/15. // Copyright (c) 2015 Øyvind Grimnes. All rights reserved. // import Foundation /** Predefined file names: - Book - User - Crowd - Shelf - BookDetail */ public struct LocalDataFile { static let Book = "book" static let User = "user" static let Crowd = "crowd" static let Shelf = "shelf" static let BookDetail = "bookDetails" } /** A class reponsible for managing a local key-value storage. :discussion: Files will be automatically created when needed. Initial values can be provided by a file in the main bundle with the same file name and type. */ public class KeyValueHandler { // MARK: - Setters /** Change the value for the provided key in a file - parameter object: object that will be the new value - parameter key: key for which to change the value - parameter fileName: name of the file in which to change the value - returns: Boolean indicatig the success of the operation */ public class func setObject(object : AnyObject?, forKey key: String, inFile fileName: String) -> Bool { var data = self.getDataFromFile(fileName) if object != nil { data[key] = object } else { data.removeValueForKey(key) } return self.setData(data, inFile: fileName) } /** Overwrites all data in a file - parameter fileName: file that will be created or overwritten - returns: Boolean indicatig the success of the operation */ public class func setData(data: [String: AnyObject]?, inFile fileName: String) -> Bool { let plistPath = self.pathToFileInDocumentsDirectory(fileName, ofType: "plist") if data == nil { do { try NSFileManager.defaultManager().removeItemAtPath(plistPath) return true } catch _ { return false } } return (data! as NSDictionary).writeToFile(plistPath, atomically: true) } // MARK: - Getters /** Returns all data found in a file as a dictionary - parameter fileName: file to be read - returns: A dictionary containing the data from the file */ public class func getDataFromFile(fileName: String) -> [String: AnyObject] { let plistPath = self.pathToFileInDocumentsDirectory(fileName, ofType: "plist") if NSFileManager.defaultManager().fileExistsAtPath(plistPath) { return NSDictionary(contentsOfFile: plistPath) as! [String: AnyObject] } else { let bundleFilePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "plist") if bundleFilePath != nil && NSFileManager.defaultManager().fileExistsAtPath(bundleFilePath!) { return NSDictionary(contentsOfFile: bundleFilePath!) as! [String: AnyObject] } } return [String: AnyObject]() } /** Get the value for the provided key in a file - parameter key: key for for the value that will be returned - parameter fileName: name of the file that will be read - returns: An optional object */ public class func getObjectForKey(key: String, fromFile fileName: String) -> AnyObject? { return self.getDataFromFile(fileName)[key] } // MARK: - Helpers /// Returns the path to a specified file in the documents directory private class func pathToFileInDocumentsDirectory(fileName: String, ofType fileType: String) -> String { let documentsPath : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] return "\(documentsPath)/\(fileName).\(fileType)" } }
mit
dc931bb1b1a32e897cbb7ef19a8bfd9c
28.444444
162
0.627831
4.858191
false
false
false
false
mumbler/PReVo-iOS
PoshReVo/Navigaciiloj/HelpaNavigationController.swift
1
3224
// // HelpaNavigationController.swift // PoshReVo // // Created by Robin Hill on 3/11/16. // Copyright © 2016 Robin Hill. All rights reserved. // import Foundation import UIKit /* UINavigationController por montri subajn paghojn kiuj aperas el la suba flanko de la ekrano. Chi tiu Navigation Controller pretigas sian propran navigacian tabulon kun X butono, ktp. */ class HelpaNavigationController : UINavigationController, Stilplena { var subLinio: UIView? override func viewDidLoad() { navigationBar.isTranslucent = false let butonujo = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) let maldekstraButono = UIBarButtonItem(customView: butonujo) let iksoButono = UIButton() iksoButono.setImage(UIImage(named: "pikto_ikso")?.withRenderingMode(.alwaysTemplate), for: .normal) iksoButono.tintColor = UzantDatumaro.stilo.navTintKoloro iksoButono.addTarget(self, action: #selector(HelpaNavigationController.forigiSin), for: .touchUpInside) butonujo.addSubview(iksoButono) iksoButono.frame = CGRect(x: 0, y: 0, width: 30, height: 30) topViewController?.navigationItem.leftBarButtonItem = maldekstraButono efektivigiStilon() } func efektivigiStilon() { navigationBar.barTintColor = UzantDatumaro.stilo.navFonKoloro navigationBar.tintColor = UzantDatumaro.stilo.navTintKoloro navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UzantDatumaro.stilo.navTekstoKoloro] if subLinio == nil { subLinio = UIView() navigationBar.addSubview(subLinio!) } // Por ke la suba linio staru bone post rotacio subLinio?.translatesAutoresizingMaskIntoConstraints = false view.addConstraint(NSLayoutConstraint(item: subLinio!, attribute: .left, relatedBy: .equal, toItem: navigationBar, attribute: .left, multiplier: 1.0, constant: 0.0)) view.addConstraint(NSLayoutConstraint(item: subLinio!, attribute: .right, relatedBy: .equal, toItem: navigationBar, attribute: .right, multiplier: 1.0, constant: 0.0)) view.addConstraint(NSLayoutConstraint(item: subLinio!, attribute: .bottom, relatedBy: .equal, toItem: navigationBar, attribute: .bottom, multiplier: 1.0, constant: 0.0)) subLinio?.addConstraint(NSLayoutConstraint(item: subLinio!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 1.0)) subLinio?.backgroundColor = UzantDatumaro.stilo.SubLinioKoloro for filo in children { if let konforma = filo as? Stilplena { konforma.efektivigiStilon() } } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { subLinio?.isHidden = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + (0.3 * Double(NSEC_PER_SEC)) ) { [weak self] in self?.subLinio?.isHidden = false } } @objc func forigiSin() { dismiss(animated: true, completion: nil) } }
mit
995ef48e5494582717a22e3b44d78ba6
41.973333
180
0.679181
4.15871
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift
2
2549
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i8**, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0), // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] protocol P {} extension Int : P {} struct Value<First : P> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TABLE:%[0-9]+]] = bitcast i8** %2 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_TABLE]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
81fd760cf793713d5b82abbb0b1dcbf6
44.517857
338
0.610828
3.038141
false
false
false
false
trilliwon/TDDByExample
TDDByExample/Model/HashTable.swift
1
2997
public struct HashTable<Key: Hashable, Value> { fileprivate typealias Element = (key: Key, value: Value) fileprivate typealias Bucket = [Element] fileprivate var buckets: [Bucket] fileprivate(set) var count = 0 public init(capacity: Int) { assert(capacity > 0) buckets = .init(repeating: [], count: capacity) } public var isEmpty: Bool { return count == 0 } fileprivate func indexForKey(_ key: Key) -> Int { return abs(key.hashValue) % buckets.count } } // MARK: - Basic operations extension HashTable { public subscript(key: Key) -> Value? { get { return valueForKey(key) } set { if let value = newValue { _ = updateValue(value, forKey: key) } else { _ = removeValueForKey(key) } } } public func valueForKey(_ key: Key) -> Value? { let index = indexForKey(key) for element in buckets[index] { if element.key == key { return element.value } } return nil // key not in hash table } public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { let index = indexForKey(key) // Do we already have this key in the bucket? for (i, element) in buckets[index].enumerated() { if element.key == key { let oldValue = element.value buckets[index][i].value = value return oldValue } } // This key isn't in the bucket yet; add it to the chain. buckets[index].append((key: key, value: value)) count += 1 return nil } public mutating func removeValueForKey(_ key: Key) -> Value? { let index = indexForKey(key) // Find the element in the bucket's chain and remove it. for (i, element) in buckets[index].enumerated() { if element.key == key { buckets[index].remove(at: i) count -= 1 return element.value } } return nil // key not in hash table } public mutating func removeAll() { buckets = .init(repeating: [], count: buckets.count) count = 0 } } // MARK: - Helper methods for inspecting the hash table extension HashTable { public var keys: [Key] { var a = [Key]() for bucket in buckets { for element in bucket { a.append(element.key) } } return a } public var values: [Value] { var a = [Value]() for bucket in buckets { for element in bucket { a.append(element.value) } } return a } } // MARK: - For debugging extension HashTable: CustomStringConvertible { public var description: String { return buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } }.joined(separator: ", ") } } extension HashTable: CustomDebugStringConvertible { public var debugDescription: String { var s = "" for (i, bucket) in buckets.enumerated() { s += "bucket \(i): " + bucket.map { e in "\(e.key) = \(e.value)" }.joined(separator: ", ") + "\n" } return s } }
mit
a8f3d4773c01d8196aa974c3e9986ee2
22.598425
103
0.590924
3.892208
false
false
false
false
3lvis/NetworkActivityIndicator
Demo/DemoTableViewController.swift
1
1856
// // DemoTableViewController.swift // Demo // // Created by Arda Oğul Üçpınar on 7.01.2018. // import UIKit class DemoTableViewController: UITableViewController { struct Option { var activated = false } var dataSource = [Option(), Option(), Option(), Option()] override func viewDidLoad() { super.viewDidLoad() self.title = "Simulated activities" self.tableView.rowHeight = 60 self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) let option = self.dataSource[indexPath.row] cell.textLabel?.text = option.activated ? "Stop activity" : "Run activity" cell.textLabel?.textColor = option.activated ? UIColor.red : UIColor.blue let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicator.hidesWhenStopped = true cell.accessoryView = indicator if option.activated { indicator.startAnimating() } else { indicator.stopAnimating() } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var option = self.dataSource[indexPath.row] option.activated = !option.activated self.dataSource[indexPath.row] = option NetworkActivityIndicator.sharedIndicator.visible = option.activated self.tableView.reloadData() } }
mit
af57c495f51f022e382195b8e1e88476
30.931034
109
0.650108
5.231638
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/PaymentDevice/CommitsApplyer.swift
1
16506
import RxSwift class CommitsApplyer { var apduConfirmOperation: APDUConfirmOperationProtocol var nonApduConfirmOperation: NonAPDUConfirmOperationProtocol var commitStatistics = [CommitStatistic]() private var commits: [Commit]! private let semaphore = DispatchSemaphore(value: 0) private var thread: Thread? private var applyerCompletionHandler: CompletionHandler! private var totalApduCommands = 0 private var appliedApduCommands = 0 private let maxCommitsRetries = 0 private let paymentDevice: PaymentDevice private var syncStorage: SyncStorage private var deviceInfo: Device // rx private let eventsPublisher: PublishSubject<SyncEvent> private var disposeBag = DisposeBag() var isRunning: Bool { return thread?.isExecuting ?? false } typealias CompletionHandler = (_ error: Error?) -> Void // MARK: - Lifecycle init(paymentDevice: PaymentDevice, deviceInfo: Device, eventsPublisher: PublishSubject<SyncEvent>, syncFactory: SyncFactory, syncStorage: SyncStorage) { self.paymentDevice = paymentDevice self.eventsPublisher = eventsPublisher self.syncStorage = syncStorage self.deviceInfo = deviceInfo self.apduConfirmOperation = syncFactory.apduConfirmOperation() self.nonApduConfirmOperation = syncFactory.nonApduConfirmOperation() } // MARK: - Internal Functions func apply(_ commits: [Commit], completion: @escaping CompletionHandler) -> Bool { if isRunning { log.warning("SYNC_DATA: Cannot apply commints, applying already in progress.") return false } self.commits = commits totalApduCommands = 0 appliedApduCommands = 0 for commit in commits { if commit.commitType == CommitType.apduPackage { if let apduCommandsCount = commit.payload?.apduPackage?.apduCommands?.count { totalApduCommands += apduCommandsCount } } } self.applyerCompletionHandler = completion self.thread = Thread(target: self, selector: #selector(CommitsApplyer.processCommits), object: nil) self.thread?.qualityOfService = .utility self.thread?.start() return true } // MARK: - Private Functions @objc private func processCommits() { var commitsApplied = 0 commitStatistics = [] for commit in commits { var errorItr: Error? // retry if error occurred for _ in 0 ..< maxCommitsRetries + 1 { DispatchQueue.global().async { self.processCommit(commit) { (error) -> Void in errorItr = error self.semaphore.signal() } } _ = self.semaphore.wait(timeout: DispatchTime.distantFuture) self.saveCommitStatistic(commit: commit, error: errorItr) // if there is no error than leave retry cycle if errorItr == nil { break } } if let error = errorItr { DispatchQueue.main.async { self.applyerCompletionHandler(error) } return } commitsApplied += 1 eventsPublisher.onNext(SyncEvent(event: .syncProgress, data: ["applied": commitsApplied, "total": commits.count])) } DispatchQueue.main.async { self.applyerCompletionHandler(nil) } } private func processCommit(_ commit: Commit, completion: @escaping CompletionHandler) { guard let commitType = commit.commitType else { log.error("SYNC_DATA: trying to process commit without commitType.") completion(NSError.unhandledError(CommitsApplyer.self)) return } let commitCompletion = { (error: Error?) -> Void in if let deviceId = self.deviceInfo.deviceIdentifier, let commit = commit.commitId { self.saveLastCommitId(deviceIdentifier: deviceId, commitId: commit) } else { log.error("SYNC_DATA: Can't get deviceId or commitId.") } completion(error) } switch commitType { case CommitType.apduPackage: log.verbose("SYNC_DATA: processing APDU commit.") processAPDUCommit(commit, completion: commitCompletion) default: log.verbose("SYNC_DATA: processing non-APDU commit.") processNonAPDUCommit(commit, completion: commitCompletion) } } private func saveLastCommitId(deviceIdentifier: String?, commitId: String?) { if let deviceId = deviceIdentifier, let storedCommitId = commitId { if let setDeviceLastCommitId = self.paymentDevice.deviceInterface.setDeviceLastCommitId, self.paymentDevice.deviceInterface.getDeviceLastCommitId != nil { setDeviceLastCommitId(storedCommitId) } else { self.syncStorage.setLastCommitId(deviceId, commitId: storedCommitId) } } else { log.error("SYNC_DATA: Can't get deviceId or commitId.") } } private func processAPDUCommit(_ commit: Commit, completion: @escaping CompletionHandler) { log.debug("SYNC_DATA: Processing APDU commit: \(commit.commitId ?? "").") guard let apduPackage = commit.payload?.apduPackage else { log.error("SYNC_DATA: trying to process apdu commit without apdu package.") completion(NSError.unhandledError(CommitsApplyer.self)) return } let applyingStartDate = Date().timeIntervalSince1970 if apduPackage.isExpired { log.warning("SYNC_DATA: package ID(\(commit.commitId ?? "nil")) expired. ") apduPackage.state = APDUPackageResponseState.expired apduPackage.executedDuration = 0 apduPackage.executedEpoch = Date().timeIntervalSince1970 // is this error? commit.confirmAPDU { (error) -> Void in completion(error) } return } self.paymentDevice.apduPackageProcessingStarted(apduPackage) { [weak self] (error) in guard error == nil else { completion(error) return } if self?.paymentDevice.executeAPDUPackageAllowed == true { self?.paymentDevice.executeAPDUPackage(apduPackage) { (error) in self?.packageProcessingFinished(commit: commit, apduPackage: apduPackage, state: nil, error: error, applyingStartDate: applyingStartDate) { commitError in completion(commitError) } } } else { self?.applyAPDUPackage(apduPackage, apduCommandIndex: 0, retryCount: 0) { (state, error) in self?.packageProcessingFinished(commit: commit, apduPackage: apduPackage, state: state, error: error, applyingStartDate: applyingStartDate) { commitError in completion(commitError) } } } } } private func packageProcessingFinished(commit: Commit, apduPackage: ApduPackage, state: APDUPackageResponseState?, error: Error?, applyingStartDate: TimeInterval, completion: @escaping CompletionHandler) { let currentTimestamp = Date().timeIntervalSince1970 apduPackage.executedDuration = Int((currentTimestamp - applyingStartDate)*1000) apduPackage.executedEpoch = TimeInterval(currentTimestamp) if state == nil { if error != nil && error as NSError? != nil && (error! as NSError).code == PaymentDevice.ErrorCode.apduErrorResponse.rawValue { log.debug("SYNC_DATA: Got a failed APDU response.") apduPackage.state = APDUPackageResponseState.failed } else if error != nil { // This will catch (error as! NSError).code == PaymentDevice.ErrorCode.apduSendingTimeout.rawValue log.debug("SYNC_DATA: Got failure on apdu.") apduPackage.state = APDUPackageResponseState.error } else { apduPackage.state = APDUPackageResponseState.processed } } else { apduPackage.state = state } var realError: NSError? if apduPackage.state == .notProcessed || apduPackage.state == .error { realError = error as NSError? } self.eventsPublisher.onNext(SyncEvent(event: .apduPackageComplete, data: ["package": apduPackage, "error": realError ?? "nil"])) self.paymentDevice.apduPackageProcessingFinished(apduPackage, completion: { (error) in guard error == nil else { completion(error) return } log.debug("SYNC_DATA: Processed APDU commit (\(commit.commitId ?? "nil")) with state: \(apduPackage.state?.rawValue ?? "nil") and error: \(String(describing: realError)).") if apduPackage.state == .notProcessed { completion(realError) } else { self.apduConfirmOperation.startWith(commit: commit).subscribe { (e) in switch e { case .completed: completion(realError) case .error(let error): log.debug("SYNC_DATA: Apdu package confirmed with error: \(error).") completion(error) case .next: break } }.disposed(by: self.disposeBag) } }) } private func processNonAPDUCommit(_ commit: Commit, completion: @escaping CompletionHandler) { guard let commitType = commit.commitType else { return } let applyingStartDate = Date().timeIntervalSince1970 self.paymentDevice.processNonAPDUCommit(commit: commit) { [weak self] (state, error) in let currentTimestamp = Date().timeIntervalSince1970 commit.executedDuration = Int((currentTimestamp - applyingStartDate) * 1000) self?.nonApduConfirmOperation.startWith(commit: commit, result: state ?? .failed).subscribe { (e) in switch e { case .completed: guard state != .failed else { log.error("SYNC_DATA: received failed state for processing non apdu commit.") completion(error ?? NSError.unhandledError(CommitsApplyer.self)) return } let eventData = ["commit": commit] self?.eventsPublisher.onNext(SyncEvent(event: .commitProcessed, data: eventData)) var syncEvent: SyncEvent? switch commitType { case .creditCardCreated: syncEvent = SyncEvent(event: .cardAdded, data: eventData) case .creditCardDeleted: syncEvent = SyncEvent(event: .cardDeleted, data: eventData) case .creditCardActivated: syncEvent = SyncEvent(event: .cardActivated, data: eventData) case .creditCardDeactivated: syncEvent = SyncEvent(event: .cardDeactivated, data: eventData) case .creditCardReactivated: syncEvent = SyncEvent(event: .cardReactivated, data: eventData) case .setDefaultCreditCard: syncEvent = SyncEvent(event: .setDefaultCard, data: eventData) case .resetDefaultCreditCard: syncEvent = SyncEvent(event: .resetDefaultCard, data: eventData) case .apduPackage: log.warning("SYNC_DATA: Processed APDU package inside nonapdu handler.") case .creditCardProvisionFailed: syncEvent = SyncEvent(event: .cardProvisionFailed, data: eventData) case .creditCardProvisionSuccess: syncEvent = SyncEvent(event: .cardProvisionSuccess, data: eventData) case .creditCardMetaDataUpdated: syncEvent = SyncEvent(event: .cardMetadataUpdated, data: eventData) case .unknown: log.warning("SYNC_DATA: Received new (unknown) commit type - \(commit.commitTypeString ?? "").") } if let syncEvent = syncEvent { self?.eventsPublisher.onNext(syncEvent) } completion(nil) case .error(let error): log.debug("SYNC_DATA: non APDU commit confirmed with error: \(error).") completion(error) case .next: break } }.disposed(by: self?.disposeBag ?? DisposeBag()) } } private func applyAPDUPackage(_ apduPackage: ApduPackage, apduCommandIndex: Int, retryCount: Int, completion: @escaping (_ state: APDUPackageResponseState?, _ error: Error?) -> Void) { let isFinished = (apduPackage.apduCommands?.count)! <= apduCommandIndex guard !isFinished else { completion(apduPackage.state, nil) return } var mutableApduCommand = apduPackage.apduCommands![apduCommandIndex] self.paymentDevice.executeAPDUCommand(mutableApduCommand) { [weak self] (apduCommand, state, error) in apduPackage.state = state if let apduCommand = apduCommand { mutableApduCommand = apduCommand } guard error == nil else { completion(state, error) return } self?.appliedApduCommands += 1 log.info("SYNC_DATA: PROCESSED \(self?.appliedApduCommands ?? 0)/\(self?.totalApduCommands ?? 0) COMMANDS") self?.eventsPublisher.onNext(SyncEvent(event: .apduCommandsProgress, data: ["applied": self?.appliedApduCommands ?? 0, "total": self?.totalApduCommands ?? 0])) //process next self?.applyAPDUPackage(apduPackage, apduCommandIndex: apduCommandIndex + 1, retryCount: 0, completion: completion) } } private func saveCommitStatistic(commit: Commit, error: Error?) { guard let commitType = commit.commitType else { let statistic = CommitStatistic(commitId: commit.commitId, total: 0, average: 0, errorDesc: error?.localizedDescription) self.commitStatistics.append(statistic) return } switch commitType { case CommitType.apduPackage: let total = commit.payload?.apduPackage?.executedDuration ?? 0 let commandsCount = commit.payload?.apduPackage?.apduCommands?.count ?? 1 let statistic = CommitStatistic(commitId: commit.commitId, total: total, average: total/commandsCount, errorDesc: error?.localizedDescription) self.commitStatistics.append(statistic) default: let statistic = CommitStatistic(commitId: commit.commitId, total: commit.executedDuration, average: commit.executedDuration, errorDesc: error?.localizedDescription) self.commitStatistics.append(statistic) } } }
mit
1de29c606a0e06d6b31f11f125e23816
42.898936
209
0.562886
5.305689
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Extensions/AVPlayerItemExtensions.swift
1
7937
// // AVPlayerItemExtension.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 4/9/18. // import AVFoundation import MediaPlayer extension AVPlayerItem { public var durationInSeconds: Float { let durationInSeconds = Float(CMTimeGetSeconds(duration)) return !durationInSeconds.isNaN ? durationInSeconds : 1 } public var currentTimeInSeconds: Float { return Float(currentTime().seconds) } public var minTimeString: String { let time = Float64(currentTime().seconds) if durationInSeconds.isHours { return time.formatedTimeInHours } return time.formatedTimeInMinutes } public var maxTimeString: String { let time = Float64(durationInSeconds - currentTimeInSeconds) if durationInSeconds.isHours { return time.formatedTimeInHours } return time.formatedTimeInMinutes } // MARK: - Time public func saveTime() { guard var url = url else { return } url.time = currentTimeInSeconds } public func loadSavedTime() { if let time = url?.time { seek(to: CMTime(seconds: Double(time), preferredTimescale: currentTime().timescale)) } } public func resetTime() { guard var url = url else { return } url.time = 0 } public var url: URL? { if let asset = self.asset as? AVURLAsset { // for normal media, we just return the asset url if AVURLAsset return asset.url } else if self.asset is AVComposition { // for subtitled media, we return the asset url from shared media params return AwesomeMediaManager.shared.mediaParams.url?.url } return nil } // Captions /*public func setCaption(_ caption: AwesomeMediaCaption?, mediaParams: AwesomeMediaParams) { saveTime() var mediaParams = mediaParams mediaParams.currentCaption = caption sharedAVPlayer.pause() if let url = mediaParams.url?.url { AwesomeMediaManager.shared.prepareMedia(withUrl: url) } /*if let composition = self.asset as? AVMutableComposition, let textTrack = composition.tracks(withMediaType: .text).first { composition.removeTrack(textTrack) if let captionUrl = caption?.url.url { AVAsset.configureAsset(for: composition, url: captionUrl, ofType: .text) } }*/ }*/ // Video in background public var isVideo: Bool { for playerItemTrack in tracks { if let assetTrack = playerItemTrack.assetTrack, assetTrack.hasMediaCharacteristic(AVMediaCharacteristic.visual) { return true } } return false } public func playInBackground(_ background: Bool) { for playerItemTrack in tracks { if let assetTrack = playerItemTrack.assetTrack, assetTrack.hasMediaCharacteristic(AVMediaCharacteristic.visual) { // Disable the track. playerItemTrack.isEnabled = !background } } if background { AwesomeMediaPlayerLayer.shared.player = nil // track event if sharedAVPlayer.isPlaying { track(event: .playingInBackground, source: .unknown) } } else { AwesomeMediaPlayerLayer.shared.player = sharedAVPlayer } } // Item public static func item(withUrl url: URL, completion: @escaping (AMAVPlayerItem) -> Void) { urlItem(withUrl: url, completion: completion) } public static func urlItem(withUrl url: URL, completion: @escaping (AMAVPlayerItem) -> Void) { DispatchQueue.global(qos: .background).async { let playerItem = AMAVPlayerItem(url: url) playerItem.selectDefaultSubtitle() // let subtitles = playerItem.tracks(type: .subtitle) // if let selectedSubtitle = playerItem.selected(type: .subtitle) { // print("\(playerItem.select(type: .subtitle, name: selectedSubtitle))") // } //let audio = playerItem.tracks(type: .audio) DispatchQueue.main.async { completion(playerItem) } } } public static func compositionItem(withUrl url: URL, andCaptionUrl subtitleUrl: URL? = nil, completion: @escaping (AMAVPlayerItem) -> Void) { DispatchQueue.global(qos: .background).async { // Create a Mix composition let mixComposition = AVMutableComposition() // Configure Video Track AVAsset.configureAsset(for: mixComposition, url: url, ofType: .video) // Configure Audio Track AVAsset.configureAsset(for: mixComposition, url: url, ofType: .audio) // Configure Caption Track if let subtitleUrl = subtitleUrl { AVAsset.configureAsset(for: mixComposition, url: subtitleUrl, ofType: .text) } // let captionSelectionGroup = AVMediaSelectionGroup() // let option = AVMediaSelectionOption() // option. // DispatchQueue.main.async { completion(AMAVPlayerItem(asset: mixComposition)) } } } } extension AVPlayerItem { enum TrackType { case subtitle case audio /** Return valid AVMediaSelectionGroup is item is available. */ fileprivate func characteristic(item:AVPlayerItem) -> AVMediaSelectionGroup? { let str = self == .subtitle ? AVMediaCharacteristic.legible : AVMediaCharacteristic.audible if item.asset.availableMediaCharacteristicsWithMediaSelectionOptions.contains(str) { return item.asset.mediaSelectionGroup(forMediaCharacteristic: str) } return nil } } func tracks(type: TrackType) -> [String] { if let characteristic = type.characteristic(item: self) { return characteristic.options.map { $0.displayName } } return [String]() } func selected(type: TrackType) -> String? { guard let group = type.characteristic(item: self) else { return nil } let selected = self.selectedMediaOption(in: group) return selected?.displayName } func select(type: TrackType, name: String?) -> Bool { guard let group = type.characteristic(item: self) else { return false } // in case it's nil, it means we are removing the subtitle, so return nil guard let name = name else { self.select(nil, in: group) return true } let matched = group.options.filter({ $0.displayName.lowercased() == name.lowercased() }).first self.select(matched, in: group) return matched != nil //false for nil (meaning no caption selected) } // Subtitles var subtitles: [String] { return tracks(type: .subtitle) } var selectedSubtitle: String? { return /*selected(type: .subtitle) ??*/ AwesomeMedia.defaultSubtitle } func selectSubtitle(_ subtitle: String?) -> Bool { //set default subtitle AwesomeMedia.defaultSubtitle = subtitle return select(type: .subtitle, name: subtitle) } func selectDefaultSubtitle() { _ = selectSubtitle(selectedSubtitle) } }
mit
3f33dfda26aa0cffb59e7f6c6c687e62
30.248031
145
0.576414
5.197773
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/ViewModel/Favorite/FavoriteViewModel.swift
1
1351
// // FavoriteViewModel.swift // MyApp // // Created by asiantech on 8/24/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import MVVM import RealmS import RealmSwift final class FavoriteViewModel: MVVM.ViewModel { // MARK: - Properties var favoriteItems: Results<Item>? var totalOrder: Double = 0 var currentBalance: Double = 0 // MARK: - Public func numberOfSections() -> Int { guard let _ = favoriteItems else { return 0 } return 1 } func favoriteIsEmpty() -> Bool { guard let favorite = favoriteItems else { return true } return favorite.isEmpty } func numberOfItems(inSection section: Int) -> Int { guard let items = favoriteItems else { return 0 } return items.count } func viewModelForItem(at indexPath: IndexPath) -> HomeCellViewModel { guard let items = favoriteItems else { fatalError("Not have food in favorite") } if indexPath.row < items.count { let item = items[indexPath.row] return HomeCellViewModel(item: item) } return HomeCellViewModel(item: nil) } func fetchFavoriteItem() { favoriteItems = RealmS().objects(Item.self).filter("isLiked = true") } }
mit
8b32c6f2c37c4aebee364b00d91dfb01
23.545455
76
0.611111
4.5
false
false
false
false
dasdom/Jupp
Jupp/AppDelegate.swift
1
1723
// // AppDelegate.swift // Jupp // // Created by dasdom on 09.08.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit import KeychainAccess @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.tintColor = UIColor(red: 0.206, green: 0.338, blue: 0.586, alpha: 1.000) if NSUserDefaults.standardUserDefaults().boolForKey("hasBeenStartedBefore") == false { KeychainAccess.deletePasswortForAccount("AccessToken") NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasBeenStartedBefore") NSUserDefaults.standardUserDefaults().synchronize() } let postNavigationController = UIStoryboard(name: "Post", bundle: nil).instantiateInitialViewController() as! UINavigationController postNavigationController.tabBarItem = UITabBarItem(title: "Post", image: UIImage(named: "compose"), tag: 0) window?.backgroundColor = UIColor.whiteColor() window?.rootViewController = postNavigationController window?.makeKeyAndVisible() let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil) NSURLCache.setSharedURLCache(urlCache) return true } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { print("background") } }
mit
056f3ab641dcf9ca0edb5555554a9721
37.288889
140
0.689495
5.367601
false
false
false
false
yokoe/gotanda
iOSDemo/ViewController.swift
1
1297
// // ViewController.swift // iOSDemo // // Created by Sota Yokoe on 2016/11/03. // // import UIKit import Gotanda class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var anotherView: UIView! private let anotherLayer = CALayer() override func viewDidLoad() { super.viewDidLoad() // let gotanda = Gotanda(width: 200, height: 200, backgroundColor: UIColor.yellow.cgColor).draw({ (context) in let gotanda = Gotanda(image: #imageLiteral(resourceName: "NightSky")).draw { (context) in context.setLineWidth(2) context.setStrokeColor(UIColor.yellow.cgColor) context.move(to: CGPoint(x: 50, y: 50)) context.addLine(to: CGPoint(x: 150, y: 150)) context.strokePath() let arrowImage = #imageLiteral(resourceName: "Arrow") context.draw(arrowImage.cgImage!, in: CGRect(origin: CGPoint(), size: CGSize(width: 50, height: 50))) } imageView.image = gotanda.uiImage anotherLayer.contents = gotanda.cgImage anotherView.layer.addSublayer(anotherLayer) } override func viewDidLayoutSubviews() { anotherLayer.frame = anotherView.layer.bounds } }
mit
6f547b1dddcd1845f64a0f580086c05c
28.477273
117
0.632999
4.323333
false
false
false
false
hughhopkins/PW-iOS
pw26/ViewController.swift
1
6207
// // ViewController.swift // pw26 // // Created by Hugh Hopkins on 04/02/2017. // Copyright © 2020 io.pwapp. All rights reserved. // import UIKit import CryptoSwift class ViewController: UIViewController { // this wasn't such a great idea in practice. Enable 15 char for everything but maybe highlight it instead? let sitesThatPraticeBadSecruity = ["apple", "lloyds", "bank", "nike", "tesco", "easyjet", "glassdoor", "spearfishingstore", "europcar", "tsb", "hsbc", "rbs", "barclays", "expedia", "three", "nexmo", "wechat", "line", "natwest"] // Even worse than the above. Should just create new version. let sitesThatPraticeBetterSecruity = ["zendesk"] // UI copy buttons @IBOutlet weak var buttonCopyNormal: UIButton! @IBOutlet weak var buttonCopy15CharYes: UIButton! @IBOutlet weak var buttonCopySpecialChar: UIButton! @IBOutlet weak var buttonWebsiteLink: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. showHide() showHideLink() // little touches serviceInput.autocorrectionType = UITextAutocorrectionType.no serviceInput.autocapitalizationType = UITextAutocapitalizationType.none buttonCopyNormal.layer.cornerRadius = 5 buttonCopy15CharYes.layer.cornerRadius = 5 buttonCopySpecialChar.layer.cornerRadius = 5 buttonWebsiteLink.layer.cornerRadius = 5 } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // UI @IBOutlet weak var serviceInput: UITextField! @IBAction func serviceInputEdit(_ sender: Any) { update() } @IBOutlet weak var passwordInput: UITextField! @IBAction func passwordInputEdit(_ sender: Any) { update() } @IBOutlet weak var pwOutput: UILabel! // PW code var pwNew: String = "" var shorterPW: String = "" var shorterPWCopy: String = "" var specialCharPW: String = "" var specialCharPWCopy: String = "" func update() { showHide() showHideLink() let srv: String = serviceInput.text! let pass: String = passwordInput.text! let srvLower = srv.lowercased() var pwHash = "\(srvLower)||\(pass)||".sha1() var pwLowered = pwHash.lowercased() var index = 0 func pwCapitalising() { for string in pwLowered { let s = "\(string)" if index % 2 == 0 { pwNew += s.uppercased() } else { pwNew += s } index += 1; } pwTextFormatting() } pwCapitalising() pwRefresh() } // to do clean all of this up // to do play around with text colour change var shortershortPW: String = "" var restOfThePW: String = "" var normalPWToBeCopiedToClipboard = "" func pwTextFormatting () { normalPWToBeCopiedToClipboard = pwNew shortershortPW = String(pwNew.prefix(15)) restOfThePW = String(pwNew.suffix(25)) if sitesThatPraticeBadSecruity.contains(serviceInput.text!.lowercased()) { pwOutput.text = "\(shortershortPW)" + " " + "\(restOfThePW)" } else if sitesThatPraticeBetterSecruity.contains(serviceInput.text!.lowercased()) { pwOutput.text = "\(pwNew)" + " (*)" } else { pwOutput.text = pwNew } } func pwRefresh() { pwNew = "" } // buttons // this needs fixing!!!!! @IBAction func copyNormal(_ sender: Any) { UIPasteboard.general.string = normalPWToBeCopiedToClipboard } @IBAction func copy15CharYes(_ sender: Any) { shorterPW = pwOutput.text! shorterPWCopy = String(shorterPW.prefix(15)) UIPasteboard.general.string = shorterPWCopy } @IBAction func copySpecialChar(_ sender: Any) { specialCharPW = pwOutput.text! specialCharPWCopy = "\(specialCharPW)" + "*" } @IBAction func websiteLink(_ sender: Any) { if let url = URL(string: "http://pwapp.io/?utm_source=iOS&utm_medium=link&utm_content=footer&utm_campaign=iOS") { UIApplication.shared.openURL(url) } } // Show / hide different UI elements func showHide () { if serviceInput.text! == "" && passwordInput.text! == "" { // When the text field is blank pwOutput.isHidden = true buttonCopyNormal.isHidden = true buttonCopy15CharYes.isHidden = true buttonCopySpecialChar.isHidden = true } else if sitesThatPraticeBadSecruity.contains(serviceInput.text!.lowercased()) { // when it should show the 15 character option buttonCopyNormal.isHidden = false buttonCopy15CharYes.isHidden = false } else if sitesThatPraticeBetterSecruity.contains(serviceInput.text!.lowercased()) { // when it should be a special characater buttonCopyNormal.isHidden = false buttonCopySpecialChar.isHidden = false } else { // when it is every other password and should just be normal pwOutput.isHidden = false buttonCopyNormal.isHidden = false buttonCopy15CharYes.isHidden = false buttonCopySpecialChar.isHidden = true } } // todo hide buttonWebsiteLink on iPhone 5 SE func showHideLink () { if UIDevice.current.orientation.isLandscape { print("Landscape") buttonWebsiteLink.isHidden = true } else { buttonWebsiteLink.isHidden = false } } // end }
mit
2482fd2a88d15b21770e46a31452e946
32.010638
231
0.602159
4.480866
false
false
false
false
omaralbeik/SwifterSwift
Sources/Extensions/CoreGraphics/CGSizeExtensions.swift
1
6398
// // CGSizeExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(CoreGraphics) import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif // MARK: - Methods public extension CGSize { /// SwifterSwift: Aspect fit CGSize. /// /// let rect = CGSize(width: 120, height: 80) /// let parentRect = CGSize(width: 100, height: 50) /// let newRect = rect.aspectFit(to: parentRect) /// //newRect.width = 75 , newRect = 50 /// /// - Parameter boundingSize: bounding size to fit self to. /// - Returns: self fitted into given bounding size public func aspectFit(to boundingSize: CGSize) -> CGSize { let minRatio = min(boundingSize.width / width, boundingSize.height / height) return CGSize(width: width * minRatio, height: height * minRatio) } /// SwifterSwift: Aspect fill CGSize. /// /// let rect = CGSize(width: 20, height: 120) /// let parentRect = CGSize(width: 100, height: 60) /// let newRect = rect.aspectFit(to: parentRect) /// //newRect.width = 100 , newRect = 60 /// /// - Parameter boundingSize: bounding size to fill self to. /// - Returns: self filled into given bounding size public func aspectFill(to boundingSize: CGSize) -> CGSize { let minRatio = max(boundingSize.width / width, boundingSize.height / height) let aWidth = min(width * minRatio, boundingSize.width) let aHeight = min(height * minRatio, boundingSize.height) return CGSize(width: aWidth, height: aHeight) } } // MARK: - Operators public extension CGSize { /// SwifterSwift: Add two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA + sizeB /// //result = CGSize(width: 8, height: 14) /// /// - Parameters: /// - lhs: CGSize to add to. /// - rhs: CGSize to add. /// - Returns: The result comes from the addition of the two given CGSize struct. public static func + (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height) } /// SwifterSwift: Add a CGSize to self. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA += sizeB /// //sizeA = CGPoint(width: 8, height: 14) /// /// - Parameters: /// - lhs: self /// - rhs: CGSize to add. public static func += (lhs: inout CGSize, rhs: CGSize) { lhs.width += rhs.width lhs.height += rhs.height } /// SwifterSwift: Subtract two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA - sizeB /// //result = CGSize(width: 2, height: 6) /// /// - Parameters: /// - lhs: CGSize to subtract from. /// - rhs: CGSize to subtract. /// - Returns: The result comes from the subtract of the two given CGSize struct. public static func - (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height) } /// SwifterSwift: Subtract a CGSize from self. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA -= sizeB /// //sizeA = CGPoint(width: 2, height: 6) /// /// - Parameters: /// - lhs: self /// - rhs: CGSize to subtract. public static func -= (lhs: inout CGSize, rhs: CGSize) { lhs.width -= rhs.width lhs.height -= rhs.height } /// SwifterSwift: Multiply two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA * sizeB /// //result = CGSize(width: 15, height: 40) /// /// - Parameters: /// - lhs: CGSize to multiply. /// - rhs: CGSize to multiply with. /// - Returns: The result comes from the multiplication of the two given CGSize structs. public static func * (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height) } /// SwifterSwift: Multiply a CGSize with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// let result = sizeA * 5 /// //result = CGSize(width: 25, height: 50) /// /// - Parameters: /// - lhs: CGSize to multiply. /// - scalar: scalar value. /// - Returns: The result comes from the multiplication of the given CGSize and scalar. public static func * (lhs: CGSize, scalar: CGFloat) -> CGSize { return CGSize(width: lhs.width * scalar, height: lhs.height * scalar) } /// SwifterSwift: Multiply a CGSize with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// let result = 5 * sizeA /// //result = CGSize(width: 25, height: 50) /// /// - Parameters: /// - scalar: scalar value. /// - rhs: CGSize to multiply. /// - Returns: The result comes from the multiplication of the given scalar and CGSize. public static func * (scalar: CGFloat, rhs: CGSize) -> CGSize { return CGSize(width: scalar * rhs.width, height: scalar * rhs.height) } /// SwifterSwift: Multiply self with a CGSize. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA *= sizeB /// //result = CGSize(width: 15, height: 40) /// /// - Parameters: /// - lhs: self. /// - rhs: CGSize to multiply. public static func *= (lhs: inout CGSize, rhs: CGSize) { lhs.width *= rhs.width lhs.height *= rhs.height } /// SwifterSwift: Multiply self with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// sizeA *= 3 /// //result = CGSize(width: 15, height: 30) /// /// - Parameters: /// - lhs: self. /// - scalar: scalar value. public static func *= (lhs: inout CGSize, scalar: CGFloat) { lhs.width *= scalar lhs.height *= scalar } } #endif
mit
2647b987cec9c62c41146c7b89987768
32.492147
92
0.569798
3.816826
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Settings/Cells/SettingsActionCell.swift
1
2957
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit protocol SettingsActionCellDelegate: AnyObject { func settingsActionCellTapped(context: Context?, button: UIButton) } struct SettingsActionCellContext: CellContext { let identifier: String = SettingsActionCell.identifier let title: String let buttonStyle: Button.ButtonStyle let context: Context? init(title: String, buttonStyle: Button.ButtonStyle = .primary, context: Context? = nil) { self.title = title self.buttonStyle = buttonStyle self.context = context } } class SettingsActionCell: ConfigurableTableViewCell { static let identifier = "SettingsActionCell" private let button = Button(style: .primary) private var context: Context? weak var delegate: SettingsActionCellDelegate? override func commonInit() { super.commonInit() button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) contentView.addSubview(button) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p48) $0.top.equalToSuperview().inset(Style.Padding.p32) $0.bottom.equalToSuperview().inset(Style.Padding.p16) } } func configure(context: CellContext) { guard let context = context as? SettingsActionCellContext else { return } button.style = context.buttonStyle button.title = context.title self.context = context.context } // MARK: - Actions @objc func buttonTapped() { delegate?.settingsActionCellTapped(context: context, button: button) } }
bsd-3-clause
227bce2cf70e5e9ba1d84c3199cc8a99
35.04878
92
0.748985
4.561728
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/Snackbar.swift
2
3687
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind 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 @objc(SnackbarStatus) public enum SnackbarStatus: Int { case visible case hidden } open class Snackbar: Bar { /// A convenience property to set the titleLabel text. open var text: String? { get { return textLabel.text } set(value) { textLabel.text = value layoutSubviews() } } /// Text label. @IBInspectable open let textLabel = UILabel() open override var intrinsicContentSize: CGSize { return CGSize(width: width, height: 49) } /// The status of the snackbar. open internal(set) var status = SnackbarStatus.hidden open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { for v in subviews { let p = v.convert(point, from: self) if v.bounds.contains(p) { return v.hitTest(p, with: event) } } return super.hitTest(point, with: event) } /// Reloads the view. open override func reload() { super.reload() centerViews = [textLabel] } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() depthPreset = .none interimSpacePreset = .interimSpace8 contentEdgeInsets.left = interimSpace contentEdgeInsets.right = interimSpace backgroundColor = Color.grey.darken3 clipsToBounds = false prepareTextLabel() } /// Prepares the textLabel. private func prepareTextLabel() { textLabel.contentScaleFactor = Screen.scale textLabel.font = RobotoFont.medium(with: 14) textLabel.textAlignment = .left textLabel.textColor = .white textLabel.numberOfLines = 0 } }
agpl-3.0
756f1544c5bdfa4c6b9e21d2d2c3d908
33.783019
88
0.675075
4.838583
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/ExpendableTransitionAnimation.swift
1
4405
// // ExpendableTransitionAnimation.swift // selluv-ios // // Created by 조백근 on 2017. 1. 3.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit public class ExpendableTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning { public var transitionStatus: TransitionStatus public var transitionContext: UIViewControllerContextTransitioning? public var cancelPop: Bool = false public var interacting: Bool = false public var keepFrame: CGRect = .zero private let bounce: Bool public init(keepFrame: CGRect, bounce: Bool = true, status: TransitionStatus = .present) { self.keepFrame = keepFrame transitionStatus = status self.bounce = bounce super.init() } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.7 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView let screenBounds = UIScreen.main.bounds var up = keepFrame var dn = keepFrame var finUp = .zero as CGRect var finDn = .zero as CGRect up.origin.y = 0 up.size.height = keepFrame.origin.y dn.origin.y = up.size.height dn.size.height = screenBounds.height - keepFrame.origin.y - keepFrame.size.height finUp = up finUp.origin.y = -up.size.height finDn = dn finDn.origin.y = dn.origin.y + dn.size.height/2 if transitionStatus == .dismiss { // swap(&fromVC, &toVC) // swap(&up, &finUp) // swap(&dn, &finDn) } containView.addSubview(fromVC!.view) containView.addSubview(toVC!.view) let upper = UIView() upper.frame = up upper.layer.contents = { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(fromVC!.view.bounds.size, true, scale) fromVC!.view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() let inRect = CGRect(x: up.origin.x * scale, y: up.origin.y * scale, width: up.size.width * scale, height: up.size.height * scale) let clip = image.cgImage?.cropping(to: inRect) return clip }() let down = UIView() down.frame = dn down.layer.contents = { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(fromVC!.view.bounds.size, true, scale) fromVC!.view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() let inRect = CGRect(x: dn.origin.x * scale, y: dn.origin.y * scale, width: dn.size.width * scale, height: dn.size.height * scale) let clip = image.cgImage?.cropping(to: inRect) return clip }() if transitionStatus != .dismiss { containView.addSubview(upper) containView.addSubview(down) } toVC!.view.layer.opacity = 0 UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: (bounce ? 0.8 : 1), initialSpringVelocity: (bounce ? 0.6 : 1), options: .curveEaseInOut, animations: { upper.frame = finUp down.frame = finDn toVC!.view.layer.opacity = 1 down.layer.opacity = 0 upper.layer.opacity = 0 }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) if finished { if self.transitionStatus != .dismiss { upper.removeFromSuperview() down.removeFromSuperview() } } } } }
mit
0f3d8bece88ce699aab70638784d56cc
37.226087
219
0.618062
5.012543
false
false
false
false
noais/ios-charts
Charts/Classes/Data/ChartData.swift
3
25759
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } if self is ScatterChartData { // In scatter chart it makes sense to have more than one y-value value for an x-index return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(start start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis let firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis let firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += _dataSets[i].yValueSum } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// - returns: the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// - returns: the average value across all entries in this Data object (all entries from the DataSets this data object holds) public var average: Double { return yValueSum / Double(yValCount) } /// - returns: the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// - returns: the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// - returns: the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// - returns: the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// - returns: the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// - returns: the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// - returns: the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue initialize(_dataSets) } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// /// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.** /// /// - parameter dataSets: the DataSet array to search /// - parameter type: /// - parameter ignorecase: if true, the search is not case-sensitive /// - returns: the index of the DataSet Object with the given label. Sensitive or not. internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// - returns: the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// - returns: the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// - parameter highlight: /// - returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.** /// /// - parameter label: /// - parameter ignorecase: /// - returns: the DataSet Object with the given label. Sensitive or not. public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { let index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } let d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { let val = e.value let set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { let val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. /// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { let set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } /// - returns: the first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found. public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } /// - returns: the first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found. public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// - returns: all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { let clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. /// If set to true, this means that values can be highlighted programmatically or by touch gesture. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. /// - returns: true if so, false if not. public func contains(entry entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. /// - returns: true if so, false if not. public func contains(dataSet dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// - returns: the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
apache-2.0
905b0bebe984b3c7063a167418fe0ec4
26.086225
169
0.480026
5.193347
false
false
false
false
hollance/swift-algorithm-club
Single-Source Shortest Paths (Weighted)/SSSP/BellmanFord.swift
9
4506
// // BellmanFord.swift // SSSP // // Created by Andrew McKnight on 5/8/16. // import Foundation import Graph public struct BellmanFord<T> where T: Hashable { public typealias Q = T } /** Encapsulation of the Bellman-Ford Single-Source Shortest Paths algorithm, which operates on a general directed graph that may contain negative edge weights. - note: In all complexity bounds, `V` is the number of vertices in the graph, and `E` is the number of edges. */ extension BellmanFord: SSSPAlgorithm { /** Compute the shortest path from `source` to each other vertex in `graph`, if such paths exist. Also report negative weight cycles reachable from `source`, which are cycles whose sum of edge weights is negative. - precondition: `graph` must have no negative weight cycles - complexity: `O(VE)` time, `Θ(V)` space - returns a `BellmanFordResult` struct which can be queried for shortest paths and their total weights, or `nil` if a negative weight cycle exists */ public static func apply(_ graph: AbstractGraph<T>, source: Vertex<Q>) -> BellmanFordResult<T>? { let vertices = graph.vertices let edges = graph.edges var predecessors = Array<Int?>(repeating: nil, count: vertices.count) var weights = Array(repeating: Double.infinity, count: vertices.count) predecessors[source.index] = source.index weights[source.index] = 0 for _ in 0 ..< vertices.count - 1 { var weightsUpdated = false edges.forEach { edge in let weight = edge.weight! let relaxedDistance = weights[edge.from.index] + weight let nextVertexIdx = edge.to.index if relaxedDistance < weights[nextVertexIdx] { predecessors[nextVertexIdx] = edge.from.index weights[nextVertexIdx] = relaxedDistance weightsUpdated = true } } if !weightsUpdated { break } } // check for negative weight cycles reachable from the source vertex // TO DO: modify to incorporate solution to 24.1-4, pg 654, to set the // weight of a path containing a negative weight cycle to -∞, // instead of returning nil for the entire result for edge in edges { if weights[edge.to.index] > weights[edge.from.index] + edge.weight! { return nil } } return BellmanFordResult(predecessors: predecessors, weights: weights) } } /** `BellmanFordResult` encapsulates the result of the computation, namely the minimized distances, and the predecessor indices. It conforms to the `SSSPResult` procotol which provides methods to retrieve distances and paths between given pairs of start and end nodes. */ public struct BellmanFordResult<T> where T: Hashable { fileprivate var predecessors: [Int?] fileprivate var weights: [Double] } extension BellmanFordResult: SSSPResult { /** - returns: the total weight of the path from the source vertex to a destination. This value is the minimal connected weight between the two vertices, or `nil` if no path exists - complexity: `Θ(1)` time/space */ public func distance(to: Vertex<T>) -> Double? { let distance = weights[to.index] guard distance != Double.infinity else { return nil } return distance } /** - returns: the reconstructed path from the source vertex to a destination, as an array containing the data property of each vertex, or `nil` if no path exists - complexity: `Θ(V)` time, `Θ(V^2)` space */ public func path(to: Vertex<T>, inGraph graph: AbstractGraph<T>) -> [T]? { guard weights[to.index] != Double.infinity else { return nil } guard let path = recursePath(to: to, inGraph: graph, path: [to]) else { return nil } return path.map { vertex in return vertex.data } } /** The recursive component to rebuilding the shortest path between two vertices using predecessors. - returns: the list of predecessors discovered so far, or `nil` if the next vertex has no predecessor */ fileprivate func recursePath(to: Vertex<T>, inGraph graph: AbstractGraph<T>, path: [Vertex<T>]) -> [Vertex<T>]? { guard let predecessorIdx = predecessors[to.index] else { return nil } let predecessor = graph.vertices[predecessorIdx] if predecessor.index == to.index { return [ to ] } guard let buildPath = recursePath(to: predecessor, inGraph: graph, path: path) else { return nil } return buildPath + [ to ] } }
mit
0e37f950fd98f023d202ae3327181228
29.821918
115
0.678889
4.043127
false
false
false
false
EstefaniaGilVaquero/ciceIOS
AppDatePickerPickerView/AppDatePickerPickerView/ViewController.swift
1
6527
// // ViewController.swift // AppDatePickerPickerView // // Created by cice on 20/5/16. // Copyright © 2016 CICE. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: - VARIABLES LOCALES GLOBALES var pickerArrayData = ["Mozzarella", "Gorgonzola", "Provolone", "Stilton", "Asiago"] var cheesImages: [UIImage] = [ UIImage(named: "mozarella.jpg")!, UIImage(named: "gorgonzola.jpg")!, UIImage(named: "provolone.jpg")!, UIImage(named: "stilton.jpg")!, UIImage(named: "asiago.jpg")! ] //MARK: - IBOUTLET @IBOutlet weak var MyTituloAlimentoLBL: UILabel! @IBOutlet weak var myTextViewDetalleAlimentoTV: UITextView! @IBOutlet weak var myPickerViewSeleccionaAlimento: UIPickerView! @IBOutlet weak var myCheesImage: UIImageView! //MARK; - CICLO DE VIDA DEL CONTROLADOR override func viewDidLoad() { super.viewDidLoad() //TODO: - Aqui va la implementacion de delegado y datasource del PickerView myPickerViewSeleccionaAlimento.delegate = self myPickerViewSeleccionaAlimento.dataSource = self //MyTituloAlimentoLBL.text = pickerArrayData[0] //self.title = pickerArrayData[0] //myTextViewDetalleAlimentoTV.text = pickerArrayData[0] myTextViewDetalleAlimentoTV.text = "La mozzarella1 (del italiano antiguo mozzare ‘cortar’) es un tipo de queso originario de la cocina italiana. Existe una variante de este queso en Dinamarca, pero la tradición italiana es más antigua. La ciudad de origen de este queso fue Aversa (Caserta). La denominación de origen con protección europea es la Mozzarella di Bufala Campana, sin que haya solicitado Italia la protección del nombre mozzarella. El queso DOP se produce en las provincias de Caserta y Salerno y en algunos municipios de las provincias de Nápoles, Benevento, Latina y Foggia con leche de búfala. En la misma Italia y en otros países, como Argentina, Colombia, España, Paraguay, Perú, República Dominicana, Uruguay, se preparan mozzarellas con leche de vaca." // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: - EXTENSION DEL PICKER VIEW extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource{ //Numero de componentes func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } //Numero de Fila func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerArrayData.count } //Que me pinte cada uno de los objetos de array func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerArrayData[row] } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 20 } //Para cambiar el color de texto del pickerview func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { var attributedString: NSAttributedString! attributedString = NSAttributedString(string: pickerArrayData[row], attributes: [NSForegroundColorAttributeName : UIColor.red]) return attributedString } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.title = pickerArrayData[row] switch row { case 0: myTextViewDetalleAlimentoTV.text = "La mozzarella1 (del italiano antiguo mozzare ‘cortar’) es un tipo de queso originario de la cocina italiana. Existe una variante de este queso en Dinamarca, pero la tradición italiana es más antigua. La ciudad de origen de este queso fue Aversa (Caserta). La denominación de origen con protección europea es la Mozzarella di Bufala Campana, sin que haya solicitado Italia la protección del nombre mozzarella. El queso DOP se produce en las provincias de Caserta y Salerno y en algunos municipios de las provincias de Nápoles, Benevento, Latina y Foggia con leche de búfala. En la misma Italia y en otros países, como Argentina, Colombia, España, Paraguay, Perú, República Dominicana, Uruguay, se preparan mozzarellas con leche de vaca." myCheesImage.image = cheesImages[0] case 1: myTextViewDetalleAlimentoTV.text = "El gorgonzola es un queso italiano de mesa, de pasta cremosa y untuosa, hecho con leche entera pasteurizada de vaca que se presenta en dos variedades: dulce y picante. La existencia de este queso se conoce desde la Edad Media, aunque solo fue en el siglo XI cuando comenzó a tener el aspecto enmohecido que posee en la actualidad. Se emplea frecuentemente como ingrediente en diversos platos de la cocina italiana." myCheesImage.image = cheesImages[1] case 2: myTextViewDetalleAlimentoTV.text = "El provolone (Provolone Val Padana) es un queso italiano originario del sur del país, donde se sigue produciendo en piezas de 10 a 15 cm con diversas formas (pera alargada, salchicha o cono). Sin embargo, la región de producción más importante de provolone es actualmente el norte de Italia (Piamonte, Lombardía y Véneto). La familia Provenzano de Venecia afirma haber sido la descubridora de este tipo de queso, pero no ha podido demostrarlo. El queso Provolone fue descubierto o creado por la Familia Visani en Deruta (centro de Italia) En Estados Unidos se comercializa con el nombre Provolone un queso relativamente barato comercializado como aliño para pizzas, que se parece al original italiano sólo en color y textura, no en sabor." case 3: myTextViewDetalleAlimentoTV.text = "" myCheesImage.image = cheesImages[2] case 4: myTextViewDetalleAlimentoTV.text = "" myCheesImage.image = cheesImages[3] case 5: myTextViewDetalleAlimentoTV.text = "" myCheesImage.image = cheesImages[4] default: break } } }
apache-2.0
e2cddea1d2817acf3a4c61a69ae2313c
34.448087
787
0.69462
3.824882
false
false
false
false
MaximilianGoetzfried/MXStatusMenu
MXStatusMenu/Timer.swift
2
3188
import Foundation class Timer { /// Closure will be called every time the timer fires typealias Closure = (_ timer: Timer) -> () /// Parameters let closure: Closure let queue: DispatchQueue var isSuspended: Bool = true /// The default initializer init(queue: DispatchQueue, closure: @escaping Closure) { self.queue = queue self.closure = closure } /// Suspend the timer before it gets destroyed deinit { suspend() } /// This timer implementation uses Grand Central Dispatch sources lazy var source: DispatchSource = { DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: self.queue) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as! DispatchSource }() /// Convenience class method that creates and start a timer class func repeatEvery(_ repeatEvery: Double, closure: @escaping Closure) -> Timer { let timer = Timer(queue: DispatchQueue.global(), closure: closure) timer.resume(0, repeat: repeatEvery, leeway: 0) return timer } /// Fire the timer by calling its closure func fire() { closure(self) } /// Start or resume the timer with the specified double values func resume(_ start: Double, repeat: Double, leeway: Double) { let NanosecondsPerSecond = Double(NSEC_PER_SEC) resume(Int64(start * NanosecondsPerSecond), repeat: UInt64(`repeat` * NanosecondsPerSecond), leeway: UInt64(leeway * NanosecondsPerSecond)) } /// Start or resume the timer with the specified integer values func resume(_ start: Int64, repeat: UInt64, leeway: UInt64) { if isSuspended { let startTime = DispatchTime.now() + Double(start) / Double(NSEC_PER_SEC) source.scheduleRepeating( deadline: startTime, interval: DispatchTimeInterval.seconds(Int(`repeat`)), leeway: DispatchTimeInterval.seconds(Int(leeway)) ) /* source. { [weak self] in if let timer = self { timer.fire() } } public func scheduleOneshot(deadline: DispatchTime, leeway: DispatchTimeInterval = default) public func scheduleOneshot(wallDeadline: DispatchWallTime, leeway: DispatchTimeInterval = default) public func scheduleRepeating(deadline: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = default) public func scheduleRepeating(deadline: DispatchTime, interval: Double, leeway: DispatchTimeInterval = default) public func scheduleRepeating(wallDeadline: DispatchWallTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = default) public func scheduleRepeating(wallDeadline: DispatchWallTime, interval: Double, leeway: DispatchTimeInterval = default) source.resume() isSuspended = false } */ } } /// Suspend the timer func suspend() { if !isSuspended { source.suspend() isSuspended = true } } }
mit
40fe46c6851cd73847f7273204f86e46
34.032967
185
0.642723
4.912173
false
false
false
false
Nucleus-Inc/gn_api_sdk_ios
gn_api_sdk_ios/Classes/GNTransaction.swift
1
7746
// // GNTransaction.swift // learning_gerencia // // Created by Nucleus on 16/11/16. // Copyright © 2016 José Lucas Souza das Chagas. All rights reserved. // import UIKit public class GNTransaction: JsonObject { static let newTransactionURl = "/charge" var chargeID:Int?{ get{ return getValueOf(Parameter: "charge_id") as? Int } } var items:[GNItem]!{ get{ let array = paramsValuesDict["items"] as! [[String:Any]] return array.map({ (item) -> GNItem in return GNItem(dictionary: item ) }) } } var shippings:[GNShipping]?{ get{ let array = paramsValuesDict["shippings"] as! [[String:Any]] return array.map({ (shipping) -> GNShipping in return GNShipping(dictionary: shipping ) }) } } var metadata:GNMetadata?{ get{ return GNMetadata(dictionary: getValueOf(Parameter: "metadata") as! [String : Any]!) } } public init(items:[GNItem]!,shippings:[GNShipping]?,metadata:GNMetadata?){ super.init() let itemsArray = items.map { (item) -> [String:Any] in return item.paramsValuesDict } setValueOf(Parameter: "items", ToValue: itemsArray) if let shippings = shippings{ let shippingsArray = shippings.map { (shipping) -> [String:Any] in return shipping.paramsValuesDict } setValueOf(Parameter: "shippings", ToValue: shippingsArray) } if let metadata = metadata{ setValueOf(Parameter: "metadata", ToValue: metadata.paramsValuesDict) } } public override init(dictionary: [String : Any]!) { super.init(dictionary: dictionary) } /** Uploads a local instaciated transaction */ public func send(onSuccess: @escaping ()->(),onFailure:@escaping (_ error:NSError,_ arrivedData:[String:Any]?)->()){ let url = URL(string: GNManager.baseSandBoxUrl+GNTransaction.newTransactionURl) GNManager.auth.requestAuthIfNeeded(onSuccess: { GNManager.executeGNRequest(method: RMHTTPRequestMethod.POST, url: url!, headers: GNTransaction.headers(), params: self.paramsValuesDict, onSuccess: { jsonDict in self.setValuesOf(Dictionary: jsonDict) onSuccess() }, onFailure: onFailure) }, onFailure: onFailure) } /** Updates the local added metadata,self.metadata, to server */ public func updateMetadata(onSuccess: @escaping ()->(),onFailure:@escaping (_ error:NSError,_ arrivedData:[String:Any]?)->()){ if let id = chargeID , let metadata = metadata{ let url = URL(string: GNManager.baseSandBoxUrl+GNTransaction.newTransactionURl+"/"+String(id)+"/metadata") GNManager.auth.requestAuthIfNeeded(onSuccess: { GNManager.executeGNRequest(method: RMHTTPRequestMethod.PUT, url: url!, headers: GNTransaction.headers(), params: metadata.paramsValuesDict, onSuccess: { jsonDict in onSuccess() }, onFailure: onFailure) }, onFailure: onFailure) } else{ let error = NSError(domain: "GN_Local_Error", code: 0, userInfo:["error_description": "params char_id and metadata can not be nil to execute this method"]) onFailure(error,nil) } } //MARK: - Class funcs /** This method gets from server a transaction that has the specified chargeID */ public class func get(ByChargeID chargeID:Int!,onSuccess: @escaping (_ transaction:GNTransaction)->(),onFailure:@escaping (_ error:NSError,_ arrivedData:[String:Any]?)->()){ let url = URL(string: GNManager.baseSandBoxUrl+GNTransaction.newTransactionURl+"/"+String(chargeID)) GNManager.auth.requestAuthIfNeeded(onSuccess: { GNManager.executeGNRequest(method: RMHTTPRequestMethod.GET, url: url!, headers: GNTransaction.headers(), params: nil, onSuccess: { jsonDict in onSuccess(GNTransaction(dictionary: jsonDict["data"] as! [String : Any]!)) }, onFailure: onFailure) }, onFailure: onFailure) } class func headers()->[String:String]{ var customHeaders = [String:String]() customHeaders["authorization"] = GNManager.auth.authorizationToken()! return customHeaders } } public class GNShipping: JsonObject { var name:String!{ get{ return getValueOf(Parameter: "name") as! String } } var value:Int!{ get{ return getValueOf(Parameter: "value") as! Int } } var payeeCode:String?{ get{ return getValueOf(Parameter: "payee_code") as? String } } public init(name:String!,value:Int!,payeeCode:String?){ super.init() setValueOf(Parameter: "name", ToValue: name) setValueOf(Parameter: "value", ToValue: value) if let payeeCode = payeeCode{ setValueOf(Parameter: "payee_code", ToValue: payeeCode) } } override init(dictionary: [String : Any]!) { super.init(dictionary: dictionary) } } public class GNMetadata: JsonObject { var customID:String?{ get{ return getValueOf(Parameter: "custom_id") as? String } } var notificationURL:String?{ get{ return getValueOf(Parameter: "notification_url") as? String } } public init(customID:String,notificationURL:String){ super.init() setValueOf(Parameter: "notification_url", ToValue: notificationURL) setValueOf(Parameter: "custom_id", ToValue: customID) } public override init(dictionary: [String : Any]!) { super.init(dictionary: dictionary) } } /*{ "id": "/Charge", "type": "object", "properties": { "items": { "id": "/MarketplaceItem", "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 255, "pattern": "^[^<>]+$" }, "value": { "type": "integer", "minimum": 0 }, "amount": { "type": "integer", "minimum": 1, "exclusiveMinimum": false }, "marketplace": { "type": "object", "properties": { "repasses": { "id": "/Repass", "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "payee_code": { "type": "string", "pattern": "^[a-fA-F0-9]{32}$" }, "percentage": { "type": "integer", "minimum": 0, "maximum": 10000 } }, "required": [ "payee_code", "percentage" ] } } }, "required": [ "repasses" ] } }, "required": [ "name", "value" ] } }, "shippings": { "id": "/Shipping", "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 255 }, "value": { "type": "integer", "minimum": 0 }, "payee_code": { "type": "string", "pattern": "^[a-fA-F0-9]{32}$" } }, "required": [ "name", "value" ] } }, "metadata": { "type": "object", "properties": { "custom_id": { "type": [ "string", "null" ], "maxLength": "255" }, "notification_url": { "type": [ "string", "null" ], "pattern": "^https?://.+", "maxLength": "255" } } } }, "required": [ "items" ] } */
mit
d2c01be7afc54257e7dbe4ae7a18e20a
21.843658
180
0.556173
3.985589
false
false
false
false
raywenderlich/swift-algorithm-club
GCD/GCD.playground/Sources/GCD.swift
3
4612
/* Finds the largest positive integer that divides both m and n without a remainder. - Parameter m: First natural number - Parameter n: Second natural number - Parameter using: The used algorithm to calculate the gcd. If nothing provided, the Iterative Euclidean algorithm is used. - Returns: The natural gcd of m and n. */ public func gcd(_ m: Int, _ n: Int, using gcdAlgorithm: (Int, Int) -> (Int) = gcdIterativeEuklid) -> Int { return gcdAlgorithm(m, n) } /* Iterative approach based on the Euclidean algorithm. The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. - Parameter m: First natural number - Parameter n: Second natural number - Returns: The natural gcd of m and n. */ public func gcdIterativeEuklid(_ m: Int, _ n: Int) -> Int { var a: Int = 0 var b: Int = max(m, n) var r: Int = min(m, n) while r != 0 { a = b b = r r = a % b } return b } /* Recursive approach based on the Euclidean algorithm. - Parameter m: First natural number - Parameter n: Second natural number - Returns: The natural gcd of m and n. - Note: The recursive version makes only tail recursive calls. Most compilers for imperative languages do not optimize these. The swift compiler as well as the obj-c compiler is able to do optimizations for tail recursive calls, even though it still ends up to be the same in terms of complexity. That said, tail call elimination is not mutually exclusive to recursion. */ public func gcdRecursiveEuklid(_ m: Int, _ n: Int) -> Int { let r: Int = m % n if r != 0 { return gcdRecursiveEuklid(n, r) } else { return n } } /* The binary GCD algorithm, also known as Stein's algorithm, is an algorithm that computes the greatest common divisor of two nonnegative integers. Stein's algorithm uses simpler arithmetic operations than the conventional Euclidean algorithm; it replaces division with arithmetic shifts, comparisons, and subtraction. - Parameter m: First natural number - Parameter n: Second natural number - Returns: The natural gcd of m and n - Complexity: worst case O(n^2), where n is the number of bits in the larger of the two numbers. Although each step reduces at least one of the operands by at least a factor of 2, the subtract and shift operations take linear time for very large integers */ public func gcdBinaryRecursiveStein(_ m: Int, _ n: Int) -> Int { if let easySolution = findEasySolution(m, n) { return easySolution } if (m & 1) == 0 { // m is even if (n & 1) == 1 { // and n is odd return gcdBinaryRecursiveStein(m >> 1, n) } else { // both m and n are even return gcdBinaryRecursiveStein(m >> 1, n >> 1) << 1 } } else if (n & 1) == 0 { // m is odd, n is even return gcdBinaryRecursiveStein(m, n >> 1) } else if (m > n) { // reduce larger argument return gcdBinaryRecursiveStein((m - n) >> 1, n) } else { // reduce larger argument return gcdBinaryRecursiveStein((n - m) >> 1, m) } } /* Finds an easy solution for the gcd. - Parameter m: First natural number - Parameter n: Second natural number - Returns: A natural gcd of m and n if possible. - Note: It might be relevant for different usecases to try finding an easy solution for the GCD calculation before even starting more difficult operations. */ func findEasySolution(_ m: Int, _ n: Int) -> Int? { if m == n { return m } if m == 0 { return n } if n == 0 { return m } return nil } public enum LCMError: Error { case divisionByZero } /* Calculates the lcm for two given numbers using a specified gcd algorithm. - Parameter m: First natural number. - Parameter n: Second natural number. - Parameter using: The used gcd algorithm to calculate the lcm. If nothing provided, the Iterative Euclidean algorithm is used. - Throws: Can throw a `divisionByZero` error if one of the given attributes turns out to be zero or less. - Returns: The least common multiplier of the two attributes as an unsigned integer */ public func lcm(_ m: Int, _ n: Int, using gcdAlgorithm: (Int, Int) -> (Int) = gcdIterativeEuklid) throws -> Int { guard m & n != 0 else { throw LCMError.divisionByZero } return m / gcdAlgorithm(m, n) * n }
mit
0e2a012edadf7cd9ab6065d2be789f07
31.251748
113
0.657199
3.975862
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/ViewTopMessageController.swift
3
2955
// // ViewTopMessageController.swift // edX // // Created by Akiva Leffert on 6/4/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class ViewTopMessageController : NSObject, ContentInsetsSource { weak public var insetsDelegate : ContentInsetsSourceDelegate? private let containerView = UIView(frame: CGRectZero) private let messageView : UIView private var wasActive : Bool = false private let active : Void -> Bool public init(messageView: UIView, active : Void -> Bool) { self.active = active self.messageView = messageView super.init() containerView.addSubview(messageView) containerView.setNeedsUpdateConstraints() containerView.clipsToBounds = true update() } public var affectsScrollIndicators : Bool { return true } final public var currentInsets : UIEdgeInsets { let height = active() ? messageView.bounds.size.height : 0 return UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0) } final public func setupInController(controller : UIViewController) { controller.view.addSubview(containerView) containerView.snp_makeConstraints {make in make.leading.equalTo(controller.view) make.trailing.equalTo(controller.view) if #available(iOS 9, *) { make.top.equalTo(controller.topLayoutGuide.bottomAnchor) } else { make.top.equalTo(controller.snp_topLayoutGuideBottom) } make.height.equalTo(messageView) } } final private func update() { messageView.snp_remakeConstraints { make in make.leading.equalTo(containerView) make.trailing.equalTo(containerView) if active() { containerView.userInteractionEnabled = true make.top.equalTo(containerView.snp_top) } else { containerView.userInteractionEnabled = false make.bottom.equalTo(containerView.snp_top) } } messageView.setNeedsLayout() messageView.layoutIfNeeded() if(!wasActive && active()) { containerView.superview?.bringSubviewToFront(containerView) } wasActive = active() self.insetsDelegate?.contentInsetsSourceChanged(self) } final func updateAnimated() { UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions(), animations: { self.update() }, completion:nil) } } extension ViewTopMessageController { public var t_messageHidden : Bool { return CGRectGetMaxY(messageView.frame) <= 0 } }
apache-2.0
83c1ba6aeb3f5fea857c49f195b961d8
28.56
72
0.605415
5.305206
false
false
false
false
spotify/SPTDataLoader
Sources/SPTDataLoaderSwift/DataLoader.swift
1
1846
// Copyright 2015-2022 Spotify AB // // 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 /// A protocol that provides data request handling. public protocol DataLoader { /// The executed requests currently awaiting a response. var activeRequests: [Request] { get } /// Creates a `Request` that can be used to retrieve the contents of a URL. /// - Parameter url: The `URL` for the request. /// - Parameter sourceIdentifier: The identifier for the request source. May be `nil`. /// - Returns: A new `Request` instance. func request(_ url: URL, sourceIdentifier: String?) -> Request /// Cancels all requests that have been executed and are awaiting a response. func cancelActiveRequests() } public extension SPTDataLoaderFactory { /// Convenience method for creating a Swift `DataLoader`. /// - Parameter responseQueue: The `DispatchQueue` on which to perform response handling. /// - Returns: A new `DataLoader` instance. func makeDataLoader(responseQueue: DispatchQueue = .global()) -> DataLoader { let sptDataLoader = createDataLoader() let dataLoaderWrapper = DataLoaderWrapper(dataLoader: sptDataLoader) sptDataLoader.delegate = dataLoaderWrapper sptDataLoader.delegateQueue = responseQueue return dataLoaderWrapper } }
apache-2.0
7b3b4d04f45b4685dcaedbc25b1ceb97
40.022222
93
0.72156
4.697201
false
false
false
false
digoreis/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0121.xcplaygroundpage/Contents.swift
1
6081
/*: # Remove `Optional` Comparison Operators * Proposal: [SE-0121](0121-remove-optional-comparison-operators.md) * Author: [Jacob Bandes-Storch](https://github.com/jtbandes) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000245.html) * Pull Request: [apple/swift#3637](https://github.com/apple/swift/pull/3637) ## Introduction Swift's [`Comparable` protocol](https://developer.apple.com/reference/swift/comparable) requires 4 operators, [`<`, `<=`, `>`, and `>=`](https://github.com/apple/swift/blob/5868f9c597088793f7131d4655dd0f702a04dea3/stdlib/public/core/Policy.swift#L729-L763), beyond the requirements of Equatable. The standard library [additionally defines](https://github.com/apple/swift/blob/2a545eaa1bfd7d058ef491135cca270bc8e4be5f/stdlib/public/core/Optional.swift#L383-L419) the following 4 variants, which accept operands of Optional type, with the semantics that `.none < .some(_)`: ```swift public func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool public func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool public func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool public func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool ``` This proposal removes the above 4 functions. swift-evolution discussion threads: - [Optional comparison operators](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160711/024121.html) - [Possible bug with arithmetic optional comparison ?](https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20160523/002095.html) - [? suffix for <, >, <=, >= comparisons with optionals to prevent subtle bugs](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001264.html) ## Motivation These optional-friendly comparison operators exist to provide an ordering between optional and non-optional values of the same (Comparable) type. Ostensibly such a feature would be useful in generic programming, allowing algorithms written for Comparable values to be used with optionals: ```swift [3, nil, 1, 2].sorted() // returns [nil, 1, 2, 3] ``` However, **this doesn't work** in current versions of Swift, because generics don't support conditional conformances like `extension Optional: Comparable where Wrapped: Comparable`, so Optional is not actually Comparable. The most common uses of these operators involve coercion or promotion from non-optional to optional types, such as: ```swift let a: Int? = 4 let b: Int = 5 a < b // b is coerced from "Int" to "Int?" to match the parameter type. ``` [SE-0123](0123-disallow-value-to-optional-coercion-in-operator-arguments.md) seeks to remove this coercion (for arguments to operators) for a variety of reasons. If the coercion is not removed (if no change is made), the results of comparisons with Optional values are sometimes **surprising**, making it easy to write bugs. In a thread from December 2015, [Al Skipp offers](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001267.html) the following example: ```swift struct Pet { let age: Int } struct Person { let name: String let pet: Pet? } let peeps = [ Person(name: "Fred", pet: Pet(age: 5)), Person(name: "Jill", pet: .None), // no pet here Person(name: "Burt", pet: Pet(age: 10)), ] let ps = peeps.filter { $0.pet?.age < 6 } ps == [Fred, Jill] // if you don’t own a pet, your non-existent pet is considered to be younger than any actual pet 🐶 ``` On the other hand, if coercion **is** removed for operator arguments, callers will be required to explicitly handle mixtures of optional and non-optional values in their code, which reduces the "surprise factor": ```swift let a: Int? = 4 let b: Int = 5 a < b // no longer works a < .some(b) // works a < Optional(b) // works ``` In either case, what remains is to decide whether these semantics (that `nil` is "less than" any non-`nil` value) are actually useful and worth keeping. Until generics are more mature, the issue of Optional being conditionally Comparable can't be fully discussed/implemented, so it makes the most sense to remove these questionably-useful operators for now (a breaking change for Swift 3), and add them back in the future if desired. ## Proposed solution Remove the versions of `<`, `<=`, `>`, and `>=` which accept optional operands. Variants of `==` and `!=` which accept optional operands are still useful, and their results unsurprising, so they will remain. (In the future, once it is possible for Optional to conditionally conform to Comparable, it may make sense to reintroduce these operators by adding such a conformance.) ## Impact on existing code Code which compares optional values: ```swift let a: Int? let b: Int if a < b { ... } // if coercion remains if a < .some(b) { ... } // if coercion is removed ``` will need to be updated to explicitly unwrap the values before comparing: ```swift if let a = a where a < b { ... } // or guard let a = a else { ... } if a < b { ... } // or if a! < b { ... } ``` This impact is potentially severe, however it may reveal previously-subtle bugs in user code. (The severity will also be somewhat mitigated if optional coercion is removed, since those changes will affect all the same call sites.) Fix-it hints for adding `!` are already provided when optional values are passed to non-optional parameters. However, this would significantly change the meaning of user code: `a! < b` may trap where `a < b` would have previously returned `false`. At the core team's discretion, deprecating the functions (with a helpful message) before removing them may be the best course of action. ## Alternatives considered The alternative is to keep these operators as they are. As discussed above, this leaves the potential for surprising results, and the fact remains that removing them after Swift 3 would break source stability (while reintroducing them later would be purely additive). ---------- [Previous](@previous) | [Next](@next) */
mit
7a7dd7211a933110b1ff44b7f012331d
46.46875
433
0.731402
3.695864
false
false
false
false
nanthi1990/CVCalendar
CVCalendar/CVCalendarViewAnimator.swift
8
4281
// // CVCalendarViewAnimator.swift // CVCalendar // // Created by E. Mozharovsky on 12/27/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarViewAnimator { private unowned let calendarView: CalendarView // MARK: - Public properties public var delegate: CVCalendarViewAnimatorDelegate! public var coordinator: CVCalendarDayViewControlCoordinator { get { return calendarView.coordinator } } // MARK: - Init public init(calendarView: CalendarView) { self.calendarView = calendarView delegate = self } } // MARK: - Public methods extension CVCalendarViewAnimator { public func animateSelectionOnDayView(dayView: DayView) { let selectionAnimation = delegate.selectionAnimation() dayView.setSelectedWithType(.Single) selectionAnimation(dayView) { [unowned dayView] _ in // Something... } } public func animateDeselectionOnDayView(dayView: DayView) { let deselectionAnimation = delegate.deselectionAnimation() deselectionAnimation(dayView) { [weak dayView] _ in if let selectedDayView = dayView { self.coordinator.deselectionPerformedOnDayView(selectedDayView) } } } } // MARK: - CVCalendarViewAnimatorDelegate extension CVCalendarViewAnimator: CVCalendarViewAnimatorDelegate { @objc public func selectionAnimation() -> ((DayView, ((Bool) -> ())) -> ()) { return selectionWithBounceEffect() } @objc public func deselectionAnimation() -> ((DayView, ((Bool) -> ())) -> ()) { return deselectionWithFadeOutEffect() } } // MARK: - Default animations private extension CVCalendarViewAnimator { func selectionWithBounceEffect() -> ((DayView, ((Bool) -> ())) -> ()) { return { dayView, completion in dayView.dayLabel?.transform = CGAffineTransformMakeScale(0.5, 0.5) dayView.circleView?.transform = CGAffineTransformMakeScale(0.5, 0.5) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { dayView.circleView?.transform = CGAffineTransformMakeScale(1, 1) dayView.dayLabel?.transform = CGAffineTransformMakeScale(1, 1) }, completion: completion) } } func deselectionWithBubbleEffect() -> ((DayView, ((Bool) -> ())) -> ()) { return { dayView, completion in UIView.animateWithDuration(0.15, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: { dayView.circleView!.transform = CGAffineTransformMakeScale(1.3, 1.3) }) { _ in UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { if let circleView = dayView.circleView { circleView.transform = CGAffineTransformMakeScale(0.1, 0.1) } }, completion: completion) } } } func deselectionWithFadeOutEffect() -> ((DayView, ((Bool) -> ())) -> ()) { return { dayView, completion in UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: nil, animations: { dayView.setDeselectedWithClearing(false) // return labels' defaults while circle view disappearing if let circleView = dayView.circleView { circleView.alpha = 0 } }, completion: completion) } } func deselectionWithRollingEffect() -> ((DayView, ((Bool) -> ())) -> ()) { return { dayView, completion in UIView.animateWithDuration(0.25, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in dayView.circleView?.transform = CGAffineTransformMakeScale(0.1, 0.1) dayView.circleView?.alpha = 0.0 }, completion: completion) } } }
mit
be238f6198dbedfbab4eab82b56bf9b0
36.226087
179
0.620416
5.151625
false
false
false
false
treejames/firefox-ios
Client/Frontend/Home/HistoryPanel.swift
3
18974
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import XCGLogger private let log = Logger.browserLogger private func getDate(#dayOffset: Int) -> NSDate { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let nowComponents = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: NSDate()) let today = calendar.dateFromComponents(nowComponents)! return calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: dayOffset, toDate: today, options: nil)! } private typealias SectionNumber = Int private typealias CategoryNumber = Int private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int) private struct HistoryPanelUX { static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize, weight: UIFontWeightLight) // Changes font size based on device. static let WelcomeScreenItemTextColor = UIColor.grayColor() static let WelcomeScreenItemWidth = 170 } class HistoryPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() private let QueryLimit = 100 private let NumSections = 4 private let Today = getDate(dayOffset: 0) private let Yesterday = getDate(dayOffset: -1) private let ThisWeek = getDate(dayOffset: -7) // Category number (index) -> (UI section, row count, cursor offset). private var categories: [CategorySpec] = [CategorySpec]() // Reverse lookup from UI section to data category. private var sectionLookup = [SectionNumber: CategoryNumber]() private lazy var defaultIcon: UIImage = { return UIImage(named: "defaultFavicon")! }() var refreshControl: UIRefreshControl? init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationPrivateDataCleared, object: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.accessibilityIdentifier = "History List" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for // the refresh to finish before removing the control. if profile.hasSyncableAccount() && self.refreshControl == nil { addRefreshControl() } else if self.refreshControl?.refreshing == false { removeRefreshControl() } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataCleared, object: nil) } func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationPrivateDataCleared: resyncHistory() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func addRefreshControl() { let refresh = UIRefreshControl() refresh.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.refreshControl = refresh self.tableView.addSubview(refresh) } func removeRefreshControl() { self.refreshControl?.removeFromSuperview() self.refreshControl = nil } func endRefreshing() { // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !self.profile.hasSyncableAccount() { self.removeRefreshControl() } } /** * sync history with the server and ensure that we update our view afterwards **/ func resyncHistory() { profile.syncManager.syncHistory().uponQueue(dispatch_get_main_queue()) { result in if result.isSuccess { self.reloadData() } else { self.endRefreshing() } } } /** * called by the table view pull to refresh **/ @objc func refresh() { self.refreshControl?.beginRefreshing() resyncHistory() } /** * fetch from the profile **/ private func fetchData() -> Deferred<Result<Cursor<Site>>> { return profile.history.getSitesByLastVisit(QueryLimit) } private func setData(data: Cursor<Site>) { self.data = data self.computeSectionOffsets() } /** * Update our view after a data refresh **/ override func reloadData() { self.fetchData().uponQueue(dispatch_get_main_queue()) { result in if let data = result.successValue { self.setData(data) self.tableView.reloadData() self.updateEmptyPanelState() } self.endRefreshing() // TODO: error handling. } } private func updateEmptyPanelState() { if data.count == 0 { if self.emptyStateOverlayView.superview == nil { self.tableView.addSubview(self.emptyStateOverlayView) self.emptyStateOverlayView.snp_makeConstraints { make -> Void in make.edges.equalTo(self.tableView) make.size.equalTo(self.view) } } } else { self.emptyStateOverlayView.removeFromSuperview() } } private func createEmptyStateOverview() -> UIView { let overlayView = UIView() overlayView.backgroundColor = UIColor.whiteColor() let logoImageView = UIImageView(image: UIImage(named: "emptyHistory")) overlayView.addSubview(logoImageView) logoImageView.snp_makeConstraints({ (make) -> Void in make.centerX.equalTo(overlayView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView.snp_centerY).offset(-160).priorityMedium() // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView.snp_top).offset(50).priorityHigh() }) let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Pages you have visited recently will show up here.", comment: "See http://bit.ly/1I7Do4b") welcomeLabel.textAlignment = NSTextAlignment.Center welcomeLabel.font = HistoryPanelUX.WelcomeScreenItemFont welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor welcomeLabel.numberOfLines = 2 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp_makeConstraints({ (make) -> Void in make.centerX.equalTo(overlayView) make.top.equalTo(logoImageView.snp_bottom).offset(HistoryPanelUX.WelcomeScreenPadding) make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth) }) return overlayView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) let category = self.categories[indexPath.section] if let site = data[indexPath.row + category.offset] { if let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView?.setIcon(site.icon, withPlaceholder: self.defaultIcon) } } return cell } private func siteForIndexPath(indexPath: NSIndexPath) -> Site? { let offset = self.categories[sectionLookup[indexPath.section]!].offset return data[indexPath.row + offset] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let site = self.siteForIndexPath(indexPath), let url = NSURL(string: site.url) { let visitType = VisitType.Typed // Means History, too. homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType) return } log.warning("No site or no URL when selecting row.") } // Functions that deal with showing header rows. func numberOfSectionsInTableView(tableView: UITableView) -> Int { var count = 0 for category in self.categories { if category.rows > 0 { count++ } } return count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = String() switch sectionLookup[section]! { case 0: title = NSLocalizedString("Today", comment: "History tableview section header") case 1: title = NSLocalizedString("Yesterday", comment: "History tableview section header") case 2: title = NSLocalizedString("Last week", comment: "History tableview section header") case 3: title = NSLocalizedString("Last month", comment: "History tableview section header") default: assertionFailure("Invalid history section \(section)") } return title.uppercaseString } func categoryForDate(date: MicrosecondTimestamp) -> Int { let date = Double(date) if date > (1000000 * Today.timeIntervalSince1970) { return 0 } if date > (1000000 * Yesterday.timeIntervalSince1970) { return 1 } if date > (1000000 * ThisWeek.timeIntervalSince1970) { return 2 } return 3 } private func isInCategory(date: MicrosecondTimestamp, category: Int) -> Bool { return self.categoryForDate(date) == category } func computeSectionOffsets() { var counts = [Int](count: NumSections, repeatedValue: 0) // Loop over all the data. Record the start of each "section" of our list. for i in 0..<data.count { if let site = data[i] { counts[categoryForDate(site.latestVisit!.date)]++ } } var section = 0 var offset = 0 self.categories = [CategorySpec]() for i in 0..<NumSections { let count = counts[i] if count > 0 { log.debug("Category \(i) has \(count) rows, and thus is section \(section).") self.categories.append((section: section, rows: count, offset: offset)) sectionLookup[section] = i offset += count section++ } else { log.debug("Category \(i) has 0 rows, and thus has no section.") self.categories.append((section: nil, rows: 0, offset: offset)) } } } // UI sections disappear as categories empty. We need to translate back and forth. private func uiSectionToCategory(section: SectionNumber) -> CategoryNumber { for i in 0..<self.categories.count { if let s = self.categories[i].section where s == section { return i } } return 0 } private func categoryToUISection(category: CategoryNumber) -> SectionNumber? { return self.categories[category].section } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.categories[uiSectionToCategory(section)].rows } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let title = NSLocalizedString("Remove", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in if let site = self.siteForIndexPath(indexPath) { // Compute the section in advance -- if we try to do this below, naturally the category // will be empty, and so there will be no section in the CategorySpec! let category = self.categoryForDate(site.latestVisit!.date) let section = self.categoryToUISection(category)! // Why the dispatches? Because we call success and failure on the DB // queue, and so calling anything else that calls through to the DB will // deadlock. This problem will go away when the history API switches to // Deferred instead of using callbacks. self.profile.history.removeHistoryForURL(site.url) .upon { res in self.fetchData().uponQueue(dispatch_get_main_queue()) { result in // If a section will be empty after removal, we must remove the section itself. if let data = result.successValue { let oldCategories = self.categories self.data = data self.computeSectionOffsets() let sectionsToDelete = NSMutableIndexSet() var rowsToDelete = [NSIndexPath]() let sectionsToAdd = NSMutableIndexSet() var rowsToAdd = [NSIndexPath]() for (index, category) in enumerate(self.categories) { let oldCategory = oldCategories[index] // don't bother if we're not displaying this category if oldCategory.section == nil && category.section == nil { continue } // 1. add a new section if the section didn't previously exist if oldCategory.section == nil && category.section != oldCategory.section { log.debug("adding section \(category.section)") sectionsToAdd.addIndex(category.section!) } // 2. add a new row if there are more rows now than there were before if oldCategory.rows < category.rows { log.debug("adding row to \(category.section) at \(category.rows-1)") rowsToAdd.append(NSIndexPath(forRow: category.rows-1, inSection: category.section!)) } // if we're dealing with the section where the row was deleted: // 1. if the category no longer has a section, then we need to delete the entire section // 2. delete a row if the number of rows has been reduced // 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same if oldCategory.section == indexPath.section { if category.section == nil { log.debug("deleting section \(indexPath.section)") sectionsToDelete.addIndex(indexPath.section) } else if oldCategory.section == category.section { if oldCategory.rows > category.rows { log.debug("deleting row from \(category.section) at \(indexPath.row)") rowsToDelete.append(indexPath) } else if category.rows == oldCategory.rows { log.debug("in section \(category.section), removing row at \(indexPath.row) and inserting row at \(category.rows-1)") rowsToDelete.append(indexPath) rowsToAdd.append(NSIndexPath(forRow: category.rows-1, inSection: indexPath.section)) } } } } tableView.beginUpdates() if sectionsToAdd.count > 0 { tableView.insertSections(sectionsToAdd, withRowAnimation: UITableViewRowAnimation.Left) } if sectionsToDelete.count > 0 { tableView.deleteSections(sectionsToDelete, withRowAnimation: UITableViewRowAnimation.Right) } if !rowsToDelete.isEmpty { tableView.deleteRowsAtIndexPaths(rowsToDelete, withRowAnimation: UITableViewRowAnimation.Right) } if !rowsToAdd.isEmpty { tableView.insertRowsAtIndexPaths(rowsToAdd, withRowAnimation: UITableViewRowAnimation.Right) } tableView.endUpdates() self.updateEmptyPanelState() } } } } }) return [delete] } }
mpl-2.0
1675835eb009886846f1832881ed6c42
42.819861
165
0.588911
5.802446
false
false
false
false
edx/edx-app-ios
Test/YoutubeVideoPlayerTests.swift
1
2502
// // YoutubeVideoPlayerTests.swift // edXTests // // Created by AndreyCanon on 9/28/18. // Copyright © 2018 edX. All rights reserved. // import XCTest @testable import edX class YoutubeVideoPlayerTests: XCTestCase { let course = OEXCourse.freshCourse() var outline: CourseOutline! var environment: TestRouterEnvironment! var youtubeVideoPlayer : YoutubeVideoPlayer? let networkManager = MockNetworkManager(baseURL: URL(string: "www.example.com")!) override func setUp() { super.setUp() outline = CourseOutlineTestDataFactory.freshCourseOutline(course.course_id!) let youtubeConfig = ["ENABLED": false] as [String: Any] let config = OEXConfig(dictionary: ["COURSE_VIDEOS_ENABLED": true, "YOUTUBE_VIDEO": youtubeConfig]) let interface = OEXInterface.shared() environment = TestRouterEnvironment(config: config, interface: interface) environment.mockCourseDataManager.querier = CourseOutlineQuerier(courseID: outline.root, interface: interface, outline: outline) youtubeVideoPlayer = YoutubeVideoPlayer(environment: environment) } func testVideoPlay() { let summary = OEXVideoSummary(videoID: "some-video", name: "Youtube Video", encodings: [ OEXVideoEncodingYoutube: OEXVideoEncoding(name: OEXVideoEncodingYoutube, url: "https://some-youtube-url/watch?v=abc123", size: 12)]) let video = OEXHelperVideoDownload() video.summary = summary youtubeVideoPlayer?.play(video: video) XCTAssertEqual("abc123", youtubeVideoPlayer?.videoID) } func testVideoPlayerProtraitView() { let screenSize: CGRect = UIScreen.main.bounds youtubeVideoPlayer?.setVideoPlayerMode(isPortrait: false) var landScapeSize = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height - (youtubeVideoPlayer?.viewHeightOffset ?? 0)) XCTAssertEqual(landScapeSize, youtubeVideoPlayer?.playerView.frame) landScapeSize = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.width * CGFloat(STANDARD_VIDEO_ASPECT_RATIO)) youtubeVideoPlayer?.setVideoPlayerMode(isPortrait: true) XCTAssertEqual(landScapeSize, youtubeVideoPlayer?.playerView.frame) } func testViewDidLoad() { youtubeVideoPlayer?.viewDidLoad() XCTAssertTrue((youtubeVideoPlayer?.playerView.isDescendant(of: (youtubeVideoPlayer?.view)!))!) } }
apache-2.0
fbb5665b07d72456cac1aba217a57d8a
42.12069
144
0.69932
4.622921
false
true
false
false
Ashok28/Kingfisher
Demo/Demo/Kingfisher-macOS-Demo/ViewController.swift
2
2884
// // ViewController.swift // Kingfisher-macOS-Demo // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import AppKit import Kingfisher class ViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Kingfisher" } @IBAction func clearCachePressed(sender: AnyObject) { KingfisherManager.shared.cache.clearMemoryCache() KingfisherManager.shared.cache.clearDiskCache() } @IBAction func reloadPressed(sender: AnyObject) { collectionView.reloadData() } } extension ViewController: NSCollectionViewDataSource { func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), for: indexPath) let url = URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.item + 1).jpg")! item.imageView?.kf.indicatorType = .activity KF.url(url) .roundCorner(radius: .point(20)) .onProgress { receivedSize, totalSize in print("\(indexPath.item + 1): \(receivedSize)/\(totalSize)") } .onSuccess { print($0) } .set(to: item.imageView!) // Set imageView's `animates` to true if you are loading a GIF. // item.imageView?.animates = true return item } }
mit
005579aff1ea399fdb5888e325054d2b
39.619718
137
0.700069
4.743421
false
false
false
false
DanielAsher/VIPER-SWIFT
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Connectable_Observable_Operators.xcplaygroundpage/Contents.swift
2
4607
/*: > # IMPORTANT: To use `Rx.playground`, please: 1. Open `Rx.xcworkspace` 2. Build `RxSwift-OSX` scheme 3. And then open `Rx` playground in `Rx.xcworkspace` tree view. 4. Choose `View > Show Debug Area` */ //: [<< Previous](@previous) - [Index](Index) import RxSwift /*: ## Below every example there is a commented method call that runs that example. To run the example just uncomment that part. E.g. `//sampleWithoutConnectableOperators()` */ /*: ## Connectable Observable Operators A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when its connect() method is called. In this way you can wait for all intended Subscribers to subscribe to the Observable before the Observable begins emitting items. Specialty Observables that have more precisely-controlled subscription dynamics. */ func sampleWithoutConnectableOperators() { let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) _ = int1 .subscribe { print("first subscription \($0)") } delay(5) { _ = int1 .subscribe { print("second subscription \($0)") } } } //sampleWithoutConnectableOperators() /*: ### `multicast` ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishconnect.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html ) */ func sampleWithMulticast() { let subject1 = PublishSubject<Int64>() _ = subject1 .subscribe { print("Subject \($0)") } let int1 = Observable<Int64>.interval(1, scheduler: MainScheduler.instance) .multicast(subject1) _ = int1 .subscribe { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { _ = int1 .subscribe { print("second subscription \($0)") } } delay(6) { _ = int1 .subscribe { print("third subscription \($0)") } } } // sampleWithMulticast() /*: ### `replay` Ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items. publish = multicast + replay subject ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replay.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/replay.html ) */ func sampleWithReplayBuffer0() { let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .replay(0) _ = int1 .subscribe { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { _ = int1 .subscribe { print("second subscription \($0)") } } delay(6) { _ = int1 .subscribe { print("third subscription \($0)") } } } // sampleWithReplayBuffer0() func sampleWithReplayBuffer2() { print("--- sampleWithReplayBuffer2 ---\n") let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .replay(2) _ = int1 .subscribe { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { _ = int1 .subscribe { print("second subscription \($0)") } } delay(6) { _ = int1 .subscribe { print("third subscription \($0)") } } } // sampleWithReplayBuffer2() /*: ### `publish` Convert an ordinary Observable into a connectable Observable. publish = multicast + publish subject so publish is basically replay(0) [More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html ) */ func sampleWithPublish() { let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .publish() _ = int1 .subscribe { print("first subscription \($0)") } delay(2) { int1.connect() } delay(4) { _ = int1 .subscribe { print("second subscription \($0)") } } delay(6) { _ = int1 .subscribe { print("third subscription \($0)") } } } // sampleWithPublish() playgroundShouldContinueIndefinitely() //: [Index](Index)
mit
5f1f7d61aa719100b59c13f5cbf0d8e7
19.846154
305
0.582592
4.246083
false
false
false
false
gregomni/swift
test/Generics/redundant_protocol_refinement.swift
2
1760
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on // RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s // CHECK-LABEL: redundant_protocol_refinement.(file).Base@ // CHECK-LABEL: Requirement signature: <Self> protocol Base {} // CHECK-LABEL: redundant_protocol_refinement.(file).Middle@ // CHECK-LABEL: Requirement signature: <Self where Self : Base> protocol Middle : Base {} // CHECK-LABEL: redundant_protocol_refinement.(file).Derived@ // CHECK-LABEL: Requirement signature: <Self where Self : Middle> protocol Derived : Middle, Base {} // expected-warning@-1 {{redundant conformance constraint 'Self' : 'Base'}} // CHECK-LABEL: redundant_protocol_refinement.(file).Derived2@ // CHECK-LABEL: Requirement signature: <Self where Self : Middle> protocol Derived2 : Middle {} // CHECK-LABEL: redundant_protocol_refinement.(file).MoreDerived@ // CHECK-LABEL: Requirement signature: <Self where Self : Derived2> protocol MoreDerived : Derived2, Base {} // expected-warning@-1 {{redundant conformance constraint 'Self' : 'Base'}} protocol P1 {} protocol P2 { associatedtype Assoc: P1 } // no warning here protocol Good: P2, P1 where Assoc == Self {} // CHECK-LABEL: redundant_protocol_refinement.(file).Good@ // CHECK-LABEL: Requirement signature: <Self where Self : P1, Self : P2, Self == Self.[P2]Assoc> // missing refinement of 'P1' protocol Bad: P2 where Assoc == Self {} // expected-warning@-1 {{protocol 'Bad' should be declared to refine 'P1' due to a same-type constraint on 'Self'}} // CHECK-LABEL: redundant_protocol_refinement.(file).Bad@ // CHECK-LABEL: Requirement signature: <Self where Self : P2, Self == Self.[P2]Assoc>
apache-2.0
35ac2cb9ac93cd5ef97b65f32afbea6b
39.930233
135
0.731818
3.689727
false
false
false
false
colemancda/NetworkObjects
NetworkObjects/NetworkObjects/CoreDataClient.swift
1
14588
// // CoreDataClient.swift // NetworkObjects // // Created by Alsey Coleman Miller on 9/28/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import Foundation import SwiftFoundation import CoreData import CoreModel /// This is the class that will fetch and cache data from the server (using CoreData). public final class CoreDataClient<Client: ClientType> { // MARK: - Properties /// The client that will be used for fetching requests. public let client: Client /** The managed object context used for caching. */ public let managedObjectContext: NSManagedObjectContext /** A convenience variable for the managed object model. */ public let managedObjectModel: NSManagedObjectModel /** The name of the string attribute that holds that resource identifier. */ public let resourceIDAttributeName: String /// The name of a for the date attribute that can be optionally added at runtime for cache validation. public let dateCachedAttributeName: String? // MARK: - Private Properties /** The managed object context running on a background thread for asyncronous caching. */ private let privateQueueManagedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType) private let store: CoreDataStore /// Request queue private let requestQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "NetworkObjects.CoreDataClient Request Queue" return queue }() // MARK: - Initialization deinit { // stop recieving 'didSave' notifications from private context NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: self.privateQueueManagedObjectContext) } /// Creates the Store using the specified options. /// /// - Note: The created ```NSManagedObjectContext``` will need a persistent store added /// to its persistent store coordinator. public init(managedObjectModel: NSManagedObjectModel, concurrencyType: NSManagedObjectContextConcurrencyType = .MainQueueConcurrencyType, client: Client, resourceIDAttributeName: String = "id", dateCachedAttributeName: String? = "dateCached") { self.client = client self.resourceIDAttributeName = resourceIDAttributeName self.dateCachedAttributeName = dateCachedAttributeName self.managedObjectModel = managedObjectModel.copy() as! NSManagedObjectModel // setup Core Data stack // edit model if self.dateCachedAttributeName != nil { self.managedObjectModel.addDateCachedAttribute(dateCachedAttributeName!) } self.managedObjectModel.markAllPropertiesAsOptional() self.managedObjectModel.addResourceIDAttribute(resourceIDAttributeName) // setup managed object contexts self.managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType) self.managedObjectContext.undoManager = nil self.managedObjectContext.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) self.privateQueueManagedObjectContext.undoManager = nil self.privateQueueManagedObjectContext.persistentStoreCoordinator = self.managedObjectContext.persistentStoreCoordinator // set private context name if #available(OSX 10.10, *) { self.privateQueueManagedObjectContext.name = "NetworkObjects.CoreDataClient Private Managed Object Context" } // setup CoreDataStore guard let store = CoreDataStore(model: client.model, managedObjectContext: privateQueueManagedObjectContext, resourceIDAttributeName: resourceIDAttributeName) else { fatalError("Could not create CoreDataStore") } self.store = store // listen for notifications (for merging changes) NSNotificationCenter.defaultCenter().addObserver(self, selector: "mergeChangesFromContextDidSaveNotification:", name: NSManagedObjectContextDidSaveNotification, object: self.privateQueueManagedObjectContext) } // MARK: - Actions /// Performs a search request on the server. /// /// - precondition: The supplied fetch request's predicate must be a ```NSComparisonPredicate``` or ```NSCompoundPredicate``` instance. /// public func search<T: NSManagedObject>(fetchRequest: FetchRequest, completionBlock: ((ErrorValue<[T]>) -> Void)) { guard let entity = self.managedObjectModel.entitiesByName[fetchRequest.entityName] else { fatalError("Entity \(fetchRequest.entityName) not found on managed object model") } requestQueue.addOperationWithBlock { var objectIDs = [NSManagedObjectID]() do { // perform request let results = try self.client.search(fetchRequest) let resourceIDs = results.map({ (resource) -> String in resource.resourceID }) // got response, cache results try self.store.cacheResponse(Response.Search(resourceIDs), forRequest: Request.Search(fetchRequest), dateCachedAttributeName: self.dateCachedAttributeName) // get object IDs for resource in results { guard let objectID = try self.store.findEntity(entity, withResourceID: resource.resourceID) else { fatalError("Could not find cached resource: \(resource)") } objectIDs.append(objectID) } } catch { completionBlock(.Error(error)) return } // get the corresponding managed objects that belong to the main queue context var mainContextResults = [T]() self.managedObjectContext.performBlockAndWait { for objectID in objectIDs { let managedObject = self.managedObjectContext.objectWithID(objectID) as! T mainContextResults.append(managedObject) } } completionBlock(.Value(mainContextResults)) } } /** Convenience method for fetching the values of a cached entity. */ public func fetch<T: NSManagedObject>(managedObject: T, completionBlock: ((ErrorValue<T>) -> Void)) { let entityName = managedObject.entity.name! let resourceID = (managedObject as NSManagedObject).valueForKey(self.resourceIDAttributeName) as! String let resource = Resource(entityName, resourceID) return self.fetch(resource, completionBlock: { (errorValue: ErrorValue<T>) -> Void in // forward completionBlock(errorValue) }) } /** Fetches the entity from the server using the specified ```entityName``` and ```resourceID```. */ public func fetch<T: NSManagedObject>(resource: Resource, completionBlock: ((ErrorValue<T>) -> Void)) { guard let entity = self.managedObjectModel.entitiesByName[resource.entityName] else { fatalError("Entity \(resource.entityName) not found on managed object model") } requestQueue.addOperationWithBlock { let objectID: NSManagedObjectID do { // perform request let values = try self.client.get(resource) // got response, cache results try self.store.cacheResponse(Response.Get(values), forRequest: Request.Get(resource), dateCachedAttributeName: self.dateCachedAttributeName) // get object ID guard let foundID = try self.store.findEntity(entity, withResourceID: resource.resourceID) else { fatalError("Could not find cached resource: \(resource)") } objectID = foundID } catch { completionBlock(.Error(error)) return } // get the corresponding managed object that belongs to the main queue context var managedObject: T! self.managedObjectContext.performBlockAndWait { managedObject = self.managedObjectContext.objectWithID(objectID) as! T } completionBlock(.Value(managedObject)) } } public func create<T: NSManagedObject>(entityName: String, initialValues: ValuesObject = ValuesObject(), completionBlock: ((ErrorValue<T>) -> Void)) { guard let entity = self.managedObjectModel.entitiesByName[entityName] else { fatalError("Entity \(entityName) not found on managed object model") } requestQueue.addOperationWithBlock { let objectID: NSManagedObjectID do { // perform request let (resource, values) = try self.client.create(entityName, initialValues: initialValues) // got response, cache results try self.store.cacheResponse(Response.Create(resource.resourceID, values), forRequest: Request.Create(entityName, initialValues), dateCachedAttributeName: self.dateCachedAttributeName) // get object ID guard let foundID = try self.store.findEntity(entity, withResourceID: resource.resourceID) else { fatalError("Could not find cached resource: \(resource)") } objectID = foundID } catch { completionBlock(.Error(error)) return } // get the corresponding managed object that belongs to the main queue context var managedObject: T! self.managedObjectContext.performBlockAndWait { managedObject = self.managedObjectContext.objectWithID(objectID) as! T } completionBlock(.Value(managedObject)) } } public func edit<T: NSManagedObject>(managedObject: T, changes: ValuesObject, completionBlock: ((ErrorType?) -> Void)) { let entityName = managedObject.entity.name! let resourceID = (managedObject as NSManagedObject).valueForKey(self.resourceIDAttributeName) as! String let resource = Resource(entityName, resourceID) requestQueue.addOperationWithBlock { do { // perform request let values = try self.client.edit(resource, changes: changes) // got response, cache results try self.store.cacheResponse(Response.Edit(values), forRequest: Request.Edit(resource, changes), dateCachedAttributeName: self.dateCachedAttributeName) } catch { completionBlock(error) return } completionBlock(nil) } } public func delete<T: NSManagedObject>(managedObject: T, URLSession: NSURLSession? = nil, completionBlock: ((ErrorType?) -> Void)) { let entityName = managedObject.entity.name! let resourceID = (managedObject as NSManagedObject).valueForKey(self.resourceIDAttributeName) as! String let resource = Resource(entityName, resourceID) requestQueue.addOperationWithBlock { do { try self.client.delete(resource) // got response, cache results try self.store.cacheResponse(Response.Delete, forRequest: Request.Delete(resource), dateCachedAttributeName: self.dateCachedAttributeName) } catch { completionBlock(error) return } completionBlock(nil) } } public func performFunction<T: NSManagedObject>(functionName: String, managedObject: T, parameters: JSON.Object? = nil, completionBlock: ((ErrorValue<JSON.Object?>) -> Void)) { let entityName = managedObject.entity.name! let resourceID = (managedObject as NSManagedObject).valueForKey(self.resourceIDAttributeName) as! String let resource = Resource(entityName, resourceID) requestQueue.addOperationWithBlock { let jsonResponse: JSON.Object? do { jsonResponse = try self.client.performFunction(resource, functionName: functionName, parameters: parameters) // no caching function responses... } catch { completionBlock(.Error(error)) return } completionBlock(.Value(jsonResponse)) } } // MARK: - Notifications @objc private func mergeChangesFromContextDidSaveNotification(notification: NSNotification) { self.managedObjectContext.performBlock { () -> Void in self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) } } } // MARK: - Supporting Types /** Basic wrapper for error / value pairs. */ public enum ErrorValue<T> { case Error(ErrorType) case Value(T) }
mit
3c7ce2f539127e59ed79ac9bb94e96e9
37.692308
219
0.587921
6.477353
false
false
false
false
bangslosan/Easy-Game-Center-Swift
Easy-Game-Center-Swift/Packet.swift
1
1922
// // Packet.swift // Easy-Game-Center-Swift // // Created by DaRk-_-D0G on 13/04/2015. // Copyright (c) 2015 DaRk-_-D0G. All rights reserved. // import Foundation /** * Packet */ struct Packet { var name: String var index: Int64 var numberOfPackets: Int64 /** * Struc */ struct ArchivedPacket { var index : Int64 var numberOfPackets : Int64 var nameLength : Int64 } /** Archive Packet :returns: NSData */ func archive() -> NSData { var archivedPacket = ArchivedPacket(index: Int64(self.index), numberOfPackets: Int64(self.numberOfPackets), nameLength: Int64(self.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) var metadata = NSData( bytes: &archivedPacket, length: sizeof(ArchivedPacket) ) let archivedData = NSMutableData(data: metadata) archivedData.appendData(name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) return archivedData } /** Unarchive Packet :param: data NSData :returns: Packet */ static func unarchive(data: NSData!) -> Packet { var archivedPacket = ArchivedPacket(index: 0, numberOfPackets: 0, nameLength: 0) //, dataLength: 0 let archivedStructLength = sizeof(ArchivedPacket) let archivedData = data.subdataWithRange(NSMakeRange(0, archivedStructLength)) archivedData.getBytes(&archivedPacket) let nameRange = NSMakeRange(archivedStructLength, Int(archivedPacket.nameLength)) let nameData = data.subdataWithRange(nameRange) let name = NSString(data: nameData, encoding: NSUTF8StringEncoding) as! String let packet = Packet(name: name, index: archivedPacket.index, numberOfPackets: archivedPacket.numberOfPackets) return packet } }
mit
e5bdf8a1836a9cdff2d9909afdefad1e
28.136364
194
0.644121
4.565321
false
false
false
false
frootloops/swift
test/stdlib/MetalKit.swift
3
1203
// RUN: rm -rf %t ; mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Metal import MetalKit var MetalKitTests = TestSuite("MetalKit") // Call each overlay to ensure nothing explodes if #available(macOS 10.12, iOS 10.0, tvOS 10.0, *) { MetalKitTests.test("Globals") { do { let _ = try MTKModelIOVertexDescriptorFromMetalWithError(MTLVertexDescriptor()) } catch _ { expectUnreachable("MTKModelIOVertexDescriptorFromMetalWithError has thrown an unexpected error") } do { let _ = try MTKMetalVertexDescriptorFromModelIOWithError(MDLVertexDescriptor()) } catch _ { expectUnreachable("MTKMetalVertexDescriptorFromModelIOWithError has thrown an unexpected error") } } } if #available(macOS 10.11, iOS 9.0, tvOS 9.0, *) { MetalKitTests.test("MTKMesh") { func apiAvailabilityTest(device: MTLDevice) { do { let _ = try MTKMesh.newMeshes(asset: MDLAsset(), device: device) } catch _ { expectUnreachable("MTKMesh.newMeshes has thrown an unexpected error") } } } } runAllTests()
apache-2.0
29b60ffb160dc5b8abb6cedb4791a3e7
26.340909
102
0.685786
3.83121
false
true
false
false
khizkhiz/swift
test/PrintAsObjC/mixed-framework.swift
20
1400
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module -parse-as-library %s -parse -emit-objc-header-path %t/mixed.h // RUN: FileCheck -check-prefix=CHECK -check-prefix=FRAMEWORK %s < %t/mixed.h // RUN: %check-in-clang -F %S/Inputs/ %t/mixed.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -parse -emit-objc-header-path %t/mixed-header.h // RUN: FileCheck -check-prefix=CHECK -check-prefix=HEADER %s < %t/mixed-header.h // RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header.h // REQUIRES: objc_interop // CHECK-LABEL: #if defined(__has_feature) && __has_feature(modules) // CHECK-NEXT: @import Foundation; // CHECK-NEXT: #endif // FRAMEWORK-LABEL: #import <Mixed/Mixed.h> // HEADER-NOT: __ObjC // HEADER: #import "{{.*}}Mixed.h" // HEADER-NOT: __ObjC import Foundation // CHECK-LABEL: @interface Dummy : NSNumber public class Dummy: NSNumber { // CHECK: - (CIntAlias)getIntAlias; public func getIntAlias() -> CIntAlias { let result: CInt = 0 return result } // FRAMEWORK: @property (nonatomic, readonly) NSInteger extraData; // HEADER: @property (nonatomic) NSInteger extraData; public internal(set) var extraData: Int = 0 } // CHECK: @end
apache-2.0
c05d4f619184b9a9537b33be892969f3
40.176471
193
0.697143
3.090508
false
false
false
false
lucaangeletti/FireworksKit
FireworksKit/Scene.swift
1
1117
// // Scene.swift // FireworksKit // // Created by Luca Angeletti on 28/07/2017. // Copyright © 2017 Luca Angeletti. All rights reserved. // import SpriteKit class Scene: SKScene { override func didMove(to view: SKView) { super.didMove(to: view) self.anchorPoint.x = 0.5 self.anchorPoint.y = 0.5 backgroundColor = .clear scaleMode = .resizeFill } func removeEmitterNodes() { children.filter { $0 is SKEmitterNode }.forEach { $0.removeFromParent() } } func add(emitterNode: SKEmitterNode, ofType type: ParticleEffectType) { removeEmitterNodes() emitterNode.position.y = { switch type.verticalPosition { case .top: return frame.maxY case .middle: return frame.midY case .bottom: return frame.minY } }() emitterNode.position.x = 0 if type.shouldResize { emitterNode.particlePositionRange.dx = frame.width / 2 emitterNode.particlePositionRange.dx = frame.height / 2 } addChild(emitterNode) } }
mit
71e07590ef2eedfa809a8dbcb7f5ba94
23.26087
81
0.603047
4.275862
false
false
false
false
Nickelfox/TemplateProject
ProjectFiles/Code/Helpers/NavigationItem.swift
1
2276
// // NavigationItem.swift // TemplateProject // // Created by Ravindra Soni on 18/12/16. // Copyright © 2016 Nickelfox. All rights reserved. // import UIKit private let titleFont: UIFont = UIFont.systemFont(ofSize: 18.0) private let barButtonFont: UIFont = UIFont.systemFont(ofSize: 18.0) class StyledNavigationItem: UINavigationItem { @IBInspectable var backButtonTitle: String? = nil { didSet { self.updateBackButtonTitle() } } override var title: String? { didSet { self.updateTitle() } } override func awakeFromNib() { super.awakeFromNib() self.updateTitle() self.updateBackButtonTitle() if let item = self.leftBarButtonItem { self.configureFontsForBarButtonItem(item: item) } if let item = self.rightBarButtonItem { self.configureFontsForBarButtonItem(item: item) } } private func configureFontsForBarButtonItem(item: UIBarButtonItem) { item.setTitleTextAttributes([ NSFontAttributeName: barButtonFont, NSForegroundColorAttributeName: UIColor.white ], for: .normal) } private func updateTitle() { if let title = self.title { self.attributedTitle = NSAttributedString(string: title, attributes: [ NSFontAttributeName: titleFont, NSForegroundColorAttributeName: UIColor.white ]) } else { self.attributedTitle = nil } } private func updateBackButtonTitle() { self.backBarButtonItem = UIBarButtonItem(title: self.backButtonTitle ?? "", style: .plain, target: nil, action: nil) } } private let kAttributedTitleLabelTag = 325 extension UINavigationItem { public var attributedTitle: NSAttributedString? { get { return self.labelForAttributedTitle()?.attributedText } set(attributedTitle){ let label: UILabel if let currentLabel = self.labelForAttributedTitle() { label = currentLabel } else { label = UILabel() label.tag = kAttributedTitleLabelTag self.titleView = label } label.attributedText = attributedTitle label.textAlignment = NSTextAlignment.center label.sizeToFit() } } private func labelForAttributedTitle() -> UILabel? { var label : UILabel? = nil if let currentLabel = self.titleView as? UILabel , currentLabel.tag == kAttributedTitleLabelTag { label = currentLabel } return label } }
mit
261e37648c6637f9081dc9fa0ddb3b81
23.202128
118
0.724396
4.012346
false
false
false
false
jcwcheng/aeire-ios
SmartDoorBell/IndexViewController.swift
1
3234
// // IndexViewController.swift // SmartDoorBell // // Created by Archerwind on 5/23/17. // Copyright © 2017 Archerwind. All rights reserved. // import UIKit import Spring import InteractiveSideMenu class IndexViewController: UIViewController, MenuContainerViewController { @IBOutlet weak var deviceCollectionView: UICollectionView! @IBOutlet weak var roomCollectionView: UICollectionView! @IBOutlet weak var sceneCollectionView: UICollectionView! @IBOutlet weak var homeButton: DesignableButton! @IBOutlet weak var officeButton: DesignableButton! @IBOutlet weak var cottageButton: DesignableButton! @IBAction func notificationAction(_ sender: Any) { let vc = storyboard?.instantiateViewController( withIdentifier: "CallViewController" ) as! CallViewController present( vc, animated: true, completion: nil ) } @IBAction func menuAction(_ sender: Any) { showMenu() } @IBAction func cottageAction(_ sender: Any) { UIView.animate( withDuration: 0.25, animations: { self.homeButton.alpha = 0.3 self.officeButton.alpha = 0.3 self.cottageButton.alpha = 1.0 }) self.sceneCollectionView.reloadData() } @IBAction func officeAction(_ sender: Any) { UIView.animate( withDuration: 0.25, animations: { self.homeButton.alpha = 0.3 self.officeButton.alpha = 1.0 self.cottageButton.alpha = 0.3 }) self.roomCollectionView.reloadData() } @IBAction func homeAction(_ sender: Any) { UIView.animate( withDuration: 0.25, animations: { self.homeButton.alpha = 1.0 self.officeButton.alpha = 0.3 self.cottageButton.alpha = 0.3 }) self.deviceCollectionView.reloadData() } func initializer() { self.deviceCollectionView.delegate = self self.deviceCollectionView.dataSource = self self.roomCollectionView.delegate = self self.roomCollectionView.dataSource = self self.sceneCollectionView.delegate = self self.sceneCollectionView.dataSource = self self.deviceCollectionView.layer.backgroundColor = UIColor.transparent.cgColor self.roomCollectionView.layer.backgroundColor = UIColor.transparent.cgColor self.sceneCollectionView.layer.backgroundColor = UIColor.transparent.cgColor homeButton.kern( 1.2 ) officeButton.kern( 1.2 ) cottageButton.kern( 1.2 ) let countNotification = Notification.Name( "count" ) NotificationCenter.default.addObserver( self, selector: #selector( self.notificationAction(_:) ), name: countNotification, object: nil ) menuViewController = self.storyboard!.instantiateViewController( withIdentifier: "CallViewController" ) as! MenuViewController contentViewControllers = contentControllers() selectContentViewController(contentViewControllers.first!) } override func viewDidLoad() { super.viewDidLoad() self.initializer() } override func viewWillAppear( _ animated: Bool ) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5af459e988a994bdf8b40f2b8cd86707
32.329897
142
0.695639
4.740469
false
false
false
false
producthunt/producthunt-osx
Source/PHPostsModule.swift
1
1275
// // PHPostsModule.swift // Product Hunt // // Created by Vlado on 4/28/16. // Copyright © 2016 ProductHunt. All rights reserved. // import Foundation import ReSwift struct PHPostsLoadAction: Action { var posts: [PHPost] } func postsReducer(_ action: Action, state: PHAppStatePosts?) -> PHAppStatePosts { let state = state ?? PHAppStatePosts(sections: [], lastUpdated: Date()) switch action { case let action as PHPostsLoadAction: if action.posts.isEmpty { return state } let section = PHSection.section(action.posts) var newSections = state.sections var newLastUpdated = state.lastUpdated if PHDateFormatter.daysAgo(section.day) == 0 { if let firstSection = newSections.first, firstSection.day == section.day { newSections[0] = section } else { newSections.insert(section, at: 0) } newLastUpdated = Date() } else { newSections.append(PHSection.section(action.posts)) } return PHAppStatePosts(sections: newSections, lastUpdated: newLastUpdated) default: return state } }
mit
5dbf6511c02ec0fc14b6ade05fbd14a1
26.106383
90
0.581633
4.683824
false
false
false
false
kkolli/MathGame
client/Speedy/LoginViewController.swift
1
5016
// // ViewController.swift // SwiftBook // // Created by Krishna Kolli on 2014-07-07. // Copyright (c) 2014 Krishna Kolli. All rights reserved. //import UIKit import UIKit import SpriteKit import Alamofire class LoginViewController: UIViewController, FBLoginViewDelegate { @IBOutlet weak var NavBar: UINavigationItem! @IBOutlet var fbLoginView : FBLoginView! var alreadyFetched = false var user: FBGraphUser! var appDelegate:AppDelegate! override func viewDidLoad() { super.viewDidLoad() appDelegate = UIApplication.sharedApplication().delegate as AppDelegate // Do any additional setup after loading the view, typically from a nib. println("loaded login view controller") self.fbLoginView.delegate = self self.fbLoginView.readPermissions = ["public_profile", "email", "user_friends"] } override func viewDidAppear(animated: Bool) { if(user != nil){ var rightButton = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action: "moveToPageViewController:") NavBar.rightBarButtonItem = rightButton } } func moveToPageViewController(sender: UIBarButtonItem){ self.performSegueWithIdentifier("login_segue", sender: nil) } // Facebook Delegate Methods func loginViewShowingLoggedInUser(loginView : FBLoginView!) { println("User Logged In") } /* After facebook returns the login info, call the facebook API to give us the friends list When we get the info back, make a post request to our server */ func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser) { self.user = user appDelegate.user = user //println("User: \(user)") //println("User ID: \(user.objectID)") //println("User Name: \(user.name)") var userEmail = user.objectForKey("email") as String //println("User Email: \(userEmail)") // call method to handle getting the user's current/updated friends if !alreadyFetched { alreadyFetched = true getFacebookFriendsList(user, makePostReq) } else { println("already fetched...") } } func makePostReq(user: FBGraphUser, data: NSDictionary) { /*Issue a post request to our server, with the updated/or new user with friends */ let params = [ "fbID": user.objectID, "firstName": user.first_name, "lastName" : user.last_name, //"friends": data.objectForKey("data") as NSArray, "friends_page" : data ] //println("PRINTING PARAMS: ") //println(params) Alamofire.request(.POST, "http://mathisspeedy.herokuapp.com/create_check_user", parameters: params, encoding:.JSON) .responseString { (request, response, data, error) in //println("request: \(request)") //println("response: \(response)") //println("data: \(data)") //println("error: \(error)") if error != nil { println(" errors found") } else { self.performSegueWithIdentifier("login_segue", sender: nil) //perform a segue } } } func getFacebookFriendsList(user: FBGraphUser, handler: (FBGraphUser, NSDictionary) -> Void) { // Get List Of Friends var friendsRequest : FBRequest = FBRequest.requestForMyFriends() friendsRequest.startWithCompletionHandler{(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in if error != nil { println("error: \(error)") return } var resultdict = result as NSDictionary // println("Result Dict: \(resultdict)") var data : NSArray = resultdict.objectForKey("data") as NSArray println("calling handler") handler(user, resultdict) println("called handler...") } } func loginViewShowingLoggedOutUser(loginView : FBLoginView!) { println("User Logged Out") alreadyFetched = false } func loginView(loginView : FBLoginView!, handleError:NSError) { println("Error: \(handleError.localizedDescription)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "login_segue" { println("performing segue") let vc = segue.destinationViewController as MainMenuViewController vc.user = user } } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> Int { return UIInterfaceOrientation.Portrait.rawValue } }
gpl-2.0
87febb51622766b2517f49af9a610457
33.833333
130
0.609051
5.082067
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/Transitions/FluidPhoto/Core/ZoomAnimator.swift
1
7059
// // ZoomAnimator.swift // FluidPhoto // // Created by Masamichi Ueta on 2016/12/23. // Copyright © 2016 Masmichi Ueta. All rights reserved. // import UIKit protocol ZoomAnimatorDelegate: AnyObject { func transitionWillStart(with zoomAnimator: ZoomAnimator) func transitionDidEnd(with zoomAnimator: ZoomAnimator) func referenceImageView(for zoomAnimator: ZoomAnimator) -> UIImageView? func targetFrame(for zoomAnimator: ZoomAnimator) -> CGRect? } class ZoomAnimator: NSObject { weak var fromDelegate: ZoomAnimatorDelegate? weak var toDelegate: ZoomAnimatorDelegate? var transitionImageView: UIImageView? var isPresenting: Bool = true fileprivate func animateZoomInTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let toVC = transitionContext.viewController(forKey: .to), let fromVC = transitionContext.viewController(forKey: .from), let fromReferenceImageView = fromDelegate?.referenceImageView(for: self), let toReferenceImageView = toDelegate?.referenceImageView(for: self), let fromReferenceImageViewFrame = fromDelegate?.targetFrame(for: self) else { return } fromDelegate?.transitionWillStart(with: self) toDelegate?.transitionWillStart(with: self) toVC.view.alpha = 0 toReferenceImageView.isHidden = true containerView.addSubview(toVC.view) let referenceImage = fromReferenceImageView.image! if self.transitionImageView == nil { let transitionImageView = UIImageView(image: referenceImage) transitionImageView.contentMode = .scaleAspectFill transitionImageView.frame = fromReferenceImageViewFrame self.transitionImageView = transitionImageView containerView.addSubview(transitionImageView) } fromReferenceImageView.isHidden = true let finalTransitionSize = calculateZoomInImageFrame(image: referenceImage, forView: toVC.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [.transitionCrossDissolve], animations: { self.transitionImageView?.frame = finalTransitionSize toVC.view.alpha = 1.0 fromVC.tabBarController?.tabBar.alpha = 0 }, completion: { completed in self.transitionImageView?.removeFromSuperview() toReferenceImageView.isHidden = false fromReferenceImageView.isHidden = false self.transitionImageView = nil transitionContext.completeTransition(!transitionContext.transitionWasCancelled) self.toDelegate?.transitionDidEnd(with: self) self.fromDelegate?.transitionDidEnd(with: self) }) } fileprivate func animateZoomOutTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let toVC = transitionContext.viewController(forKey: .to), let fromVC = transitionContext.viewController(forKey: .from), let fromReferenceImageView = fromDelegate?.referenceImageView(for: self), let toReferenceImageView = toDelegate?.referenceImageView(for: self), let fromReferenceImageViewFrame = fromDelegate?.targetFrame(for: self), let toReferenceImageViewFrame = toDelegate?.targetFrame(for: self) else { return } fromDelegate?.transitionWillStart(with: self) toDelegate?.transitionWillStart(with: self) toReferenceImageView.isHidden = true let referenceImage = fromReferenceImageView.image! if self.transitionImageView == nil { let transitionImageView = UIImageView(image: referenceImage) transitionImageView.contentMode = .scaleAspectFill transitionImageView.clipsToBounds = true transitionImageView.frame = fromReferenceImageViewFrame self.transitionImageView = transitionImageView containerView.addSubview(transitionImageView) } containerView.insertSubview(toVC.view, belowSubview: fromVC.view) fromReferenceImageView.isHidden = true let finalTransitionSize = toReferenceImageViewFrame UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: [], animations: { fromVC.view.alpha = 0 self.transitionImageView?.frame = finalTransitionSize toVC.tabBarController?.tabBar.alpha = 1 }, completion: { completed in self.transitionImageView?.removeFromSuperview() toReferenceImageView.isHidden = false fromReferenceImageView.isHidden = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled) self.toDelegate?.transitionDidEnd(with: self) self.fromDelegate?.transitionDidEnd(with: self) }) } private func calculateZoomInImageFrame(image: UIImage, forView view: UIView) -> CGRect { let viewRatio = view.frame.width / view.frame.height let imageRatio = image.size.width / image.size.height let touchesSides = (imageRatio > viewRatio) if touchesSides { let height = view.frame.width / imageRatio let yPoint = view.frame.minY + (view.frame.height - height) / 2 return CGRect(x: 0, y: yPoint, width: view.frame.width, height: height) } else { let width = view.frame.height * imageRatio let xPoint = view.frame.minX + (view.frame.width - width) / 2 return CGRect(x: xPoint, y: 0, width: width, height: view.frame.height) } } } extension ZoomAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return isPresenting ? 0.5 : 0.25 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresenting { animateZoomInTransition(using: transitionContext) } else { animateZoomOutTransition(using: transitionContext) } } }
mit
c2631620aa60edc0fd87a7b0c5134ec4
41.011905
110
0.62964
6.032479
false
false
false
false
dbart01/Spyder
Spyder/Identity.swift
1
3722
// // Identity.swift // Spyder // // Copyright (c) 2016 Dima Bart // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // import Foundation struct Identity { let label: String let reference: SecIdentity private let attributes: [String : AnyObject] // ---------------------------------- // MARK: - Init - // static func list() -> [Identity] { let query: [String : Any] = [ kSecMatchLimit as String : kSecMatchLimitAll, kSecClass as String : kSecClassIdentity, kSecAttrAccess as String : kSecAttrAccessibleWhenUnlocked, kSecReturnRef as String : true, kSecReturnAttributes as String : true, ] var items: AnyObject? let result = SecItemCopyMatching(query as CFDictionary, &items) if result == errSecSuccess && items != nil { let identityAttributes = items as! [Dictionary<String,AnyObject>] let identities = identityAttributes.map { Identity(attributes: $0) }.sorted { $0.label < $1.label } return identities } return [] } private init(attributes: [String : AnyObject]) { self.attributes = attributes self.reference = attributes[kSecValueRef as String] as! SecIdentity self.label = attributes[kSecAttrLabel as String] as! String } } // ---------------------------------- // MARK: - Array Pretty Printing - // extension Array where Element == Identity { var prettyPrinted: String { let collection = self var string = "" for (i, identity) in collection.enumerated() { let padding = self.paddingForIndex(i + 1, count: collection.count) string += "\(i).\(padding) \(identity.label)\n" } return string } private func paddingForIndex(_ index: Int, count: Int) -> String { var padding = "" let delta = String(describing: count).count - String(describing: index).count for _ in 0..<delta { padding += " " } return padding } }
bsd-2-clause
1056aa29d5f222f5b967c372ccd5a198
36.979592
85
0.635411
4.865359
false
false
false
false
bgrozev/jitsi-meet
ios/sdk/src/picture-in-picture/DragGestureController.swift
1
4260
/* * Copyright @ 2017-present Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ final class DragGestureController { var insets: UIEdgeInsets = UIEdgeInsets.zero private var frameBeforeDragging: CGRect = CGRect.zero private weak var view: UIView? private lazy var panGesture: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:))) }() func startDragListener(inView view: UIView) { self.view = view view.addGestureRecognizer(panGesture) panGesture.isEnabled = true } func stopDragListener() { panGesture.isEnabled = false view?.removeGestureRecognizer(panGesture) view = nil } @objc private func handlePan(gesture: UIPanGestureRecognizer) { guard let view = self.view else { return } let translation = gesture.translation(in: view.superview) let velocity = gesture.velocity(in: view.superview) var frame = frameBeforeDragging switch gesture.state { case .began: frameBeforeDragging = view.frame case .changed: frame.origin.x = floor(frame.origin.x + translation.x) frame.origin.y = floor(frame.origin.y + translation.y) view.frame = frame case .ended: let currentPos = view.frame.origin let finalPos = calculateFinalPosition() let distance = CGPoint(x: currentPos.x - finalPos.x, y: currentPos.y - finalPos.y) let distanceMagnitude = magnitude(vector: distance) let velocityMagnitude = magnitude(vector: velocity) let animationDuration = 0.5 let initialSpringVelocity = velocityMagnitude / distanceMagnitude / CGFloat(animationDuration) frame.origin = CGPoint(x: finalPos.x, y: finalPos.y) UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: initialSpringVelocity, options: .curveLinear, animations: { view.frame = frame }, completion: nil) default: break } } private func calculateFinalPosition() -> CGPoint { guard let view = self.view, let bounds = view.superview?.frame else { return CGPoint.zero } let currentSize = view.frame.size let adjustedBounds = bounds.inset(by: insets) let threshold: CGFloat = 20.0 let velocity = panGesture.velocity(in: view.superview) let location = panGesture.location(in: view.superview) let goLeft: Bool if abs(velocity.x) > threshold { goLeft = velocity.x < -threshold } else { goLeft = location.x < bounds.midX } let goUp: Bool if abs(velocity.y) > threshold { goUp = velocity.y < -threshold } else { goUp = location.y < bounds.midY } let finalPosX: CGFloat = goLeft ? adjustedBounds.origin.x : bounds.size.width - insets.right - currentSize.width let finalPosY: CGFloat = goUp ? adjustedBounds.origin.y : bounds.size.height - insets.bottom - currentSize.height return CGPoint(x: finalPosX, y: finalPosY) } private func magnitude(vector: CGPoint) -> CGFloat { return sqrt(pow(vector.x, 2) + pow(vector.y, 2)) } }
apache-2.0
83425ce56a97e78bfc682e4f3df90162
33.08
82
0.593897
4.879725
false
false
false
false
sberrevoets/SDCAlertView
Example/DemoViewController.swift
1
5980
import UIKit import SDCAlertView final class DemoViewController: UITableViewController { @IBOutlet private var typeControl: UISegmentedControl! @IBOutlet private var styleControl: UISegmentedControl! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var messageTextField: UITextField! @IBOutlet private var textFieldCountTextField: UITextField! @IBOutlet private var buttonCountTextField: UITextField! @IBOutlet private var buttonLayoutControl: UISegmentedControl! @IBOutlet private var contentControl: UISegmentedControl! @IBAction private func presentAlert() { if self.typeControl.selectedSegmentIndex == 0 { self.presentSDCAlertController() } else { self.presentUIAlertController() } } private func presentSDCAlertController() { let title = self.titleTextField.text let message = self.messageTextField.text let style = AlertControllerStyle(rawValue: self.styleControl.selectedSegmentIndex)! let alert = AlertController(title: title, message: message, preferredStyle: style) let textFields = Int(self.textFieldCountTextField.content ?? "0")! for _ in 0..<textFields { alert.addTextField() } let buttons = Int(self.buttonCountTextField.content ?? "0")! for i in 0..<buttons { if i == 0 { alert.addAction(AlertAction(title: "Cancel", style: .preferred)) } else if i == 1 { alert.addAction(AlertAction(title: "OK", style: .normal)) } else if i == 2 { alert.addAction(AlertAction(title: "Delete", style: .destructive)) } else { alert.addAction(AlertAction(title: "Button \(i)", style: .normal)) } } alert.actionLayout = ActionLayout(rawValue: self.buttonLayoutControl.selectedSegmentIndex)! addContentToAlert(alert) alert.present() } private func addContentToAlert(_ alert: AlertController) { switch self.contentControl.selectedSegmentIndex { case 1: let contentView = alert.contentView let spinner = UIActivityIndicatorView(style: .gray) spinner.translatesAutoresizingMaskIntoConstraints = false spinner.startAnimating() contentView.addSubview(spinner) spinner.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true spinner.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true spinner.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true case 2: let contentView = alert.contentView let switchControl = UISwitch() switchControl.isOn = true switchControl.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(switchControl) switchControl.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true switchControl.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true switchControl.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true alert.shouldDismissHandler = { [unowned switchControl] _ in return switchControl.isOn } case 3: let bar = UIProgressView(progressViewStyle: .default) bar.translatesAutoresizingMaskIntoConstraints = false alert.contentView.addSubview(bar) bar.leadingAnchor.constraint(equalTo: alert.contentView.leadingAnchor, constant: 20).isActive = true bar.trailingAnchor.constraint(equalTo: alert.contentView.trailingAnchor, constant: -20).isActive = true bar.topAnchor.constraint(equalTo: alert.contentView.topAnchor).isActive = true bar.bottomAnchor.constraint(equalTo: alert.contentView.bottomAnchor).isActive = true Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateProgressBar), userInfo: bar, repeats: true) default: break } } @objc private func updateProgressBar(_ timer: Timer) { let bar = timer.userInfo as? UIProgressView bar?.progress += 0.005 if let progress = bar?.progress, progress >= 1.0 { timer.invalidate() } } private func presentUIAlertController() { let title = self.titleTextField.content let message = self.messageTextField.content let style = UIAlertController.Style(rawValue: self.styleControl.selectedSegmentIndex)! let alert = UIAlertController(title: title, message: message, preferredStyle: style) let textFields = Int(self.textFieldCountTextField.content ?? "0")! for _ in 0..<textFields { alert.addTextField(configurationHandler: nil) } let buttons = Int(self.buttonCountTextField.content ?? "0")! for i in 0..<buttons { if i == 0 { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) } else if i == 1 { alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) } else if i == 2 { alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: nil)) } else { alert.addAction(UIAlertAction(title: "Button \(i)", style: .default, handler: nil)) } } present(alert, animated: true, completion: nil) } } private extension UITextField { var content: String? { if let text = self.text, !text.isEmpty { return text } return self.placeholder } }
mit
75d2cb80241747a853c31152ebf293f5
41.714286
106
0.629097
5.461187
false
false
false
false
BelowTheHorizon/Mocaccino
Mocaccino/AppDelegate.swift
1
2867
// // AppDelegate.swift // Mocaccino // // Created by Cirno MainasuK on 2016-2-5. // Copyright © 2016年 Cirno MainasuK. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var coreDataStack: CoreDataStack = { let options = [NSPersistentStoreUbiquitousContentNameKey : "Mocaccino", NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true] return CoreDataStack(modelName: "Mocaccino", storeName: "Mocaccino", options: options) }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.statusBarStyle = .LightContent let rootViewController = window!.rootViewController as! RootViewController rootViewController.coreDataStack = self.coreDataStack 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. coreDataStack.saveContext() } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. coreDataStack.saveContext() } }
mit
6c9e16c400b7623f76e23a269f222ddb
48.37931
285
0.738478
5.809331
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Model/User.swift
1
4727
// // User.swift // Inbbbox // // Created by Radoslaw Szeja on 14/12/15. // Copyright © 2015 Netguru Sp. z o.o. All rights reserved. // import Foundation import SwiftyJSON final class User: NSObject, UserType { let identifier: String let name: String? let username: String let avatarURL: URL? let shotsCount: UInt let accountType: UserAccountType? let followersCount: UInt let followingsCount: UInt let projectsCount: UInt let bucketsCount: UInt let isPro: Bool let bio: String let location: String init(json: JSON) { identifier = json[Key.identifier.rawValue].stringValue name = json[Key.name.rawValue].string username = json[Key.username.rawValue].stringValue avatarURL = json[Key.avatar.rawValue].url shotsCount = json[Key.shotsCount.rawValue].uIntValue accountType = UserAccountType(rawValue: json[Key.accountType.rawValue].stringValue) followersCount = json[Key.followersCount.rawValue].uIntValue followingsCount = json[Key.followingsCount.rawValue].uIntValue projectsCount = json[Key.projectsCount.rawValue].uIntValue bucketsCount = json[Key.bucketsCount.rawValue].uIntValue isPro = json[Key.pro.rawValue].boolValue bio = json[Key.bio.rawValue].stringValue location = json[Key.location.rawValue].stringValue } required init(coder aDecoder: NSCoder) { identifier = aDecoder.decodeObject(forKey: Key.identifier.rawValue) as? String ?? "" name = aDecoder.decodeObject(forKey: Key.name.rawValue) as? String username = aDecoder.decodeObject(forKey: Key.username.rawValue) as? String ?? "" avatarURL = aDecoder.decodeObject(forKey: Key.avatar.rawValue) as? URL shotsCount = aDecoder.decodeObject(forKey: Key.shotsCount.rawValue) as? UInt ?? 0 accountType = { if let key = aDecoder.decodeObject(forKey: Key.accountType.rawValue) as? String { return UserAccountType(rawValue: key) } return nil }() followersCount = aDecoder.decodeObject(forKey: Key.followersCount.rawValue) as? UInt ?? 0 followingsCount = aDecoder.decodeObject(forKey: Key.followingsCount.rawValue) as? UInt ?? 0 projectsCount = aDecoder.decodeObject(forKey: Key.projectsCount.rawValue) as? UInt ?? 0 bucketsCount = aDecoder.decodeObject(forKey: Key.bucketsCount.rawValue) as? UInt ?? 0 isPro = aDecoder.decodeBool(forKey: Key.pro.rawValue) bio = aDecoder.decodeObject(forKey: Key.bio.rawValue) as? String ?? "" location = aDecoder.decodeObject(forKey: Key.location.rawValue) as? String ?? "" } func encode(with aCoder: NSCoder) { aCoder.encode(identifier, forKey: Key.identifier.rawValue) aCoder.encode(name, forKey: Key.name.rawValue) aCoder.encode(username, forKey: Key.username.rawValue) aCoder.encode(avatarURL, forKey: Key.avatar.rawValue) aCoder.encode(shotsCount, forKey: Key.shotsCount.rawValue) aCoder.encode(accountType?.rawValue, forKey: Key.accountType.rawValue) aCoder.encode(followersCount, forKey: Key.followersCount.rawValue) aCoder.encode(followingsCount, forKey: Key.followingsCount.rawValue) aCoder.encode(projectsCount, forKey: Key.projectsCount.rawValue) aCoder.encode(bucketsCount, forKey: Key.bucketsCount.rawValue) aCoder.encode(isPro, forKey: Key.pro.rawValue) aCoder.encode(bio, forKey: Key.bio.rawValue) aCoder.encode(location, forKey: Key.location.rawValue) } } private extension User { enum Key: String { case identifier = "id" case name = "name" case username = "username" case avatar = "avatar_url" case shotsCount = "shots_count" case accountType = "type" case followersCount = "followers_count" case followingsCount = "followings_count" case projectsCount = "projects_count" case bucketsCount = "buckets_count" case pro = "pro" case bio = "bio" case location = "location" } } extension User: NSSecureCoding { static var supportsSecureCoding: Bool { return true } } extension User: Mappable { static var map: (JSON) -> User { return { json in User(json: json) } } } extension User { override var debugDescription: String { return "<Class: " + String(describing: type(of: self)) + "> " + "{ " + "ID: " + identifier + ", " + "Username: " + username + ", " + "Name: " + (name ?? "unknown") + " }" } }
gpl-3.0
ecccca7788dc9b7b2cac696144f8614e
36.212598
99
0.650868
4.288566
false
false
false
false
vmachiel/swift
SwiftUITest/SwiftUITest/SceneDelegate.swift
1
2767
// // SceneDelegate.swift // SwiftUITest // // Created by Machiel van Dorst on 11/10/2019. // Copyright © 2019 vmachiel. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
c05b5e166ed567346414da3733e010ae
42.21875
147
0.704266
5.298851
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Profiles/HealthThermometer/HealthTermometerTableViewController.swift
1
2906
/* * Copyright (c) 2020, Nordic Semiconductor * 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 CoreBluetooth private extension Identifier where Value == Section { static let temperature: Identifier<Section> = "temperature" static let additionalInfo: Identifier<Section> = "additionalInfo" } class HealthTermometerTableViewController: PeripheralTableViewController { private var temperatureSection = HealthTemperatureSection(id: .temperature) private var additionalInfoSection = HealthTemperatureAditionalSection(id: .additionalInfo) override var peripheralDescription: PeripheralDescription { .healthTemperature } override var internalSections: [Section] { [temperatureSection, additionalInfoSection] } override var navigationTitle: String { "Health Thermometer" } override func didUpdateValue(for characteristic: CBCharacteristic) { switch characteristic.uuid { case CBUUID.Characteristics.HealthTemperature.measurement: do { let temperature = try HealthTermometerCharacteristic(data: characteristic.value!) temperatureSection.update(with: temperature) additionalInfoSection.update(with: temperature) tableView.reloadData() } catch let error { displayErrorAlert(error: error) } default: super.didUpdateValue(for: characteristic) } } }
bsd-3-clause
c38648d626094d017b8715a3b4826ba3
43.707692
94
0.754301
5.107206
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Utilities/Extensions/UINavigationController+Ext.swift
1
2989
/* * Copyright (c) 2020, Nordic Semiconductor * 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 extension UINavigationController { static func nordicBranded(rootViewController: UIViewController? = nil, prefersLargeTitles: Bool = false) -> UINavigationController { let nc = UINavigationController() nc.viewControllers = [rootViewController].compactMap { $0 } nc.navigationBar.tintColor = .nordicAlmostWhite nc.navigationBar.barTintColor = .nordicBlue if #available(iOS 11.0, *) { let attributes: [NSAttributedString.Key : Any] = [ .foregroundColor : UIColor.nordicAlmostWhite ] nc.navigationBar.titleTextAttributes = attributes nc.navigationBar.largeTitleTextAttributes = attributes nc.navigationBar.prefersLargeTitles = prefersLargeTitles } if #available(iOS 13.0, *) { let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] navBarAppearance.backgroundColor = UIColor.NavigationBar.barTint nc.navigationBar.standardAppearance = navBarAppearance nc.navigationBar.scrollEdgeAppearance = navBarAppearance } return nc } }
bsd-3-clause
420c7a3acb608aa244656610ec517b36
44.984615
136
0.72265
5.347048
false
false
false
false
xiawuacha/DouYuzhibo
DouYuzhibo/DouYuzhibo/Classses/Main/ViewModel/BaseViewModel.swift
1
1574
// // BaseViewModel.swift // DouYuzhibo // // Created by 汪凯 on 2016/11/2. // Copyright © 2016年 汪凯. All rights reserved. // import UIKit class BaseViewModel { lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() } //MARK:将推荐界面和后面游戏界面数据请求做一个兼容 extension BaseViewModel { func loadAnchorData(isGroupData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) { NetworkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in // 1.对界面进行处理 guard let resultDict = result as? [String : Any] else { return } guard let dataArray = resultDict["data"] as? [[String : Any]] else { return } // 2.判断是否分组数据 if isGroupData { // 2.1.遍历数组中的字典 for dict in dataArray { self.anchorGroups.append(AnchorGroup(dict: dict)) } } else { // 2.1.创建组 let group = AnchorGroup() // 2.2.遍历dataArray的所有的字典 for dict in dataArray { group.anchors.append(AnchorModel(dict: dict)) } // 2.3.将group,添加到anchorGroups self.anchorGroups.append(group) } // 3.完成回调 finishedCallback() } } }
mit
1c15a4a6b2f59602732415a84570b593
29.574468
140
0.51009
4.504702
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/WordPressAuthenticationManager.swift
1
24487
import Foundation import WordPressAuthenticator import Gridicons // MARK: - WordPressAuthenticationManager // @objc class WordPressAuthenticationManager: NSObject { static var isPresentingSignIn = false private let windowManager: WindowManager /// Allows overriding some WordPressAuthenticator delegate methods /// without having to reimplement WordPressAuthenticatorDelegate private let authenticationHandler: AuthenticationHandler? init(windowManager: WindowManager, authenticationHandler: AuthenticationHandler? = nil) { self.windowManager = windowManager self.authenticationHandler = authenticationHandler } /// Support is only available to the WordPress iOS App. Our Authentication Framework doesn't have direct access. /// We'll setup a mechanism to relay the Support event back to the Authenticator. /// func startRelayingSupportNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(supportPushNotificationReceived), name: .ZendeskPushNotificationReceivedNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(supportPushNotificationCleared), name: .ZendeskPushNotificationClearedNotification, object: nil) } } // MARK: - Initialization Methods // extension WordPressAuthenticationManager { /// Initializes WordPressAuthenticator with all of the parameters that will be needed during the login flow. /// func initializeWordPressAuthenticator() { let displayStrings = WordPressAuthenticatorDisplayStrings( continueWithWPButtonTitle: AppConstants.Login.continueButtonTitle ) WordPressAuthenticator.initialize(configuration: authenticatorConfiguation(), style: authenticatorStyle(), unifiedStyle: unifiedStyle(), displayStrings: displayStrings) } private func authenticatorConfiguation() -> WordPressAuthenticatorConfiguration { // SIWA can not be enabled for internal builds // Ref https://github.com/wordpress-mobile/WordPress-iOS/pull/12332#issuecomment-521994963 let enableSignInWithApple = AppConfiguration.allowSignUp && !(BuildConfiguration.current ~= [.a8cBranchTest, .a8cPrereleaseTesting]) return WordPressAuthenticatorConfiguration(wpcomClientId: ApiCredentials.client, wpcomSecret: ApiCredentials.secret, wpcomScheme: WPComScheme, wpcomTermsOfServiceURL: WPAutomatticTermsOfServiceURL, wpcomBaseURL: WordPressComOAuthClient.WordPressComOAuthDefaultBaseUrl, wpcomAPIBaseURL: Environment.current.wordPressComApiBase, googleLoginClientId: ApiCredentials.googleLoginClientId, googleLoginServerClientId: ApiCredentials.googleLoginServerClientId, googleLoginScheme: ApiCredentials.googleLoginSchemeId, userAgent: WPUserAgent.wordPress(), showLoginOptions: true, enableSignUp: AppConfiguration.allowSignUp, enableSignInWithApple: enableSignInWithApple, enableSignupWithGoogle: AppConfiguration.allowSignUp, enableUnifiedAuth: true, enableUnifiedCarousel: FeatureFlag.unifiedPrologueCarousel.enabled) } private func authenticatorStyle() -> WordPressAuthenticatorStyle { let prologueVC: UIViewController? = { guard let viewController = authenticationHandler?.prologueViewController else { return FeatureFlag.unifiedPrologueCarousel.enabled ? UnifiedPrologueViewController() : nil } return viewController }() let statusBarStyle: UIStatusBarStyle = { guard let statusBarStyle = authenticationHandler?.statusBarStyle else { return FeatureFlag.unifiedPrologueCarousel.enabled ? .default : .lightContent } return statusBarStyle }() let buttonViewTopShadowImage: UIImage? = { guard let image = authenticationHandler?.buttonViewTopShadowImage else { return UIImage(named: "darkgrey-shadow") } return image }() let prologuePrimaryButtonStyle = authenticationHandler?.prologuePrimaryButtonStyle let prologueSecondaryButtonStyle = authenticationHandler?.prologueSecondaryButtonStyle return WordPressAuthenticatorStyle(primaryNormalBackgroundColor: .primaryButtonBackground, primaryNormalBorderColor: nil, primaryHighlightBackgroundColor: .primaryButtonDownBackground, primaryHighlightBorderColor: nil, secondaryNormalBackgroundColor: .authSecondaryButtonBackground, secondaryNormalBorderColor: .secondaryButtonBorder, secondaryHighlightBackgroundColor: .secondaryButtonDownBackground, secondaryHighlightBorderColor: .secondaryButtonDownBorder, disabledBackgroundColor: .textInverted, disabledBorderColor: .neutral(.shade10), primaryTitleColor: .white, secondaryTitleColor: .text, disabledTitleColor: .neutral(.shade20), disabledButtonActivityIndicatorColor: .text, textButtonColor: .primary, textButtonHighlightColor: .primaryDark, instructionColor: .text, subheadlineColor: .textSubtle, placeholderColor: .textPlaceholder, viewControllerBackgroundColor: .listBackground, textFieldBackgroundColor: .listForeground, buttonViewBackgroundColor: .authButtonViewBackground, buttonViewTopShadowImage: buttonViewTopShadowImage, navBarImage: .gridicon(.mySites), navBarBadgeColor: .accent(.shade20), navBarBackgroundColor: .appBarBackground, prologueBackgroundColor: .primary, prologueTitleColor: .textInverted, prologuePrimaryButtonStyle: prologuePrimaryButtonStyle, prologueSecondaryButtonStyle: prologueSecondaryButtonStyle, prologueTopContainerChildViewController: prologueVC, statusBarStyle: statusBarStyle) } private func unifiedStyle() -> WordPressAuthenticatorUnifiedStyle { let prologueButtonsBackgroundColor: UIColor = { guard let color = authenticationHandler?.prologueButtonsBackgroundColor else { return .clear } return color }() /// Uses the same prologueButtonsBackgroundColor but we need to be able to return nil let prologueViewBackgroundColor: UIColor? = authenticationHandler?.prologueButtonsBackgroundColor return WordPressAuthenticatorUnifiedStyle(borderColor: .divider, errorColor: .error, textColor: .text, textSubtleColor: .textSubtle, textButtonColor: .primary, textButtonHighlightColor: .primaryDark, viewControllerBackgroundColor: .basicBackground, prologueButtonsBackgroundColor: prologueButtonsBackgroundColor, prologueViewBackgroundColor: prologueViewBackgroundColor, navBarBackgroundColor: .appBarBackground, navButtonTextColor: .appBarTint, navTitleTextColor: .appBarText) } } // MARK: - Static Methods // extension WordPressAuthenticationManager { /// Returns an Authentication ViewController (configured to allow only WordPress.com). This method pre-populates the Email + Username /// with the values returned by the default WordPress.com account (if any). /// /// - Parameter onDismissed: Closure to be executed whenever the returned ViewController is dismissed. /// @objc class func signinForWPComFixingAuthToken(_ onDismissed: ((_ cancelled: Bool) -> Void)? = nil) -> UIViewController { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) let account = service.defaultWordPressComAccount() return WordPressAuthenticator.signinForWPCom(dotcomEmailAddress: account?.email, dotcomUsername: account?.username, onDismissed: onDismissed) } /// Presents the WordPress Authentication UI from the rootViewController (configured to allow only WordPress.com). /// This method pre-populates the Email + Username with the values returned by the default WordPress.com account (if any). /// @objc class func showSigninForWPComFixingAuthToken() { guard let presenter = UIApplication.shared.mainWindow?.rootViewController else { assertionFailure() return } guard !isPresentingSignIn else { return } isPresentingSignIn = true let controller = signinForWPComFixingAuthToken({ (_) in isPresentingSignIn = false }) presenter.present(controller, animated: true) } } // MARK: - Notification Handlers // extension WordPressAuthenticationManager { @objc func supportPushNotificationReceived(_ notification: Foundation.Notification) { WordPressAuthenticator.shared.supportPushNotificationReceived() } @objc func supportPushNotificationCleared(_ notification: Foundation.Notification) { WordPressAuthenticator.shared.supportPushNotificationCleared() } } // MARK: - WordPressAuthenticator Delegate // extension WordPressAuthenticationManager: WordPressAuthenticatorDelegate { /// Indicates if the active Authenticator can be dismissed, or not. Authentication is Dismissable when there is a /// default wpcom account, or at least one self-hosted blog. /// var dismissActionEnabled: Bool { let context = ContextManager.sharedInstance().mainContext let blogService = BlogService(managedObjectContext: context) return AccountHelper.isDotcomAvailable() || blogService.blogCountForAllAccounts() > 0 } /// Indicates whether if the Support Action should be enabled, or not. /// var supportActionEnabled: Bool { return true } /// Indicates whether a link to WP.com TOS should be available, or not. /// var wpcomTermsOfServiceEnabled: Bool { return true } /// Indicates if Support is Enabled. /// var supportEnabled: Bool { return ZendeskUtils.zendeskEnabled } /// Indicates if the Support notification indicator should be displayed. /// var showSupportNotificationIndicator: Bool { return ZendeskUtils.showSupportNotificationIndicator } private var tracker: AuthenticatorAnalyticsTracker { AuthenticatorAnalyticsTracker.shared } /// We allow to connect with WordPress.com account only if there is no default account connected already. var allowWPComLogin: Bool { let accountService = AccountService(managedObjectContext: ContextManager.shared.mainContext) return accountService.defaultWordPressComAccount() == nil } /// Returns an instance of a SupportView, configured to be displayed from a specified Support Source. /// func presentSupport(from sourceViewController: UIViewController, sourceTag: WordPressSupportSourceTag) { // Reset the nav style so the Support nav bar has the WP style, not the Auth style. WPStyleGuide.configureNavigationAppearance() // Since we're presenting the support VC as a form sheet, the parent VC's viewDidAppear isn't called // when this VC is dismissed. This means the tracking step isn't reset properly, so we'll need to do // it here manually before tracking the new step. let step = tracker.state.lastStep tracker.track(step: .help) let controller = SupportTableViewController { [weak self] in self?.tracker.track(click: .dismiss) self?.tracker.set(step: step) } controller.sourceTag = sourceTag let navController = UINavigationController(rootViewController: controller) navController.modalPresentationStyle = .formSheet sourceViewController.present(navController, animated: true) } /// Presents Support new request, with the specified ViewController as a source. /// Additional metadata is supplied, such as the sourceTag and Login details. /// func presentSupportRequest(from sourceViewController: UIViewController, sourceTag: WordPressSupportSourceTag) { ZendeskUtils.sharedInstance.showNewRequestIfPossible(from: sourceViewController, with: sourceTag) } /// A self-hosted site URL is available and needs validated /// before presenting the username and password view controller. /// - Parameters: /// - site: passes in the site information to the delegate method. /// - onCompletion: Closure to be executed on completion. /// func shouldPresentUsernamePasswordController(for siteInfo: WordPressComSiteInfo?, onCompletion: @escaping (WordPressAuthenticatorResult) -> Void) { if let authenticationHandler = authenticationHandler { authenticationHandler.shouldPresentUsernamePasswordController(for: siteInfo, onCompletion: onCompletion) return } let result: WordPressAuthenticatorResult = .presentPasswordController(value: true) onCompletion(result) } /// Presents the Login Epilogue, in the specified NavigationController. /// func presentLoginEpilogue(in navigationController: UINavigationController, for credentials: AuthenticatorCredentials, onDismiss: @escaping () -> Void) { if let authenticationHandler = authenticationHandler, authenticationHandler.presentLoginEpilogue(in: navigationController, for: credentials, windowManager: windowManager, onDismiss: onDismiss) { return } if PostSignUpInterstitialViewController.shouldDisplay() { self.presentPostSignUpInterstitial(in: navigationController, onDismiss: onDismiss) return } //Present the epilogue view let storyboard = UIStoryboard(name: "LoginEpilogue", bundle: .main) guard let epilogueViewController = storyboard.instantiateInitialViewController() as? LoginEpilogueViewController else { fatalError() } epilogueViewController.credentials = credentials epilogueViewController.onDismiss = { [weak self] in onDismiss() self?.windowManager.dismissFullscreenSignIn() } navigationController.pushViewController(epilogueViewController, animated: true) } /// Presents the Signup Epilogue, in the specified NavigationController. /// func presentSignupEpilogue(in navigationController: UINavigationController, for credentials: AuthenticatorCredentials, service: SocialService?) { let storyboard = UIStoryboard(name: "SignupEpilogue", bundle: .main) guard let epilogueViewController = storyboard.instantiateInitialViewController() as? SignupEpilogueViewController else { fatalError() } epilogueViewController.credentials = credentials epilogueViewController.socialService = service epilogueViewController.onContinue = { [weak self] in guard let self = self else { return } if PostSignUpInterstitialViewController.shouldDisplay() { self.presentPostSignUpInterstitial(in: navigationController) } else { if self.windowManager.isShowingFullscreenSignIn { self.windowManager.dismissFullscreenSignIn() } else { navigationController.dismiss(animated: true) } } UserDefaults.standard.set(false, forKey: UserDefaults.standard.welcomeNotificationSeenKey) } navigationController.pushViewController(epilogueViewController, animated: true) } /// Indicates if the Login Epilogue should be presented. This is false only when we're doing a Jetpack Connect, and the new /// WordPress.com account has no sites. Capicci? /// func shouldPresentLoginEpilogue(isJetpackLogin: Bool) -> Bool { guard isJetpackLogin else { return true } let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) let numberOfBlogs = service.defaultWordPressComAccount()?.blogs?.count ?? 0 return numberOfBlogs > 0 } /// Indicates if the Signup Epilogue should be displayed. /// func shouldPresentSignupEpilogue() -> Bool { return true } /// Whenever a WordPress.com account has been created during the Auth flow, we'll add a new local WPCOM Account, and set it as /// the new DefaultWordPressComAccount. /// func createdWordPressComAccount(username: String, authToken: String) { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) let account = service.createOrUpdateAccount(withUsername: username, authToken: authToken) if service.defaultWordPressComAccount() == nil { service.setDefaultWordPressComAccount(account) } } /// When an Apple account is used during the Auth flow, save the Apple user id to the keychain. /// It will be used on app launch to check the user id state. /// func userAuthenticatedWithAppleUserID(_ appleUserID: String) { do { try SFHFKeychainUtils.storeUsername(WPAppleIDKeychainUsernameKey, andPassword: appleUserID, forServiceName: WPAppleIDKeychainServiceName, updateExisting: true) } catch { DDLogInfo("Error while saving Apple User ID: \(error)") } } /// Synchronizes the specified WordPress Account. /// func sync(credentials: AuthenticatorCredentials, onCompletion: @escaping () -> Void) { if let wpcom = credentials.wpcom { syncWPCom(authToken: wpcom.authToken, isJetpackLogin: wpcom.isJetpackLogin, onCompletion: onCompletion) } else if let wporg = credentials.wporg { syncWPOrg(username: wporg.username, password: wporg.password, xmlrpc: wporg.xmlrpc, options: wporg.options, onCompletion: onCompletion) } } /// Indicates if the given Auth error should be handled by the host app. /// func shouldHandleError(_ error: Error) -> Bool { // Here for protocol compliance. return false } /// Handles the given error. /// Called if `shouldHandleError` is true. /// func handleError(_ error: Error, onCompletion: @escaping (UIViewController) -> Void) { // Here for protocol compliance. let vc = UIViewController() onCompletion(vc) } /// Tracks a given Analytics Event. /// func track(event: WPAnalyticsStat) { WPAppAnalytics.track(event) } /// Tracks a given Analytics Event, with the specified properties. /// func track(event: WPAnalyticsStat, properties: [AnyHashable: Any]) { WPAppAnalytics.track(event, withProperties: properties) } /// Tracks a given Analytics Event, with the specified error. /// func track(event: WPAnalyticsStat, error: Error) { WPAppAnalytics.track(event, error: error) } } // MARK: - WordPressAuthenticatorManager // private extension WordPressAuthenticationManager { /// Displays the post sign up interstitial if needed, if it's not displayed private func presentPostSignUpInterstitial( in navigationController: UINavigationController, onDismiss: (() -> Void)? = nil) { let viewController = PostSignUpInterstitialViewController() let windowManager = self.windowManager viewController.dismiss = { dismissAction in let completion: (() -> Void)? switch dismissAction { case .none: completion = nil case .addSelfHosted: completion = { NotificationCenter.default.post(name: .addSelfHosted, object: nil) } case .createSite: completion = { NotificationCenter.default.post(name: .createSite, object: nil) } } if windowManager.isShowingFullscreenSignIn { windowManager.dismissFullscreenSignIn(completion: completion) } else { navigationController.dismiss(animated: true, completion: completion) } onDismiss?() } navigationController.pushViewController(viewController, animated: true) } /// Synchronizes a WordPress.com account with the specified credentials. /// private func syncWPCom(authToken: String, isJetpackLogin: Bool, onCompletion: @escaping () -> ()) { let service = WordPressComSyncService() service.syncWPCom(authToken: authToken, isJetpackLogin: isJetpackLogin, onSuccess: { account in /// HACK: An alternative notification to LoginFinished. Observe this instead of `WPSigninDidFinishNotification` for Jetpack logins. /// When WPTabViewController no longer destroy's and rebuilds the view hierarchy this alternate notification can be removed. /// let notification = isJetpackLogin == true ? .wordpressLoginFinishedJetpackLogin : Foundation.Notification.Name(rawValue: WordPressAuthenticator.WPSigninDidFinishNotification) NotificationCenter.default.post(name: notification, object: account) onCompletion() }, onFailure: { _ in onCompletion() }) } /// Synchronizes a WordPress.org account with the specified credentials. /// private func syncWPOrg(username: String, password: String, xmlrpc: String, options: [AnyHashable: Any], onCompletion: @escaping () -> ()) { let service = BlogSyncFacade() service.syncBlog(withUsername: username, password: password, xmlrpc: xmlrpc, options: options) { blog in RecentSitesService().touch(blog: blog) onCompletion() } } }
gpl-2.0
b0d19254e8bc577106611c4ed78938e9
44.599628
186
0.630212
6.251468
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Connection/PeripheralScanner.swift
1
7013
/* * Copyright (c) 2020, Nordic Semiconductor * 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 CoreBluetooth import os.log protocol PeripheralScannerDelegate: AnyObject { func statusChanges(_ status: PeripheralScanner.Status) func newPeripherals(_ peripherals: [Peripheral], willBeAddedTo existing: [Peripheral]) func peripherals(_ peripherals: [Peripheral], addedTo old: [Peripheral]) } public struct Peripheral: Hashable, Equatable { let peripheral: CBPeripheral let rssi: NSNumber let name: String public static func == (lhs: Peripheral, rhs: Peripheral) -> Bool { lhs.peripheral == rhs.peripheral } public func hash(into hasher: inout Hasher) { hasher.combine(peripheral) } } open class PeripheralScanner: NSObject { public enum Status { case uninitialized, ready, notReady(CBManagerState), scanning, connecting(Peripheral), connected(Peripheral), failedToConnect(Peripheral, Error?) var singleName: String { switch self { case .connected(let p): return "Connected to \(p.name)" case .uninitialized: return "Uninitialized" case .ready: return "Ready to scan" case .notReady: return "Not Ready" case .scanning: return "Scanning..." case .connecting(let p): return "Connecting to \(p.name)" case .failedToConnect(let p, _): return "Failed to connect to \(p.name)" } } } let scanServices: [CBUUID]? var serviceFilterEnabled = true { didSet { refresh() } } private (set) var status: Status = .uninitialized { didSet { DispatchQueue.main.async { [weak self] in guard let `self` = self else { return } self.scannerDelegate?.statusChanges(self.status) } } } private var centralManager: CBCentralManager! private let bgQueue = DispatchQueue(label: "no.nordicsemi.nRF-Toolbox.ConnectionManager", qos: .utility) private lazy var dispatchSource: DispatchSourceTimer = { let t = DispatchSource.makeTimerSource(queue: bgQueue) t.setEventHandler { let oldPeripherals = self.peripherals let oldSet: Set<Peripheral> = Set(oldPeripherals) self.tmpPeripherals.subtract(oldSet) let p = Array(self.tmpPeripherals) DispatchQueue.main.sync { [weak self] in guard let `self` = self else { return } self.scannerDelegate?.newPeripherals(p, willBeAddedTo: oldPeripherals) self.peripherals += p self.scannerDelegate?.peripherals(p, addedTo: oldPeripherals) } self.tmpPeripherals.removeAll() } return t }() weak var scannerDelegate: PeripheralScannerDelegate? { didSet { scannerDelegate?.statusChanges(status) } } private var tmpPeripherals = Set<Peripheral>() private (set) var peripherals: [Peripheral] = [] init(services: [CBUUID]?) { scanServices = services super.init() centralManager = CBCentralManager(delegate: self, queue: bgQueue) } open func startScanning() { rescan() dispatchSource.schedule(deadline: .now() + .seconds(1), repeating: 1) dispatchSource.activate() status = .scanning } open func refresh() { stopScanning() peripherals.removeAll() tmpPeripherals.removeAll() rescan() } open func stopScanning() { centralManager.stopScan() status = .ready } open func connect(to peripheral: Peripheral) { stopScanning() status = .connecting(peripheral) } private func rescan() { let services = serviceFilterEnabled ? scanServices : nil centralManager.scanForPeripherals(withServices: services, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true]) status = .scanning } } extension PeripheralScanner: CBCentralManagerDelegate { public func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOn, .resetting: status = .ready startScanning() case .poweredOff, .unauthorized, .unknown, .unsupported: status = .notReady(central.state) @unknown default: break } } public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? peripheral.name ?? "N/A" let p = Peripheral(peripheral: peripheral, rssi: RSSI, name: name) tmpPeripherals.insert(p) } public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { guard case .connecting(let p) = status else { return } guard p.peripheral == peripheral else { return } status = .connected(p) } public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { guard case .connecting(let p) = status else { return } guard p.peripheral == peripheral else { return } status = .failedToConnect(p, error) } }
bsd-3-clause
691d545536aab68a2be48a3c317bc39b
35.717277
155
0.653358
4.995014
false
false
false
false
maxkonovalov/MKRingProgressView
Example/ProgressRingExample/ParametersViewController.swift
1
1734
// // ParametersViewController.swift // ProgressRingExample // // Created by Max Konovalov on 22/10/2018. // Copyright © 2018 Max Konovalov. All rights reserved. // import MKRingProgressView import UIKit protocol ParametersViewControllerDelegate: AnyObject { func parametersViewControllerDidChangeProgress(_ progress: Double) func parametersViewControllerDidChangeStyle(_ style: RingProgressViewStyle) func parametersViewControllerDidChangeShadowOpacity(_ shadowOpacity: CGFloat) func parametersViewControllerDidChangeHidesRingForZeroProgressValue(_ hidesRingForZeroProgress: Bool) } class ParametersViewController: UITableViewController { weak var delegate: ParametersViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } @IBAction func progressChanged(_ sender: UISlider) { let progress = Double(sender.value) delegate?.parametersViewControllerDidChangeProgress(progress) } @IBAction func styleChanged(_ sender: UISegmentedControl) { guard let style = RingProgressViewStyle(rawValue: sender.selectedSegmentIndex) else { return } delegate?.parametersViewControllerDidChangeStyle(style) } @IBAction func shadowChanged(_ sender: UISwitch) { let shadowOpacity: CGFloat = sender.isOn ? 1.0 : 0.0 delegate?.parametersViewControllerDidChangeShadowOpacity(shadowOpacity) } @IBAction func hidesRingForZeroProgressChanged(_ sender: UISwitch) { let hidesRingForZeroProgress = sender.isOn delegate?.parametersViewControllerDidChangeHidesRingForZeroProgressValue(hidesRingForZeroProgress) } }
mit
d4236b6be302a527eaec2863b5e268cd
35.104167
106
0.747836
5.299694
false
false
false
false
wosheesh/uchatclient
uchat/Helpers/ImageFilters.swift
1
2881
// // ImageFilters.swift // uchat // // Created by Wojtek Materka on 29/02/2016. // Copyright © 2016 Wojtek Materka. All rights reserved. // import UIKit import CoreImage typealias Filter = CIImage -> CIImage infix operator >>> { associativity left } func >>> (filter1: Filter, filter2: Filter) -> Filter { return { image in filter2(filter1(image)) } } // Apply default Channel Filter extension PictureCache { func applyFilters(toImage image: UIImage) -> UIImage? { guard let beginImage = CIImage(image: image) else { print("couldn't find a picture") return nil } let myFilter = bw(OTMColors.bgLight, intensity: 0.4) let filteredImage = myFilter(beginImage) // https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_tasks/ci_tasks.html#//apple_ref/doc/uid/TP30001185-CH3-SW19 let myEAGLContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2) let options = [kCIContextWorkingColorSpace : NSNull()] let eagContext = CIContext(EAGLContext: myEAGLContext, options: options) let cgimg = eagContext.createCGImage(filteredImage, fromRect: filteredImage.extent) let endImage = UIImage(CGImage: cgimg) return endImage } } // Filters extension PictureCache { func sepia(intensity: Double) -> Filter { return { image in let parameters = [ kCIInputImageKey: image, kCIInputIntensityKey: intensity ] guard let filter = CIFilter(name: "CISepiaTone", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func blur(radius: Double) -> Filter { return { image in let parameters = [ kCIInputRadiusKey: radius, kCIInputImageKey: image ] guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func bw(color: UIColor, intensity: Double) -> Filter { return { image in let parameters = [ kCIInputColorKey: CIColor(color: color), kCIInputIntensityKey: intensity, kCIInputImageKey: image ] guard let filter = CIFilter(name: "CIColorMonochrome", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } }
mit
c535bd6242260056918995f050cc1c39
27.8
166
0.595486
4.956971
false
false
false
false
jegumhon/URWeatherView
URWeatherView/SpriteAssets/URNodeMovable.swift
1
2191
// // URNodeMovable.swift // URWeatherView // // Created by DongSoo Lee on 2017. 5. 31.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit protocol URNodeMovable: class { var lastLocation: CGPoint { get set } var touchedNode: SKNode! { get set } var movableNodes: [SKNode] { get set } func handleTouch(_ touches: Set<UITouch>, isEnded: Bool) func updateNodePosition() func removeAllMovableNodes() } extension URNodeMovable { func removeAllMovableNodes() { } } extension URNodeMovable where Self: URWeatherScene { func handleTouch(_ touches: Set<UITouch>, isEnded: Bool = false) { guard !isEnded else { self.touchedNode = nil return } for touch in touches { let location = touch.location(in: self) let nodes = self.nodes(at: location) if self.touchedNode == nil { self.touchedNode = nodes.first } else { var isFound: Bool = false for node in nodes { if node === self.touchedNode { isFound = true break } } if !isFound { self.touchedNode = nodes.first } } self.lastLocation = location } } func updateNodePosition() { // for movableNode in self.movableNodes { // movableNode.position = CGPoint(x: self.lastLocation.x, y: self.lastLocation.y) // } if self.touchedNode != nil { self.touchedNode.position = CGPoint(x: self.lastLocation.x, y: self.lastLocation.y) } } func removeAllMovableNodes() { self.movableNodes = [SKNode]() } } extension URNodeMovable where Self: SKNode { func handleTouch(_ touches: Set<UITouch>, isEnded: Bool = false) { for touch in touches { let location = touch.location(in: self) self.lastLocation = location } } func updateNodePosition() { self.position = CGPoint(x: self.lastLocation.x, y: self.lastLocation.y) } }
mit
15a536122fb00b2f4a61d16f97a4cebc
26.35
95
0.558501
4.315582
false
false
false
false
Clustox/swift-style-guidelines
ToDoList-Swift/ToDoList/ItemsList/ViewControllerDelegate.swift
1
1187
// // ViewControllerDelegate.swift // ToDoList // // Created by Saira on 8/11/16. // Copyright © 2016 Saira. All rights reserved. // import Foundation import UIKit final class ViewControllerDelegate: NSObject { // table view of to do items weak var tableView: UITableView? init(tableView: UITableView) { self.tableView = tableView super.init() configureTableView() } /** Configures table view's row height and header here */ func configureTableView() { self.tableView?.estimatedRowHeight = ToDoItemCell.prefferedHeight self.tableView?.rowHeight = UITableViewAutomaticDimension self.configureTableHeader() tableView?.delegate = self } } // MARK: - UITableViewDelegate conformance extension ViewControllerDelegate: UITableViewDelegate { /** Configuring table header is necessary else it will show empty space above table view */ func configureTableHeader() { let tableHeader = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 1)) tableHeader.backgroundColor = UIColor.clearColor() self.tableView?.tableHeaderView = tableHeader } }
mit
3f56fc4025ebe15221083dd953d5ee8f
25.355556
80
0.678752
4.801619
false
true
false
false
shvets/WebAPI
Sources/WebAPI/GidOnlineAPI.swift
1
28578
import Foundation import SwiftSoup // import SwiftyJSON import Alamofire open class GidOnlineAPI: HttpService { // //public static let SiteUrl = "http://gidonline.club" // public static let SiteUrl = "http://gidvkino.club" // let UserAgent = "Gid Online User Agent" // // public static let CyrillicLetters = [ // "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", // "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я" // ] // // let SessionUrl1 = "http://pandastream.cc/sessions/create_new" // let SessionUrl2 = "http://pandastream.cc/sessions/new" // let SessionUrl3 = "http://pandastream.cc/sessions/new_session" // // func sessionUrl() -> String { // return SessionUrl3 // } // // public func available() throws -> Bool { // let document = try fetchDocument(GidOnlineAPI.SiteUrl) // // return try document!.select("div[id=main] div[id=posts] a[class=mainlink]").size() > 0 // } // // public func getPagePath(_ path: String, page: Int=1) -> String { // var newPath: String // // if page == 1 { // newPath = path // } // else { // var params = [String: String]() // params["p"] = String(page) // // newPath = "\(path)/page/\(page)/" // } // // return newPath // } // // public func getAllMovies(page: Int=1) throws -> [String: Any] { // let document = try fetchDocument(getPagePath(GidOnlineAPI.SiteUrl, page: page)) // // return try getMovies(document!) // } // // public func getGenres(_ document: Document, type: String="") throws -> [Any] { // var data = [Any]() // // let links = try document.select("div[id='catline'] li a") // // for link: Element in links.array() { // let path = try link.attr("href") // let text = try link.text() // // let index1 = text.index(after: text.startIndex) // let index2 = text.index(before: text.endIndex) // // let name = text[text.startIndex...text.startIndex] + text[index1...index2].lowercased() // // data.append(["id": path, "name": name ]) // } // // let familyGroup = [ // data[14], // data[15], // data[12], // data[8], // data[10], // data[5], // data[13] // ] // // let crimeGroup = [ // data[4], // data[9], // data[2], // data[0] // ] // // let fictionGroup = [ // data[20], // data[19], // data[17], // data[18] // ] // // let educationGroup = [ // data[1], // data[7], // data[3], // data[6], // data[11], // data[16] // ] // // switch type { // case "FAMILY": // return familyGroup // case "CRIME": // return crimeGroup // case "FICTION": // return fictionGroup // case "EDUCATION": // return educationGroup // default: // return familyGroup + crimeGroup + fictionGroup + educationGroup // } // } // // public func getTopLinks(_ document: Document) throws -> [Any] { // var data = [Any]() // // let links = try document.select("div[id='topls'] a[class='toplink']") // // for link: Element in links.array() { // let path = try link.attr("href") // let name = try link.text() // let thumb = GidOnlineAPI.SiteUrl + (try link.select("img").attr("src")) // // data.append(["type": "movie", "id": path, "name": name, "thumb": thumb]) // } // // return data // } // // public func getActors(_ document: Document, letter: String="") throws -> [Any] { // var data = [Any]() // // let list = fixName(try getCategory( "actors-dropdown", document: document)) // // let allList = sortByName(list) // // if !letter.isEmpty { // data = [] // // for item in allList { // let currentItem = item as! [String: Any] // let name = currentItem["name"] as! String // // if name.hasPrefix(letter) { // data.append(item) // } // } // } // else { // data = allList // } // // return fixPath(data) // } // // public func getDirectors(_ document: Document, letter: String="") throws -> [Any] { // var data = [Any]() // // let list = fixName(try getCategory( "director-dropdown", document: document)) // // let allList = sortByName(list) // // if !letter.isEmpty { // data = [] // // for item in allList { // let currentItem = item as! [String: Any] // let name = currentItem["name"] as! String // // if name.hasPrefix(letter) { // data.append(item) // } // } // } // else { // data = allList // } // // return fixPath(data) // } // // public func getCountries(_ document: Document) throws -> [Any] { // return fixPath(try getCategory("country-dropdown", document: document)) // } // // public func getYears(_ document: Document) throws -> [Any] { // return fixPath(try getCategory("year-dropdown", document: document)) // } // // public func getSeasons(_ url: String, parentName: String?=nil, thumb: String?=nil) throws -> [Any] { // var newSeasons = [Any]() // // let seasons = try getCategory("season", document: getMovieDocument(url)!) // // for item in seasons { // var season = item as! [String: String] // // season["type"] = "season" // season["parentId"] = url // // if let parentName = parentName { // season["parentName"] = parentName // } // // if let thumb = thumb { // season["thumb"] = thumb // } // // season["parentId"] = url // // newSeasons.append(season) // } // // return newSeasons // } // // public func getEpisodes(_ url: String, seasonNumber: String, thumb: String?=nil) throws -> [Any] { // var newEpisodes = [Any]() // // let serialInfo = try getSerialInfo(url, season: seasonNumber, episode: "1") // // let episodes = serialInfo["episodes"] as! [String] // // for name in episodes { // let index1 = name.index(name.startIndex, offsetBy: 6) // let index2 = name.endIndex // // let episodeNumber = String(name[index1..<index2]) // // var episode = [String: String]() // // episode["name"] = name // episode["id"] = url // episode["type"] = "episode" // episode["seasonNumber"] = seasonNumber // episode["episodeNumber"] = episodeNumber // // if let thumb = thumb { // episode["thumb"] = thumb // } // // newEpisodes.append(episode) // } // // return newEpisodes // } // // func getCategory(_ id: String, document: Document) throws -> [Any] { // var data = [Any]() // // let links = try document.select("select[id='" + id + "'] option") // // for link: Element in links.array() { // let id = try link.attr("value") // let name = try link.text() // // if id != "#" { // data.append(["id": id, "name": name]) // } // } // // return data // } // // public func getMovieDocument(_ url: String, season: String="", episode: String="") throws -> Document? { // let content = try getMovieContent(url, season: season, episode: episode) // // return try toDocument(content) // } // // func getMovieContent(_ url: String, season: String="", episode: String="") throws -> Data? { // var data: Data? // // let document = try fetchDocument(url)! // let gatewayUrl = try getGatewayUrl(document) // // if let gatewayUrl = gatewayUrl { // var movieUrl: String! // // if !season.isEmpty { // movieUrl = "\(gatewayUrl)?season=\(season)&episode=\(episode)" // } // else { // movieUrl = gatewayUrl // } // // if movieUrl.contains("//www.youtube.com") { // movieUrl = movieUrl.replacingOccurrences(of: "//", with: "http://") // } // // if let response = httpRequest(movieUrl, headers: getHeaders(gatewayUrl)) { // if response.response!.statusCode == 302 { // let newGatewayUrl = response.response!.allHeaderFields["Location"] as! String // // let response2 = httpRequest(movieUrl, headers: getHeaders(newGatewayUrl))! // // data = response2.data // } // else { // data = response.data // } // } // } // // return data // } // // func getGatewayUrl(_ document: Document) throws -> String? { // var gatewayUrl: String? // // let frameBlock = try document.select("div[class=tray]").array()[0] // // var urls = try frameBlock.select("iframe").attr("src") // // if !urls.isEmpty { // gatewayUrl = urls // } // else { // let url = "\(GidOnlineAPI.SiteUrl)/trailer.php" // // let idPost = try document.select("head meta[id=meta]").attr("content") // // let parameters: Parameters = [ // "id_post": idPost // ] // // let document2 = try fetchDocument(url, parameters: parameters, method: .post) // // urls = try document2!.select("iframe[class='ifram']").attr("src") // // if !urls.trim().isEmpty { // gatewayUrl = urls // } // } // // return gatewayUrl // } // // public func getMovies(_ document: Document, path: String="") throws -> [String: Any] { // var data = [Any]() // var paginationData = [String: Any]() // // let items = try document.select("div[id=main] div[id=posts] div[class=mainlink] a") // // for item: Element in items.array() { // let href = try item.attr("href") // let name = try item.select("span").text() // let thumb = GidOnlineAPI.SiteUrl + (try item.select("img").attr("src")) // // data.append(["id": href, "name": name, "thumb": thumb ]) // } // // if !items.array().isEmpty { // paginationData = try extractPaginationData(document, path: path) // } // // return ["movies": data, "pagination": paginationData] // } // // func extractPaginationData(_ document: Document, path: String) throws -> [String: Any] { // var page = 1 // var pages = 1 // // let paginationRoot = try document.select("div[id=page_navi] div[class='wp-pagenavi']") // // if !paginationRoot.array().isEmpty { // let paginationBlock = paginationRoot.get(0) // // print(try paginationBlock.select("span").array()[1].text()) // // page = Int(try paginationBlock.select("span").array()[1].text())! // // let links = try paginationBlock.select("a").array() // // pages = try Int(links[links.count-2].text())! // //// let lastBlock = try paginationBlock.select("a[class=last]") //// //// if !lastBlock.array().isEmpty { //// let pagesLink = try lastBlock.get(0).attr("href") //// //// pages = try findPages(path, link: pagesLink) //// } //// else { //// let pageBlock = try paginationBlock.select("a[class='page larger']") //// let pagesLen = pageBlock.array().count //// //// if pagesLen == 0 { //// pages = page //// } //// else { //// let pagesLink = try pageBlock.get(pagesLen - 1).attr("href") //// //// pages = try findPages(path, link: pagesLink) //// } //// } // } // // return [ // "page": page, // "pages": pages, // "has_previous": page > 1, // "has_next": page < pages // ] // } // // public func getUrls(_ url: String, season: String = "", episode: String="") throws -> [[String: String]] { // var newUrl = url // // if url.find(GidOnlineAPI.SiteUrl) != nil && url.find("http://") == nil { // newUrl = GidOnlineAPI.SiteUrl + url // } // // let content = try getMovieContent(newUrl, season: season, episode: episode) // // let html = String(data: content!, encoding: .utf8) // //// let frameCommit = getRequestTokens(html!) // // let parameters = getRequestParams(html!) // // //let userToken = parameters["user_token"]! // // let headers: HTTPHeaders = [ // //"X-Access-Level": userToken, // "X-Requested-With": "XMLHttpRequest" // ] // // let videoToken = parameters["video_token"]! // let allManifestsUrl = "http://pandastream.cc/manifests/video/\(videoToken)/all" // // var params: [String: String] = [:] // // params["mw_key"] = "1ffd4aa558cc51f5a9fc6888e7bc5cb4" // params["c90b4ca500a12b91e2b54b2d4a1e4fb7"] = "cc5610c93fa23befc2d244a76500ee6c" // params["mw_pid"] = "4" // params["p_domain_id"] = parameters["domain_id"] // params["ad_attr"] = "0" // params["iframe_version"] = "2" // // let response2 = httpRequest(allManifestsUrl, headers: headers, parameters: params, method: .post) // //// let data2 = try JSON(data: response2!.data!) //// //// print(data2) // //// let manifests = data2["mans"] //// //// let manifestMp4Url = JSON(data: try manifests.rawData())["manifest_mp4"].rawString()! //// //// return try getMp4Urls(manifestMp4Url).reversed() // return [] // } // // func getRequestParams(_ content: String) -> [String: String] { // var params: [String: String] = [:] // // content.enumerateLines { (line, _) in // if line.find("video_token:") != nil { // let index1 = line.index(line.find("'")!, offsetBy: 1) // let index2 = line.index(line.endIndex, offsetBy: -3) // // let video_token = String(line[index1...index2]) // // params["video_token"] = video_token // } // else if line.find("partner_id:") != nil { // let index1 = line.index(line.find(":")!, offsetBy: 2) // let index2 = line.index(line.endIndex, offsetBy: -2) // // let partner_id = String(line[index1...index2]) // // params["partner_id"] = partner_id // } // else if line.find("domain_id:") != nil { // let index1 = line.index(line.find(":")!, offsetBy: 2) // let index2 = line.index(line.endIndex, offsetBy: -2) // // let domain_id = String(line[index1...index2]) // // params["domain_id"] = domain_id // } // else if line.find("user_token:") != nil { // let index1 = line.index(line.find("'")!, offsetBy: 1) // let index2 = line.index(line.endIndex, offsetBy: -3) // // let user_token = String(line[index1...index2]) // // params["user_token"] = user_token // } // } // // return params // } // // //// func getRequestTokens(_ content: String) -> String { //// var frameCommit = "" //// //// var frameSection = false //// //// content.enumerateLines { (line, _) in //// if line.find("$.ajaxSetup({") != nil { //// frameSection = true //// } //// else if frameSection == true { //// if line.find("});") != nil { //// frameSection = false //// } //// else if !line.isEmpty { //// if line.find("'X-Frame-Commit'") != nil { //// let index1 = line.find("'X-Frame-Commit':") //// //// frameCommit = String(line[line.index(index1!, offsetBy: "'X-Frame-Commit':".characters.count+2) ..< line.index(line.endIndex, offsetBy: -1)]) //// } //// } //// } //// } //// //// return frameCommit //// } // // func getSessionData(_ content: String) -> [String: String] { // var items = [String: String]() // // var mw_key: String? // var random_key: String? // // var dataSection = false // // content.enumerateLines { (line, _) in // if line.find("post_method.runner_go =") != nil { // let index1 = line.find("'") // let index2 = line.find(";") // let index11 = line.index(index1!, offsetBy: 1) // let index21 = line.index(index2!, offsetBy: -2) // // items["runner_go"] = String(line[index11 ... index21]) // } //// else if line.find("var post_method = {") != nil { //// dataSection = true //// } // else if line.find("var mw_key =") != nil { // dataSection = true // // let index1 = line.find("'") // let index2 = line.find(";") // let index11 = line.index(index1!, offsetBy: 1) // let index21 = line.index(index2!, offsetBy: -2) // // mw_key = String(line[index11 ... index21]) // } // else if dataSection == true { // if line.find("};") != nil { // dataSection = false // } // else if !line.isEmpty { // if line.find("var ") != nil { // let index2 = line.find(" = {") // let index11 = line.index(line.startIndex, offsetBy: 4) // let index21 = line.index(index2!, offsetBy: -1) // random_key = String(line[index11 ... index21]) // } // // var data = line // // data = data.replacingOccurrences(of: "'", with: "") // data = data.replacingOccurrences(of: ",", with: "") // // let components = data.components(separatedBy: ":") // // if components.count > 1 { // let key = components[0].trim() // let value = components[1].trim() // // items[key] = value // } // } // } // } // // if mw_key != nil { // items["mw_key"] = mw_key // } // // if random_key != nil { // content.enumerateLines { (line, _) in // if line.find("\(random_key!)['") != nil { // let text1 = line.trim() // // let index1 = text1.find("['") // // let text2 = String(text1[index1! ..< text1.endIndex]) // // let index2 = text2.find("']") // let index3 = text2.find("= '") // // let key = String(text2[text2.index(text2.startIndex, offsetBy: 2) ..< index2!]) // let value = String(text2[text2.index(index3!, offsetBy: 3) ..< text2.index(text2.endIndex, offsetBy: -2)]) // // items[key] = value // } // } // } // // items["ad_attr"] = "0" // items["mw_pid"] = "4" // // //print(items) // // return items // } // // func getMp4Urls(_ url: String) throws -> [[String: String]] { // var urls = [[String: String]]() // //// let response = httpRequest(url) //// //// let list = try JSON(data: response!.data!) //// //// for (bandwidth, url) in list { //// urls.append(["url": url.rawString()!.replacingOccurrences(of: "\\/", with: "/"), "bandwidth": bandwidth]) //// } // // return urls // } // // override func getPlayListUrls(_ url: String) throws -> [[String: String]] { // var urls = [[String: String]]() // // var items = [[String]]() // // let response = httpRequest(url) // // let playList = String(data: response!.data!, encoding: .utf8)! // // var index = 0 // // playList.enumerateLines {(line, _) in // if !line.hasPrefix("#EXTM3U") { // if line.hasPrefix("#EXT-X-STREAM-INF") { // let pattern = "#EXT-X-STREAM-INF:RESOLUTION=(\\d*)x(\\d*),BANDWIDTH=(\\d*)" // // do { // let regex = try NSRegularExpression(pattern: pattern) // // let matches = regex.matches(in: line, options: [], range: NSRange(location: 0, length: line.count)) // // let width = self.getMatched(line, matches: matches, index: 1) // let height = self.getMatched(line, matches: matches, index: 2) // let bandwidth = self.getMatched(line, matches: matches, index: 3) // // items.append(["", width!, height!, bandwidth!]) // } // catch { // print("Error in regular expression.") // } // } // else if !line.isEmpty { // items[index][0] = line // // index += 1 // } // } // } // // for item in items { // urls.append(["url": item[0], "width": item[1], "height": item[2], "bandwidth": item[3]]) // } // // return urls // } // // public func search(_ query: String, page: Int=1) throws -> [String: Any] { // var result: [String: Any] = ["movies": []] // // let path = getPagePath(GidOnlineAPI.SiteUrl, page: page) + "/" // // var params = [String: String]() // params["s"] = query.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! // // let fullPath = self.buildUrl(path: path, params: params as [String : AnyObject]) // // if let response = httpRequest(fullPath), // let data = response.data, // let document = try toDocument(data) { // let movies = try getMovies(document, path: fullPath) // // if !movies.isEmpty { // result = movies // } // else { // if let response = response.response, // let url = response.url, // let document2 = try fetchDocument(url.path) { // // let mediaData = try getMediaData(document2) // // if mediaData["title"] != nil { // result = ["movies": [ // "id": fullPath, // "name": mediaData["title"], // "thumb": mediaData["thumb"] // ]] // } // } // } // } // // return result // } // // func searchActors(_ document: Document, query: String) throws -> [Any] { // return searchInList(try getActors(document), query: query) // } // // func searchDirectors(_ document: Document, query: String) throws -> [Any] { // return searchInList(try getDirectors(document), query: query) // } // // func searchCountries(_ document: Document, query: String) throws -> [Any] { // return searchInList(try getCountries(document), query: query) // } // // func searchYears(_ document: Document, query: String) throws -> [Any] { // return searchInList(try getYears(document), query: query) // } // // func searchInList(_ list: [Any], query: String) -> [Any] { // var newList = [Any]() // // for item in list { // let name = (item as! [String: String])["name"]!.lowercased() // // if name.find(query.lowercased()) != nil { // newList.append(item) // } // } // // return newList // } // // public func getMediaData(_ document: Document) throws -> [String: Any] { // var data = [String: Any]() // // let mediaNode = try document.select("div[id=face]") // // if !mediaNode.array().isEmpty { // let block = mediaNode.get(0) // // let thumb = try block.select("div img[class=t-img]").attr("src") // // data["thumb"] = GidOnlineAPI.SiteUrl + thumb // // let items1 = try block.select("div div[class=t-row] div[class='r-1'] div[class='rl-2']") // let items2 = try block.select("div div[class=t-row] div[class='r-2'] div[class='rl-2']") // // data["title"] = try items1.array()[0].text() // data["countries"] = try items1.array()[1].text().components(separatedBy: ",") // data["duration"] = try items1.array()[2].text() // data["year"] = try items2.array()[0].text() // data["tags"] = try items2.array()[1].text().components(separatedBy: ", ") // data["genres"] = try items2.array()[2].text().components(separatedBy: ", ") // // let descriptionBlock = try document.select("div[class=description]").array()[0] // // data["summary"] = try descriptionBlock.select("div[class=infotext]").array()[0].text() // // data["rating"] = try document.select("div[class=nvz] meta").attr("content") // } // // return data // } // // public func getSerialInfo(_ path: String, season: String="", episode: String="") throws -> [String: Any] { // var result = [String: Any]() // // let content = try getMovieContent(path, season: season, episode: episode) // // //let data = getSessionData(toString(content!)!) // // let document = try toDocument(content) // // var seasons = [Any]() // // let items1 = try document!.select("select[id=season] option") // // for item in items1.array() { // let value = try item.attr("value") // // seasons.append(try item.text()) // // if try !item.attr("selected").isEmpty { // result["current_season"] = value // } // } // // result["seasons"] = seasons // // var episodes = [Any]() // // let items2 = try document!.select("select[id=episode] option") // // for item in items2.array() { // let value = try item.attr("value") // // episodes.append(try item.text()) // // if try !item.attr("selected").isEmpty { // result["current_episode"] = value // } // } // // result["episodes"] = episodes // // return result // } // // func findPages(_ path: String, link: String) throws -> Int { // let searchMode = (!path.isEmpty && path.find("?s=") != nil) // // var pattern: String? // // if !path.isEmpty { // if searchMode { // pattern = GidOnlineAPI.SiteUrl + "/page/" // } // else { // pattern = GidOnlineAPI.SiteUrl + path + "page/" // } // } // else { // pattern = GidOnlineAPI.SiteUrl + "/page/" // } // // pattern = pattern!.replacingOccurrences(of: "/", with: "\\/") // pattern = pattern!.replacingOccurrences(of: ".", with: "\\.") // // let rePattern = "(\(pattern!))(\\d*)\\/" // // let regex = try NSRegularExpression(pattern: rePattern) // // let matches = regex.matches(in: link, options: [], range: NSRange(location: 0, length: link.count)) // // if let matched = getMatched(link, matches: matches, index: 2) { // return Int(matched)! // } // else { // return 1 // } // } // // func getMatched(_ link: String, matches: [NSTextCheckingResult], index: Int) -> String? { // var matched: String? // // let match = matches.first // // if match != nil && index < match!.numberOfRanges { // let capturedGroupIndex = match!.range(at: index) // // let index1 = link.index(link.startIndex, offsetBy: capturedGroupIndex.location) // let index2 = link.index(index1, offsetBy: capturedGroupIndex.length-1) // // matched = String(link[index1 ... index2]) // } // // return matched // } // // public func isSerial(_ path: String) throws -> Bool { // let content = try getMovieContent(path) // // let text = String(data: content!, encoding: .utf8) // // let data = getSessionData(text!) // //// let anySeason = try hasSeasons(path) //// //// return data != nil && data["content_type"] == "serial" || anySeason // // return data["content_type"] == "serial" // } // //// func hasSeasons(_ url: String) throws -> Bool { //// //let path = urlparse.urlparse(url).path //// //// let path = NSURL(fileURLWithPath: url).deletingLastPathComponent!.path ////// let dirUrl = url.URLByDeletingLastPathComponent! ////// print(dirUrl.path!) //// //// return try !getSeasons(path).isEmpty //// } // // func fixName(_ items: [Any]) -> [Any] { // var newItems = [Any]() // // for item in items { // var currentItem = (item as! [String: Any]) // // let name = currentItem["name"] as! String // // let names = name.components(separatedBy: " ") // // var newName = "" // var suffix = "" // var delta = 0 // // if names[names.count-1] == "мл." { // delta = 1 // suffix = names[names.count-1] // // newName = names[names.count-2] // } // else { // newName = names[names.count-1] // } // // if names.count > 1 { // newName += "," // // for index in 0 ..< names.count-1-delta { // newName += " " + names[index] // } // } // // if !suffix.isEmpty { // newName = newName + " " + suffix // } // // currentItem["name"] = newName // // newItems.append(currentItem) // } // // return newItems // } // // func fixPath(_ items: [Any]) -> [Any] { // var newItems = [Any]() // // for item in items { // var currentItem = (item as! [String: Any]) // // let path = currentItem["id"] as! String // // let index1 = path.index(path.startIndex, offsetBy: GidOnlineAPI.SiteUrl.count, limitedBy: path.endIndex) // let index2 = path.index(before: path.endIndex) // // if index1 != nil { // currentItem["id"] = path[index1! ... index2] // } // else { // currentItem["id"] = path // } // // newItems.append(currentItem) // } // // return newItems // } // // func getEpisodeUrl(url: String, season: String, episode: String) -> String { // var episodeUrl = url // // if !season.isEmpty { // episodeUrl = "\(url)?season=\(season)&episode=\(episode)" // } // // return episodeUrl // } // // func getHeaders(_ referer: String) -> [String: String] { // return [ // "User-Agent": UserAgent, // "Referer": referer // ] // } // // func sortByName(_ list: [Any]) -> [Any] { // return list.sorted { element1, element2 in // let name1 = (element1 as! [String: Any])["name"] as! String // let name2 = (element2 as! [String: Any])["name"] as! String // // return name1 < name2 // } // } }
mit
6977853ce48728ca7aaf53621e3a4cdb
27.831313
157
0.542655
3.194874
false
false
false
false
omaralbeik/SwifterSwift
Sources/Extensions/SwiftStdlib/ArrayExtensions.swift
1
8226
// // ArrayExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // #if canImport(Foundation) import Foundation #endif // MARK: - Methods public extension Array { /// SwifterSwift: Insert an element at the beginning of array. /// /// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5] /// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"] /// /// - Parameter newElement: element to insert. public mutating func prepend(_ newElement: Element) { insert(newElement, at: 0) } /// SwifterSwift: Safely Swap values at index positions. /// /// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5] /// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"] /// /// - Parameters: /// - index: index of first element. /// - otherIndex: index of other element. public mutating func safeSwap(from index: Index, to otherIndex: Index) { guard index != otherIndex else { return } guard startIndex..<endIndex ~= index else { return } guard startIndex..<endIndex ~= otherIndex else { return } swapAt(index, otherIndex) } /// SwifterSwift: Keep elements of Array while condition is true. /// /// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4] /// /// - Parameter condition: condition to evaluate each element against. /// - Returns: self after applying provided condition. /// - Throws: provided condition exception. @discardableResult public mutating func keep(while condition: (Element) throws -> Bool) rethrows -> [Element] { for (index, element) in lazy.enumerated() where try !condition(element) { self = Array(self[startIndex..<index]) break } return self } /// SwifterSwift: Take element of Array while condition is true. /// /// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4] /// /// - Parameter condition: condition to evaluate each element against. /// - Returns: All elements up until condition evaluates to false. public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] { for (index, element) in lazy.enumerated() where try !condition(element) { return Array(self[startIndex..<index]) } return self } /// SwifterSwift: Skip elements of Array while condition is true. /// /// [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -> [6, 8] /// /// - Parameter condition: condition to evaluate each element against. /// - Returns: All elements after the condition evaluates to false. public func skip(while condition: (Element) throws-> Bool) rethrows -> [Element] { for (index, element) in lazy.enumerated() where try !condition(element) { return Array(self[index..<endIndex]) } return [Element]() } /// SwifterSwift: Separates an array into 2 arrays based on a predicate. /// /// [0, 1, 2, 3, 4, 5].divided { $0 % 2 == 0 } -> ( [0, 2, 4], [1, 3, 5] ) /// /// - Parameter condition: condition to evaluate each element against. /// - Returns: Two arrays, the first containing the elements for which the specified condition evaluates to true, the second containing the rest. public func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) { //Inspired by: http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-partition var matching = [Element]() var nonMatching = [Element]() for element in self { try condition(element) ? matching.append(element) : nonMatching.append(element) } return (matching, nonMatching) } /// SwifterSwift: Returns a sorted array based on an optional keypath. /// /// - Parameter path: Key path to sort. The key path type must be Comparable. /// - Parameter ascending: If order must be ascending. /// - Returns: Sorted array based on keyPath. public func sorted<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] { return sorted(by: { (lhs, rhs) -> Bool in guard let lhsValue = lhs[keyPath: path], let rhsValue = rhs[keyPath: path] else { return false } return ascending ? lhsValue < rhsValue : lhsValue > rhsValue }) } /// SwifterSwift: Returns a sorted array based on a keypath. /// /// - Parameter path: Key path to sort. The key path type must be Comparable. /// - Parameter ascending: If order must be ascending. /// - Returns: Sorted array based on keyPath. public func sorted<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) -> [Element] { return sorted(by: { (lhs, rhs) -> Bool in return ascending ? lhs[keyPath: path] < rhs[keyPath: path] : lhs[keyPath: path] > rhs[keyPath: path] }) } /// SwifterSwift: Sort the array based on an optional keypath. /// /// - Parameters: /// - path: Key path to sort, must be Comparable. /// - ascending: whether order is ascending or not. /// - Returns: self after sorting. @discardableResult public mutating func sort<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] { self = sorted(by: path, ascending: ascending) return self } /// SwifterSwift: Sort the array based on a keypath. /// /// - Parameters: /// - path: Key path to sort, must be Comparable. /// - ascending: whether order is ascending or not. /// - Returns: self after sorting. @discardableResult public mutating func sort<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) -> [Element] { self = sorted(by: path, ascending: ascending) return self } } // MARK: - Methods (Equatable) public extension Array where Element: Equatable { /// SwifterSwift: Remove all instances of an item from array. /// /// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5] /// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"] /// /// - Parameter item: item to remove. /// - Returns: self after removing all instances of item. @discardableResult public mutating func removeAll(_ item: Element) -> [Element] { removeAll(where: { $0 == item }) return self } /// SwifterSwift: Remove all instances contained in items parameter from array. /// /// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4] /// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"] /// /// - Parameter items: items to remove. /// - Returns: self after removing all instances of all items in given array. @discardableResult public mutating func removeAll(_ items: [Element]) -> [Element] { guard !items.isEmpty else { return self } removeAll(where: { items.contains($0) }) return self } /// SwifterSwift: Remove all duplicate elements from Array. /// /// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5] /// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"] /// public mutating func removeDuplicates() { // Thanks to https://github.com/sairamkotha for improving the method self = reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } } /// SwifterSwift: Return array with all duplicate elements removed. /// /// [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -> [1, 2, 3, 4, 5]) /// ["h", "e", "l", "l", "o"].withoutDuplicates() -> ["h", "e", "l", "o"]) /// /// - Returns: an array of unique elements. /// public func withoutDuplicates() -> [Element] { // Thanks to https://github.com/sairamkotha for improving the method return reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } } }
mit
fe970957e9190509f7e1374d7de7a43c
38.724638
149
0.571446
3.90827
false
false
false
false
YevhenHerasymenko/SwiftGroup1
Lesson3.playground/Contents.swift
1
1345
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" struct Animal { enum AnimalType { case Cat case Dog case Lion } let animalType: AnimalType let name: String let age: Int? init(age: Int) { animalType = AnimalType.Cat name = "Cat" self.age = age } func isOldCat() { if age > 8 { print("It Is Old Cat") } else if age < 2 { print("It is Young Cat") } else { print("It isn`t Old Cat") } if let animalAge = age { print(animalAge) } } } let oldCat = Animal(age: 10) let youngCat = Animal(age: 1) oldCat.isOldCat() youngCat.isOldCat() var animalsArray: [Animal] = [oldCat, youngCat] let myCat = Animal(age: 3) animalsArray.append(myCat) let index = 2 if index < animalsArray.count { animalsArray[index] } animalsArray.count let numbersArray = 0...100 var j = 0 j = j - 1 j-=1 for animal in animalsArray { animal.isOldCat() } var i = 0 while i < animalsArray.count { animalsArray[i].isOldCat() i+=1 } Animal.AnimalType.Cat struct Weel { let radius: Int let width: Int } struct Car { let model: String let weel: Weel }
apache-2.0
0d1f42c94100e354568e7f5e8e611cad
13.473118
52
0.551673
3.413706
false
false
false
false
FroeMic/FMTabBarController
FMTabBarController/FMExtensions/UIColorExtension.swift
2
760
import UIKit extension UIColor { /** Initializes a UIColor object given by RGB values with opacaity 1.0. */ convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } /** Initializes a UIColor object given by an RGB hex value with opacaity 1.0. */ convenience init(hexValue: Int) { self.init(red: (hexValue >> 16) & 0xff, green: (hexValue >> 8) & 0xff, blue: hexValue & 0xff) } }
mit
4aebbadf921b069b7a1d99af3e7155cb
35.190476
116
0.589474
3.619048
false
false
false
false
getaccent/accent-ios
Accent/ArticleViewController.swift
1
10636
// // ArticleViewController.swift // Accent // // Created by Jack Cook on 4/9/16. // Copyright © 2016 Tiny Pixels. All rights reserved. // import AVFoundation import UIKit class ArticleViewController: UIViewController, ArticleTextViewDelegate, AudioBarDelegate { @IBOutlet weak var topBar: UIView! @IBOutlet weak var topBarLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var bottomBar: AudioBar! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! var article: Article! private var articleTitle: UILabel! private var imageView: UIImageView! private var textView: ArticleTextView! private var backTextView: ArticleTextView! private var translateView: UIView! private var translateLabel: UILabel! private var audio = false private var terms = [String: String]() override func viewDidLoad() { super.viewDidLoad() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) } catch {} navigationController?.isNavigationBarHidden = true bottomBar.article = article bottomBar.delegate = self let articlesText = NSLocalizedString("Article", comment: "news article") topBarLabel.text = articlesText } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) try AVAudioSession.sharedInstance().setActive(false) } catch {} if Quizlet.sharedInstance.setId == 0 && terms.count > 2 { guard let _ = Language.savedLanguage() else { return } Quizlet.sharedInstance.createSet(terms, completion: { (url) in }) } } let margin: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 32 : 16 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let topShadowPath = UIBezierPath(rect: topBar.bounds) topBar.layer.masksToBounds = false topBar.layer.shadowColor = UIColor.black.cgColor topBar.layer.shadowOffset = CGSize(width: 0, height: 1) topBar.layer.shadowOpacity = 0.15 topBar.layer.shadowPath = topShadowPath.cgPath let bottomShadowPath = UIBezierPath(rect: bottomBar.bounds) bottomBar.layer.masksToBounds = false bottomBar.layer.shadowColor = UIColor.black.cgColor bottomBar.layer.shadowOffset = CGSize(width: 0, height: -1) bottomBar.layer.shadowOpacity = 0.15 bottomBar.layer.shadowPath = bottomShadowPath.cgPath if articleTitle == nil { articleTitle = UILabel() articleTitle.font = UIFont.systemFont(ofSize: 22, weight: UIFontWeightSemibold) articleTitle.numberOfLines = 0 articleTitle.text = article.title scrollView.addSubview(articleTitle) } let articleTitleHeight = (articleTitle.text! as NSString).boundingRect(with: CGSize(width: scrollView.bounds.width - margin * 2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: articleTitle.font], context: nil).height articleTitle.frame = CGRect(x: margin, y: margin, width: scrollView.bounds.width - margin * 2, height: articleTitleHeight) if imageView == nil { imageView = UIImageView() scrollView.addSubview(imageView) Accent.sharedInstance.getArticleThumbnail(article) { (image) in self.imageView.image = image } } let imageWidth = scrollView.bounds.width - (UIDevice.current.userInterfaceIdiom == .pad ? margin * 6 : 0) if article.image == "" { imageView.frame = CGRect(x: 0, y: articleTitle.frame.origin.y + articleTitle.frame.size.height, width: imageWidth, height: 0) } else { imageView.frame = CGRect(x: (scrollView.bounds.width - imageWidth) / 2, y: articleTitle.frame.origin.y + articleTitle.frame.size.height + margin, width: imageWidth, height: imageWidth * (9/16)) } if textView == nil { textView = ArticleTextView(delegate: self) textView.backgroundColor = UIColor.clear textView.isEditable = false textView.font = UIFont.systemFont(ofSize: 16) textView.isScrollEnabled = false textView.text = article.text scrollView.addSubview(textView) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 let attributes = [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: textView.font!] as [String : Any] textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes) } let textViewHeight = textView.sizeThatFits(CGSize(width: scrollView.bounds.width - margin * 2, height: CGFloat.greatestFiniteMagnitude)).height textView.frame = CGRect(x: margin, y: imageView.frame.origin.y + imageView.frame.size.height + margin * 0.625, width: scrollView.bounds.width - margin * 2, height: textViewHeight) scrollView.contentSize = CGSize(width: scrollView.bounds.width, height: textView.frame.origin.y + textView.frame.size.height + margin) if backTextView == nil { backTextView = ArticleTextView(delegate: self) backTextView.isEditable = textView.isEditable backTextView.isSelectable = false backTextView.font = textView.font backTextView.isScrollEnabled = textView.isScrollEnabled backTextView.attributedText = textView.attributedText backTextView.textColor = UIColor.white scrollView.insertSubview(backTextView, belowSubview: textView) } backTextView.frame = textView.frame if translateView == nil { translateView = UIView() translateView.alpha = 0 translateView.backgroundColor = UIColor(white: 0, alpha: 0.85) translateView.layer.cornerRadius = 8 view.addSubview(translateView) } translateView.frame = CGRect(x: margin, y: 80, width: view.bounds.width - margin * 2, height: 36) if translateLabel == nil { translateLabel = UILabel() translateLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightSemibold) translateLabel.text = "" translateLabel.textAlignment = .center translateLabel.textColor = UIColor.white translateView.addSubview(translateLabel) } translateLabel.frame = CGRect(x: margin, y: 4, width: translateView.frame.size.width - margin * 2, height: 28) } func longTouchReceived(_ point: CGPoint, state: UIGestureRecognizerState, text: String) { func moveTranslationView() { translateView.frame = CGRect(x: margin, y: point.y - 96 - translateView.frame.size.height, width: translateView.frame.size.width, height: translateView.frame.size.height) let text = (textView.text as NSString).substring(with: textView.selectedRange) Accent.sharedInstance.translateTerm(text) { (translation) in guard let translation = translation else { return } var word = "" if let translation = translation as? String { word = translation } else if let translation = translation as? Translation { word = translation.translation } DispatchQueue.main.async { self.translateLabel.text = word } if Quizlet.sharedInstance.setId > 0 { Quizlet.sharedInstance.addTermToSet(text, translation: word) } else { self.terms[text] = word } } } switch state { case .began: UIView.animate(withDuration: 0.25) { self.translateView.alpha = 1 moveTranslationView() } case .changed: moveTranslationView() case .ended: UIView.animate(withDuration: 0.25) { self.translateView.alpha = 0 self.translateView.frame = CGRect(x: self.margin, y: 80, width: self.view.bounds.width - self.margin * 2, height: 36) } becomeFirstResponder() default: break } } @IBAction func backButtonPressed(_ sender: UIButton) { let _ = navigationController?.popViewController(animated: true) } @IBAction func speechButtonPressed(_ sender: UIButton?) { audio = !audio bottomConstraint.constant = audio ? 0 : -56 backTextView.attributedText = textView.attributedText backTextView.textColor = UIColor.white UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } func hiding() { speechButtonPressed(nil) } func updatedSpeechRange(_ range: NSRange) { let attributedString = NSMutableAttributedString(string: backTextView.text) attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.accentBlueColor(), range: range) attributedString.addAttribute(NSFontAttributeName, value: backTextView.font!, range: NSMakeRange(0, attributedString.length)) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length)) backTextView.attributedText = attributedString backTextView.textColor = UIColor.white } override var canBecomeFirstResponder : Bool { return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return false } }
mit
a2f50f5c5bc013a1945c6ba6c87fa3fc
39.747126
287
0.619182
5.379363
false
false
false
false
benlangmuir/swift
test/stdlib/EmptyCollectionSingletonRealization.swift
9
1892
// 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 // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation // Test to make sure that empty collections don't cause a crash if we smuggle // them into the ObjC runtime without doing anything that would trigger // realization. The ObjC runtime expects all classes to have been realized // (i.e. runtime data structures initialized, triggered the first time a class // is accessed or used) before being queried in any way. // // Note: this test deliberately avoids StdlibUnittest to make sure // no other code runs that might inadvertently trigger realization behind our // back. @objc protocol P {} if #available(SwiftStdlib 5.3, *) { do { let d: [NSObject: NSObject] = [:] let c: AnyClass? = object_getClass(d) let conforms = class_conformsToProtocol(c, P.self) print("Dictionary: ", conforms) // CHECK: Dictionary: false } do { let a: [NSObject] = [] let c: AnyClass? = object_getClass(a) let p = objc_getProtocol("NSObject") let conforms = class_conformsToProtocol(c, p) print("Array:", conforms) // CHECK: Array: false } do { let s: Set<NSObject> = [] let c: AnyClass? = object_getClass(s) let p = objc_getProtocol("NSObject") let conforms = class_conformsToProtocol(c, p) print("Set:", conforms) // CHECK: Set: false } } else { // When testing against an older runtime that doesn't have this fix, lie. print("Dictionary: false") print("Array: false") print("Set: false") }
apache-2.0
2590fac8734a54941848859df4514c67
32.785714
80
0.665433
4.051392
false
true
false
false
sharath-cliqz/browser-ios
Storage/RecentlyClosedTabs.swift
2
2515
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared open class ClosedTabsStore { let prefs: Prefs lazy open var tabs: [ClosedTab] = { guard let tabsArray: AnyObject = self.prefs.objectForKey("recentlyClosedTabs"), let dataObj = tabsArray as? Data, let unarchivedArray = NSKeyedUnarchiver.unarchiveObject(with: dataObj) as? [ClosedTab] else { return [] } return unarchivedArray }() public init(prefs: Prefs) { self.prefs = prefs } open func addTab(_ url: URL, title: String?, faviconURL: String?) { let recentlyClosedTab = ClosedTab(url: url, title: title ?? "", faviconURL: faviconURL ?? "") tabs.insert(recentlyClosedTab, at: 0) if tabs.count > 5 { tabs.removeLast() } let archivedTabsArray = NSKeyedArchiver.archivedData(withRootObject: tabs) prefs.setObject(archivedTabsArray as AnyObject?, forKey: "recentlyClosedTabs") } open func clearTabs() { prefs.removeObjectForKey("recentlyClosedTabs") tabs = [] } } open class ClosedTab: NSObject, NSCoding { open let url: URL open let title: String? open let faviconURL: String? var jsonDictionary: [String: AnyObject] { let json: [String: AnyObject] = [ "title": title as AnyObject? ?? "" as AnyObject, "url": url as AnyObject, "faviconURL": faviconURL as AnyObject? ?? "" as AnyObject, ] return json } init(url: URL, title: String?, faviconURL: String?) { assert(Thread.isMainThread) self.title = title self.url = url self.faviconURL = faviconURL super.init() } required convenience public init?(coder: NSCoder) { guard let url = coder.decodeObject(forKey: "url") as? URL, let faviconURL = coder.decodeObject(forKey: "faviconURL") as? String, let title = coder.decodeObject(forKey: "title") as? String else { return nil } self.init( url: url, title: title, faviconURL: faviconURL ) } open func encode(with coder: NSCoder) { coder.encode(url, forKey: "url") coder.encode(faviconURL, forKey: "faviconURL") coder.encode(title, forKey: "title") } }
mpl-2.0
75c0ddf705ec36dfa61c5b77684e0afa
30.835443
107
0.611531
4.420035
false
false
false
false
kevindelord/DKDBManager
Example/DKDBManagerTests/ValidateEntityTests.swift
1
2205
// // ValidateEntityTests.swift // DKDBManager // // Created by kevin delord on 20/06/16. // Copyright © 2016 Smart Mobile Factory. All rights reserved. // import Foundation import XCTest import DKDBManager class ValidateEntityTest: DKDBTestCase { override func setUp() { super.setUp() self.createDefaultEntities() } } extension ValidateEntityTest { func testCreatedEntityAsValid() { let predicate = NSPredicate(format: "%K ==[c] %@ && %K ==[c] %@", JSON.Origin, "Paris", JSON.Destination, "London") let plane = Plane.mr_findFirst(with: predicate) XCTAssertEqual(plane?.isDeleted, false, "plane entity shoud be not be deleted") XCTAssertEqual(plane?.hasBeenDeleted, false, "plane entity shoud not have been deleted") XCTAssertEqual(plane?.doesExist, true, "plane entity shoud exist") XCTAssertEqual(plane?.hasValidContext, true, "plane entity shoud have valid context") XCTAssertNotEqual(plane?.doesExist, plane?.hasBeenDeleted) XCTAssertEqual(plane?.isValidInCurrentContext, true, "plane entity shoud be valid in context") } func testEntityShouldNotBeWithinContext() { var bag : Baggage? = nil TestDataManager.save(blockAndWait: { (savingContext) in bag = Baggage.crudEntity(in: savingContext) bag?.deleteEntity(withReason: nil, in: savingContext) }) XCTAssert(bag?.hasValidContext == false) XCTAssert(bag?.doesExist == false) } func testDeleteEntityState() { let plane = Plane.mr_findFirst() XCTAssertEqual(plane?.isValidInCurrentContext, true, "plane entity shoud be valid in context") // set expectation let expectation = self.expectation(description: "Wait for the Response") TestDataManager.save({ (savingContext: NSManagedObjectContext) -> Void in // background thread Plane.deleteAllEntities(in: savingContext) }, completion: { (contextDidSave: Bool, error: Error?) -> Void in XCTAssertTrue(contextDidSave) XCTAssertNil(error) XCTAssertEqual(plane?.entityInDefaultContext()?.isValidInCurrentContext, false, "plane entity shoud be NOT valid in context") XCTAssertNotEqual(plane?.doesExist, plane?.hasBeenDeleted) expectation.fulfill() }) self.waitForExpectations(timeout: 5, handler: nil) } }
mit
597ab23ed8a490f909c38da44d38f1bf
29.191781
128
0.743648
3.887125
false
true
false
false
exponent/exponent
ios/versioned/sdk44/ExpoModulesCore/Swift/Views/ConcreteViewProp.swift
2
1706
// Copyright 2021-present 650 Industries. All rights reserved. import UIKit /** Specialized class for the view prop. Specifies the prop name and its setter. */ public final class ConcreteViewProp<ViewType: UIView, PropType: AnyArgument>: AnyViewProp { public typealias SetterType = (ViewType, PropType) -> Void /** Name of the view prop that JavaScript refers to. */ public let name: String /** An argument type wrapper for the prop's value type. */ private let propType: AnyArgumentType /** Closure to call to set the actual property on the given view. */ private let setter: SetterType internal init(name: String, propType: AnyArgumentType, setter: @escaping SetterType) { self.name = name self.propType = propType self.setter = setter } /** Function that sets the underlying prop value for given view. */ public func set(value: Any, onView view: UIView) throws { // Method's signature must be type-erased to conform to `AnyViewProp` protocol. // Given view must be castable to the generic `ViewType` type. guard let view = view as? ViewType else { throw IncompatibleViewError(propName: name, viewType: ViewType.self) } guard let value = try propType.cast(value) as? PropType else { throw Conversions.CastingError<PropType>(value: value) } setter(view, value) } } /** An error that is thrown when the view passed to prop's setter doesn't match the type in setter's definition. */ internal struct IncompatibleViewError: CodedError { let propName: String let viewType: UIView.Type var description: String { "Tried to set prop `\(propName)` on the view that isn't `\(viewType)`" } }
bsd-3-clause
e59bccc6ca19b6c7da26a68dd9f77580
28.929825
109
0.704572
4.212346
false
false
false
false
nixzhu/MonkeyKing
Sources/MonkeyKing/MonkeyKing+Message.swift
1
31873
import UIKit extension MonkeyKing { public enum MiniAppType: Int { case release = 0 case test = 1 case preview = 2 } /// https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/iOS.html public enum Media { case url(URL) case image(UIImage) case imageData(Data) case gif(Data) case audio(audioURL: URL, linkURL: URL?) case video(URL) /// file extension for wechat file share case file(Data, fileExt: String?) /** - url : 含义[兼容低版本的网页链接] 备注[限制长度不超过10KB] - path: [小程序的页面路径] [小程序页面路径;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"] - withShareTicket: 通常开发者希望分享出去的小程序被二次打开时可以获取到更多信息,例如群的标识。可以设置withShareTicket为true,当分享卡片在群聊中被其他用户打开时,可以获取到shareTicket,用于获取更多分享信息。详见小程序获取更多分享信息 ,最低客户端版本要求:6.5.13 - miniprogramType: 小程序的类型,默认正式版,1.8.1及以上版本开发者工具包支持分享开发版和体验版小程序 - userName: 小程序原始ID获取方法:登录小程序管理后台-设置-基本设置-帐号信息 */ case miniApp(url: URL, path: String, withShareTicket: Bool, type: MiniAppType, userName: String?) } public typealias Info = (title: String?, description: String?, thumbnail: UIImage?, media: Media?) public enum Message { public enum WeChatSubtype { case session(info: Info) case timeline(info: Info) case favorite(info: Info) var scene: String { switch self { case .session: return "0" case .timeline: return "1" case .favorite: return "2" } } var info: Info { switch self { case .session(let info): return info case .timeline(let info): return info case .favorite(let info): return info } } } case weChat(WeChatSubtype) public enum QQSubtype { case friends(info: Info) case zone(info: Info) case favorites(info: Info) case dataline(info: Info) var scene: Int { switch self { case .friends: return 0x00 case .zone: return 0x01 case .favorites: return 0x08 case .dataline: return 0x10 } } var info: Info { switch self { case .friends(let info): return info case .zone(let info): return info case .favorites(let info): return info case .dataline(let info): return info } } } case qq(QQSubtype) public enum WeiboSubtype { case `default`(info: Info, accessToken: String?) var info: Info { switch self { case .default(let info, _): return info } } var accessToken: String? { switch self { case .default(_, let accessToken): return accessToken } } } case weibo(WeiboSubtype) public enum AlipaySubtype { case friends(info: Info) case timeline(info: Info) var scene: NSNumber { switch self { case .friends: return 0 case .timeline: return 1 } } var info: Info { switch self { case .friends(let info): return info case .timeline(let info): return info } } } case alipay(AlipaySubtype) public enum TwitterSubtype { case `default`(info: Info, mediaIDs: [String]?, accessToken: String?, accessTokenSecret: String?) var info: Info { switch self { case .default(let info, _, _, _): return info } } var mediaIDs: [String]? { switch self { case .default(_, let mediaIDs, _, _): return mediaIDs } } var accessToken: String? { switch self { case .default(_, _, let accessToken, _): return accessToken } } var accessTokenSecret: String? { switch self { case .default(_, _, _, let accessTokenSecret): return accessTokenSecret } } } case twitter(TwitterSubtype) public var canBeDelivered: Bool { switch platform { case .weibo, .twitter: return true default: return platform.isAppInstalled } } } private class func fallbackToScheme(url: URL, completionHandler: @escaping DeliverCompletionHandler) { shared.openURL(url) { succeed in if succeed { return } completionHandler(.failure(.sdk(.invalidURLScheme))) } } public class func deliver(_ message: Message, completionHandler: @escaping DeliverCompletionHandler) { guard message.canBeDelivered else { completionHandler(.failure(.noApp)) return } guard let account = shared.accountSet[message.platform] else { completionHandler(.failure(.noAccount)) return } shared.deliverCompletionHandler = completionHandler shared.payCompletionHandler = nil shared.oauthCompletionHandler = nil shared.openSchemeCompletionHandler = nil let appID = account.appID switch message { case .weChat(let type): var weChatMessageInfo: [String: Any] = [ "scene": type.scene, "command": "1010", ] let info = type.info if let title = info.title { weChatMessageInfo["title"] = title } if let description = info.description { weChatMessageInfo["description"] = description } if let thumbnailImage = info.thumbnail { weChatMessageInfo["thumbData"] = thumbnailImage.monkeyking_compressedImageData } if let media = info.media { switch media { case .url(let url): weChatMessageInfo["objectType"] = "5" weChatMessageInfo["mediaUrl"] = url.absoluteString case .image(let image): weChatMessageInfo["objectType"] = "2" if let imageData = image.jpegData(compressionQuality: 0.9) { weChatMessageInfo["fileData"] = imageData } case .imageData(let imageData): weChatMessageInfo["objectType"] = "2" weChatMessageInfo["fileData"] = imageData case .gif(let data): weChatMessageInfo["objectType"] = "8" weChatMessageInfo["fileData"] = data case .audio(let audioURL, let linkURL): weChatMessageInfo["objectType"] = "3" if let urlString = linkURL?.absoluteString { weChatMessageInfo["mediaUrl"] = urlString } weChatMessageInfo["mediaDataUrl"] = audioURL.absoluteString case .video(let url): weChatMessageInfo["objectType"] = "4" weChatMessageInfo["mediaUrl"] = url.absoluteString case .miniApp(let url, let path, let withShareTicket, let type, let userName): if case .weChat(_, _, let miniProgramID, let universalLink) = account { weChatMessageInfo["objectType"] = "36" if let hdThumbnailImage = info.thumbnail { weChatMessageInfo["hdThumbData"] = hdThumbnailImage.monkeyking_resetSizeOfImageData(maxSize: 127 * 1024) } weChatMessageInfo["mediaUrl"] = url.absoluteString weChatMessageInfo["appBrandPath"] = path weChatMessageInfo["withShareTicket"] = withShareTicket weChatMessageInfo["miniprogramType"] = type.rawValue weChatMessageInfo["universalLink"] = universalLink if let userName = userName { weChatMessageInfo["appBrandUserName"] = userName } else if let miniProgramID = miniProgramID { weChatMessageInfo["appBrandUserName"] = miniProgramID } else { fatalError("Missing `miniProgramID`!") } } case .file(let fileData, let fileExt): weChatMessageInfo["objectType"] = "6" weChatMessageInfo["fileData"] = fileData weChatMessageInfo["fileExt"] = fileExt if let fileExt = fileExt, let title = info.title { let suffix = ".\(fileExt)" weChatMessageInfo["title"] = title.hasSuffix(suffix) ? title : title + suffix } } } else { // Text Share weChatMessageInfo["command"] = "1020" } lastMessage = message shared.setPasteboard(of: appID, with: weChatMessageInfo) if let ulURL = shared.wechatUniversalLink(of: "sendreq"), let universalLink = MonkeyKing.shared.accountSet[.weChat]?.universalLink { weChatMessageInfo["universalLink"] = universalLink weChatMessageInfo["isAutoResend"] = false shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in if !succeed, let schemeURL = URL(string: "weixin://app/\(appID)/sendreq/?") { fallbackToScheme(url: schemeURL, completionHandler: completionHandler) } } } else if let schemeURL = URL(string: "weixin://app/\(appID)/sendreq/?") { fallbackToScheme(url: schemeURL, completionHandler: completionHandler) } case .qq(let type): let callbackName = appID.monkeyking_qqCallbackName var qqSchemeURLString = "mqqapi://share/to_fri?" if let encodedAppDisplayName = Bundle.main.monkeyking_displayName?.monkeyking_base64EncodedString { qqSchemeURLString += "thirdAppDisplayName=" + encodedAppDisplayName } else { qqSchemeURLString += "thirdAppDisplayName=" + "nixApp" // Should not be there } qqSchemeURLString += "&version=1&cflag=\(type.scene)" qqSchemeURLString += "&callback_type=scheme&generalpastboard=1" qqSchemeURLString += "&callback_name=\(callbackName)" qqSchemeURLString += "&src_type=app&shareType=0&file_type=" if let media = type.info.media { func handleNews(with url: URL, mediaType: String?) { if let thumbnailData = type.info.thumbnail?.monkeyking_compressedImageData { var dic: [String: Any] = ["previewimagedata": thumbnailData] if let oldText = UIPasteboard.general.oldText { dic["pasted_string"] = oldText } let data = NSKeyedArchiver.archivedData(withRootObject: dic) UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData") } qqSchemeURLString += mediaType ?? "news" guard let encodedURLString = url.absoluteString.monkeyking_base64AndURLEncodedString else { completionHandler(.failure(.sdk(.urlEncodeFailed))) return } qqSchemeURLString += "&url=\(encodedURLString)" } switch media { case .url(let url): handleNews(with: url, mediaType: "news") case .image(let image): guard let imageData = image.jpegData(compressionQuality: 0.9) else { completionHandler(.failure(.resource(.invalidImageData))) return } var dic: [String: Any] = ["file_data": imageData] if let thumbnail = type.info.thumbnail, let thumbnailData = thumbnail.jpegData(compressionQuality: 0.9) { dic["previewimagedata"] = thumbnailData } // TODO: handle previewimageUrl string aswell if let oldText = UIPasteboard.general.oldText { dic["pasted_string"] = oldText } let data = NSKeyedArchiver.archivedData(withRootObject: dic) UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData") qqSchemeURLString += "img" case .imageData(let data), .gif(let data): var dic: [String: Any] = ["file_data": data] if let thumbnail = type.info.thumbnail, let thumbnailData = thumbnail.jpegData(compressionQuality: 0.9) { dic["previewimagedata"] = thumbnailData } if let oldText = UIPasteboard.general.oldText { dic["pasted_string"] = oldText } let archivedData = NSKeyedArchiver.archivedData(withRootObject: dic) UIPasteboard.general.setData(archivedData, forPasteboardType: "com.tencent.mqq.api.apiLargeData") qqSchemeURLString += "img" case .audio(let audioURL, _): handleNews(with: audioURL, mediaType: "audio") case .video(let url): handleNews(with: url, mediaType: nil) // No video type, default is news type. case .file(let fileData, _): var dic: [String: Any] = ["file_data": fileData] if let oldText = UIPasteboard.general.oldText { dic["pasted_string"] = oldText } let data = NSKeyedArchiver.archivedData(withRootObject: dic) UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData") qqSchemeURLString += "localFile" if let filename = type.info.description?.monkeyking_urlEncodedString { qqSchemeURLString += "&fileName=\(filename)" } case .miniApp: fatalError("QQ not supports Mini App type") } if let encodedTitle = type.info.title?.monkeyking_base64AndURLEncodedString { qqSchemeURLString += "&title=\(encodedTitle)" } if let encodedDescription = type.info.description?.monkeyking_base64AndURLEncodedString { qqSchemeURLString += "&objectlocation=pasteboard&description=\(encodedDescription)" } qqSchemeURLString += "&sdkv=3.3.9_lite" } else { // Share Text // fix #75 switch type { case .zone: qqSchemeURLString += "qzone&title=" default: qqSchemeURLString += "text&file_data=" } if let encodedDescription = type.info.description?.monkeyking_base64AndURLEncodedString { qqSchemeURLString += "\(encodedDescription)" } } guard let comps = URLComponents(string: qqSchemeURLString), let url = comps.url else { completionHandler(.failure(.sdk(.urlEncodeFailed))) return } lastMessage = message if account.universalLink != nil, var ulComps = URLComponents(string: "https://qm.qq.com/opensdkul/mqqapi/share/to_fri") { ulComps.query = comps.query if let token = qqAppSignToken { ulComps.queryItems?.append(.init(name: "appsign_token", value: token)) } if let txid = qqAppSignTxid { ulComps.queryItems?.append(.init(name: "appsign_txid", value: txid)) } if let ulURL = ulComps.url { shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in if !succeed { fallbackToScheme(url: url, completionHandler: completionHandler) } } } } else { fallbackToScheme(url: url, completionHandler: completionHandler) } case .weibo(let type): guard !shared.canOpenURL(URL(string: "weibosdk://request")!) else { // App Share var messageInfo: [String: Any] = [ "__class": "WBMessageObject", ] let info = type.info if let description = info.description { messageInfo["text"] = description } if let media = info.media { switch media { case .url(let url): if let thumbnailData = info.thumbnail?.monkeyking_compressedImageData { var mediaObject: [String: Any] = [ "__class": "WBWebpageObject", "objectID": "identifier1", ] mediaObject["webpageUrl"] = url.absoluteString mediaObject["title"] = info.title ?? "" mediaObject["thumbnailData"] = thumbnailData messageInfo["mediaObject"] = mediaObject } else { // Deliver text directly. let text = info.description ?? "" messageInfo["text"] = text.isEmpty ? url.absoluteString : text + " " + url.absoluteString } case .image(let image): if let imageData = image.jpegData(compressionQuality: 0.9) { messageInfo["imageObject"] = ["imageData": imageData] } case .imageData(let imageData): messageInfo["imageObject"] = ["imageData": imageData] case .gif: fatalError("Weibo not supports GIF type") case .audio: fatalError("Weibo not supports Audio type") case .video: fatalError("Weibo not supports Video type") case .file: fatalError("Weibo not supports File type") case .miniApp: fatalError("Weibo not supports Mini App type") } } let uuidString = UUID().uuidString let dict: [String: Any] = [ "__class": "WBSendMessageToWeiboRequest", "message": messageInfo, "requestID": uuidString, ] let appData = NSKeyedArchiver.archivedData( withRootObject: [ "appKey": appID, "bundleID": Bundle.main.monkeyking_bundleID ?? "", "universalLink": account.universalLink ?? "" ] ) let messageData: [[String: Any]] = [ ["transferObject": NSKeyedArchiver.archivedData(withRootObject: dict)], ["app": appData], ] UIPasteboard.general.items = messageData guard let url = weiboSchemeLink(uuidString: uuidString) else { completionHandler(.failure(.sdk(.urlEncodeFailed))) return } if account.universalLink != nil, let ulURL = weiboUniversalLink(query: url.query) { shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in if !succeed { fallbackToScheme(url: url, completionHandler: completionHandler) } } } else { fallbackToScheme(url: url, completionHandler: completionHandler) } return } // Weibo Web Share let info = type.info var parameters = [String: Any]() guard let accessToken = type.accessToken else { completionHandler(.failure(.noAccount)) return } parameters["access_token"] = accessToken var status: [String?] = [info.title, info.description] var mediaType = Media.url(NSURL() as URL) if let media = info.media { switch media { case .url(let url): status.append(url.absoluteString) mediaType = Media.url(url) case .image(let image): guard let imageData = image.jpegData(compressionQuality: 0.9) else { completionHandler(.failure(.resource(.invalidImageData))) return } parameters["pic"] = imageData mediaType = Media.image(image) case .imageData(let imageData): parameters["pic"] = imageData mediaType = Media.imageData(imageData) case .gif: fatalError("web Weibo not supports GIF type") case .audio: fatalError("web Weibo not supports Audio type") case .video: fatalError("web Weibo not supports Video type") case .file: fatalError("web Weibo not supports File type") case .miniApp: fatalError("web Weibo not supports Mini App type") } } let statusText = status.compactMap { $0 }.joined(separator: " ") parameters["status"] = statusText switch mediaType { case .url: let urlString = "https://api.weibo.com/2/statuses/share.json" shared.request(urlString, method: .post, parameters: parameters) { responseData, _, error in if error != nil { completionHandler(.failure(.apiRequest(.connectFailed))) } else if let responseData = responseData, (responseData["idstr"] as? String) == nil { completionHandler(.failure(shared.buildError(with: responseData, at: .weibo))) } else { completionHandler(.success(nil)) } } case .image, .imageData: let urlString = "https://api.weibo.com/2/statuses/share.json" shared.upload(urlString, parameters: parameters) { responseData, _, error in if error != nil { completionHandler(.failure(.apiRequest(.connectFailed))) } else if let responseData = responseData, (responseData["idstr"] as? String) == nil { completionHandler(.failure(shared.buildError(with: responseData, at: .weibo))) } else { completionHandler(.success(nil)) } } case .gif: fatalError("web Weibo not supports GIF type") case .audio: fatalError("web Weibo not supports Audio type") case .video: fatalError("web Weibo not supports Video type") case .file: fatalError("web Weibo not supports File type") case .miniApp: fatalError("web Weibo not supports Mini App type") } case .alipay(let type): let dictionary = createAlipayMessageDictionary(withScene: type.scene, info: type.info, appID: appID) guard let data = try? PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: .init()) else { completionHandler(.failure(.sdk(.serializeFailed))) return } UIPasteboard.general.setData(data, forPasteboardType: "com.alipay.openapi.pb.req.\(appID)") var urlComponents = URLComponents(string: "alipayshare://platformapi/shareService") urlComponents?.queryItems = [ URLQueryItem(name: "action", value: "sendReq"), URLQueryItem(name: "shareId", value: appID), ] guard let url = urlComponents?.url else { completionHandler(.failure(.sdk(.urlEncodeFailed))) return } shared.openURL(url) { flag in if flag { return } completionHandler(.failure(.sdk(.invalidURLScheme))) } case .twitter(let type): // MARK: - Twitter Deliver guard let accessToken = type.accessToken, let accessTokenSecret = type.accessTokenSecret else { completionHandler(.failure(.noAccount)) return } let info = type.info var status = [info.title, info.description] var parameters = [String: Any]() var mediaType = Media.url(NSURL() as URL) if let media = info.media { switch media { case .url(let url): status.append(url.absoluteString) mediaType = Media.url(url) case .image(let image): guard let imageData = image.jpegData(compressionQuality: 0.9) else { completionHandler(.failure(.resource(.invalidImageData))) return } parameters["media"] = imageData mediaType = Media.image(image) case .imageData(let imageData): parameters["media"] = imageData mediaType = Media.imageData(imageData) default: fatalError("web Twitter not supports this type") } } switch mediaType { case .url: let statusText = status.compactMap { $0 }.joined(separator: " ") let updateStatusAPI = "https://api.twitter.com/1.1/statuses/update.json" var parameters = ["status": statusText] if let mediaIDs = type.mediaIDs { parameters["media_ids"] = mediaIDs.joined(separator: ",") } if case .twitter(let appID, let appKey, _) = account { let oauthString = Networking.shared.authorizationHeader(for: .post, urlString: updateStatusAPI, appID: appID, appKey: appKey, accessToken: accessToken, accessTokenSecret: accessTokenSecret, parameters: parameters, isMediaUpload: true) let headers = ["Authorization": oauthString] // ref: https://dev.twitter.com/rest/reference/post/statuses/update let urlString = "\(updateStatusAPI)?\(parameters.urlEncodedQueryString(using: .utf8))" shared.request(urlString, method: .post, parameters: nil, headers: headers) { responseData, URLResponse, error in if error != nil { completionHandler(.failure(.apiRequest(.connectFailed))) } else { if let HTTPResponse = URLResponse as? HTTPURLResponse, HTTPResponse.statusCode == 200 { completionHandler(.success(nil)) return } if let responseData = responseData, let _ = responseData["errors"] { completionHandler(.failure(shared.buildError(with: responseData, at: .twitter))) return } completionHandler(.failure(.apiRequest(.unrecognizedError(response: responseData)))) } } } case .image, .imageData: let uploadMediaAPI = "https://upload.twitter.com/1.1/media/upload.json" if case .twitter(let appID, let appKey, _) = account { // ref: https://dev.twitter.com/rest/media/uploading-media#keepinmind let oauthString = Networking.shared.authorizationHeader(for: .post, urlString: uploadMediaAPI, appID: appID, appKey: appKey, accessToken: accessToken, accessTokenSecret: accessTokenSecret, parameters: nil, isMediaUpload: false) let headers = ["Authorization": oauthString] shared.upload(uploadMediaAPI, parameters: parameters, headers: headers) { responseData, URLResponse, error in if let statusCode = (URLResponse as? HTTPURLResponse)?.statusCode, statusCode == 200 { completionHandler(.success(responseData)) return } if error != nil { completionHandler(.failure(.apiRequest(.connectFailed))) } else { completionHandler(.failure(.apiRequest(.unrecognizedError(response: responseData)))) } } } default: fatalError("web Twitter not supports this mediaType") } } } }
mit
e41a4553a116e970cf36200c3f96d5e7
43.995702
254
0.495017
5.607392
false
false
false
false
SwiftFS/Swift-FS-China
Sources/SwiftFSChina/server/TopicServer.swift
1
11157
// // Topic.swift // PerfectChina // // Created by mubin on 2017/7/28. // // import PerfectLib import MySQL import Foundation struct TopicServer { public static func new(title:String,content:String,user_id:Int,user_name:String,category_id:Int)throws -> Int?{ let status = try pool.execute{ try $0.query("insert into topic(title, content, user_id, user_name, category_id, create_time) values(?,?,?,?,?,?)" ,[title,content,user_id,user_name,category_id,Utils.now()]) } return status.affectedRows > 0 ? Int(status.insertedID) : nil } public static func update(topic_id:Int,title:String,content:String,user_id:Int,category_id:Int) throws -> Bool { return try pool.execute{ try $0.query("update topic set title=?, content=?, category_id=?, update_time=? where id=? and user_id=?" ,[title,content,category_id,Utils.now(),topic_id,user_id]) }.affectedRows > 0 } public static func get_my_topic(user_id:Int,id:Int) throws -> [ArticleEntity] { return try pool.execute{ try $0.query("select t.*, u.avatar as avatar, c.name as category_name from topic t " + " left join user u on t.user_id=u.id " + " left join category c on t.category_id=c.id " + " where t.id=? and user_id=?" ,[id,user_id] ) } } public static func delete_topic(user_id:Int,topic_id:Int) throws -> Bool { return try pool.execute{ try $0.query("delete from topic where id=? and user_id=?",[topic_id,user_id]) }.affectedRows > 0 } public static func get_all_of_user(user_id:Int,page_no:Int,page_size:Int) throws -> [ArticleEntity] { var page_no = page_no if page_no < 1 { page_no = 1 } return try pool.execute{ try $0.query("select t.*, u.avatar as avatar, c.name as category_name from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + " where t.user_id=? order by t.id desc limit ?,?" ,[user_id,(page_no - 1) * page_size,page_size] ) } } public static func get_all_hot_of_user(user_id:Int,page_no:Int,page_size:Int) throws -> [ArticleEntity] { var page_no = page_no if page_no < 1 { page_no = 1 } return try pool.execute{ try $0.query("select t.*, u.avatar as avatar, c.name as category_name from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.user_id=? order by t.reply_num desc, like_num desc limit ?,?" ,[user_id,(page_no - 1) * page_size,page_size] ) } } public static func get_total_hot_count_of_user(user_id:Int) throws -> Int { let row:[Count] = try pool.execute{ try $0.query("select count(id) as count from topic where user_id=?",[user_id]) } return row.count > 0 ? row[0].count : 0 } public static func get_total_count() throws -> [Count] { return try pool.execute{ try $0.query("select count(*) from topic") } } public static func get_total_count_of_user(user_id:Int) throws -> Int { let row:[Count] = try pool.execute{ try $0.query("select count(id) as c from topic where user_id=?",[user_id]); } return row.count > 0 ? row[0].count : 0 } public static func get(id:Int) throws -> [ArticleEntity]{ return try pool.execute{ // ("update topic set view_num=view_num+1 where id=?", {tonumber(id)}) try $0.query("select t.*, u.avatar as avatar, c.name as category_name from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.id=?",[id]) } } public static func get_all(topic_type:String,category:String,page_no:Int,page_size:Int) -> [ArticleEntity]?{ var page_no = page_no let page_size = page_size let category = category.int! if page_no < 1 { page_no = 1 } var row:[ArticleEntity]? do{ if category != 0 { if topic_type == "default" { row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.category_id=? " + "order by t.id desc limit ?,? ", [category,(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "recent-reply"{ row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.category_id=? " + "order by t.last_reply_time desc limit ?,?", [category,(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "good"{ row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.is_good=1 and t.category_id=? " + "order by t.id desc limit ?,?", [category,(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "noreply" { row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.reply_num=0 and t.category_id=? " + "order by t.id desc limit ?,?", [category,(page_no - 1)*page_size,page_size] ) }) } }else{ if topic_type == "default" { row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "order by t.id desc limit ?,?", [(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "recent-reply" { row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "order by t.last_reply_time desc limit ?,?", [(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "good" { row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.is_good=1 " + "order by t.id desc limit ?,? ", [(page_no - 1)*page_size,page_size] ) }) }else if topic_type == "noreply"{ row = try pool.execute({ conn in try conn.query("select t.*, c.name as category_name, u.avatar as avatar from topic t " + "left join user u on t.user_id=u.id " + "left join category c on t.category_id=c.id " + "where t.reply_num=0 " + "order by t.id desc limit ?,?", [(page_no - 1)*page_size,page_size] ) }) } } }catch{ Log.error(message: "\(error)") return nil } return row } public static func get_total_count(topic_type:String?,category:String?) throws -> Int { let categoryNum = category?.int do{ let row:[Count] = try pool.execute{ if let type = topic_type{ switch type { case "recent-reply": return try $0.query("select count(id) as c from topic" + (categoryNum != 0 ? "where category_id=?" : ""),[category]) case "good": return try $0.query("select count(id) as c from topic where is_good=1" + (categoryNum != 0 ? "and category_id=?" : ""),[category]) case "noreply": return try $0.query("select count(id) as c from topic where reply_num=0" + (categoryNum != 0 ? "and category_id=?" : ""),[category]) default: return try $0.query("select count(id) as c from topic" + (categoryNum != 0 ? "where category_id=?" : ""),[category]) } } else{ return try $0.query("select count(id) as c from topic" + (categoryNum != 0 ? "where category_id=?" : ""),[category]) } } return row[0].count }catch{ return 0 } } public static func reset_last_reply(topic_id:Int,user_id:Int,user_name:String,last_reply_time:Date) throws{ _ = try pool.execute{ try $0.query("update topic set last_reply_id=?, last_reply_name=?, last_reply_time=? where id=?", [user_id,user_name,last_reply_time,topic_id]) } } }
mit
48730f5a35bfc501c00b98665885be38
43.27381
156
0.46007
4.064481
false
false
false
false
ryuichis/swift-ast
Tests/ParserTests/Expression/Binary/ParserTernaryConditionalOperatorExpressionTests.swift
2
5252
/* Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import AST class ParserTernaryConditionalOperatorExpressionTests: XCTestCase { func testConditional() { parseExpressionAndTest("condition ? true : false", "condition ? true : false", testClosure: { expr in guard let condExpr = expr as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a conditional operator expression") return } XCTAssertTrue(condExpr.conditionExpression is IdentifierExpression) XCTAssertTrue(condExpr.trueExpression is LiteralExpression) XCTAssertTrue(condExpr.falseExpression is LiteralExpression) }) } func testFunctions() { parseExpressionAndTest("c() ? t() : f()", "c() ? t() : f()", testClosure: { expr in guard let condExpr = expr as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a conditional operator expression") return } XCTAssertTrue(condExpr.conditionExpression is FunctionCallExpression) XCTAssertTrue(condExpr.trueExpression is FunctionCallExpression) XCTAssertTrue(condExpr.falseExpression is FunctionCallExpression) }) } func testTryOperators() { parseExpressionAndTest("try? c() ? try t() : try! f()", "try? c() ? try t() : try! f()", testClosure: { expr in guard let tryOpExpr = expr as? TryOperatorExpression else { XCTFail("Failed in getting a try operator expression") return } guard case .optional(let tryExpr) = tryOpExpr.kind, let condExpr = tryExpr as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a conditional operator expression") return } XCTAssertTrue(condExpr.conditionExpression is FunctionCallExpression) XCTAssertTrue(condExpr.trueExpression is TryOperatorExpression) XCTAssertTrue(condExpr.falseExpression is TryOperatorExpression) }) } func testNested() { // a ? (b ? (c ? d : e) : f) : g parseExpressionAndTest( "a ? b ? c ? d : e : f : g", "a ? b ? c ? d : e : f : g", testClosure: { expr in guard let ternaryOpExpr = expr as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a ternary cond op expr for code `a ? b ? c ? d : e : f : g`.") return } XCTAssertTrue(ternaryOpExpr.conditionExpression is IdentifierExpression) XCTAssertEqual(ternaryOpExpr.conditionExpression.textDescription, "a") XCTAssertTrue(ternaryOpExpr.falseExpression is IdentifierExpression) XCTAssertEqual(ternaryOpExpr.falseExpression.textDescription, "g") guard let trueTernaryOpExpr = ternaryOpExpr.trueExpression as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a ternary conditional operator expression for code `f ? g : h`.") return } XCTAssertEqual(trueTernaryOpExpr.textDescription, "b ? c ? d : e : f") XCTAssertTrue(trueTernaryOpExpr.conditionExpression is IdentifierExpression) XCTAssertEqual(trueTernaryOpExpr.conditionExpression.textDescription, "b") XCTAssertTrue(trueTernaryOpExpr.falseExpression is IdentifierExpression) XCTAssertEqual(trueTernaryOpExpr.falseExpression.textDescription, "f") guard let trueTrueTernaryOpExpr = trueTernaryOpExpr.trueExpression as? TernaryConditionalOperatorExpression else { XCTFail("Failed in getting a ternary conditional operator expression for code `c ? d : e`.") return } XCTAssertEqual(trueTrueTernaryOpExpr.textDescription, "c ? d : e") XCTAssertTrue(trueTrueTernaryOpExpr.conditionExpression is IdentifierExpression) XCTAssertEqual(trueTrueTernaryOpExpr.conditionExpression.textDescription, "c") XCTAssertTrue(trueTrueTernaryOpExpr.trueExpression is IdentifierExpression) XCTAssertEqual(trueTrueTernaryOpExpr.trueExpression.textDescription, "d") XCTAssertTrue(trueTrueTernaryOpExpr.falseExpression is IdentifierExpression) XCTAssertEqual(trueTrueTernaryOpExpr.falseExpression.textDescription, "e") } ) } func testSourceRange() { parseExpressionAndTest("condition ? true : false", "condition ? true : false", testClosure: { expr in XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, 25)) }) } static var allTests = [ ("testConditional", testConditional), ("testFunctions", testFunctions), ("testTryOperators", testTryOperators), ("testNested", testNested), ("testSourceRange", testSourceRange), ] }
apache-2.0
2f1b7eb930fbf754d0f0e4da9ca01750
41.016
115
0.709254
4.96878
false
true
false
false
buttacciot/Hiragana
Pods/ScrollableGraphView/Classes/ScrollableGraphView.swift
1
73458
import UIKit // MARK: - ScrollableGraphView @objc public class ScrollableGraphView: UIScrollView, UIScrollViewDelegate, ScrollableGraphViewDrawingDelegate { // MARK: - Public Properties // Use these to customise the graph. // ################################# // Line Styles // ########### /// Specifies how thick the graph of the line is. In points. public var lineWidth: CGFloat = 2 /// The color of the graph line. UIColor. public var lineColor = UIColor.blackColor() /// Whether or not the line should be rendered using bezier curves are straight lines. public var lineStyle = ScrollableGraphViewLineStyle.Straight /// How each segment in the line should connect. Takes any of the Core Animation LineJoin values. public var lineJoin = kCALineJoinRound /// The line caps. Takes any of the Core Animation LineCap values. public var lineCap = kCALineCapRound public var lineCurviness: CGFloat = 0.5 // Bar styles // ########## /// Whether bars should be drawn or not. If you want a bar graph, this should be set to true. public var shouldDrawBarLayer = false /// The width of an individual bar on the graph. public var barWidth: CGFloat = 25; /// The actual colour of the bar. public var barColor = UIColor.grayColor() /// The width of the outline of the bar public var barLineWidth: CGFloat = 1 /// The colour of the bar outline public var barLineColor = UIColor.darkGrayColor() // Fill Styles // ########### /// The background colour for the entire graph view, not just the plotted graph. public var backgroundFillColor = UIColor.whiteColor() /// Specifies whether or not the plotted graph should be filled with a colour or gradient. public var shouldFill = false /// Specifies whether to fill the graph with a solid colour or gradient. public var fillType = ScrollableGraphViewFillType.Solid /// If fillType is set to .Solid then this colour will be used to fill the graph. public var fillColor = UIColor.blackColor() /// If fillType is set to .Gradient then this will be the starting colour for the gradient. public var fillGradientStartColor = UIColor.whiteColor() /// If fillType is set to .Gradient, then this will be the ending colour for the gradient. public var fillGradientEndColor = UIColor.blackColor() /// If fillType is set to .Gradient, then this defines whether the gradient is rendered as a linear gradient or radial gradient. public var fillGradientType = ScrollableGraphViewGradientType.Linear // Spacing // ####### /// How far the "maximum" reference line is from the top of the view's frame. In points. public var topMargin: CGFloat = 10 /// How far the "minimum" reference line is from the bottom of the view's frame. In points. public var bottomMargin: CGFloat = 10 /// How far the first point on the graph should be placed from the left hand side of the view. public var leftmostPointPadding: CGFloat = 50 /// How far the final point on the graph should be placed from the right hand side of the view. public var rightmostPointPadding: CGFloat = 50 /// How much space should be between each data point. public var dataPointSpacing: CGFloat = 40 /// Which side of the graph the user is expected to scroll from. public var direction = ScrollableGraphViewDirection.LeftToRight // Graph Range // ########### /// If this is set to true, then the range will automatically be detected from the data the graph is given. public var shouldAutomaticallyDetectRange = false /// Forces the graph's minimum to always be zero. Used in conjunction with shouldAutomaticallyDetectRange or shouldAdaptRange, if you want to force the minimum to stay at 0 rather than the detected minimum. public var shouldRangeAlwaysStartAtZero = false // Used in conjunction with shouldAutomaticallyDetectRange, if you want to force the min to stay at 0. /// The minimum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true public var rangeMin: Double = 0 /// The maximum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true public var rangeMax: Double = 100 // Data Point Drawing // ################## /// Whether or not to draw a symbol for each data point. public var shouldDrawDataPoint = true /// The shape to draw for each data point. public var dataPointType = ScrollableGraphViewDataPointType.Circle /// The size of the shape to draw for each data point. public var dataPointSize: CGFloat = 5 /// The colour with which to fill the shape. public var dataPointFillColor: UIColor = UIColor.blackColor() /// If dataPointType is set to .Custom then you,can provide a closure to create any kind of shape you would like to be displayed instead of just a circle or square. The closure takes a CGPoint which is the centre of the shape and it should return a complete UIBezierPath. public var customDataPointPath: ((centre: CGPoint) -> UIBezierPath)? // Adapting & Animations // ##################### /// Whether or not the y-axis' range should adapt to the points that are visible on screen. This means if there are only 5 points visible on screen at any given time, the maximum on the y-axis will be the maximum of those 5 points. This is updated automatically as the user scrolls along the graph. public var shouldAdaptRange = false /// If shouldAdaptRange is set to true then this specifies whether or not the points on the graph should animate to their new positions. Default is set to true. public var shouldAnimateOnAdapt = true /// How long the animation should take. Affects both the startup animation and the animation when the range of the y-axis adapts to onscreen points. public var animationDuration: Double = 1 /// The animation style. public var adaptAnimationType = ScrollableGraphViewAnimationType.EaseOut /// If adaptAnimationType is set to .Custom, then this is the easing function you would like applied for the animation. public var customAnimationEasingFunction: ((t: Double) -> Double)? /// Whether or not the graph should animate to their positions when the graph is first displayed. public var shouldAnimateOnStartup = true // Reference Lines // ############### /// Whether or not to show the y-axis reference lines and labels. public var shouldShowReferenceLines = true /// The colour for the reference lines. public var referenceLineColor = UIColor.blackColor() /// The thickness of the reference lines. public var referenceLineThickness: CGFloat = 0.5 /// Where the labels should be displayed on the reference lines. public var referenceLinePosition = ScrollableGraphViewReferenceLinePosition.Left /// The type of reference lines. Currently only .Cover is available. public var referenceLineType = ScrollableGraphViewReferenceLineType.Cover /// How many reference lines should be between the minimum and maximum reference lines. If you want a total of 4 reference lines, you would set this to 2. This can be set to 0 for no intermediate reference lines.This can be used to create reference lines at specific intervals. If the desired result is to have a reference line at every 10 units on the y-axis, you could, for example, set rangeMax to 100, rangeMin to 0 and numberOfIntermediateReferenceLines to 9. public var numberOfIntermediateReferenceLines: Int = 3 /// Whether or not to add labels to the intermediate reference lines. public var shouldAddLabelsToIntermediateReferenceLines = true /// Whether or not to add units specified by the referenceLineUnits variable to the labels on the intermediate reference lines. public var shouldAddUnitsToIntermediateReferenceLineLabels = false // Reference Line Labels // ##################### /// The font to be used for the reference line labels. public var referenceLineLabelFont = UIFont.systemFontOfSize(8) /// The colour of the reference line labels. public var referenceLineLabelColor = UIColor.blackColor() /// Whether or not to show the units on the reference lines. public var shouldShowReferenceLineUnits = true /// The units that the y-axis is in. This string is used for labels on the reference lines. public var referenceLineUnits: String? /// The number of decimal places that should be shown on the reference line labels. public var referenceLineNumberOfDecimalPlaces: Int = 0 // Data Point Labels // ################# /// Whether or not to show the labels on the x-axis for each point. public var shouldShowLabels = true /// How far from the "minimum" reference line the data point labels should be rendered. public var dataPointLabelTopMargin: CGFloat = 10 /// How far from the bottom of the view the data point labels should be rendered. public var dataPointLabelBottomMargin: CGFloat = 0 /// The font for the data point labels. public var dataPointLabelColor = UIColor.blackColor() /// The colour for the data point labels. public var dataPointLabelFont: UIFont? = UIFont.systemFontOfSize(10) /// Used to force the graph to show every n-th dataPoint label public var dataPointLabelsSparsity: Int = 1 // MARK: - Private State // ##################### // Graph Data for Display private var data = [Double]() private var labels = [String]() private var isInitialSetup = true private var dataNeedsReloading = true private var isCurrentlySettingUp = false private var viewportWidth: CGFloat = 0 { didSet { if(oldValue != viewportWidth) { viewportDidChange() }} } private var viewportHeight: CGFloat = 0 { didSet { if(oldValue != viewportHeight) { viewportDidChange() }} } private var totalGraphWidth: CGFloat = 0 private var offsetWidth: CGFloat = 0 // Graph Line private var currentLinePath = UIBezierPath() private var zeroYPosition: CGFloat = 0 // Labels private var labelsView = UIView() private var labelPool = LabelPool() // Graph Drawing private var graphPoints = [GraphPoint]() private var drawingView = UIView() private var barLayer: BarDrawingLayer? private var lineLayer: LineDrawingLayer? private var dataPointLayer: DataPointDrawingLayer? private var fillLayer: FillDrawingLayer? private var gradientLayer: GradientDrawingLayer? // Reference Lines private var referenceLineView: ReferenceLineDrawingView? // Animation private var displayLink: CADisplayLink! private var previousTimestamp: CFTimeInterval = 0 private var currentTimestamp: CFTimeInterval = 0 private var currentAnimations = [GraphPointAnimation]() // Active Points & Range Calculation private var previousActivePointsInterval: Range<Int> = -1 ..< -1 private var activePointsInterval: Range<Int> = -1 ..< -1 { didSet { if(oldValue.startIndex != activePointsInterval.startIndex || oldValue.endIndex != activePointsInterval.endIndex) { if !isCurrentlySettingUp { activePointsDidChange() } } } } private var range: (min: Double, max: Double) = (0, 100) { didSet { if(oldValue.min != range.min || oldValue.max != range.max) { if !isCurrentlySettingUp { rangeDidChange() } } } } // MARK: - INIT, SETUP & VIEWPORT RESIZING // ####################################### override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { displayLink?.invalidate() } private func setup() { isCurrentlySettingUp = true // Make sure everything is in a clean state. reset() self.delegate = self // Calculate the viewport and drawing frames. self.viewportWidth = self.frame.width self.viewportHeight = self.frame.height totalGraphWidth = graphWidthForNumberOfDataPoints(data.count) self.contentSize = CGSize(width: totalGraphWidth, height: viewportHeight) // Scrolling direction. if (direction == .RightToLeft) { self.offsetWidth = self.contentSize.width - viewportWidth } // Otherwise start of all the way to the left. else { self.offsetWidth = 0 } // Set the scrollview offset. self.contentOffset.x = self.offsetWidth // Calculate the initial range depending on settings. let initialActivePointsInterval = calculateActivePointsInterval() let detectedRange = calculateRangeForEntireDataset(self.data) if(shouldAutomaticallyDetectRange) { self.range = detectedRange } else { self.range = (min: rangeMin, max: rangeMax) } if (shouldAdaptRange) { // This supercedes the shouldAutomaticallyDetectRange option let range = calculateRangeForActivePointsInterval(initialActivePointsInterval) self.range = range } // If the graph was given all 0s as data, we can't use a range of 0->0, so make sure we have a sensible range at all times. if (self.range.min == 0 && self.range.max == 0) { self.range = (min: 0, max: rangeMax) } // DRAWING let viewport = CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight) // Create all the GraphPoints which which are used for drawing. for i in 0 ..< data.count { let value = (shouldAnimateOnStartup) ? self.range.min : data[i] let position = calculatePosition(i, value: value) let point = GraphPoint(position: position) graphPoints.append(point) } // Drawing Layers drawingView = UIView(frame: viewport) drawingView.backgroundColor = backgroundFillColor self.addSubview(drawingView) addDrawingLayers(inViewport: viewport) // References Lines if(shouldShowReferenceLines) { addReferenceLines(inViewport: viewport) } // X-Axis Labels self.insertSubview(labelsView, aboveSubview: drawingView) updateOffsetWidths() // Animation loop for when the range adapts displayLink = CADisplayLink(target: self, selector: #selector(animationUpdate)) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true isCurrentlySettingUp = false // Set the first active points interval. These are the points that are visible when the view loads. self.activePointsInterval = initialActivePointsInterval } // Makes sure everything is in a clean state for when we want to reset the data for a graph. private func reset() { drawingView.removeFromSuperview() referenceLineView?.removeFromSuperview() labelPool = LabelPool() for labelView in labelsView.subviews { labelView.removeFromSuperview() } graphPoints.removeAll() currentAnimations.removeAll() displayLink?.invalidate() previousTimestamp = 0 currentTimestamp = 0 previousActivePointsInterval = -1 ..< -1 activePointsInterval = -1 ..< -1 range = (0, 100) } private func addDrawingLayers(inViewport viewport: CGRect) { // Line Layer lineLayer = LineDrawingLayer(frame: viewport, lineWidth: lineWidth, lineColor: lineColor, lineStyle: lineStyle, lineJoin: lineJoin, lineCap: lineCap) lineLayer?.graphViewDrawingDelegate = self drawingView.layer.addSublayer(lineLayer!) // Data Point layer if(shouldDrawDataPoint) { dataPointLayer = DataPointDrawingLayer(frame: viewport, fillColor: dataPointFillColor, dataPointType: dataPointType, dataPointSize: dataPointSize, customDataPointPath: customDataPointPath) dataPointLayer?.graphViewDrawingDelegate = self drawingView.layer.insertSublayer(dataPointLayer!, above: lineLayer) } // Gradient and Fills switch (self.fillType) { case .Solid: if(shouldFill) { // Setup fill fillLayer = FillDrawingLayer(frame: viewport, fillColor: fillColor) fillLayer?.graphViewDrawingDelegate = self drawingView.layer.insertSublayer(fillLayer!, below: lineLayer) } case .Gradient: if(shouldFill) { gradientLayer = GradientDrawingLayer(frame: viewport, startColor: fillGradientStartColor, endColor: fillGradientEndColor, gradientType: fillGradientType) gradientLayer!.graphViewDrawingDelegate = self drawingView.layer.insertSublayer(gradientLayer!, below: lineLayer) } } // The bar layer if (shouldDrawBarLayer) { // Bar Layer barLayer = BarDrawingLayer(frame: viewport, barWidth: barWidth, barColor: barColor, barLineWidth: barLineWidth, barLineColor: barLineColor) barLayer?.graphViewDrawingDelegate = self drawingView.layer.insertSublayer (barLayer!, below: lineLayer) } } private func addReferenceLines(inViewport viewport: CGRect) { var referenceLineBottomMargin = bottomMargin if(shouldShowLabels && dataPointLabelFont != nil) { referenceLineBottomMargin += (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) } referenceLineView = ReferenceLineDrawingView( frame: viewport, topMargin: topMargin, bottomMargin: referenceLineBottomMargin, referenceLineColor: self.referenceLineColor, referenceLineThickness: self.referenceLineThickness) // Reference line settings. referenceLineView?.referenceLinePosition = self.referenceLinePosition referenceLineView?.referenceLineType = self.referenceLineType referenceLineView?.numberOfIntermediateReferenceLines = self.numberOfIntermediateReferenceLines // Reference line label settings. referenceLineView?.shouldAddLabelsToIntermediateReferenceLines = self.shouldAddLabelsToIntermediateReferenceLines referenceLineView?.shouldAddUnitsToIntermediateReferenceLineLabels = self.shouldAddUnitsToIntermediateReferenceLineLabels referenceLineView?.labelUnits = referenceLineUnits referenceLineView?.labelFont = self.referenceLineLabelFont referenceLineView?.labelColor = self.referenceLineLabelColor referenceLineView?.labelDecimalPlaces = self.referenceLineNumberOfDecimalPlaces referenceLineView?.setRange(self.range) self.addSubview(referenceLineView!) } // If the view has changed we have to make sure we're still displaying the right data. override public func layoutSubviews() { super.layoutSubviews() updateUI() } private func updateUI() { // Make sure we have data, if don't, just get out. We can't do anything without any data. guard data.count > 0 else { return } // If the data has been updated, we need to re-init everything if (dataNeedsReloading) { setup() if(shouldAnimateOnStartup) { startAnimations(withStaggerValue: 0.15) } // We're done setting up. dataNeedsReloading = false isInitialSetup = false } // Otherwise, the user is just scrolling and we just need to update everything. else { // Needs to update the viewportWidth and viewportHeight which is used to calculate which // points we can actually see. viewportWidth = self.frame.width viewportHeight = self.frame.height // If the scrollview has scrolled anywhere, we need to update the offset // and move around our drawing views. offsetWidth = self.contentOffset.x updateOffsetWidths() // Recalculate active points for this size. // Recalculate range for active points. let newActivePointsInterval = calculateActivePointsInterval() self.previousActivePointsInterval = self.activePointsInterval self.activePointsInterval = newActivePointsInterval // If adaption is enabled we want to if(shouldAdaptRange) { let newRange = calculateRangeForActivePointsInterval(newActivePointsInterval) self.range = newRange } } } private func updateOffsetWidths() { drawingView.frame.origin.x = offsetWidth drawingView.bounds.origin.x = offsetWidth gradientLayer?.offset = offsetWidth referenceLineView?.frame.origin.x = offsetWidth } private func updateFrames() { // Drawing view needs to always be the same size as the scrollview. drawingView.frame.size.width = viewportWidth drawingView.frame.size.height = viewportHeight // Gradient should extend over the entire viewport gradientLayer?.frame.size.width = viewportWidth gradientLayer?.frame.size.height = viewportHeight // Reference lines should extend over the entire viewport referenceLineView?.setViewport(viewportWidth, viewportHeight: viewportHeight) self.contentSize.height = viewportHeight } // MARK: - Public Methods // ###################### public func setData(data: [Double], withLabels labels: [String]) { // If we are setting exactly the same data and labels, there's no need to re-init everything. if(self.data == data && self.labels == labels) { return } self.dataNeedsReloading = true self.data = data self.labels = labels if(!isInitialSetup) { updateUI() } } // MARK: - Private Methods // ####################### // MARK: Animation // Animation update loop for co-domain changes. @objc private func animationUpdate() { let dt = timeSinceLastFrame() for animation in currentAnimations { animation.update(dt) if animation.finished { dequeueAnimation(animation) } } updatePaths() } private func animatePoint(point: GraphPoint, toPosition position: CGPoint, withDelay delay: Double = 0) { let currentPoint = CGPoint(x: point.x, y: point.y) let animation = GraphPointAnimation(fromPoint: currentPoint, toPoint: position, forGraphPoint: point) animation.animationEasing = getAnimationEasing() animation.duration = animationDuration animation.delay = delay enqueueAnimation(animation) } private func getAnimationEasing() -> (Double) -> Double { switch(self.adaptAnimationType) { case .Elastic: return Easings.EaseOutElastic case .EaseOut: return Easings.EaseOutQuad case .Custom: if let customEasing = customAnimationEasingFunction { return customEasing } else { fallthrough } default: return Easings.EaseOutQuad } } private func enqueueAnimation(animation: GraphPointAnimation) { if (currentAnimations.count == 0) { // Need to kick off the loop. displayLink.paused = false } currentAnimations.append(animation) } private func dequeueAnimation(animation: GraphPointAnimation) { if let index = currentAnimations.indexOf(animation) { currentAnimations.removeAtIndex(index) } if(currentAnimations.count == 0) { // Stop animation loop. displayLink.paused = true } } private func dequeueAllAnimations() { for animation in currentAnimations { animation.animationDidFinish() } currentAnimations.removeAll() displayLink.paused = true } private func timeSinceLastFrame() -> Double { if previousTimestamp == 0 { previousTimestamp = displayLink.timestamp } else { previousTimestamp = currentTimestamp } currentTimestamp = displayLink.timestamp var dt = currentTimestamp - previousTimestamp if dt > 0.032 { dt = 0.032 } return dt } // MARK: Layout Calculations private func calculateActivePointsInterval() -> Range<Int> { // Calculate the "active points" let min = Int((offsetWidth) / dataPointSpacing) let max = Int(((offsetWidth + viewportWidth)) / dataPointSpacing) // Add and minus two so the path goes "off the screen" so we can't see where it ends. let minPossible = 0 let maxPossible = data.count - 1 let numberOfPointsOffscreen = 2 let actualMin = clamp(min - numberOfPointsOffscreen, min: minPossible, max: maxPossible) let actualMax = clamp(max + numberOfPointsOffscreen, min: minPossible, max: maxPossible) return actualMin ..< actualMax } private func calculateRangeForActivePointsInterval(interval: Range<Int>) -> (min: Double, max: Double) { let dataForActivePoints = data[interval.startIndex...interval.endIndex] // We don't have any active points, return defaults. if(dataForActivePoints.count == 0) { return (min: self.rangeMin, max: self.rangeMax) } else { let range = calculateRange(dataForActivePoints) return cleanRange(range) } } private func calculateRangeForEntireDataset(data: [Double]) -> (min: Double, max: Double) { let range = calculateRange(self.data) return cleanRange(range) } private func calculateRange<T: CollectionType where T.Generator.Element == Double>(data: T) -> (min: Double, max: Double) { var rangeMin: Double = Double(Int.max) var rangeMax: Double = Double(Int.min) for dataPoint in data { if (dataPoint > rangeMax) { rangeMax = dataPoint } if (dataPoint < rangeMin) { rangeMin = dataPoint } } return (min: rangeMin, max: rangeMax) } private func cleanRange(range: (min: Double, max: Double)) -> (min: Double, max: Double){ if(range.min == range.max) { let min = shouldRangeAlwaysStartAtZero ? 0 : range.min let max = range.max + 1 return (min: min, max: max) } else if (shouldRangeAlwaysStartAtZero) { let min: Double = 0 var max: Double = range.max // If we have all negative numbers and the max happens to be 0, there will cause a division by 0. Return the default height. if(range.max == 0) { max = rangeMax } return (min: min, max: max) } else { return range } } private func graphWidthForNumberOfDataPoints(numberOfPoints: Int) -> CGFloat { let width: CGFloat = (CGFloat(numberOfPoints - 1) * dataPointSpacing) + (leftmostPointPadding + rightmostPointPadding) return width } private func calculatePosition(index: Int, value: Double) -> CGPoint { // Set range defaults based on settings: // self.range.min/max is the current ranges min/max that has been detected // self.rangeMin/Max is the min/max that should be used as specified by the user let rangeMax = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.max : self.rangeMax let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin // y = the y co-ordinate in the view for the value in the graph // ( ( value - max ) ) value = the value on the graph for which we want to know its corresponding location on the y axis in the view // y = ( ( ----------- ) * graphHeight ) + topMargin t = the top margin // ( ( min - max ) ) h = the height of the graph space without margins // min = the range's current mininum // max = the range's current maximum // Calculate the position on in the view for the value specified. var graphHeight = viewportHeight - topMargin - bottomMargin if(shouldShowLabels && dataPointLabelFont != nil) { graphHeight -= (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) } let x = (CGFloat(index) * dataPointSpacing) + leftmostPointPadding let y = (CGFloat((value - rangeMax) / (rangeMin - rangeMax)) * graphHeight) + topMargin return CGPoint(x: x, y: y) } private func clamp<T: Comparable>(value:T, min:T, max:T) -> T { if (value < min) { return min } else if (value > max) { return max } else { return value } } // MARK: Line Path Creation private func createLinePath() -> UIBezierPath { currentLinePath.removeAllPoints() let numberOfPoints = min(data.count, activePointsInterval.endIndex) let pathSegmentAdder = lineStyle == .Straight ? addStraightLineSegment : addCurvedLineSegment zeroYPosition = calculatePosition(0, value: self.range.min).y // Connect the line to the starting edge if we are filling it. if(shouldFill) { // Add a line from the base of the graph to the first data point. let firstDataPoint = graphPoints[activePointsInterval.startIndex] let viewportLeftZero = CGPoint(x: firstDataPoint.x - (leftmostPointPadding), y: zeroYPosition) let leftFarEdgeTop = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: zeroYPosition) let leftFarEdgeBottom = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: viewportHeight) currentLinePath.moveToPoint(leftFarEdgeBottom) pathSegmentAdder(startPoint: leftFarEdgeBottom, endPoint: leftFarEdgeTop, inPath: currentLinePath) pathSegmentAdder(startPoint: leftFarEdgeTop, endPoint: viewportLeftZero, inPath: currentLinePath) pathSegmentAdder(startPoint: viewportLeftZero, endPoint: CGPoint(x: firstDataPoint.x, y: firstDataPoint.y), inPath: currentLinePath) } else { let firstDataPoint = graphPoints[activePointsInterval.startIndex] currentLinePath.moveToPoint(firstDataPoint.location) } // Connect each point on the graph with a segment. for i in activePointsInterval.startIndex ..< numberOfPoints { let startPoint = graphPoints[i].location let endPoint = graphPoints[i+1].location pathSegmentAdder(startPoint: startPoint, endPoint: endPoint, inPath: currentLinePath) } // Connect the line to the ending edge if we are filling it. if(shouldFill) { // Add a line from the last data point to the base of the graph. let lastDataPoint = graphPoints[activePointsInterval.endIndex] let viewportRightZero = CGPoint(x: lastDataPoint.x + (rightmostPointPadding), y: zeroYPosition) let rightFarEdgeTop = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: zeroYPosition) let rightFarEdgeBottom = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: viewportHeight) pathSegmentAdder(startPoint: lastDataPoint.location, endPoint: viewportRightZero, inPath: currentLinePath) pathSegmentAdder(startPoint: viewportRightZero, endPoint: rightFarEdgeTop, inPath: currentLinePath) pathSegmentAdder(startPoint: rightFarEdgeTop, endPoint: rightFarEdgeBottom, inPath: currentLinePath) } return currentLinePath } private func addStraightLineSegment(startPoint startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) { path.addLineToPoint(endPoint) } private func addCurvedLineSegment(startPoint startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) { // calculate control points let difference = endPoint.x - startPoint.x var x = startPoint.x + (difference * lineCurviness) var y = startPoint.y let controlPointOne = CGPoint(x: x, y: y) x = endPoint.x - (difference * lineCurviness) y = endPoint.y let controlPointTwo = CGPoint(x: x, y: y) // add curve from start to end currentLinePath.addCurveToPoint(endPoint, controlPoint1: controlPointOne, controlPoint2: controlPointTwo) } // MARK: Events // If the active points (the points we can actually see) change, then we need to update the path. private func activePointsDidChange() { let deactivatedPoints = determineDeactivatedPoints() let activatedPoints = determineActivatedPoints() updatePaths() if(shouldShowLabels) { let deactivatedLabelPoints = filterPointsForLabels(fromPoints: deactivatedPoints) let activatedLabelPoints = filterPointsForLabels(fromPoints: activatedPoints) updateLabels(deactivatedLabelPoints, activatedLabelPoints) } } private func rangeDidChange() { // If shouldAnimateOnAdapt is enabled it will kickoff any animations that need to occur. startAnimations() referenceLineView?.setRange(range) } private func viewportDidChange() { // We need to make sure all the drawing views are the same size as the viewport. updateFrames() // Basically this recreates the paths with the new viewport size so things are in sync, but only // if the viewport has changed after the initial setup. Because the initial setup will use the latest // viewport anyway. if(!isInitialSetup) { updatePaths() // Need to update the graph points so they are in their right positions for the new viewport. // Animate them into position if animation is enabled, but make sure to stop any current animations first. dequeueAllAnimations() startAnimations() // The labels will also need to be repositioned if the viewport has changed. repositionActiveLabels() } } // Update any paths with the new path based on visible data points. private func updatePaths() { createLinePath() if let drawingLayers = drawingView.layer.sublayers { for layer in drawingLayers { if let layer = layer as? ScrollableGraphViewDrawingLayer { // The bar layer needs the zero Y position to set the bottom of the bar layer.zeroYPosition = zeroYPosition // Need to make sure this is set in createLinePath assert (layer.zeroYPosition > 0); layer.updatePath() } } } } // Update any labels for any new points that have been activated and deactivated. private func updateLabels(deactivatedPoints: [Int], _ activatedPoints: [Int]) { // Disable any labels for the deactivated points. for point in deactivatedPoints { labelPool.deactivateLabelForPointIndex(point) } // Grab an unused label and update it to the right position for the newly activated poitns for point in activatedPoints { let label = labelPool.activateLabelForPointIndex(point) label.text = (point < labels.count) ? labels[point] : "" label.textColor = dataPointLabelColor label.font = dataPointLabelFont label.sizeToFit() // self.range.min is the current ranges minimum that has been detected // self.rangeMin is the minimum that should be used as specified by the user let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin let position = calculatePosition(point, value: rangeMin) label.frame = CGRect(origin: CGPoint(x: position.x - label.frame.width / 2, y: position.y + dataPointLabelTopMargin), size: label.frame.size) labelsView.addSubview(label) } } private func repositionActiveLabels() { for label in labelPool.activeLabels { let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin let position = calculatePosition(0, value: rangeMin) label.frame.origin.y = position.y + dataPointLabelTopMargin } } // Returns the indices of any points that became inactive (that is, "off screen"). (No order) private func determineDeactivatedPoints() -> [Int] { let prevSet = setFromClosedRange(previousActivePointsInterval) let currSet = setFromClosedRange(activePointsInterval) let deactivatedPoints = prevSet.subtract(currSet) return Array(deactivatedPoints) } // Returns the indices of any points that became active (on screen). (No order) private func determineActivatedPoints() -> [Int] { let prevSet = setFromClosedRange(previousActivePointsInterval) let currSet = setFromClosedRange(activePointsInterval) let activatedPoints = currSet.subtract(prevSet) return Array(activatedPoints) } private func setFromClosedRange(range: Range<Int>) -> Set<Int> { var set = Set<Int>() for index in range.startIndex...range.endIndex { set.insert(index) } return set } private func filterPointsForLabels(fromPoints points:[Int]) -> [Int] { if(self.dataPointLabelsSparsity == 1) { return points } return points.filter({ $0 % self.dataPointLabelsSparsity == 0 }) } private func startAnimations(withStaggerValue stagger: Double = 0) { var pointsToAnimate = 0 ..< 0 if (shouldAnimateOnAdapt || (dataNeedsReloading && shouldAnimateOnStartup)) { pointsToAnimate = activePointsInterval } // For any visible points, kickoff the animation to their new position after the axis' min/max has changed. //let numberOfPointsToAnimate = pointsToAnimate.endIndex - pointsToAnimate.startIndex var index = 0 for i in pointsToAnimate.startIndex ... pointsToAnimate.endIndex { let newPosition = calculatePosition(i, value: data[i]) let point = graphPoints[i] animatePoint(point, toPosition: newPosition, withDelay: Double(index) * stagger) index += 1 } // Update any non-visible & non-animating points so they come on to screen at the right scale. for i in 0 ..< graphPoints.count { if(i > pointsToAnimate.startIndex && i < pointsToAnimate.endIndex || graphPoints[i].currentlyAnimatingToPosition) { continue } let newPosition = calculatePosition(i, value: data[i]) graphPoints[i].x = newPosition.x graphPoints[i].y = newPosition.y } } // MARK: - Drawing Delegate private func currentPath() -> UIBezierPath { return currentLinePath } private func intervalForActivePoints() -> Range<Int> { return activePointsInterval } private func rangeForActivePoints() -> (min: Double, max: Double) { return range } private func dataForGraph() -> [Double] { return data } private func graphPointForIndex(index: Int) -> GraphPoint { return graphPoints[index] } } // MARK: - LabelPool private class LabelPool { var labels = [UILabel]() var relations = [Int : Int]() var unused = [Int]() func deactivateLabelForPointIndex(pointIndex: Int){ if let unusedLabelIndex = relations[pointIndex] { unused.append(unusedLabelIndex) } relations[pointIndex] = nil } func activateLabelForPointIndex(pointIndex: Int) -> UILabel { var label: UILabel if(unused.count >= 1) { let unusedLabelIndex = unused.first! unused.removeFirst() label = labels[unusedLabelIndex] relations[pointIndex] = unusedLabelIndex } else { label = UILabel() labels.append(label) let newLabelIndex = labels.indexOf(label)! relations[pointIndex] = newLabelIndex } return label } var activeLabels: [UILabel] { get { var currentlyActive = [UILabel]() let numberOfLabels = labels.count for i in 0 ..< numberOfLabels { if(!unused.contains(i)) { currentlyActive.append(labels[i]) } } return currentlyActive } } } // MARK: - GraphPoints and Animation Classes private class GraphPoint { var location = CGPoint(x: 0, y: 0) var currentlyAnimatingToPosition = false private var x: CGFloat { get { return location.x } set { location.x = newValue } } private var y: CGFloat { get { return location.y } set { location.y = newValue } } init(position: CGPoint = CGPointZero) { x = position.x y = position.y } } private class GraphPointAnimation : Equatable { // Public Properties var animationEasing = Easings.EaseOutQuad var duration: Double = 1 var delay: Double = 0 private(set) var finished = false private(set) var animationKey: String // Private State private var startingPoint: CGPoint private var endingPoint: CGPoint private var elapsedTime: Double = 0 private var graphPoint: GraphPoint? private var multiplier: Double = 1 static private var animationsCreated = 0 init(fromPoint: CGPoint, toPoint: CGPoint, forGraphPoint graphPoint: GraphPoint, forKey key: String = "animation\(animationsCreated)") { self.startingPoint = fromPoint self.endingPoint = toPoint self.animationKey = key self.graphPoint = graphPoint self.graphPoint?.currentlyAnimatingToPosition = true GraphPointAnimation.animationsCreated += 1 } func update(dt: Double) { if(!finished) { if elapsedTime > delay { let animationElapsedTime = elapsedTime - delay let changeInX = endingPoint.x - startingPoint.x let changeInY = endingPoint.y - startingPoint.y // t is in the range of 0 to 1, indicates how far through the animation it is. let t = animationElapsedTime / duration let interpolation = animationEasing(t) let x = startingPoint.x + changeInX * CGFloat(interpolation) let y = startingPoint.y + changeInY * CGFloat(interpolation) if(animationElapsedTime >= duration) { animationDidFinish() } graphPoint?.x = CGFloat(x) graphPoint?.y = CGFloat(y) elapsedTime += dt * multiplier } // Keep going until we are passed the delay else { elapsedTime += dt * multiplier } } } func animationDidFinish() { self.graphPoint?.currentlyAnimatingToPosition = false self.finished = true } } private func ==(lhs: GraphPointAnimation, rhs: GraphPointAnimation) -> Bool { return lhs.animationKey == rhs.animationKey } // MARK: - Drawing Layers // MARK: Delegate definition that provides the data required by the drawing layers. private protocol ScrollableGraphViewDrawingDelegate { func intervalForActivePoints() -> Range<Int> func rangeForActivePoints() -> (min: Double, max: Double) func dataForGraph() -> [Double] func graphPointForIndex(index: Int) -> GraphPoint func currentPath() -> UIBezierPath } // MARK: Drawing Layer Classes // MARK: Base Class private class ScrollableGraphViewDrawingLayer : CAShapeLayer { var offset: CGFloat = 0 { didSet { offsetDidChange() } } var viewportWidth: CGFloat = 0 var viewportHeight: CGFloat = 0 var zeroYPosition: CGFloat = 0 var graphViewDrawingDelegate: ScrollableGraphViewDrawingDelegate? = nil var active = true init(viewportWidth: CGFloat, viewportHeight: CGFloat, offset: CGFloat = 0) { super.init() self.viewportWidth = viewportWidth self.viewportHeight = viewportHeight self.frame = CGRect(origin: CGPoint(x: offset, y: 0), size: CGSize(width: self.viewportWidth, height: self.viewportHeight)) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { // Get rid of any animations. self.actions = ["position" : NSNull(), "bounds" : NSNull()] } private func offsetDidChange() { self.frame.origin.x = offset self.bounds.origin.x = offset } func updatePath() { fatalError("updatePath needs to be implemented by the subclass") } } // MARK: Drawing the bars private class BarDrawingLayer: ScrollableGraphViewDrawingLayer { private var barPath = UIBezierPath() private var barWidth: CGFloat = 4 init(frame: CGRect, barWidth: CGFloat, barColor: UIColor, barLineWidth: CGFloat, barLineColor: UIColor) { super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height) self.barWidth = barWidth self.lineWidth = barLineWidth self.strokeColor = barLineColor.CGColor self.fillColor = barColor.CGColor self.lineJoin = lineJoin self.lineCap = lineCap } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createBarPath(centre: CGPoint) -> UIBezierPath { let squarePath = UIBezierPath() squarePath.moveToPoint(centre) let barWidthOffset: CGFloat = self.barWidth / 2 let topLeft = CGPoint(x: centre.x - barWidthOffset, y: centre.y) let topRight = CGPoint(x: centre.x + barWidthOffset, y: centre.y) let bottomLeft = CGPoint(x: centre.x - barWidthOffset, y: zeroYPosition) let bottomRight = CGPoint(x: centre.x + barWidthOffset, y: zeroYPosition) squarePath.moveToPoint(topLeft) squarePath.addLineToPoint(topRight) squarePath.addLineToPoint(bottomRight) squarePath.addLineToPoint(bottomLeft) squarePath.addLineToPoint(topLeft) return squarePath } private func createPath () -> UIBezierPath { barPath.removeAllPoints() // We can only move forward if we can get the data we need from the delegate. guard let activePointsInterval = self.graphViewDrawingDelegate?.intervalForActivePoints(), data = self.graphViewDrawingDelegate?.dataForGraph() else { return barPath } let numberOfPoints = min(data.count, activePointsInterval.endIndex) for i in activePointsInterval.startIndex ... numberOfPoints { var location = CGPointZero if let pointLocation = self.graphViewDrawingDelegate?.graphPointForIndex(i).location { location = pointLocation } let pointPath = createBarPath(location) barPath.appendPath(pointPath) } return barPath } override func updatePath() { self.path = createPath ().CGPath } } // MARK: Drawing the Graph Line private class LineDrawingLayer : ScrollableGraphViewDrawingLayer { init(frame: CGRect, lineWidth: CGFloat, lineColor: UIColor, lineStyle: ScrollableGraphViewLineStyle, lineJoin: String, lineCap: String) { super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height) self.lineWidth = lineWidth self.strokeColor = lineColor.CGColor self.lineJoin = lineJoin self.lineCap = lineCap // Setup self.fillColor = UIColor.clearColor().CGColor // This is handled by the fill drawing layer. } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updatePath() { self.path = graphViewDrawingDelegate?.currentPath().CGPath } } // MARK: Drawing the Individual Data Points private class DataPointDrawingLayer: ScrollableGraphViewDrawingLayer { private var dataPointPath = UIBezierPath() private var dataPointSize: CGFloat = 5 private var dataPointType: ScrollableGraphViewDataPointType = .Circle private var customDataPointPath: ((centre: CGPoint) -> UIBezierPath)? init(frame: CGRect, fillColor: UIColor, dataPointType: ScrollableGraphViewDataPointType, dataPointSize: CGFloat, customDataPointPath: ((centre: CGPoint) -> UIBezierPath)? = nil) { self.dataPointType = dataPointType self.dataPointSize = dataPointSize self.customDataPointPath = customDataPointPath super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height) self.fillColor = fillColor.CGColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createDataPointPath() -> UIBezierPath { dataPointPath.removeAllPoints() // We can only move forward if we can get the data we need from the delegate. guard let activePointsInterval = self.graphViewDrawingDelegate?.intervalForActivePoints(), data = self.graphViewDrawingDelegate?.dataForGraph() else { return dataPointPath } let pointPathCreator = getPointPathCreator() let numberOfPoints = min(data.count, activePointsInterval.endIndex) for i in activePointsInterval.startIndex ... numberOfPoints { var location = CGPointZero if let pointLocation = self.graphViewDrawingDelegate?.graphPointForIndex(i).location { location = pointLocation } let pointPath = pointPathCreator(centre: location) dataPointPath.appendPath(pointPath) } return dataPointPath } private func createCircleDataPoint(centre: CGPoint) -> UIBezierPath { return UIBezierPath(arcCenter: centre, radius: dataPointSize, startAngle: 0, endAngle: CGFloat(2.0 * M_PI), clockwise: true) } private func createSquareDataPoint(centre: CGPoint) -> UIBezierPath { let squarePath = UIBezierPath() squarePath.moveToPoint(centre) let topLeft = CGPoint(x: centre.x - dataPointSize, y: centre.y - dataPointSize) let topRight = CGPoint(x: centre.x + dataPointSize, y: centre.y - dataPointSize) let bottomLeft = CGPoint(x: centre.x - dataPointSize, y: centre.y + dataPointSize) let bottomRight = CGPoint(x: centre.x + dataPointSize, y: centre.y + dataPointSize) squarePath.moveToPoint(topLeft) squarePath.addLineToPoint(topRight) squarePath.addLineToPoint(bottomRight) squarePath.addLineToPoint(bottomLeft) squarePath.addLineToPoint(topLeft) return squarePath } private func getPointPathCreator() -> (centre: CGPoint) -> UIBezierPath { switch(self.dataPointType) { case .Circle: return createCircleDataPoint case .Square: return createSquareDataPoint case .Custom: if let customCreator = self.customDataPointPath { return customCreator } else { // We don't have a custom path, so just return the default. fallthrough } default: return createCircleDataPoint } } override func updatePath() { self.path = createDataPointPath().CGPath } } // MARK: Drawing the Graph Gradient Fill private class GradientDrawingLayer : ScrollableGraphViewDrawingLayer { private var startColor: UIColor private var endColor: UIColor private var gradientType: ScrollableGraphViewGradientType lazy private var gradientMask: CAShapeLayer = ({ let mask = CAShapeLayer() mask.frame = CGRect(x: 0, y: 0, width: self.viewportWidth, height: self.viewportHeight) mask.fillRule = kCAFillRuleEvenOdd mask.path = self.graphViewDrawingDelegate?.currentPath().CGPath mask.lineJoin = self.lineJoin return mask })() init(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientType: ScrollableGraphViewGradientType, lineJoin: String = kCALineJoinRound) { self.startColor = startColor self.endColor = endColor self.gradientType = gradientType //self.lineJoin = lineJoin super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height) addMaskLayer() self.setNeedsDisplay() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addMaskLayer() { self.mask = gradientMask } override func updatePath() { gradientMask.path = graphViewDrawingDelegate?.currentPath().CGPath } override func drawInContext(ctx: CGContext) { let colors = [startColor.CGColor, endColor.CGColor] let colorSpace = CGColorSpaceCreateDeviceRGB() let locations: [CGFloat] = [0.0, 1.0] let gradient = CGGradientCreateWithColors(colorSpace, colors, locations) let displacement = ((viewportWidth / viewportHeight) / 2.5) * self.bounds.height let topCentre = CGPoint(x: offset + self.bounds.width / 2, y: -displacement) let bottomCentre = CGPoint(x: offset + self.bounds.width / 2, y: self.bounds.height) let startRadius: CGFloat = 0 let endRadius: CGFloat = self.bounds.width switch(gradientType) { case .Linear: CGContextDrawLinearGradient(ctx, gradient, topCentre, bottomCentre, .DrawsAfterEndLocation) case .Radial: CGContextDrawRadialGradient(ctx, gradient, topCentre, startRadius, topCentre, endRadius, .DrawsAfterEndLocation) } } } // MARK: Drawing the Graph Fill private class FillDrawingLayer : ScrollableGraphViewDrawingLayer { init(frame: CGRect, fillColor: UIColor) { super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height) self.fillColor = fillColor.CGColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updatePath() { self.path = graphViewDrawingDelegate?.currentPath().CGPath } } // MARK: - Reference Lines private class ReferenceLineDrawingView : UIView { // PUBLIC PROPERTIES // Reference line settings. var referenceLineColor: UIColor = UIColor.blackColor() var referenceLineThickness: CGFloat = 0.5 var referenceLinePosition = ScrollableGraphViewReferenceLinePosition.Left var referenceLineType = ScrollableGraphViewReferenceLineType.Cover var numberOfIntermediateReferenceLines = 3 // Number of reference lines between the min and max line. // Reference line label settings. var shouldAddLabelsToIntermediateReferenceLines: Bool = true var shouldAddUnitsToIntermediateReferenceLineLabels: Bool = false var labelUnits: String? var labelFont: UIFont = UIFont.systemFontOfSize(8) var labelColor: UIColor = UIColor.blackColor() var labelDecimalPlaces: Int = 2 // PRIVATE PROPERTIES private var intermediateLineWidthMultiplier: CGFloat = 1 //FUTURE: Can make the intermediate lines shorter using this. private var referenceLineWidth: CGFloat = 100 // FUTURE: Used when referenceLineType == .Edge private var labelMargin: CGFloat = 4 private var leftLabelInset: CGFloat = 10 private var rightLabelInset: CGFloat = 10 // Store information about the ScrollableGraphView private var currentRange: (min: Double, max: Double) = (0,100) private var topMargin: CGFloat = 10 private var bottomMargin: CGFloat = 10 // Partition recursion depth // FUTURE: For .Edge // private var referenceLinePartitions: Int = 3 private var lineWidth: CGFloat { get { if(self.referenceLineType == ScrollableGraphViewReferenceLineType.Cover) { return self.bounds.width } else { return referenceLineWidth } } } private var units: String { get { if let units = self.labelUnits { return " \(units)" } else { return "" } } } // Layers private var labels = [UILabel]() private let referenceLineLayer = CAShapeLayer() private let referenceLinePath = UIBezierPath() init(frame: CGRect, topMargin: CGFloat, bottomMargin: CGFloat, referenceLineColor: UIColor, referenceLineThickness: CGFloat) { super.init(frame: frame) self.topMargin = topMargin self.bottomMargin = bottomMargin // The reference line layer draws the reference lines and we handle the labels elsewhere. self.referenceLineLayer.frame = self.frame self.referenceLineLayer.strokeColor = referenceLineColor.CGColor self.referenceLineLayer.lineWidth = referenceLineThickness self.layer.addSublayer(referenceLineLayer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createLabelAtPosition(position: CGPoint, withText text: String) -> UILabel { let frame = CGRect(x: position.x, y: position.y, width: 0, height: 0) let label = UILabel(frame: frame) return label } private func createReferenceLinesPath() -> UIBezierPath { referenceLinePath.removeAllPoints() for label in labels { label.removeFromSuperview() } labels.removeAll() let maxLineStart = CGPoint(x: 0, y: topMargin) let maxLineEnd = CGPoint(x: lineWidth, y: topMargin) let minLineStart = CGPoint(x: 0, y: self.bounds.height - bottomMargin) let minLineEnd = CGPoint(x: lineWidth, y: self.bounds.height - bottomMargin) let maxString = String(format: "%.\(labelDecimalPlaces)f", arguments: [self.currentRange.max]) + units let minString = String(format: "%.\(labelDecimalPlaces)f", arguments: [self.currentRange.min]) + units addLineWithTag(maxString, from: maxLineStart, to: maxLineEnd, inPath: referenceLinePath) addLineWithTag(minString, from: minLineStart, to: minLineEnd, inPath: referenceLinePath) let initialRect = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y + topMargin, width: self.bounds.size.width, height: self.bounds.size.height - (topMargin + bottomMargin)) createIntermediateReferenceLines(initialRect, numberOfIntermediateReferenceLines: self.numberOfIntermediateReferenceLines, forPath: referenceLinePath) return referenceLinePath } private func createIntermediateReferenceLines(rect: CGRect, numberOfIntermediateReferenceLines: Int, forPath path: UIBezierPath) { let height = rect.size.height let spacePerPartition = height / CGFloat(numberOfIntermediateReferenceLines + 1) for i in 0 ..< numberOfIntermediateReferenceLines { let lineStart = CGPoint(x: 0, y: rect.origin.y + (spacePerPartition * CGFloat(i + 1))) let lineEnd = CGPoint(x: lineStart.x + lineWidth * intermediateLineWidthMultiplier, y: lineStart.y) createReferenceLineFrom(from: lineStart, to: lineEnd, inPath: path) } } // FUTURE: Can use the recursive version to create a ruler like look on the edge. private func recursiveCreateIntermediateReferenceLines(rect: CGRect, width: CGFloat, forPath path: UIBezierPath, remainingPartitions: Int) -> UIBezierPath { if(remainingPartitions <= 0) { return path } let lineStart = CGPoint(x: 0, y: rect.origin.y + (rect.size.height / 2)) let lineEnd = CGPoint(x: lineStart.x + width, y: lineStart.y) createReferenceLineFrom(from: lineStart, to: lineEnd, inPath: path) let topRect = CGRect( x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height / 2) let bottomRect = CGRect( x: rect.origin.x, y: rect.origin.y + (rect.size.height / 2), width: rect.size.width, height: rect.size.height / 2) recursiveCreateIntermediateReferenceLines(topRect, width: width * intermediateLineWidthMultiplier, forPath: path, remainingPartitions: remainingPartitions - 1) recursiveCreateIntermediateReferenceLines(bottomRect, width: width * intermediateLineWidthMultiplier, forPath: path, remainingPartitions: remainingPartitions - 1) return path } private func createReferenceLineFrom(from lineStart: CGPoint, to lineEnd: CGPoint, inPath path: UIBezierPath) { if(shouldAddLabelsToIntermediateReferenceLines) { let value = calculateYAxisValueForPoint(lineStart) var valueString = String(format: "%.\(labelDecimalPlaces)f", arguments: [value]) if(shouldAddUnitsToIntermediateReferenceLineLabels) { valueString += " \(units)" } addLineWithTag(valueString, from: lineStart, to: lineEnd, inPath: path) } else { addLineFrom(lineStart, to: lineEnd, inPath: path) } } private func addLineWithTag(tag: String, from: CGPoint, to: CGPoint, inPath path: UIBezierPath) { let boundingSize = boundingSizeForText(tag) let leftLabel = createLabelWithText(tag) let rightLabel = createLabelWithText(tag) // Left label gap. leftLabel.frame = CGRect( origin: CGPoint(x: from.x + leftLabelInset, y: from.y - (boundingSize.height / 2)), size: boundingSize) let leftLabelStart = CGPoint(x: leftLabel.frame.origin.x - labelMargin, y: to.y) let leftLabelEnd = CGPoint(x: (leftLabel.frame.origin.x + leftLabel.frame.size.width) + labelMargin, y: to.y) // Right label gap. rightLabel.frame = CGRect( origin: CGPoint(x: (from.x + self.frame.width) - rightLabelInset - boundingSize.width, y: from.y - (boundingSize.height / 2)), size: boundingSize) let rightLabelStart = CGPoint(x: rightLabel.frame.origin.x - labelMargin, y: to.y) let rightLabelEnd = CGPoint(x: (rightLabel.frame.origin.x + rightLabel.frame.size.width) + labelMargin, y: to.y) // Add the lines and tags depending on the settings for where we want them. var gaps = [(start: CGFloat, end: CGFloat)]() switch(self.referenceLinePosition) { case .Left: gaps.append((start: leftLabelStart.x, end: leftLabelEnd.x)) self.addSubview(leftLabel) self.labels.append(leftLabel) case .Right: gaps.append((start: rightLabelStart.x, end: rightLabelEnd.x)) self.addSubview(rightLabel) self.labels.append(rightLabel) case .Both: gaps.append((start: leftLabelStart.x, end: leftLabelEnd.x)) gaps.append((start: rightLabelStart.x, end: rightLabelEnd.x)) self.addSubview(leftLabel) self.addSubview(rightLabel) self.labels.append(leftLabel) self.labels.append(rightLabel) } addLineWithGaps(from, to: to, withGaps: gaps, inPath: path) } private func addLineWithGaps(from: CGPoint, to: CGPoint, withGaps gaps: [(start: CGFloat, end: CGFloat)], inPath path: UIBezierPath) { // If there are no gaps, just add a single line. if(gaps.count <= 0) { addLineFrom(from, to: to, inPath: path) } // If there is only 1 gap, it's just two lines. else if (gaps.count == 1) { let gapLeft = CGPoint(x: gaps.first!.start, y: from.y) let gapRight = CGPoint(x: gaps.first!.end, y: from.y) addLineFrom(from, to: gapLeft, inPath: path) addLineFrom(gapRight, to: to, inPath: path) } // If there are many gaps, we have a series of intermediate lines. else { let firstGap = gaps.first! let lastGap = gaps.last! let firstGapLeft = CGPoint(x: firstGap.start, y: from.y) let lastGapRight = CGPoint(x: lastGap.end, y: to.y) // Add the first line to the start of the first gap addLineFrom(from, to: firstGapLeft, inPath: path) // Add lines between all intermediate gaps for i in 0 ..< gaps.count - 1 { let startGapEnd = gaps[i].end let endGapStart = gaps[i + 1].start let lineStart = CGPoint(x: startGapEnd, y: from.y) let lineEnd = CGPoint(x: endGapStart, y: from.y) addLineFrom(lineStart, to: lineEnd, inPath: path) } // Add the final line to the end addLineFrom(lastGapRight, to: to, inPath: path) } } private func addLineFrom(from: CGPoint, to: CGPoint, inPath path: UIBezierPath) { path.moveToPoint(from) path.addLineToPoint(to) } private func boundingSizeForText(text: String) -> CGSize { return (text as NSString).sizeWithAttributes([NSFontAttributeName:labelFont]) } private func calculateYAxisValueForPoint(point: CGPoint) -> Double { let graphHeight = self.frame.size.height - (topMargin + bottomMargin) // value = the corresponding value on the graph for any y co-ordinate in the view // y - t y = the y co-ordinate in the view for which we want to know the corresponding value on the graph // value = --------- * (min - max) + max t = the top margin // h h = the height of the graph space without margins // min = the range's current mininum // max = the range's current maximum var value = (((point.y - topMargin) / (graphHeight)) * CGFloat((self.currentRange.min - self.currentRange.max))) + CGFloat(self.currentRange.max) // Sometimes results in "negative zero" if(value == 0) { value = 0 } return Double(value) } private func createLabelWithText(text: String) -> UILabel { let label = UILabel() label.text = text label.textColor = labelColor label.font = labelFont return label } // Public functions to update the reference lines with any changes to the range and viewport (phone rotation, etc). // When the range changes, need to update the max for the new range, then update all the labels that are showing for the axis and redraw the reference lines. func setRange(range: (min: Double, max: Double)) { self.currentRange = range self.referenceLineLayer.path = createReferenceLinesPath().CGPath } func setViewport(viewportWidth: CGFloat, viewportHeight: CGFloat) { self.frame.size.width = viewportWidth self.frame.size.height = viewportHeight self.referenceLineLayer.path = createReferenceLinesPath().CGPath } } // MARK: - ScrollableGraphView Settings Enums @objc public enum ScrollableGraphViewLineStyle : Int { case Straight case Smooth } @objc public enum ScrollableGraphViewFillType : Int { case Solid case Gradient } @objc public enum ScrollableGraphViewGradientType : Int { case Linear case Radial } @objc public enum ScrollableGraphViewDataPointType : Int { case Circle case Square case Custom } @objc public enum ScrollableGraphViewReferenceLinePosition : Int { case Left case Right case Both } @objc public enum ScrollableGraphViewReferenceLineType : Int { case Cover //case Edge // FUTURE: Implement } @objc public enum ScrollableGraphViewAnimationType : Int { case EaseOut case Elastic case Custom } @objc public enum ScrollableGraphViewDirection : Int { case LeftToRight case RightToLeft } // Simplified easing functions from: http://www.joshondesign.com/2013/03/01/improvedEasingEquations private struct Easings { static let EaseInQuad = { (t:Double) -> Double in return t*t; } static let EaseOutQuad = { (t:Double) -> Double in return 1 - Easings.EaseInQuad(1-t); } static let EaseOutElastic = { (t: Double) -> Double in var p = 0.3; return pow(2,-10*t) * sin((t-p/4)*(2*M_PI)/p) + 1; } }
mit
3a25176d40501f6657b367e632b072d2
37.459686
468
0.623118
5.11546
false
false
false
false
Xiomara7/bookiao-ios
bookiao-ios/AppointmentsViewController.swift
1
6708
// // AppointmentsViewController.swift // bookiao-ios // // Created by Xiomara on 10/2/14. // Copyright (c) 2014 UPRRP. All rights reserved. // import UIKit import CoreData class AppointmentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let application = UIApplication.sharedApplication().delegate as AppDelegate var names: NSArray! = [] var tableView: UITableView! var dataSource: [[String: String]] = [] var refreshControl:UIRefreshControl! var customDesign = CustomDesign() var requests = HTTPrequests() override func viewDidLoad() { self.view = UIView(frame: self.view.bounds) self.view.backgroundColor = UIColor.whiteColor() let tableAppearance = UITableView.appearance() tableView = UITableView(frame: CGRectMake(0, -40, self.view.frame.width, self.view.frame.height), style: .Grouped) tableView.delegate = self tableView.dataSource = self tableView.tintColor = UIColor.whiteColor() tableView.separatorColor = UIColor.grayColor() tableView.backgroundColor = customDesign.UIColorFromRGB(0xE4E4E4) tableView.showsVerticalScrollIndicator = true self.view.addSubview(tableView) self.tabBarController?.navigationItem.title = DataManager.sharedManager.dateLabel self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refersh") self.refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refreshControl) } func refresh() { // let ut = DataManager.sharedManager.userInfo["userType"] as String // let id = DataManager.sharedManager.userInfo["id"] as Int // // if ut == "client" { // self.requests.getClientAppointments(id) // self.requests.getClientAppointmentsPerDay(id, date: DataManager.sharedManager.date) // } // if ut == "employee" { // self.requests.getEmployeeAppointments(id) // self.requests.getEmployeeAppointmentsPerDay(id, date: DataManager.sharedManager.date) // } } override func viewWillAppear(animated: Bool) { self.tabBarController?.navigationItem.title = DataManager.sharedManager.dateLabel self.tabBarController?.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.tabBarItem.setTitlePositionAdjustment(UIOffsetMake(0, -50)) } // MARK: - Private Methods func updateDataSource() { tableView.reloadData() } // MARK: - UITableViewDataSource Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let ut = DataManager.sharedManager.userInfo["userType"] as String! let eAppointments = DataManager.sharedManager.employeeAppointmentsPerDay let cAppointments = DataManager.sharedManager.clientAppointmentsPerDay if eAppointments.count == 0 { return 1 } if cAppointments.count == 0 { return 1 } if ut == "employee" { return eAppointments.count } if ut == "client" { return cAppointments.count } return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellIdentifier = "Cell" let ut = DataManager.sharedManager.userInfo["userType"] as String! let eAppointments = DataManager.sharedManager.employeeAppointmentsPerDay as NSArray! let cAppointments = DataManager.sharedManager.clientAppointmentsPerDay as NSArray! var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as CustomCell! if cell == nil { cell = CustomCell(reuseIdentifier: "Cell") } let cellFrame = self.view.bounds if ut == "employee" { if eAppointments.count == 0 && cAppointments.count == 0 { cell.sTitle.text = DataManager.sharedManager.Title cell.status.text = DataManager.sharedManager.status } else { let day = eAppointments[indexPath.row]["day"] as String! let time = eAppointments[indexPath.row]["time"] as String! let serv = eAppointments[indexPath.row]["services"] as NSArray! cell.priceLabel.text = serv[0] as? String cell.titleLabel.text = eAppointments[indexPath.row]["client"] as String! cell.phoneLabel.text = DataManager.sharedManager.userInfo["phone_number"] as String! cell.stitleLabel.text = "\(DataManager.sharedManager.phrase) \(time)" } } else if ut! == "client" { if cAppointments.count == 0 && eAppointments.count == 0 { cell.sTitle.text = DataManager.sharedManager.Title cell.status.text = DataManager.sharedManager.status } else { let day = cAppointments[indexPath.row]["day"] as String! let time = cAppointments[indexPath.row]["time"] as String! let serv = cAppointments[indexPath.row]["services"] as NSArray! cell.priceLabel.text = serv[0] as? String cell.titleLabel.text = cAppointments[indexPath.row]["employee"] as String! cell.phoneLabel.text = DataManager.sharedManager.userInfo["phone_number"] as String! cell.stitleLabel.text = "\(DataManager.sharedManager.phrase) \(time)" } } cell.selectionStyle = .Default cell.accessoryType = .None cell.frame.origin.y = 4 cell.setNeedsUpdateConstraints() return cell } // MARK: UITableViewDelegate Methods func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 140.0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("Hello") } func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!){ println(item) } func post() { let newPost = newAppointmentViewController() self.presentViewController(newPost, animated: true, completion: nil) } }
mit
e3a2a0c6adf23a453817ef7fdb9d380f
37.774566
122
0.63059
4.910688
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/SimpleParser.swift
2
6036
// // SimpleParser.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // /* <abstract> A very limited parser which looks for simple language constructs. Known limitations: - Cannot distinguish between functions based on argument labels or parameter type (only name). - Only checks for (func, if, else, else if, for, while) keywords. - Makes no attempt to recover if a parsing error is discovered. </abstract> */ import Foundation enum ParseError: Error { case fail(String) } class SimpleParser { let tokens: [Token] var index = 0 init(tokens: [Token]) { self.tokens = tokens } var currentToken: Token? { guard tokens.indices.contains(index) else { return nil } return tokens[index] } var nextToken: Token? { let nextIndex = tokens.index(after: index) guard nextIndex < tokens.count else { return nil } return tokens[nextIndex] } /// Advances the index, and returns the new current token if any. @discardableResult func advanceToNextToken() -> Token? { index = tokens.index(after: index) return currentToken } /// Converts the `tokens` into `Node`s. func createNodes() throws -> [Node] { var nodes = [Node]() while let token = currentToken { if let node = try parseToken(token) { nodes.append(node) } } return nodes } // MARK: Main Parsers private func parseToken(_ token: Token) throws -> Node? { var node: Node? = nil switch token { case let .keyword(word): node = try parseKeyword(word) case let .identifier(name): if case .delimiter(.openParen)? = advanceToNextToken() { // Ignoring parameters for now. consumeTo(.closingParen) advanceToNextToken() node = CallNode(identifier: name) } else { // This is by no means completely correct, but works for the // kind of information we're trying to glean. node = VariableNode(identifier: name) } case .number(_): // Discard numbers for now. advanceToNextToken() case .delimiter(_): // Discard tokens that don't map to a top level node. advanceToNextToken() } return node } func parseKeyword(_ word: Keyword) throws -> Node { let node: Node // Parse for known keywords. switch word { case .func: node = try parseDefinition() case .if, .else, .elseIf: node = try parseConditionalStatement() case .for, .while: node = try parseLoop() } return node } // MARK: Token Parsers func parseDefinition() throws -> DefinitionNode { guard case .identifier(let funcName)? = advanceToNextToken() else { throw ParseError.fail(#function) } // Ignore any hidden comments (e.g. /*#-end-editable-code*/). consumeTo(.openParen) let argTokens = consumeTo(.closingParen) let args = reduce(argTokens) consumeTo(.openBrace) let body = try parseToClosingBrace() return DefinitionNode(name: funcName, parameters: args, body: body) } func parseConditionalStatement() throws -> Node { guard case .keyword(var type)? = currentToken else { throw ParseError.fail(#function) } // Check if this is a compound "else if" statement. if case .keyword(let subtype)? = nextToken, subtype == .if { type = .elseIf advanceToNextToken() } let conditionTokens = consumeTo(.openBrace) let condition = reduce(conditionTokens) let body = try parseToClosingBrace() return ConditionalStatementNode(type: type, condition: condition, body: body) } func parseLoop() throws -> Node { guard case .keyword(let type)? = currentToken else { throw ParseError.fail(#function) } let conditionTokens = consumeTo(.openBrace) let condition = reduce(conditionTokens) let body = try parseToClosingBrace() return LoopNode(type: type, condition: condition, body: body) } // MARK: Convenience Methods func parseToClosingBrace() throws -> [Node] { var nodes = [Node]() loop: while let token = currentToken { switch token { case .delimiter(.openBrace): advanceToNextToken() // Recurse on opening brace. nodes += try parseToClosingBrace() break loop case .delimiter(.closingBrace): // Complete. advanceToNextToken() break loop default: if let node = try parseToken(token) { nodes.append(node) } } } return nodes } @discardableResult func consumeTo(_ match: Token) -> [Token] { var content = [Token]() while let token = advanceToNextToken() { if token == match { break } content.append(token) } return content } @discardableResult func consumeTo(_ delimiter: Delimiter) -> [Token] { return consumeTo(.delimiter(delimiter)) } func reduce(_ tokens: [Token], separator: String = "") -> String { let contents = tokens.reduce("") { $0 + $1.contents + separator } return contents } }
mit
3f7b25d38dd15eb36ca651cbe038d81e
27.742857
110
0.532969
5.063758
false
false
false
false
mgsergio/omim
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewStatus/TransportRoutePreviewStatus.swift
2
3546
@objc(MWMTransportRoutePreviewStatus) final class TransportRoutePreviewStatus: SolidTouchView { @IBOutlet private weak var etaLabel: UILabel! @IBOutlet private weak var stepsCollectionView: TransportTransitStepsCollectionView! @IBOutlet private weak var stepsCollectionViewHeight: NSLayoutConstraint! private var hiddenConstraint: NSLayoutConstraint! @objc weak var ownerView: UIView! weak var navigationInfo: MWMNavigationDashboardEntity? private var isVisible = false { didSet { alternative(iPhone: { guard self.isVisible != oldValue else { return } if self.isVisible { self.addView() } DispatchQueue.main.async { guard let sv = self.superview else { return } sv.setNeedsLayout() self.hiddenConstraint.isActive = !self.isVisible UIView.animate(withDuration: kDefaultAnimationDuration, animations: { sv.layoutIfNeeded() }, completion: { _ in if !self.isVisible { self.removeFromSuperview() } }) } }, iPad: { self.isHidden = !self.isVisible })() } } private func addView() { guard superview != ownerView else { return } ownerView.addSubview(self) NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: ownerView, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: ownerView, attribute: .right, multiplier: 1, constant: 0).isActive = true hiddenConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: ownerView, attribute: .bottom, multiplier: 1, constant: 0) hiddenConstraint.priority = UILayoutPriority.defaultHigh hiddenConstraint.isActive = true let visibleConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: ownerView, attribute: .bottom, multiplier: 1, constant: 0) visibleConstraint.priority = UILayoutPriority.defaultLow visibleConstraint.isActive = true } @objc func hide() { isVisible = false } @objc func showReady() { isVisible = true updateHeight() } @objc func onNavigationInfoUpdated(_ info: MWMNavigationDashboardEntity) { navigationInfo = info etaLabel.attributedText = info.estimate stepsCollectionView.steps = info.transitSteps } private func updateHeight() { guard stepsCollectionViewHeight.constant != stepsCollectionView.contentSize.height else { return } DispatchQueue.main.async { self.setNeedsLayout() self.stepsCollectionViewHeight.constant = self.stepsCollectionView.contentSize.height UIView.animate(withDuration: kDefaultAnimationDuration) { self.layoutIfNeeded() } } } override func layoutSubviews() { super.layoutSubviews() updateHeight() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateHeight() } override var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } }
apache-2.0
b22ece32254baa34a89e6a94e502acb8
35.556701
164
0.701354
5.036932
false
false
false
false
storehouse/Advance
Samples/SampleApp-iOS/Sources/DecayViewController.swift
1
2743
import UIKit import Advance final class DecayViewController: DemoViewController { let draggableView: UIView let centerAnimator: Animator<CGPoint> override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { draggableView = UIView() centerAnimator = Animator(initialValue: CGPoint.zero) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) centerAnimator.onChange = { [weak self] center in self?.draggableView.center = center } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Decay" note = "Drag the box." draggableView.bounds.size = CGSize(width: 64.0, height: 64.0) draggableView.backgroundColor = UIColor.lightGray draggableView.layer.cornerRadius = 8.0 contentView.addSubview(draggableView) let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan)) draggableView.addGestureRecognizer(gestureRecognizer) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped)) contentView.addGestureRecognizer(tapRecognizer) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) centerAnimator.value = CGPoint(x: view.bounds.midX, y: view.bounds.midY) } override func didLeaveFullScreen() { super.didLeaveFullScreen() centerAnimator.simulate(using: SpringFunction(target: CGPoint(x: view.bounds.midX, y: view.bounds.midY))) } @objc private func pan(recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: centerAnimator.cancelRunningAnimation() case .changed: let translation = recognizer.translation(in: contentView) recognizer.setTranslation(.zero, in: contentView) centerAnimator.value.x += translation.x centerAnimator.value.y += translation.y case .ended, .cancelled: let velocity = recognizer.velocity(in: contentView) centerAnimator.simulate(using: DecayFunction(), initialVelocity: velocity) default: break } } @objc private func tapped(recognizer: UITapGestureRecognizer) { let tapLocation = recognizer.location(in: contentView) guard !draggableView.frame.contains(tapLocation) else { return } centerAnimator.simulate(using: SpringFunction(target: tapLocation)) } }
bsd-2-clause
de3e2aa3e0b3f3bfe0682e392b79ca76
32.45122
113
0.645279
5.254789
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/dfa/DFA.swift
1
6587
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. public class DFA: CustomStringConvertible { /// A set of all DFA states. Use {@link java.util.Map} so we can get old state back /// ({@link java.util.Set} only allows you to see if it's there). public final var states: HashMap<DFAState, DFAState?> = HashMap<DFAState, DFAState?>() public /*volatile*/ var s0: DFAState? public final var decision: Int /// From which ATN state did we create this DFA? public let atnStartState: DecisionState /// {@code true} if this DFA is for a precedence decision; otherwise, /// {@code false}. This is the backing field for {@link #isPrecedenceDfa}. private final var precedenceDfa: Bool public convenience init(_ atnStartState: DecisionState) { self.init(atnStartState, 0) } public init(_ atnStartState: DecisionState, _ decision: Int) { self.atnStartState = atnStartState self.decision = decision var precedenceDfa: Bool = false if atnStartState is StarLoopEntryState { if (atnStartState as! StarLoopEntryState).precedenceRuleDecision { precedenceDfa = true let precedenceState: DFAState = DFAState(ATNConfigSet()) precedenceState.edges = [DFAState]() //new DFAState[0]; precedenceState.isAcceptState = false precedenceState.requiresFullContext = false self.s0 = precedenceState } } self.precedenceDfa = precedenceDfa } /// Gets whether this DFA is a precedence DFA. Precedence DFAs use a special /// start state {@link #s0} which is not stored in {@link #states}. The /// {@link org.antlr.v4.runtime.dfa.DFAState#edges} array for this start state contains outgoing edges /// supplying individual start states corresponding to specific precedence /// values. /// /// - returns: {@code true} if this is a precedence DFA; otherwise, /// {@code false}. /// - seealso: org.antlr.v4.runtime.Parser#getPrecedence() public final func isPrecedenceDfa() -> Bool { return precedenceDfa } /// Get the start state for a specific precedence value. /// /// - parameter precedence: The current precedence. /// - returns: The start state corresponding to the specified precedence, or /// {@code null} if no start state exists for the specified precedence. /// /// - IllegalStateException if this is not a precedence DFA. /// - seealso: #isPrecedenceDfa() ////@SuppressWarnings("null") public final func getPrecedenceStartState(_ precedence: Int) throws -> DFAState? { if !isPrecedenceDfa() { throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.") } // s0.edges is never null for a precedence DFA // if (precedence < 0 || precedence >= s0!.edges!.count) { if precedence < 0 || s0 == nil || s0!.edges == nil || precedence >= s0!.edges!.count { return nil } return s0!.edges![precedence] } /// Set the start state for a specific precedence value. /// /// - parameter precedence: The current precedence. /// - parameter startState: The start state corresponding to the specified /// precedence. /// /// - IllegalStateException if this is not a precedence DFA. /// - seealso: #isPrecedenceDfa() ////@SuppressWarnings({"SynchronizeOnNonFinalField", "null"}) public final func setPrecedenceStartState(_ precedence: Int, _ startState: DFAState) throws { if !isPrecedenceDfa() { throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.") } guard let s0 = s0,let edges = s0.edges , precedence >= 0 else { return } // synchronization on s0 here is ok. when the DFA is turned into a // precedence DFA, s0 will be initialized once and not updated again synced(s0) { // s0.edges is never null for a precedence DFA if precedence >= edges.count { let increase = [DFAState?](repeating: nil, count: (precedence + 1 - edges.count)) s0.edges = edges + increase //Array( self.s0!.edges![0..<precedence + 1]) //s0.edges = Arrays.copyOf(s0.edges, precedence + 1); } s0.edges[precedence] = startState } } /// Sets whether this is a precedence DFA. /// /// - parameter precedenceDfa: {@code true} if this is a precedence DFA; otherwise, /// {@code false} /// /// - UnsupportedOperationException if {@code precedenceDfa} does not /// match the value of {@link #isPrecedenceDfa} for the current DFA. /// /// - This method no longer performs any action. ////@Deprecated public final func setPrecedenceDfa(_ precedenceDfa: Bool) throws { if precedenceDfa != isPrecedenceDfa() { throw ANTLRError.unsupportedOperation(msg: "The precedenceDfa field cannot change after a DFA is constructed.") } } /// Return a list of all states in this DFA, ordered by state number. public func getStates() -> Array<DFAState> { var result: Array<DFAState> = Array<DFAState>(states.keys) result = result.sorted { $0.stateNumber < $1.stateNumber } return result } public var description: String { return toString(Vocabulary.EMPTY_VOCABULARY) } public func toString() -> String { return description } /// - Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. ////@Deprecated public func toString(_ tokenNames: [String?]?) -> String { if s0 == nil { return "" } let serializer: DFASerializer = DFASerializer(self, tokenNames) return serializer.toString() } public func toString(_ vocabulary: Vocabulary) -> String { if s0 == nil { return "" } let serializer: DFASerializer = DFASerializer(self, vocabulary) return serializer.toString() } public func toLexerString() -> String { if s0 == nil { return "" } let serializer: DFASerializer = LexerDFASerializer(self) return serializer.toString() } }
mit
992f568f8690bfee14a344713b6f636a
34.994536
123
0.620768
4.438679
false
false
false
false
velvetroom/columbus
Source/Model/CreateSave/MCreateSave+TileFactory.swift
1
1221
import Foundation extension MCreateSave { //MARK: private private class func factoryBoundingMin(min:Double) -> Double { var min:Double = min - MCreateSave.Constants.Tile.padding if min < 0 { min = 0 } return min } private class func factoryBoundingMax(max:Double) -> Double { let max:Double = max + MCreateSave.Constants.Tile.padding return max } //MARK: internal class func factoryBoundingTileRange(tileRange:MCreateSaveTileRange) -> MCreateSaveTileRange { let minX:Double = factoryBoundingMin(min:tileRange.minX) let maxX:Double = factoryBoundingMax(max:tileRange.maxX) let minY:Double = factoryBoundingMin(min:tileRange.minY) let maxY:Double = factoryBoundingMax(max:tileRange.maxY) let boundingTileRange:MCreateSaveTileRange = MCreateSaveTileRange( tileSize:tileRange.tileSize, tileMapSize:tileRange.tileMapSize, zoom:tileRange.zoom, minX:minX, maxX:maxX, minY:minY, maxY:maxY) return boundingTileRange } }
mit
c3d227a45d32ef6853a75f25f084aca8
25.543478
95
0.601966
4.522222
false
false
false
false
banxi1988/Staff
Pods/BXiOSUtils/Pod/Classes/UIApplicationExtensions.swift
1
477
// // UIApplicationExtensions.swift // Pods // // Created by Haizhen Lee on 15/12/6. // // import UIKit public extension UIApplication{ public var isActive:Bool{ return applicationState == .Active } public var isInactive:Bool{ return applicationState == .Inactive } public var isBackground:Bool{ return applicationState == .Background } public var rootViewController:UIViewController?{ return keyWindow?.rootViewController } }
mit
3ea3fb426f71b5310ce3c650faecc35a
16.035714
50
0.696017
4.297297
false
false
false
false
blokadaorg/blokada
ios/App/UI/Settings/AccountView.swift
1
3623
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2020 Blocka AB. All rights reserved. // // @author Karol Gusak // import SwiftUI struct AccountView: View { @ObservedObject var vm = ViewModels.account @ObservedObject var contentVM = ViewModels.content @State var showChangeAccount = false @State var showDevices = false @State var id = "••••••" var body: some View { Form { Section(header: Text(L10n.accountSectionHeaderGeneral)) { Button(action: { if self.id == "••••••" { self.vm.authenticate { id in self.id = id } } }) { HStack { Text(L10n.accountLabelId) .foregroundColor(Color.cPrimary) Spacer() Text(self.id) .foregroundColor(Color.secondary) } } .contextMenu { Button(action: { self.vm.authenticate { id in self.vm.copyAccountIdToClipboard() } }) { Text(L10n.universalActionCopy) Image(systemName: Image.fCopy) } } } if self.vm.active { Section(header: Text(L10n.accountSectionHeaderSubscription)) { HStack { Text(L10n.accountLabelType) Spacer() Text(self.vm.type.toString()).foregroundColor(.secondary) } HStack { Text(L10n.accountLabelActiveUntil) Spacer() Text(self.vm.activeUntil).foregroundColor(.secondary) } if self.vm.active { Button(action: { self.contentVM.openLink(Link.ManageSubscriptions) }) { Text(L10n.accountActionManageSubscription) } } else { Button(action: { self.contentVM.showSheet(.Payment) }) { L10n.universalActionUpgrade.toBlokadaPlusText() } } } } Section(header: Text(L10n.universalLabelHelp)) { HStack { Text(L10n.accountActionWhyUpgrade) Spacer() Button(action: { self.contentVM.openLink(Link.WhyVpn) }) { Image(systemName: Image.fInfo) .imageScale(.large) .foregroundColor(Color.cAccent) .frame(width: 32, height: 32) } } } } .navigationBarTitle(L10n.accountActionMyAccount) .accentColor(Color.cAccent) } } struct AccountView_Previews: PreviewProvider { static var previews: some View { AccountView() } }
mpl-2.0
780180f2db88edd4fc96e78d8feb1987
32.314815
81
0.426348
5.346211
false
false
false
false
iOS-mamu/SS
P/Pods/PSOperations/PSOperations/UserNotificationCondition.swift
1
4378
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if os(iOS) import UIKit /** A condition for verifying that we can present alerts to the user via `UILocalNotification` and/or remote notifications. */ @available(*, deprecated, message: "use Capability(UserNotification(...)) instead") public struct UserNotificationCondition: OperationCondition { public enum Behavior { /// Merge the new `UIUserNotificationSettings` with the `currentUserNotificationSettings`. case merge /// Replace the `currentUserNotificationSettings` with the new `UIUserNotificationSettings`. case replace } public static let name = "UserNotification" static let currentSettings = "CurrentUserNotificationSettings" static let desiredSettings = "DesiredUserNotificationSettigns" public static let isMutuallyExclusive = false let settings: UIUserNotificationSettings let application: UIApplication let behavior: Behavior /** The designated initializer. - parameter settings: The `UIUserNotificationSettings` you wish to be registered. - parameter application: The `UIApplication` on which the `settings` should be registered. - parameter behavior: The way in which the `settings` should be applied to the `application`. By default, this value is `.Merge`, which means that the `settings` will be combined with the existing settings on the `application`. You may also specify `.Replace`, which means the `settings` will overwrite the exisiting settings. */ public init(settings: UIUserNotificationSettings, application: UIApplication, behavior: Behavior = .merge) { self.settings = settings self.application = application self.behavior = behavior } public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? { return UserNotificationPermissionOperation(settings: settings, application: application, behavior: behavior) } public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) { let result: OperationConditionResult let current = application.currentUserNotificationSettings switch (current, settings) { case (let current?, let settings) where current.contains(settings): result = .satisfied default: let error = NSError(code: .conditionFailed, userInfo: [ OperationConditionKey: type(of: self).name, type(of: self).currentSettings: current ?? NSNull(), type(of: self).desiredSettings: settings ]) result = .failed(error) } completion(result) } } /** A private `Operation` subclass to register a `UIUserNotificationSettings` object with a `UIApplication`, prompting the user for permission if necessary. */ private class UserNotificationPermissionOperation: Operation { let settings: UIUserNotificationSettings let application: UIApplication let behavior: UserNotificationCondition.Behavior init(settings: UIUserNotificationSettings, application: UIApplication, behavior: UserNotificationCondition.Behavior) { self.settings = settings self.application = application self.behavior = behavior super.init() addCondition(AlertPresentation()) } override func execute() { DispatchQueue.main.async { let current = self.application.currentUserNotificationSettings let settingsToRegister: UIUserNotificationSettings switch (current, self.behavior) { case (let currentSettings?, .merge): settingsToRegister = currentSettings.settingsByMerging(self.settings) default: settingsToRegister = self.settings } self.application.registerUserNotificationSettings(settingsToRegister) } } } #endif
mit
6a4edef67471b157fa028ca94e7627ff
34.290323
122
0.663391
5.913514
false
false
false
false
OpenSourceContributions/SwiftOCR
framework/SwiftOCR/GPUImage2-master/framework/Source/Mac/PictureOutput.swift
4
5610
import OpenGL.GL3 import Cocoa public enum PictureFileFormat { case png case jpeg } public class PictureOutput: ImageConsumer { public var encodedImageAvailableCallback:((Data) -> ())? public var encodedImageFormat:PictureFileFormat = .png public var imageAvailableCallback:((NSImage) -> ())? public var onlyCaptureNextFrame:Bool = true public let sources = SourceContainer() public let maximumInputs:UInt = 1 var url:URL! public init() { } deinit { } public func saveNextFrameToURL(_ url:URL, format:PictureFileFormat) { onlyCaptureNextFrame = true encodedImageFormat = format self.url = url // Create an intentional short-term retain cycle to prevent deallocation before next frame is captured encodedImageAvailableCallback = {imageData in do { // FIXME: Xcode 8 beta 2 try imageData.write(to: self.url, options:.atomic) // try imageData.write(to: self.url, options:NSData.WritingOptions.dataWritingAtomic) } catch { // TODO: Handle this better print("WARNING: Couldn't save image with error:\(error)") } } } // TODO: Replace with texture caches and a safer capture routine func cgImageFromFramebuffer(_ framebuffer:Framebuffer) -> CGImage { let renderFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:framebuffer.orientation, size:framebuffer.size) renderFramebuffer.lock() renderFramebuffer.activateFramebufferForRendering() clearFramebufferWithColor(Color.transparent) // Need the blending here to enable non-1.0 alpha on output image glBlendEquation(GLenum(GL_FUNC_ADD)) glBlendFunc(GLenum(GL_ONE), GLenum(GL_ONE)) glEnable(GLenum(GL_BLEND)) renderQuadWithShader(sharedImageProcessingContext.passthroughShader, uniformSettings:ShaderUniformSettings(), vertices:standardImageVertices, inputTextures:[framebuffer.texturePropertiesForOutputRotation(.noRotation)]) glDisable(GLenum(GL_BLEND)) framebuffer.unlock() let imageByteSize = Int(framebuffer.size.width * framebuffer.size.height * 4) let data = UnsafeMutablePointer<UInt8>.allocate(capacity:imageByteSize) glReadPixels(0, 0, framebuffer.size.width, framebuffer.size.height, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data) renderFramebuffer.unlock() guard let dataProvider = CGDataProvider(dataInfo: nil, data: data, size: imageByteSize, releaseData: dataProviderReleaseCallback) else {fatalError("Could not create CGDataProvider")} let defaultRGBColorSpace = CGColorSpaceCreateDeviceRGB() return CGImage(width: Int(framebuffer.size.width), height: Int(framebuffer.size.height), bitsPerComponent:8, bitsPerPixel:32, bytesPerRow:4 * Int(framebuffer.size.width), space:defaultRGBColorSpace, bitmapInfo:CGBitmapInfo() /*| CGImageAlphaInfo.Last*/, provider:dataProvider, decode:nil, shouldInterpolate:false, intent:.defaultIntent)! } public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) { if let imageCallback = imageAvailableCallback { let cgImageFromBytes = cgImageFromFramebuffer(framebuffer) let image = NSImage(cgImage:cgImageFromBytes, size:NSZeroSize) imageCallback(image) if onlyCaptureNextFrame { imageAvailableCallback = nil } } if let imageCallback = encodedImageAvailableCallback { let cgImageFromBytes = cgImageFromFramebuffer(framebuffer) let bitmapRepresentation = NSBitmapImageRep(cgImage:cgImageFromBytes) let imageData:Data switch encodedImageFormat { case .png: imageData = bitmapRepresentation.representation(using: .PNG, properties: ["":""])! case .jpeg: imageData = bitmapRepresentation.representation(using: .JPEG, properties: ["":""])! } imageCallback(imageData) if onlyCaptureNextFrame { encodedImageAvailableCallback = nil } } } } public extension ImageSource { public func saveNextFrameToURL(_ url:URL, format:PictureFileFormat) { let pictureOutput = PictureOutput() pictureOutput.saveNextFrameToURL(url, format:format) self --> pictureOutput } } public extension NSImage { public func filterWithOperation<T:ImageProcessingOperation>(_ operation:T) -> NSImage { return filterWithPipeline{input, output in input --> operation --> output } } public func filterWithPipeline(_ pipeline:(PictureInput, PictureOutput) -> ()) -> NSImage { let picture = PictureInput(image:self) var outputImage:NSImage? let pictureOutput = PictureOutput() pictureOutput.onlyCaptureNextFrame = true pictureOutput.imageAvailableCallback = {image in outputImage = image } pipeline(picture, pictureOutput) picture.processImage(synchronously:true) return outputImage! } } // Why are these flipped in the callback definition? func dataProviderReleaseCallback(_ context:UnsafeMutableRawPointer?, data:UnsafeRawPointer, size:Int) { // UnsafeMutablePointer<UInt8>(data).deallocate(capacity:size) // FIXME: Verify this is correct data.deallocate(bytes:size, alignedTo:1) }
apache-2.0
feee0ecbb406744b949a2c5ee9627ab7
41.180451
345
0.680214
5.223464
false
false
false
false
RobinFalko/Ubergang
Ubergang/Ease/Elastic.swift
1
2593
// // Elastic.swift // Ubergang // // Created by Robin Frielingsdorf on 10/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation open class Elastic: Easing, CurveEasing { /** Elastic ease in. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeIn(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t if t == 0 { return b } t = t / d if t == 1 { return b+c } let p = d * 0.3 let a = c let s = p / 4 t = t - 1 let postFix = a * pow(2.0, 10.0 * t) // this is a fix, again, with post-increment operators return -(postFix * sin((t*d-s) * (2 * .pi)/p )) + b } /** Elastic ease out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeOut(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t if t == 0 { return b } t = t / d if t == 1 { return b+c } let p = d * 0.3 let a = c let s = p / 4 return (a * pow(2, -10 * t) * sin( (t*d-s) * (2 * .pi)/p ) + c + b) } /** Elastic ease in out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeInOut(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t if t == 0 { return b } t = t / (d / 2) if t == 2 { return b+c } let p = d * (0.3*1.5) let a = c let s = p / 4 t = t - 1 if (t < 1) { let postFix = a * pow(2.0, 10.0 * t) // postIncrement is evil return -0.5 * (postFix * sin((t*d-s) * (2 * .pi)/p)) + b } let postFix = a * pow(2.0, -10.0 * t) // postIncrement is evil return postFix * sin((t*d-s) * (2 * .pi) / p) * 0.5 + c + b } }
apache-2.0
ba89e6c1e4f4b8bad60edefe8cfb70a7
23.923077
99
0.45216
3.545828
false
false
false
false
aschwaighofer/swift
test/Incremental/Dependencies/private-typealias-fine.swift
2
1091
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // 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: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.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: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps private struct Wrapper { static func test() -> InterestingType { fatalError() } } // CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double public var x = Wrapper.test() + 0 // CHECK-DEPS: topLevel interface '' InterestingType false
apache-2.0
0de3d28dc661789f3891a3183c747406
50.952381
203
0.713107
3.296073
false
true
false
false
ric2b/Vivaldi-browser
thirdparty/macsparkle/generate_appcast/URL+Hashing.swift
1
1530
// // URL+Hashing.swift // generate_appcast // // Created by Nate Weaver on 2020-05-01. // Copyright © 2020 Sparkle Project. All rights reserved. // import Foundation import CommonCrypto extension FileHandle { /// Calculate the SHA-256 hash of the file referenced by the file handle. /// /// - Returns: The SHA-256 hash of the file (as a hexadecimal string). func sha256String() -> String { // This uses CommonCrypto instead of CryptoKit so it can work on macOS < 10.15 var context = CC_SHA256_CTX() CC_SHA256_Init(&context) while true { let data = self.readData(ofLength: 65_536) guard data.count > 0 else { break } _ = data.withUnsafeBytes { CC_SHA256_Update(&context, $0.baseAddress, numericCast($0.count)) } } let hash = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH)) CC_SHA256_Final(hash.baseAddress, &context) return hash.reduce("") { $0 + String(format: "%02x", $1) } } } extension URL { /// Calculates the SHA-256 hash of the file referened by the URL. /// /// - Returns: The SHA-256 hash of the file (as a hexadecimal string), or `nil` if /// the URL doesn't point to a file. func sha256String() -> String? { guard self.isFileURL else { return nil } guard let filehandle = try? FileHandle(forReadingFrom: self) else { return nil } return filehandle.sha256String() } }
bsd-3-clause
3da60b8ff459450e601bfa7268846b81
27.314815
101
0.618705
3.940722
false
false
false
false
TaimurAyaz/PaginationManager
Source/PaginationManager.swift
1
11940
// // PaginationManager.swift // PaginationManager // // Created by Taimur Ayaz on 2016-09-27. // Copyright © 2016 Taimur Ayaz. All rights reserved. // // MIT License // // Copyright (c) 2016 Taimur Ayaz // // 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 UIKit // Alias for the pagination manager reset block. public typealias PaginationManagerResetBlock = (shouldReset: Bool) -> () /// The pagination manager delegate. public protocol PaginationManagerDelegate: class { /// Tells the conforming object that the pagination manager has exceeded the given threshold. /// /// - parameter manager: The pagination manager. /// - parameter reset: The reset block for the pagination manager. Used to tell the pagination manager to reset its state. func paginationManagerDidExceedThreshold(manager: PaginationManager, reset: PaginationManagerResetBlock) } /// Private enum defining the possible states of the pagination manager. private enum PaginationManagerState { case normal case exceeded } /// The scroll direction for the pagination manager public enum PaginationManagerDirection { case horizontal case vertical } /// The threshold type for the pagination manager public enum PaginationManagerThresholdType { /// Percentage based threshold. /// The `value` argument defines the threshold percentage. case percentage(value: CGFloat) /// Constant value based threshold. This is taken as a constant threshold value from the end of the scrollView. /// The `value` argument defines the threshold constant from the end of the scrollView's content. case constant(value: CGFloat) } public let PaginationManagerConstantThresholdScreenDimension: CGFloat = -1 public class PaginationManager: NSObject, UIScrollViewDelegate { // Weak reference to the pagination manager delegate public weak var delegate: PaginationManagerDelegate? // The threshold type for the pagination manager. public var thresholdType: PaginationManagerThresholdType = .constant(value: PaginationManagerConstantThresholdScreenDimension) // The default direction for the pagination manager. Overridable in the initializer. public private(set) var direction: PaginationManagerDirection = .vertical // The default state of the pagination manager. private var state: PaginationManagerState = .normal // The last offset of the scrollview. Used to make sure that threshold exceeded requests // are not made if the scrollview is scrolled in the opposite direction. private var lastOffset: CGFloat = 0 // Weak reference to the original delegate of the scrollView. private weak var originalDelegate: UIScrollViewDelegate? // Static constant threshold initializer for objective-c interop. With scrollView. public static func constantThresholdManager(forScrollView scrollView: UIScrollView, direction: PaginationManagerDirection, constant: CGFloat) -> PaginationManager { let paginationManager = PaginationManager(scrollView: scrollView, direction: direction, thresholdType: .constant(value: constant)) return paginationManager } // Static constant threshold initializer for objective-c interop. Without scrollView. public static func constantThresholdManager(withDirection direction: PaginationManagerDirection, constant: CGFloat) -> PaginationManager { let paginationManager = PaginationManager(direction: direction, thresholdType: .constant(value: constant)) return paginationManager } // Static percentage threshold initializer for objective-c interop. With scrollView. public static func percentageThresholdManager(forScrollView scrollView: UIScrollView, direction: PaginationManagerDirection, percentage: CGFloat) -> PaginationManager { let paginationManager = PaginationManager(scrollView: scrollView, direction: direction, thresholdType: .percentage(value: percentage)) return paginationManager } // Static percentage threshold initializer for objective-c interop. Without scrollView. public static func percentageThresholdManager(withDirection direction: PaginationManagerDirection, percentage: CGFloat) -> PaginationManager { let paginationManager = PaginationManager(direction: direction, thresholdType: .percentage(value: percentage)) return paginationManager } /// Initializer for the pagination manager. /// /// - parameter scrollView: The scrollView to be associated with the apgination manager /// - parameter direction: The scroll direction of the scrollView. /// - parameter thresholdType: The threshold type for the pagination manager. See `PaginationManagerThresholdType` /// /// - returns: A newly created pagnination manager. public init(scrollView: UIScrollView, direction: PaginationManagerDirection, thresholdType: PaginationManagerThresholdType = .constant(value: PaginationManagerConstantThresholdScreenDimension)) { self.originalDelegate = scrollView.delegate self.direction = direction self.thresholdType = thresholdType super.init() scrollView.delegate = self } /// Initializer for the pagination manager without hooking into the scrollView delegate methods. In this /// case you need to call the manager's `scrollViewDidScroll:` from your scrollView delegate. /// /// - parameter direction: The scroll direction of the scrollView. /// - parameter thresholdType: The threshold type for the pagination manager. See `PaginationManagerThresholdType` /// /// - returns: A newly created pagnination manager. public init(direction: PaginationManagerDirection, thresholdType: PaginationManagerThresholdType = .constant(value: PaginationManagerConstantThresholdScreenDimension)) { self.direction = direction self.thresholdType = thresholdType super.init() } } public extension PaginationManager { // Hook into the scrollview delegate method to compute the percentage scrolled. func scrollViewDidScroll(scrollView: UIScrollView) { originalDelegate?.scrollViewDidScroll?(scrollView) handleScroll(forScrollView: scrollView) } // Pass unsed delegate methods back to the original delegate. override func respondsToSelector(aSelector: Selector) -> Bool { if let delegateResponds = self.originalDelegate?.respondsToSelector(aSelector) where delegateResponds == true { return true } return super.respondsToSelector(aSelector) } override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? { return self.originalDelegate } } private extension PaginationManager { func informDelegateIfPossible() { if state != .exceeded { state = .exceeded delegate?.paginationManagerDidExceedThreshold(self, reset: { [weak self] (shouldReset) in if shouldReset { self?.state = .normal } }) } } func handleScroll(forScrollView scrollView: UIScrollView) { guard judge(shouldProceedForScrollView: scrollView, lastOffset: lastOffset, state: state, direction: direction) == true else { return } let normalizedTuple = normalized(sizeAndOffsetForScrollView: scrollView, direction: direction) judge(managerDidExceedbasedOnOffset: normalizedTuple.offset, size: normalizedTuple.size, thresholdType: thresholdType) lastOffset = direction == .horizontal ? scrollView.contentOffset.x : scrollView.contentOffset.y } } private extension PaginationManager { func judge(managerDidExceedbasedOnOffset offset: CGFloat, size: CGFloat, thresholdType: PaginationManagerThresholdType) { if size > 0 && offset >= 0 { switch thresholdType { case .percentage(let value): let percentageScrolled = offset / size if percentageScrolled > value { informDelegateIfPossible() } break case .constant(let value): let normalizedValue = normalized(constantForConstantThresholdValue: value, direction: direction) let distanceFromBottom = fabs(size - offset) if distanceFromBottom < normalizedValue { informDelegateIfPossible() } break } } } func judge(shouldProceedForScrollView scrollView: UIScrollView, lastOffset: CGFloat, state: PaginationManagerState, direction: PaginationManagerDirection) -> Bool { let directionalOffset = direction == .horizontal ? scrollView.contentOffset.x : scrollView.contentOffset.y guard state == .normal && scrollView.contentSize != CGSizeZero && directionalOffset >= lastOffset else { return false } return true } } private extension PaginationManager { func normalized(constantForConstantThresholdValue value: CGFloat, direction: PaginationManagerDirection) -> CGFloat { var normalizedValue: CGFloat = value >= -1 ? value : 0 if direction == .vertical { normalizedValue = value == PaginationManagerConstantThresholdScreenDimension ? UIScreen.mainScreen().bounds.size.height : value } else { normalizedValue = value == PaginationManagerConstantThresholdScreenDimension ? UIScreen.mainScreen().bounds.size.width : value } return normalizedValue } func normalized(sizeAndOffsetForScrollView scrollView: UIScrollView, direction: PaginationManagerDirection) -> (size: CGFloat, offset: CGFloat) { let scrollViewContentInsets = scrollView.contentInset var scrollViewKeyOffset = scrollView.contentOffset.y var scrollViewKeyDimension = scrollView.frame.size.height var scrollViewContentKeyDimension = scrollView.contentSize.height var normalizedOffset = scrollViewKeyOffset + scrollViewContentInsets.top var normalizedSize = scrollViewContentKeyDimension - (scrollViewKeyDimension - scrollViewContentInsets.top - scrollViewContentInsets.bottom) if direction == .horizontal { scrollViewKeyOffset = scrollView.contentOffset.x scrollViewKeyDimension = scrollView.frame.size.width scrollViewContentKeyDimension = scrollView.contentSize.width normalizedOffset = scrollViewKeyOffset + scrollViewContentInsets.left normalizedSize = scrollViewContentKeyDimension - (scrollViewKeyDimension - scrollViewContentInsets.left - scrollViewContentInsets.right) } return (normalizedSize, normalizedOffset) } }
mit
dd746bcce000a0dae9d23580c8f48fa5
44.919231
199
0.721333
5.375507
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift
33
2783
// // RxScrollViewDelegateProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit /** For more information take a look at `DelegateProxyType`. */ public class RxScrollViewDelegateProxy : DelegateProxy , UIScrollViewDelegate , DelegateProxyType { private var _contentOffsetSubject: ReplaySubject<CGPoint>? /** Typed parent object. */ public weak private(set) var scrollView: UIScrollView? /** Optimized version used for observing content offset changes. */ internal var contentOffsetSubject: Observable<CGPoint> { if _contentOffsetSubject == nil { let replaySubject = ReplaySubject<CGPoint>.create(bufferSize: 1) _contentOffsetSubject = replaySubject replaySubject.on(.Next(self.scrollView?.contentOffset ?? CGPointZero)) } return _contentOffsetSubject! } /** Initializes `RxScrollViewDelegateProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.scrollView = (parentObject as! UIScrollView) super.init(parentObject: parentObject) } // MARK: delegate methods /** For more information take a look at `DelegateProxyType`. */ public func scrollViewDidScroll(scrollView: UIScrollView) { if let contentOffset = _contentOffsetSubject { contentOffset.on(.Next(scrollView.contentOffset)) } self._forwardToDelegate?.scrollViewDidScroll?(scrollView) } // MARK: delegate proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let scrollView = (object as! UIScrollView) return castOrFatalError(scrollView.rx_createDelegateProxy()) } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UIScrollView = castOrFatalError(object) collectionView.delegate = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UIScrollView = castOrFatalError(object) return collectionView.delegate } deinit { if let contentOffset = _contentOffsetSubject { contentOffset.on(.Completed) } } } #endif
mit
9caf421fbd58c4ae6e2541410ed965f8
26.544554
92
0.667505
5.391473
false
false
false
false
dongishan/SayIt-iOS-Machine-Learning-App
Carthage/Checkouts/ios-sdk/Source/PersonalityInsightsV3/PersonalityInsights.swift
1
11407
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** The Watson Personality Insights service uses linguistic analytics to extract a spectrum of cognitive and social characteristics from the text data that a person generates through blogs, tweets, forum posts, and more. */ public class PersonalityInsights { /// The base URL to use when contacting the service. public var serviceURL = "https://gateway.watsonplatform.net/personality-insights/api" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() private let credentials: Credentials private let version: String private let domain = "com.ibm.watson.developer-cloud.PersonalityInsightsV3" /** Create a `PersonalityInsights` object. - parameter username: The username used to authenticate with the service. - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ public init(username: String, password: String, version: String) { credentials = Credentials.basicAuthentication(username: username, password: password) self.version = version } /** If the given data represents an error returned by the Visual Recognition service, then return an NSError with information about the error that occured. Otherwise, return nil. - parameter data: Raw data returned from the service that may represent an error. */ private func dataToError(data: Data) -> NSError? { do { let json = try JSON(data: data) let code = try json.getInt(at: "code") let error = try json.getString(at: "error") let help = try json.getString(at: "help") let userInfo = [ NSLocalizedFailureReasonErrorKey: error, NSLocalizedRecoverySuggestionErrorKey: help ] return NSError(domain: domain, code: code, userInfo: userInfo) } catch { return nil } } /** Analyze text to generate a personality profile. - parameter fromText: The text to analyze. - parameter acceptLanguage: The desired language of the response. - parameter contentLanguage: The language of the text being analyzed. - parameter rawScores: If true, then a raw score for each characteristic is returned in addition to a normalized score. Raw scores are not compared with a sample population. An average Mean Absolute Error (MAE) is returned to measure the results' precision. - parameter consumptionPreferences: If true, then information inferred about consumption preferences is returned in addition to the results. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the personality profile. */ public func getProfile( fromText text: String, acceptLanguage: String? = nil, contentLanguage: String? = nil, rawScores: Bool? = nil, consumptionPreferences: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Profile) -> Void) { guard let content = text.data(using: String.Encoding.utf8) else { let failureReason = "Text could not be encoded to NSData with NSUTF8StringEncoding." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) failure?(error) return } getProfile( fromContent: content, withType: "text/plain", acceptLanguage: acceptLanguage, contentLanguage: contentLanguage, rawScores: rawScores, consumptionPreferences: consumptionPreferences, failure: failure, success: success ) } /** Analyze the text of a webpage to generate a personality profile. The HTML tags are stripped before the text is analyzed. - parameter fromHTML: The HTML text to analyze. - parameter acceptLanguage: The desired language of the response. - parameter contentLanguage: The language of the text being analyzed. - parameter rawScores: If true, then a raw score for each characteristic is returned in addition to a normalized score. Raw scores are not compared with a sample population. An average Mean Absolute Error (MAE) is returned to measure the results' precision. - parameter consumptionPreferences: If true, then information inferred about consumption preferences is returned in addition to the results. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the personality profile. */ public func getProfile( fromHTML html: String, acceptLanguage: String? = nil, contentLanguage: String? = nil, rawScores: Bool? = nil, consumptionPreferences: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Profile) -> Void) { guard let content = html.data(using: String.Encoding.utf8) else { let failureReason = "HTML could not be encoded to NSData with NSUTF8StringEncoding." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) failure?(error) return } getProfile( fromContent: content, withType: "text/html", acceptLanguage: acceptLanguage, contentLanguage: contentLanguage, rawScores: rawScores, consumptionPreferences: consumptionPreferences, failure: failure, success: success ) } /** Analyze input content items to generate a personality profile. - parameter fromContentItems: The content items to analyze. - parameter acceptLanguage: The desired language of the response. - parameter contentLanguage: The language of the text being analyzed. - parameter rawScores: If true, then a raw score for each characteristic is returned in addition to a normalized score. Raw scores are not compared with a sample population. An average Mean Absolute Error (MAE) is returned to measure the results' precision. - parameter consumptionPreferences: If true, then information inferred about consumption preferences is returned in addition to the results. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the personality profile. */ public func getProfile( fromContentItems contentItems: [ContentItem], acceptLanguage: String? = nil, contentLanguage: String? = nil, rawScores: Bool? = nil, consumptionPreferences: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Profile) -> Void) { let json = JSON(dictionary: ["contentItems": contentItems.map { $0.toJSONObject() }]) guard let content = try? json.serialize() else { let failureReason = "Content items could not be serialized to JSON." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) failure?(error) return } getProfile( fromContent: content, withType: "application/json", acceptLanguage: acceptLanguage, contentLanguage: contentLanguage, rawScores: rawScores, consumptionPreferences: consumptionPreferences, failure: failure, success: success ) } /** Analyze content to generate a personality profile. - parameter fromContent: The content to analyze. - parameter withType: The MIME content-type of the content. - parameter acceptLanguage: The desired language of the response. - parameter contentLanguage: The language of the text being analyzed. - parameter rawScores: If true, then a raw score for each characteristic is returned in addition to a normalized score. Raw scores are not compared with a sample population. An average Mean Absolute Error (MAE) is returned to measure the results' precision. - parameter consumptionPreferences: If true, then information inferred about consumption preferences is returned in addition to the results. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the personality profile. */ private func getProfile( fromContent content: Data?, withType contentType: String, acceptLanguage: String? = nil, contentLanguage: String? = nil, rawScores: Bool? = nil, consumptionPreferences: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Profile) -> Void) { // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let rawScores = rawScores { queryParameters.append(URLQueryItem(name: "raw_scores", value: "\(rawScores)")) } if let consumptionPreferences = consumptionPreferences { queryParameters.append(URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")) } // construct header parameters var headerParameters = defaultHeaders if let acceptLanguage = acceptLanguage { headerParameters["Accept-Language"] = acceptLanguage } if let contentLanguage = contentLanguage { headerParameters["Content-Language"] = contentLanguage } // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v3/profile", credentials: credentials, headerParameters: headerParameters, acceptType: "application/json", contentType: contentType, queryItems: queryParameters, messageBody: content ) // execute REST request request.responseObject(dataToError: dataToError) { (response: RestResponse<Profile>) in switch response.result { case .success(let profile): success(profile) case .failure(let error): failure?(error) } } } }
gpl-3.0
426c94f5c4e66eca05dd77ed450ea9dd
41.563433
117
0.658894
5.177939
false
false
false
false
yinnieryou/DesignPattern
Principle/LiskovSubstitutionPrinciple.playground/contents.swift
1
2238
// Playground - noun: a place where people can play import UIKit /* 里氏替换原则 Liskov Substitution Principle (LSP) 定义1:如果对每一个类型为 T1的对象 O1,都有类型为 T2 的对象O2,使得以 T1定义的所有程序 P 在所有的对象 O1 都代换成 O2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。 定义2:所有引用基类的地方必须能透明地使用其子类的对象。 问题由来:有一功能P1,由类A完成。现需要将功能P1进行扩展,扩展后的功能为P,其中P由原有功能P1与新功能P2组成。新功能P由类A的子类B来完成,则子类B在完成新功能P2的同时,有可能会导致原有功能P1发生故障。 解决方案:当使用继承时,遵循里氏替换原则。类B继承类A时,除添加新的方法完成新增功能P2外,尽量不要重写父类A的方法,也尽量不要重载父类A的方法。 里氏替换原则通俗的来讲就是:子类可以扩展父类的功能,但不能改变父类原有的功能. 包含四层含义: 1.子类可以实现父类的抽象方法,但不能覆盖父类的非抽象方法。 2.子类中可以增加自己特有的方法。 3.当子类的方法重载父类的方法时,方法的前置条件(即方法的形参)要比父类方法的输入参数更宽松。 4.当子类的方法实现父类的抽象方法时,方法的后置条件(即方法的返回值)要比父类更严格。 */ class A { func func1(a:Int,b:Int) -> Int{ return a - b } } class B: A { //在对func1覆写的时候没有考虑原本的父类的作用 override func func1(a: Int, b: Int) -> Int { return a + b } func func2(a:Int,b:Int) -> Int { return func1(a, b: b) + 100 } } class Client { init(){ var a = A() println("100-50=\(a.func1(100, b: 50))") println("100-80=\(a.func1(100, b: 80))") var b = B() //显然,func1被破坏了 println("100-50=\(b.func1(100, b: 50))") println("100-80=\(b.func1(100, b: 80))") println("100+20+100=\(b.func2(100, b: 20))") } } var client = Client()
mit
27c345e9c9d4f1eaf355b8faa67e5da9
25.44
113
0.633132
2.1152
false
false
false
false
ylovesy/CodeFun
wuzhentao/intersect.swift
1
640
class Solution { func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { var map :[Int:Int] = [:] var result:[Int] = [] for i in nums1 { if let count = map[i] { map[i] = count + 1 } else { map[i] = 1 } } for i in nums2 { if let count = map[i]{ if count > 0 { result.append(i) map[i] = count - 1 } } } return result } } let s = Solution() s.intersect([1], [1,1])
apache-2.0
e47d87cb8df16783d76cde622d20f3a5
20.333333
61
0.321875
4.129032
false
false
false
false
mathcamp/Carlos
Tests/ConditionedCacheTests.swift
1
9745
import Foundation import Quick import Nimble import Carlos import PiedPiper struct ConditionedCacheSharedExamplesContext { static let CacheToTest = "cache" static let InternalCache = "internalCache" } class ConditionedCacheSharedExamplesConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("a conditioned fetch closure") { (sharedExampleContext: SharedExampleContext) in var cache: BasicCache<String, Int>! var internalCache: CacheLevelFake<String, Int>! beforeEach { cache = sharedExampleContext()[ConditionedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> internalCache = sharedExampleContext()[ConditionedCacheSharedExamplesContext.InternalCache] as? CacheLevelFake<String, Int> } context("when calling get") { let value = 221 var fakeRequest: Promise<Int>! var successSentinel: Bool? var successValue: Int? var failureSentinel: Bool? var failureValue: ErrorType? var cancelSentinel: Bool? beforeEach { failureSentinel = nil failureValue = nil successSentinel = nil successValue = nil cancelSentinel = nil fakeRequest = Promise<Int>() internalCache.cacheRequestToReturn = fakeRequest.future } context("when the condition is satisfied") { let key = "this key works" beforeEach { cache.get(key).onSuccess { success in successSentinel = true successValue = value }.onFailure { error in failureValue = error failureSentinel = true }.onCancel { cancelSentinel = true } } it("should forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledGet).to(equal(1)) } it("should pass the right key") { expect(internalCache.didGetKey).to(equal(key)) } context("when the request succeeds") { beforeEach { fakeRequest.succeed(value) } it("should call the original closure") { expect(successSentinel).notTo(beNil()) } it("should pass the right value") { expect(successValue).to(equal(value)) } it("should not call the cancel closure") { expect(cancelSentinel).to(beNil()) } it("should not call the failure closure") { expect(failureSentinel).to(beNil()) } } context("when the request is canceled") { beforeEach { fakeRequest.cancel() } it("should call the original closure") { expect(cancelSentinel).to(beTrue()) } it("should not call the success closure") { expect(successSentinel).to(beNil()) } it("should not call the failure closure") { expect(failureSentinel).to(beNil()) } } context("when the request fails") { let errorCode = TestError.SimpleError beforeEach { fakeRequest.fail(errorCode) } it("should call the original closure") { expect(failureSentinel).notTo(beNil()) } it("should pass the right error") { expect(failureValue as? TestError).to(equal(errorCode)) } it("should not call the cancel closure") { expect(cancelSentinel).to(beNil()) } it("should not call the success closure") { expect(successSentinel).to(beNil()) } } } context("when the condition is not satisfied") { let key = ":(" beforeEach { cache.get(key).onSuccess { success in successSentinel = true successValue = value }.onFailure { error in failureValue = error failureSentinel = true } } it("should not forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledGet).to(equal(0)) } it("should call the failure closure") { expect(failureSentinel).notTo(beNil()) } it("should pass the provided error") { expect(failureValue as? ConditionError).to(equal(ConditionError.MyError)) } it("should not call the cancel closure") { expect(cancelSentinel).to(beNil()) } it("should not call the success closure") { expect(successSentinel).to(beNil()) } } } } sharedExamples("a conditioned cache") { (sharedExampleContext: SharedExampleContext) in var cache: BasicCache<String, Int>! var internalCache: CacheLevelFake<String, Int>! beforeEach { cache = sharedExampleContext()[ConditionedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> internalCache = sharedExampleContext()[ConditionedCacheSharedExamplesContext.InternalCache] as? CacheLevelFake<String, Int> } itBehavesLike("a conditioned fetch closure") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache, ] } context("when calling set") { let key = "test-key" let value = 201 beforeEach { cache.set(value, forKey: key) } it("should forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledSet).to(equal(1)) } it("should pass the right key") { expect(internalCache.didSetKey).to(equal(key)) } it("should pass the right value") { expect(internalCache.didSetValue).to(equal(value)) } } context("when calling clear") { beforeEach { cache.clear() } it("should forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledClear).to(equal(1)) } } context("when calling onMemoryWarning") { beforeEach { cache.onMemoryWarning() } it("should forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledOnMemoryWarning).to(equal(1)) } } } } } private enum ConditionError: ErrorType { case MyError case AnotherError } class ConditionedCacheTests: QuickSpec { override func spec() { var cache: BasicCache<String, Int>! var internalCache: CacheLevelFake<String, Int>! let closure: (String -> Future<Bool>) = { key in if key.characters.count >= 5 { return Future(true) } else { return Future(ConditionError.MyError) } } describe("The conditioned instance function, applied to a cache level") { beforeEach { internalCache = CacheLevelFake<String, Int>() cache = internalCache.conditioned(closure) } itBehavesLike("a conditioned cache") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache ] } } describe("The conditioned function, applied to a cache level") { beforeEach { internalCache = CacheLevelFake<String, Int>() cache = conditioned(internalCache, condition: closure) } itBehavesLike("a conditioned cache") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache ] } } describe("The conditioned cache operator, applied to a cache level") { beforeEach { internalCache = CacheLevelFake<String, Int>() cache = closure <?> internalCache } itBehavesLike("a conditioned cache") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache ] } } describe("The conditioned function, applied to a fetch closure") { beforeEach { internalCache = CacheLevelFake<String, Int>() cache = conditioned(internalCache.get, condition: closure) } itBehavesLike("a conditioned fetch closure") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache ] } } describe("The conditioned cache operator, applied to a fetch closure") { beforeEach { internalCache = CacheLevelFake<String, Int>() cache = closure <?> internalCache.get } itBehavesLike("a conditioned fetch closure") { [ ConditionedCacheSharedExamplesContext.CacheToTest: cache, ConditionedCacheSharedExamplesContext.InternalCache: internalCache ] } } } }
mit
56591d03908085fd8dcd7b00d070ae86
30.038217
131
0.568189
5.549544
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Foundation/Date+Extension.swift
1
6516
// // Date+Extension.swift // Pods // // Created by 王小涛 on 2017/7/12. // // import Foundation fileprivate struct TimeStamp { static let secondInMinute: TimeInterval = 60 static let secondsInHour: TimeInterval = 60 * secondInMinute static let secondsInDay: TimeInterval = 24 * secondsInHour static let secondsInWeek: TimeInterval = 7 * secondsInDay } extension Date { private var allComponents: Set<Calendar.Component> { return [ .era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone ] } fileprivate var calendar: Calendar { return Calendar.current } fileprivate var dateComponents: DateComponents { return calendar.dateComponents(allComponents, from: self) } private init(era: Int?, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int, on calendar: Calendar) { let now = Date() var dateComponents = calendar.dateComponents([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond], from: now) dateComponents.era = era dateComponents.year = year dateComponents.month = month dateComponents.day = day dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = second dateComponents.nanosecond = nanosecond let date = calendar.date(from: dateComponents)! self = Date(timeInterval: 0, since: date) } public init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int = 0) { self.init(era: nil, year: year, month: month, day: day, hour: hour, minute: minute, second: second, nanosecond: nanosecond, on: .current) } public init(year: Int, month: Int, day: Int) { self.init(year: year, month: month, day: day, hour: 0, minute: 0, second: 0) } } extension Date { public var year: Int { return dateComponents.year! } public var month: Int { return dateComponents.month! } public var day: Int { return dateComponents.day! } public var hour: Int { return dateComponents.hour! } public var minute: Int { return dateComponents.minute! } public var second: Int { return dateComponents.second! } public var nanosecond: Int { return dateComponents.nanosecond! } public var weekday: Int { return dateComponents.weekday! } public var weekOfMonth: Int { return dateComponents.weekOfMonth! } public var weekOfYear: Int { return dateComponents.weekOfYear! } } extension Date { public var isToday: Bool { return calendar.isDateInToday(self) } public var isYesterday: Bool { return calendar.isDateInYesterday(self) } public var isTomorrow: Bool { return calendar.isDateInTomorrow(self) } public var isWeekend: Bool { return calendar.isDateInWeekend(self) } public var isThisMonth: Bool { return isInSameMonthAs(Date()) } public var isThisYear: Bool { return isInSameYearAs(Date()) } public var start: Date { return calendar.startOfDay(for: self) } } extension Date { public func isInSameYearAs(_ date: Date) -> Bool { return calendar.compare(self, to: date, toGranularity: .year) == .orderedSame } public func isInSameMonthAs(_ date: Date) -> Bool { return calendar.compare(self, to: date, toGranularity: .month) == .orderedSame } public func isInSameDayAs(_ date: Date) -> Bool { return calendar.compare(self, to: date, toGranularity: .day) == .orderedSame // return calendar.isDate(base, inSameDayAs: date) } public func isAfterDateIgnoringTime(date: Date) -> Bool { return calendar.compare(self, to: date, toGranularity: .day) == .orderedDescending } public func isBeforeDateIgoringTime(date: Date) -> Bool { return calendar.compare(self, to: date, toGranularity: .day) == .orderedAscending } } extension Date { public func days(toDate date: Date) -> Int { let components = calendar.dateComponents([.day], from: self, to: date) return components.day ?? 0 } public func days(fromDate date: Date) -> Int { let components = calendar.dateComponents([.day], from: date, to: self) return components.day ?? 0 } } extension Date { public func changed(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, nanosecond: Int? = nil) -> Date? { var dateComponents = self.dateComponents dateComponents.year = year ?? self.year dateComponents.month = month ?? self.month dateComponents.day = day ?? self.day dateComponents.hour = hour ?? self.hour dateComponents.minute = minute ?? self.minute dateComponents.second = second ?? self.second dateComponents.nanosecond = nanosecond ?? self.nanosecond return calendar.date(from: dateComponents) } } extension Date { public func addingDays(_ days: Int) -> Date { return calendar.date(byAdding: DateComponents(day: days), to: self)! } public func addingMonths(_ months: Int) -> Date { return calendar.date(byAdding: DateComponents(month: months), to: self)! } public func addingYears(_ years: Int) -> Date { return calendar.date(byAdding: DateComponents(year: years), to: self)! } } extension Date { public static func days(inYear year: Int, month: Int) -> Int { let calendar = Calendar.current var startComps = DateComponents() startComps.day = 1 startComps.month = month startComps.year = year var endComps = DateComponents() endComps.day = 1 endComps.month = month == 12 ? 1 : month + 1 endComps.year = month == 12 ? year + 1 : year let startDate = calendar.date(from: startComps)! let endDate = calendar.date(from: endComps)! let diff = calendar.dateComponents([.day], from: startDate, to: endDate) return diff.day! } }
mit
0899b26b4a7f2efa555fcd1e2d0465f8
28.192825
181
0.616283
4.369128
false
false
false
false