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
AlexChekanov/Gestalt
Gestalt/SupportingClasses/General classes Extensions/UISearchBar+fontAndColor.swift
1
503
import UIKit extension UISearchBar { func change(textFont : UIFont?, textColor: UIColor?, textFieldColor : UIColor) { for view : UIView in (self.subviews[0]).subviews { if let textField = view as? UITextField { textField.backgroundColor = textFieldColor if textFont != nil { textField.font = textFont } if textColor != nil { textField.textColor = textColor } } } } }
apache-2.0
c45799564d603047cbd4c85b9a4c9b4b
30.4375
84
0.540755
5.588889
false
false
false
false
stripe/stripe-ios
Tests/Tests/STPPaymentCardTextFieldTestsSwift.swift
1
2351
// // STPPaymentCardTextFieldTestsSwift.swift // StripeiOS Tests // // Created by Cameron Sabol on 8/24/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class STPPaymentCardTextFieldTestsSwift: XCTestCase { func testClearMaintainsPostalCodeEntryEnabled() { let textField = STPPaymentCardTextField() let postalCodeEntryDefaultEnabled = textField.postalCodeEntryEnabled textField.clear() XCTAssertEqual( postalCodeEntryDefaultEnabled, textField.postalCodeEntryEnabled, "clear overrode default postalCodeEntryEnabled value" ) // -- textField.postalCodeEntryEnabled = false textField.clear() XCTAssertFalse( textField.postalCodeEntryEnabled, "clear overrode custom postalCodeEntryEnabled false value" ) // -- textField.postalCodeEntryEnabled = true // The ORs in this test are to handle if these tests are run in an environment // where the locale doesn't require postal codes, in which case the calculated // value for postalCodeEntryEnabled can be different than the value set // (this is a legacy API). let stillTrueOrRequestedButNoPostal = textField.postalCodeEntryEnabled || (textField.viewModel.postalCodeRequested && STPPostalCodeValidator.postalCodeIsRequired( forCountryCode: textField.viewModel.postalCodeCountryCode )) XCTAssertTrue( stillTrueOrRequestedButNoPostal, "clear overrode custom postalCodeEntryEnabled true value" ) } func testPostalCodeIsValidWhenExpirationIsNot() { let cardTextField = STPPaymentCardTextField() // Old expiration date cardTextField.expirationField.text = "10/10" XCTAssertFalse(cardTextField.expirationField.validText) cardTextField.postalCode = "10001" cardTextField.formTextFieldTextDidChange(cardTextField.postalCodeField) XCTAssertTrue(cardTextField.postalCodeField.validText) } }
mit
4f656bab83634b6cdfaafc2d99e0fd25
34.074627
86
0.689787
5.465116
false
true
false
false
nghialv/Mockingjay
Mockingjay/Matchers.swift
2
1438
// // Matchers.swift // Mockingjay // // Created by Kyle Fuller on 28/02/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation import URITemplate // Collection of generic matchers /// Mockingjay matcher which returns true for every request public func everything(request:NSURLRequest) -> Bool { return true } /// Mockingjay matcher which matches URIs public func uri(uri:String)(request:NSURLRequest) -> Bool { let template = URITemplate(template:uri) if let URLString = request.URL?.absoluteString { if template.extract(URLString) != nil { return true } } if let path = request.URL?.path { if template.extract(path) != nil { return true } } return false } public enum HTTPMethod : Printable { case GET case POST case PATCH case PUT case DELETE case OPTIONS case HEAD public var description : String { switch self { case .GET: return "GET" case .POST: return "POST" case .PATCH: return "PATCH" case .PUT: return "PUT" case .DELETE: return "DELETE" case .OPTIONS: return "OPTIONS" case .HEAD: return "HEAD" } } } public func http(method:HTTPMethod, uri:String)(request:NSURLRequest) -> Bool { if let requestMethod = request.HTTPMethod { if requestMethod == method.description { return Mockingjay.uri(uri)(request: request) } } return false }
bsd-3-clause
3ebc942e64ce71519303f68d02e38d19
18.173333
79
0.654381
3.994444
false
false
false
false
hollyschilling/EssentialElements
EssentialElements/EssentialElements/Interface/Views/BorderedView.swift
1
3151
// // BorderedView.swift // EssentialElements // // Created by Holly Schilling on 6/24/16. // Copyright © 2016 Better Practice Solutions. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @IBDesignable open class BorderedView: UIView { //MARK: - Inspectable Properties @IBInspectable open var cornerRadius : CGFloat = 5 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable open var borderWidth : CGFloat = 2 { didSet { layer.borderWidth = borderWidth } } @IBInspectable open var borderColor : UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } @IBInspectable open var shadowOffset : CGSize = CGSize(width: 0, height: 3) { didSet { layer.shadowOffset = shadowOffset } } @IBInspectable open var shadowRadius : CGFloat = 3 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable open var shadowOpacity : Float = 0.3 { didSet { layer.shadowOpacity = shadowOpacity } } @IBInspectable open var shadowColor : UIColor? { didSet { layer.shadowColor = shadowColor?.cgColor } } //MARK: - Lifecycle public override init(frame: CGRect) { super.init(frame: frame) applyStyle() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) applyStyle() } open override func prepareForInterfaceBuilder() { applyStyle() } fileprivate func applyStyle() { layer.masksToBounds = false layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor?.cgColor layer.shadowOffset = shadowOffset layer.shadowRadius = shadowRadius layer.shadowOpacity = shadowOpacity layer.shadowColor = shadowColor?.cgColor } }
mit
0ef7444ed04d2479c1c665d43652c478
27.636364
81
0.640952
5.007949
false
false
false
false
saeta/penguin
Sources/PenguinGraphs/PredecessorRecorder.swift
1
5067
// Copyright 2020 Penguin Authors // // 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 PenguinStructures /// A table that records the parents of every discovered vertex in a graph search algorithm. /// /// Example: /// /// ``` /// var g = makeAdjacencyList() /// let predecessors = TablePredecessorRecorder(for: g) /// g.breadthFirstSearch(startingAt: g.vertices.first!) { e, g in /// predecessors.record(e, graph: g) /// } /// ``` public struct TablePredecessorRecorder<Graph: IncidenceGraph> where Graph.VertexId: IdIndexable { /// A table of the predecessor for a vertex, organized by `Graph.VertexId.index`. public private(set) var predecessors: [Graph.VertexId?] /// Creates a PredecessorVisitor for use on graph `Graph` with `vertexCount` verticies. public init(vertexCount: Int) { predecessors = Array(repeating: nil, count: vertexCount) } /// Returns the sequence of vertices on the recorded path to `vertex`. public func path(to vertex: Graph.VertexId) -> ReversedCollection<[Graph.VertexId]>? { guard var i = predecessors[vertex.index] else { return nil } var reversePath = [vertex, i] while let next = predecessors[i.index] { reversePath.append(next) i = next } return reversePath.reversed() } } extension TablePredecessorRecorder where Graph: VertexListGraph { /// Creates a `PredecessorVisitor` for use on `graph`. /// /// Note: use this initializer to avoid spelling out the types, as this initializer helps along /// type inference nicely. public init(for graph: Graph) { self.init(vertexCount: graph.vertexCount) } } extension TablePredecessorRecorder { /// Captures predecessor information during depth first search. public mutating func record(_ event: DFSEvent<Graph>, graph: Graph) { if case .treeEdge(let edge) = event { predecessors[graph.destination(of: edge).index] = graph.source(of: edge) } } /// Captures predecessor information during Dijkstra's search. public mutating func record(_ event: DijkstraSearchEvent<Graph>, graph: Graph) { if case .edgeRelaxed(let edge) = event { predecessors[graph.destination(of: edge).index] = graph.source(of: edge) } } /// Captures predecessor information during breadth first search. public mutating func record(_ event: BFSEvent<Graph>, graph: Graph) { if case .treeEdge(let edge) = event { predecessors[graph.destination(of: edge).index] = graph.source(of: edge) } } } /// A dictionary that records the parents of every discovered vertex in a graph search algorithm. /// /// Example: /// /// ``` /// var g = CompleteInfiniteGrid() /// let preds = DictionaryPredecessorRecorder(for: g) /// g.breadthFirstSearch(startingAt: .origin) { e, g in preds.record(e, graph: g) } /// ``` /// public struct DictionaryPredecessorRecorder<Graph: IncidenceGraph>: DefaultInitializable where Graph.VertexId: Hashable { /// A dictionary of the predecessor for a vertex. public private(set) var predecessors: [Graph.VertexId: Graph.VertexId] /// Creates an empty predecessor recorder. public init() { self.predecessors = .init() } /// Creates an empty predecessor recorder (uses `graph` for type inference). public init(for graph: Graph) { self.init() } public subscript(vertex: Graph.VertexId) -> Graph.VertexId? { predecessors[vertex] } /// Captures predecessor information during depth first search. public mutating func record(_ event: DFSEvent<Graph>, graph: Graph) { if case .treeEdge(let edge) = event { predecessors[graph.destination(of: edge)] = graph.source(of: edge) } } /// Captures predecessor information during Dijkstra's search. public mutating func record(_ event: DijkstraSearchEvent<Graph>, graph: Graph) { if case .edgeRelaxed(let edge) = event { predecessors[graph.destination(of: edge)] = graph.source(of: edge) } } /// Captures predecessor information during breadth first search. public mutating func record(_ event: BFSEvent<Graph>, graph: Graph) { if case .treeEdge(let edge) = event { predecessors[graph.destination(of: edge)] = graph.source(of: edge) } } /// Returns the sequence of vertices on the recorded path to `vertex`. public func path(to vertex: Graph.VertexId) -> ReversedCollection<[Graph.VertexId]>? { guard var i = predecessors[vertex] else { return nil } var reversePath = [vertex, i] while let next = predecessors[i] { reversePath.append(next) i = next } return reversePath.reversed() } }
apache-2.0
de23d5fe087f129a3b24d59b05f04453
34.683099
97
0.703967
4.073151
false
false
false
false
mgireesh05/leetcode
LeetCodeSwiftPlayground.playground/Sources/populating-next-right-pointers-in-each-node.swift
1
2148
/** * Solution to the problem: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ and https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii */ //Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground. public class Solution116_and_117 { public init(){ } var dict = [Int: TreeLinkNode?]() public func connect(_ root: TreeLinkNode?) { dict[1] = nil deepConnect(root, depth: 1) } func deepConnect(_ root: TreeLinkNode?, depth: Int){ if(root == nil){ return } if(root?.right != nil){ deepConnect(root?.right, depth: depth + 1) } if(dict[depth] == nil) { root?.next = nil }else{ root?.next = dict[depth]! } dict[depth] = root if(root?.left != nil){ deepConnect(root?.left, depth: depth + 1) } } public func printLinks(_ root: TreeLinkNode?) { if(root == nil){ return } print("\(root?.val ?? 0)->\(root?.next?.val ?? 0)") if(root?.left != nil) { printLinks(root?.left) } if(root?.right != nil) { printLinks(root?.right) } } } //Swift is not available for this problem on OJ. So tested with Java. /* import java.util.HashMap; public class Solution { HashMap<Integer, TreeLinkNode> map = new HashMap<Integer, TreeLinkNode>(); public void connect(TreeLinkNode root) { map.put(1, null); deepConnect(root, 1); } void deepConnect(TreeLinkNode root, Integer depth){ if(root == null){ return; } if(root.right != null){ deepConnect(root.right, depth + 1); } if(map.get(depth) == null) { root.next = null; }else{ root.next = map.get(depth); } map.put(depth, root); if(root.left != null){ deepConnect(root.left, depth + 1); } } public void printLinks(TreeLinkNode root) { if(root == null){ return; } if(root.next != null) { System.out.println(root.val + "->" + root.next.val); }else{ System.out.println(root.val + "->" + "NULL"); } if(root.left != null) { printLinks(root.left); } if(root.right != null) { printLinks(root.right); } } } */
mit
79bee74af0a23d09a47495bd0363cd80
17.842105
182
0.623371
2.84127
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/UITextFieldExtensions.swift
1
1323
// // UITextFieldExtensions.swift // DNSwiftProject // // Created by mainone on 16/12/20. // Copyright © 2016年 wjn. All rights reserved. // import UIKit extension UITextField { // 添加文本左侧间隔大小 public func addLeftTextPadding(_ blankSize: CGFloat) { let leftView = UIView() leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height) self.leftView = leftView self.leftViewMode = UITextFieldViewMode.always } // 在文本框左侧添加图标 public func addLeftIcon(_ image: UIImage?, frame: CGRect, imageSize: CGSize) { let leftView = UIView() leftView.frame = frame let imgView = UIImageView() imgView.frame = CGRect(x: frame.width - 8 - imageSize.width, y: (frame.height - imageSize.height) / 2, width: imageSize.width, height: imageSize.height) imgView.image = image leftView.addSubview(imgView) self.leftView = leftView self.leftViewMode = UITextFieldViewMode.always } // 设置提示语文字颜色 public func setPlaceHolderTextColor(_ color: UIColor) { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: color]) } }
apache-2.0
ec6ed2a8db2be3d4c0b7848e7bb7a821
32.210526
164
0.662441
4.321918
false
false
false
false
DanielSmith1239/KosherSwift
KosherSwift/Categories/Foundation/nscalendar/NSCalendar_Juncture.swift
1
1479
// // Created by Daniel Smith on 3/9/16. // Copyright (c) 2016 Dani Smith. All rights reserved. // import Foundation extension NSCalendar { public func firstDayOfTheWeek() -> NSDate { return firstDayOfTheWeekUsingReferenceDate(NSDate()) } public func firstDayOfTheWeekUsingReferenceDate(date: NSDate) -> NSDate { let weekday: Int = weekdayInDate(date) - 1 return dateBySubtractingDays(weekday, fromDate: date) } public func lastDayOfTheWeek() -> NSDate { return lastDayOfTheWeekUsingReferenceDate(NSDate()) } public func lastDayOfTheWeekUsingReferenceDate(date: NSDate) -> NSDate { let d: NSDate = firstDayOfTheWeekUsingReferenceDate(date) let daysPerWeek: Int = daysPerWeekUsingReferenceDate(d) return dateByAddingDays(daysPerWeek - 1, toDate: d) } public func firstDayOfTheMonth() -> NSDate { return firstDayOfTheMonthUsingReferenceDate(NSDate()) } public func firstDayOfTheMonthUsingReferenceDate(date: NSDate) -> NSDate { let c: NSDateComponents = components([.Month, .Year], fromDate: date) c.day = 1 return dateFromComponents(c)! } public func lastDayOfTheMonth() -> NSDate { return firstDayOfTheMonthUsingReferenceDate(NSDate()) } public func lastDayOfTheMonthUsingReferenceDate(date: NSDate) -> NSDate { let c: NSDateComponents = components([.Year, .Month], fromDate: date) c.day = daysPerMonthUsingReferenceDate(date) return dateFromComponents(c)! } }
lgpl-3.0
2ac211ce034b8304579422cfa48e7d4d
25.428571
74
0.726842
4.07438
false
false
false
false
tndatacommons/Compass-iOS
Compass/src/Controller/SettingsController.swift
1
4977
// // SettingsController.swift // Compass // // Created by Ismael Alonso on 7/13/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit import Just import Locksmith class SettingsController: UITableViewController{ @IBOutlet weak var userName: UILabel! @IBOutlet weak var dailyNotificationLimit: UILabel! @IBOutlet weak var versionName: UILabel! var selectedLimit: Int = SharedData.user.getDailyNotificationLimit(); override func viewDidLoad(){ userName.text = SharedData.user.getFullName(); dailyNotificationLimit.text = "\(SharedData.user.getDailyNotificationLimit())"; let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String; versionName.text = version; } override func viewDidAppear(animated: Bool){ if (selectedLimit != SharedData.user.getDailyNotificationLimit()){ SharedData.user.setDailyNotificationLimit(selectedLimit); dailyNotificationLimit.text = "\(selectedLimit)"; Just.put(API.getPutUserProfileUrl(SharedData.user), headers: SharedData.user.getHeaderMap(), json: API.getPutUserProfileBody(SharedData.user)){ (response) in print(response.statusCode); } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ if (indexPath.section == 0){ print("General"); if (indexPath.row == 0){ if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString){ CompassUtil.openUrl(appSettings); } tableView.deselectRowAtIndexPath(indexPath, animated: true); } else if (indexPath.row == 1){ let recipient = "[email protected]"; let subject = "Compass Feedback"; let string = "mailto:?to=\(recipient)&subject=\(subject)"; let set = NSCharacterSet.URLQueryAllowedCharacterSet(); let encodedString = string.stringByAddingPercentEncodingWithAllowedCharacters(set)!; print("before"); let url = NSURL(string: encodedString)!; print("after"); CompassUtil.openUrl(url); tableView.deselectRowAtIndexPath(indexPath, animated: true); } else if (indexPath.row == 2){ do{ //Send the logout request let defaults = NSUserDefaults.standardUserDefaults(); let token = defaults.objectForKey("APNsToken") as? String; if (token != nil){ Just.post(API.getLogOutUrl(), headers: SharedData.user.getHeaderMap(), json: API.getLogOutBody(token!)); } //Remove the user info try Locksmith.deleteDataForUserAccount("CompassAccount"); DefaultsManager.emptyNewAwardsRecords(); TourManager.reset(); NotificationUtil.logOut(); //Back to the login screen let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil); let viewController = mainStoryboard.instantiateViewControllerWithIdentifier("LauncherNavController"); UIApplication.sharedApplication().keyWindow?.rootViewController = viewController; } catch{ } } } else if (indexPath.section == 1){ print("Notifications"); if (indexPath.row == 0){ performSegueWithIdentifier("PickerFromSettings", sender: self); } } else if (indexPath.section == 2){ print("About"); if (indexPath.row == 0){ CompassUtil.openUrl(NSURL(string: "https://app.tndata.org/terms/")!); tableView.deselectRowAtIndexPath(indexPath, animated: true); } else if (indexPath.row == 1){ CompassUtil.openUrl(NSURL(string: "https://app.tndata.org/privacy/")!); tableView.deselectRowAtIndexPath(indexPath, animated: true); } else if (indexPath.row == 2){ performSegueWithIdentifier("ShowSources", sender: self); } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ segue.destinationViewController.hidesBottomBarWhenPushed = true; if (segue.identifier == "PickerFromSettings"){ let pickerController = segue.destinationViewController as! PickerController; pickerController.delegate = self; } } }
mit
016947c58658e9848362134c9feb20dd
41.529915
121
0.575563
5.759259
false
false
false
false
scotlandyard/expocity
expocity/View/Chat/Display/VChatDisplay.swift
1
6483
import UIKit class VChatDisplay:UIView { weak var controller:CChat! weak var marks:VChatDisplayMarks! weak var imageView:UIImageView! weak var layoutHeight:NSLayoutConstraint! weak var layoutBorderHeight:NSLayoutConstraint! let maxHeight:CGFloat let kMinHeight:CGFloat = 3 private let kMaxHeightPercent:CGFloat = 0.8 private let kBorderHeight:CGFloat = 1 private let kAnimationDuration:TimeInterval = 0.3 init(controller:CChat) { let screenSize:CGSize = UIScreen.main.bounds.size let smallerSize:CGFloat if screenSize.width > screenSize.height { smallerSize = screenSize.height } else { smallerSize = screenSize.width } maxHeight = smallerSize * kMaxHeightPercent super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.collectionBackground() self.controller = controller let border:UIView = UIView() border.isUserInteractionEnabled = false border.translatesAutoresizingMaskIntoConstraints = false border.backgroundColor = UIColor.black let imageView:UIImageView = UIImageView() imageView.contentMode = controller.model.displayOption.contentMode imageView.clipsToBounds = true imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView let marks:VChatDisplayMarks = VChatDisplayMarks(controller:controller) self.marks = marks addSubview(border) addSubview(imageView) addSubview(marks) let views:[String:UIView] = [ "border":border, "imageView":imageView, "marks":marks] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[border]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[imageView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[marks]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[border]-0-[imageView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[border]-0-[marks]-0-|", options:[], metrics:metrics, views:views)) layoutBorderHeight = NSLayoutConstraint( item:border, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:0) addConstraint(layoutBorderHeight) NotificationCenter.default.addObserver( self, selector:#selector(notifiedDisplayOptionChanged(sender:)), name:Notification.Notifications.chatDisplayOptionChanged.Value, object:nil) } required init?(coder:NSCoder) { fatalError() } deinit { NotificationCenter.default.removeObserver(self) } override func layoutSubviews() { layoutImage() super.layoutSubviews() } //MARK: notified func notifiedDisplayOptionChanged(sender notification:Notification) { DispatchQueue.main.async { [weak self] in self?.updateDisplayOption() } } //MARK: private private func updateDisplayOption() { imageView.contentMode = controller.model.displayOption.contentMode } private func layoutImage() { var animate:Bool = false let newHeight:CGFloat let newBorderHeight:CGFloat if imageView.image == nil { newHeight = kMinHeight newBorderHeight = 0 } else { let screenSize:CGSize = UIScreen.main.bounds.size let screenWidth:CGFloat = screenSize.width let screenHeight:CGFloat = screenSize.height if screenWidth < screenHeight { newHeight = maxHeight newBorderHeight = kBorderHeight } else { newHeight = 0 newBorderHeight = 0 } } if newHeight != layoutHeight.constant { animate = true } if animate { if newBorderHeight == 0 { layoutBorderHeight.constant = newBorderHeight layoutHeight.constant = newHeight } else { layoutHeight.constant = newHeight layoutBorderHeight.constant = newBorderHeight } UIView.animate(withDuration:kAnimationDuration, animations: { [weak self] in self?.superview?.layoutIfNeeded() }) { [weak self] (done) in if self != nil { if newHeight == self!.maxHeight { self!.controller.viewChat.conversation.scrollToBottom() } } } } } //MARK: public func displayImage(image:UIImage?) { imageView.image = image controller.viewChat.input.updateStandbyMenu() layoutImage() marks.addItems() } func removeImage() { imageView.image = nil controller.viewChat.input.updateStandbyMenu() layoutImage() } func displayAnnotations() { marks.isHidden = true } func hideAnnotations() { marks.isHidden = false } }
mit
387e40c8696fb8272b21836bebcc26b2
26.705128
79
0.550362
5.931382
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/StyleChoiceView.swift
1
6101
// // StyleChoiceView.swift // Feature Demo // // Created by Aare Undo on 19/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit import CartoMobileSDK class StyleChoiceView : MapBaseView { var languageButton: PopupButton! var baseMapButton: PopupButton! var mapOptionsButton: PopupButton! var languageContent: LanguagePopupContent! var baseMapContent: StylePopupContent! var mapOptionsContent: MapOptionsPopupContent! var currentLanguage: String = "" var currentSource: String = "carto.streets" var currentLayer: NTTileLayer! var buildings3D: Bool = false var texts3D: Bool = true var pois: Bool = false convenience init() { self.init(frame: CGRect.zero) initialize() currentLayer = addBaseLayer() languageButton = PopupButton(imageUrl: "icon_language.png") baseMapButton = PopupButton(imageUrl: "icon_basemap.png") mapOptionsButton = PopupButton(imageUrl: "icon_switches.png") addButton(button: languageButton) addButton(button: baseMapButton) addButton(button: mapOptionsButton) infoContent.setText(headerText: Texts.basemapInfoHeader, contentText: Texts.basemapInfoContainer) languageContent = LanguagePopupContent() baseMapContent = StylePopupContent() baseMapContent.highlightDefault() mapOptionsContent = MapOptionsPopupContent() } override func addRecognizers() { super.addRecognizers() var recognizer = UITapGestureRecognizer(target: self, action: #selector(self.languageButtonTapped(_:))) languageButton.addGestureRecognizer(recognizer) recognizer = UITapGestureRecognizer(target: self, action: #selector(self.baseMapButtonTapped(_:))) baseMapButton.addGestureRecognizer(recognizer) recognizer = UITapGestureRecognizer(target: self, action: #selector(self.mapOptionsButtonTapped(_:))) mapOptionsButton.addGestureRecognizer(recognizer) } override func removeRecognizers() { super.removeRecognizers() languageButton.gestureRecognizers?.forEach(languageButton.removeGestureRecognizer) baseMapButton.gestureRecognizers?.forEach(baseMapButton.removeGestureRecognizer) mapOptionsButton.gestureRecognizers?.forEach(mapOptionsButton.removeGestureRecognizer) } @objc func languageButtonTapped(_ sender: UITapGestureRecognizer) { if (languageButton.isEnabled) { popup.setContent(content: languageContent) popup.popup.header.setText(text: "SELECT A LANGUAGE") popup.show() } } @objc func baseMapButtonTapped(_ sender: UITapGestureRecognizer) { popup.setContent(content: baseMapContent) popup.popup.header.setText(text: "SELECT A BASEMAP") popup.show() } @objc func mapOptionsButtonTapped(_ sender: UITapGestureRecognizer) { popup.setContent(content: mapOptionsContent) popup.popup.header.setText(text: "CONFIGURE RENDERING") popup.show() } func updateMapLanguage(language: String) { currentLanguage = language let decoder = (currentLayer as? NTVectorTileLayer)?.getTileDecoder() as? NTMBVectorTileDecoder decoder?.setStyleParameter("lang", value: currentLanguage) } func updateBaseLayer(selection: String, source: String) { if (source == StylePopupContent.CartoVectorSource) { if (selection == StylePopupContent.Positron) { currentLayer = NTCartoOnlineVectorTileLayer(style: .CARTO_BASEMAP_STYLE_POSITRON) } else if (selection == StylePopupContent.DarkMatter) { currentLayer = NTCartoOnlineVectorTileLayer(style: .CARTO_BASEMAP_STYLE_DARKMATTER) } else if (selection == StylePopupContent.Voyager) { currentLayer = NTCartoOnlineVectorTileLayer(style: .CARTO_BASEMAP_STYLE_VOYAGER) } } else if (source == StylePopupContent.CartoRasterSource) { if (selection == StylePopupContent.HereSatelliteDaySource) { currentLayer = NTCartoOnlineRasterTileLayer(source: "here.satellite.day@2x") } else if (selection == StylePopupContent.HereNormalDaySource) { currentLayer = NTCartoOnlineRasterTileLayer(source: "here.normal.day@2x") } } if (source == StylePopupContent.CartoRasterSource) { languageButton.disable() } else { languageButton.enable() } map.getLayers().clear() map.getLayers().add(currentLayer) updateMapLanguage(language: currentLanguage) updateMapOption(option: "buildings3d", value: buildings3D) updateMapOption(option: "texts3d", value: texts3D) updateMapOption(option: "pois", value: pois) } func updateMapOption(option:String!, value:Bool) { if (option == "globe") { map.getOptions()?.setRenderProjectionMode(value ? NTRenderProjectionMode.RENDER_PROJECTION_MODE_SPHERICAL : NTRenderProjectionMode.RENDER_PROJECTION_MODE_PLANAR) return } let decoder = (currentLayer as? NTVectorTileLayer)?.getTileDecoder() as? NTMBVectorTileDecoder if (option == "buildings3d") { buildings3D = value decoder?.setStyleParameter("buildings", value: value ? "2" : "1") } if (option == "texts3d") { texts3D = value decoder?.setStyleParameter("texts3d", value: value ? "1" : "0") } if (option == "pois") { pois = value let cartoLayer = currentLayer as? NTCartoVectorTileLayer cartoLayer?.setPOIRenderMode(value ? NTCartoBaseMapPOIRenderMode.CARTO_BASEMAP_POI_RENDER_MODE_FULL : NTCartoBaseMapPOIRenderMode.CARTO_BASEMAP_POI_RENDER_MODE_NONE) } } }
bsd-2-clause
ba701d1c29a284dd7207d8804ebc1156
37.125
177
0.656557
4.559043
false
false
false
false
4np/UitzendingGemist
UitzendingGemist/EpisodeViewController.swift
1
18658
// // EpisodeViewController.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 16/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import UIKit import NPOKit import CocoaLumberjack import AVKit import UIColor_Hex_Swift class EpisodeViewController: UIViewController, NPOPlayerViewControllerDelegate { @IBOutlet weak private var backgroundImageView: UIImageView! @IBOutlet weak private var episodeImageView: UIImageView! @IBOutlet weak private var programNameLabel: UILabel! @IBOutlet weak private var episodeNameLabel: UILabel! @IBOutlet weak private var dateLabel: UILabel! @IBOutlet weak private var durationLabel: UILabel! @IBOutlet weak private var descriptionLabel: UILabel! @IBOutlet weak private var genreTitleLabel: UILabel! @IBOutlet weak private var genreLabel: UILabel! @IBOutlet weak private var broadcasterTitleLabel: UILabel! @IBOutlet weak private var broadcasterLabel: UILabel! @IBOutlet weak private var warningLabel: UILabel! @IBOutlet weak private var playButton: UIButton! @IBOutlet weak private var playLabel: UILabel! @IBOutlet weak private var toProgramButton: UIButton! @IBOutlet weak private var toProgramLabel: UILabel! @IBOutlet weak private var markAsWatchedButton: UIButton! @IBOutlet weak private var markAsWatchedLabel: UILabel! @IBOutlet weak private var favoriteButton: UIButton! @IBOutlet weak private var favoriteLabel: UILabel! @IBOutlet weak private var stillCollectionView: UICollectionView! private var tip: NPOTip? private var episode: NPOEpisode? private var program: NPOProgram? private var needLayout = false { didSet { if needLayout { layout() } } } // MARK: Calculated Properties private var programName: String? { if let program = self.program, let name = program.name, !name.isEmpty { return name } else if let program = episode?.program, let name = program.name, !name.isEmpty { return name } else if let name = tip?.name, !name.isEmpty { return name } else if let episode = self.episode, let name = episode.name, !name.isEmpty { return name } return nil } private var episodeName: String? { var episodeName = "" if let episode = self.episode, let name = episode.name, !name.isEmpty { episodeName = name } else if let name = tip?.name, !name.isEmpty { episodeName = name } else { episodeName = String.unknownEpisodeName } guard let programName = self.programName else { return episodeName } // replace program name episodeName = episodeName.replacingOccurrences(of: programName, with: "", options: .caseInsensitive, range: nil) // remove garbage from beginning of name if let regex = try? NSRegularExpression(pattern: "^([^a-z0-9]+)", options: .caseInsensitive) { let range = NSRange(0..<episodeName.utf16.count) episodeName = regex.stringByReplacingMatches(in: episodeName, options: .withTransparentBounds, range: range, withTemplate: "") } // got a name? if episodeName.characters.count == 0 { episodeName = programName } // capitalize episodeName = episodeName.capitalized // add watched indicator if let watchedIndicator = episode?.watchedIndicator { episodeName = watchedIndicator + episodeName } return episodeName } private var broadcastDisplayValue: String? { if let value = episode?.broadcastedDisplayValue { return value } else if let value = tip?.publishedDisplayValue { return value } return nil } private var episodeDescription: String? { if let description = tip?.description { return description } else if let description = episode?.description { return description } return nil } private var genres: String? { guard let genres = episode?.genres, genres.count > 0 else { return nil } return genres.map({ $0.rawValue }).joined(separator: "\n") } private var broadcasters: String? { guard let broadcasters = episode?.broadcasters, broadcasters.count > 0 else { return nil } return broadcasters.map({ $0.rawValue }).joined(separator: "\n") } // MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // clear out values backgroundImageView.image = nil episodeImageView.image = nil programNameLabel.text = nil episodeNameLabel.text = nil dateLabel.text = nil durationLabel.text = nil descriptionLabel.text = nil genreTitleLabel.text = nil genreLabel.text = nil broadcasterTitleLabel.text = nil broadcasterLabel.text = nil warningLabel.text = nil playButton.isEnabled = true playLabel.isEnabled = true playLabel.text = nil toProgramButton.isEnabled = true toProgramLabel.isEnabled = true toProgramLabel.text = nil markAsWatchedButton.isEnabled = true markAsWatchedLabel.isEnabled = true markAsWatchedLabel.text = nil favoriteButton.isEnabled = false favoriteLabel.isEnabled = false favoriteLabel.text = nil } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // layout view layout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateWatchedButtonAndLabel() } // MARK: Configuration func configure(withTip tip: NPOTip) { self.tip = tip configure(withEpisode: tip.episode) } func configure(withEpisode episode: NPOEpisode?) { self.episode = episode getDetails(forEpisode: episode) } func configureAndPlay(withEpisode episode: NPOEpisode?) { getDetails(forEpisode: episode) { [weak self] in self?.play() } } // MARK: Networking private func getDetails(forEpisode episode: NPOEpisode?, withCompletion completed: @escaping () -> Void = {}) { guard let episode = episode else { return } // fetch episode details _ = NPOManager.sharedInstance.getDetails(forEpisode: episode) { [weak self] episode, error in guard let episode = episode else { DDLogError("Could not fetch episode details (\(String(describing: error)))") self?.needLayout = true return } // update episode self?.episode = episode self?.getDetails(forProgram: episode.program, withCompletion: completed) } } private func getDetails(forProgram program: NPOProgram?, withCompletion completed: @escaping () -> Void = {}) { guard let program = program else { return } // fetch program details _ = NPOManager.sharedInstance.getDetails(forProgram: program) { [weak self] program, error in guard let program = program else { DDLogError("Could not fetch program details (\(String(describing: error)))") self?.needLayout = true return } // update program self?.program = program self?.needLayout = true completed() } } // MARK: Update UI private func layout() { guard needLayout else { return } // mark that we do not need layout anymore needLayout = false // layout images layoutImages() // layout labels programNameLabel.text = programName episodeNameLabel.text = episodeName dateLabel.text = broadcastDisplayValue?.capitalized durationLabel.text = episode?.duration.timeDisplayValue descriptionLabel.text = episodeDescription?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) genreTitleLabel.text = String.genreText.uppercased() genreLabel.text = genres ?? String.unknownText broadcasterTitleLabel.text = String.broadcasterText.uppercased() broadcasterLabel.text = broadcasters ?? String.unknownText // determine is the episode can be watched let canPlay = episode?.available ?? true if !canPlay { warningLabel.text = String.warningEpisodeUnavailable let isGeoAllowed = episode?.restriction?.isGeoAllowed() ?? true if !isGeoAllowed { if let countryName = NPOManager.sharedInstance.geo?.countryName { warningLabel.text = String.localizedStringWithFormat(String.warningEpisodeUnavailableFromCountry, countryName) } else { warningLabel.text = String.warningEpisodeUnavailableFromLocation } } } playButton.isEnabled = true // canPlay playLabel.isEnabled = true playLabel.text = canPlay ? String.playText : String.playUnavailableText toProgramButton.isEnabled = (program != nil) toProgramLabel.isEnabled = (program != nil) toProgramLabel.text = String.toProgramText markAsWatchedButton.isEnabled = canPlay markAsWatchedLabel.isEnabled = true updateWatchedButtonAndLabel() favoriteButton.isEnabled = (program != nil) favoriteLabel.isEnabled = (program != nil) favoriteLabel.text = String.favoriteText updateFavoriteButtonTitleColor() stillCollectionView.reloadData() } private func updateFavoriteButtonTitleColor() { let color = program?.getUnfocusedColor() ?? UIColor.white let focusColor = program?.getFocusedColor() ?? UIColor.black favoriteButton.setTitleColor(color, for: .normal) favoriteButton.setTitleColor(focusColor, for: .focused) } private func updateWatchedButtonAndLabel() { guard let episode = self.episode else { return } if episode.watched == .unwatched || episode.watched == .partially { markAsWatchedLabel.text = String.markAsWatchedText } else { markAsWatchedLabel.text = String.markAsUnwatchedText } episodeNameLabel.text = episodeName } // MARK: Images private func layoutImages() { if let tip = self.tip { getImage(forTip: tip, andImageView: backgroundImageView) getImage(forTip: tip, andImageView: episodeImageView) } else if let episode = self.episode { getImage(forEpisode: episode, andImageView: backgroundImageView) getImage(forEpisode: episode, andImageView: episodeImageView) } } private func getImage(forTip tip: NPOTip, andImageView imageView: UIImageView) { _ = tip.getImage(ofSize: imageView.frame.size) { [weak self] image, error, _ in guard let image = image else { DDLogError("Could not get image for tip (\(String(describing: error)))") self?.getImage(forEpisode: tip.episode, andImageView: imageView) return } imageView.image = image } } private func getImage(forEpisode episode: NPOEpisode?, andImageView imageView: UIImageView) { guard let episode = episode else { return } _ = episode.getImage(ofSize: imageView.frame.size) { [weak self] image, error, _ in guard let image = image else { DDLogError("Could not get image for episode (\(String(describing: error)))") self?.getImage(forProgram: episode.program, andImageView: imageView) return } imageView.image = image } } private func getImage(forProgram program: NPOProgram?, andImageView imageView: UIImageView) { guard let program = program else { return } _ = program.getImage(ofSize: imageView.frame.size) { image, error, _ in guard let image = image else { DDLogError("Could not get image for program (\(String(describing: error)))") return } imageView.image = image } } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(_ collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return episode?.stills?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCells.still.rawValue, for: indexPath) guard let stillCell = cell as? StillCollectionViewCell, let stills = episode?.stills, indexPath.row >= 0 && indexPath.row < stills.count else { return cell } stillCell.configure(withStill: stills[indexPath.row]) return stillCell } // MARK: Play @IBAction private func didPressPlayButton(_ sender: UIButton) { play() } // MARK: Player private func play() { guard let episode = self.episode else { DDLogError("Could not play episode...") return } // check if this episode has already been watched guard episode.watchDuration > 0 && episode.watched == .partially else { play(beginAt: 0) return } // show alert let alertController = UIAlertController(title: String.continueWatchingTitleText, message: String.continueWatchingMessageText, preferredStyle: .actionSheet) let coninueTitleText = String.localizedStringWithFormat(String.coninueWatchingFromText, episode.watchDuration.timeDisplayValue) let continueAction = UIAlertAction(title: coninueTitleText, style: .default) { [weak self] _ in self?.play(beginAt: episode.watchDuration) } alertController.addAction(continueAction) let fromBeginningAction = UIAlertAction(title: String.watchFromStartText, style: .default) { [weak self] _ in self?.play(beginAt: 0) } alertController.addAction(fromBeginningAction) let cancelAction = UIAlertAction(title: String.cancelText, style: .cancel) { _ in alertController.dismiss(animated: true, completion: nil) } alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } private func play(beginAt begin: Int) { guard let episode = self.episode else { DDLogError("Could not play episode...") return } // show progress hud view.startLoading() // play video stream episode.getVideoStream { [weak self] url, error in self?.view.stopLoading() guard let url = url else { DDLogError("Could not play episode (\(String(describing: error)))") return } self?.play(episode: episode, withVideoStream: url, beginAt: begin) } } private func play(episode: NPOEpisode, withVideoStream url: URL, beginAt seconds: Int) { let playerViewController = NPOPlayerViewController() playerViewController.npoDelegate = self var title = "" if let programName = self.programName { title += programName } if let episodeName = self.episodeName { if title != "" { title += ": " } title += episodeName } let metadata: [String: Any?] = [ AVMetadataCommonKeyTitle: title, AVMetadataCommonKeyDescription: self.episodeDescription, AVMetadataCommonKeyPublisher: self.broadcasters, AVMetadataCommonKeyArtwork: self.episodeImageView.image ] present(playerViewController, animated: true) { playerViewController.play(videoStream: url, subtitles: episode.subtitleURL, beginAt: seconds, externalMetadata: metadata) } } // MARK: NPOPlayerViewControllerDelegate func playerDidFinishPlayback(atSeconds seconds: Int) { episode?.watchDuration = seconds } // MARK: Favorite @IBAction private func didPressFavoriteButton(_ sender: UIButton) { program?.toggleFavorite() updateFavoriteButtonTitleColor() } // MARK: Mark as watched @IBAction private func didPressMarkAsWatchedButton(_ sender: UIButton) { episode?.toggleWatched() updateWatchedButtonAndLabel() } // MARK: Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueIdentifier = segue.identifier else { return } switch segueIdentifier { case Segues.episodeToProgramDetails.rawValue: prepareForSegueToProgramView(segue, sender: sender as AnyObject?) break default: DDLogError("Unhandled segue with identifier '\(segueIdentifier)' in Home view") break } } private func prepareForSegueToProgramView(_ segue: UIStoryboardSegue, sender: AnyObject?) { guard let vc = segue.destination as? ProgramViewController, let program = self.program else { return } vc.configure(withProgram: program) } }
apache-2.0
fb0c8263990ddca1cdd8bcf5a03347fd
33.107861
163
0.607332
5.392197
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/KillmailsPageInteractor.swift
2
1202
// // KillmailsPageInteractor.swift // Neocom // // Created by Artem Shimanski on 11/13/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData class KillmailsPageInteractor: TreeInteractor { typealias Presenter = KillmailsPagePresenter typealias Content = Presenter.View.Input weak var presenter: Presenter? required init(presenter: Presenter) { self.presenter = presenter } var api = Services.api.current func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> { guard let input = presenter?.view?.input else {return .init(.failure(NCError.reloadInProgress))} return .init(input) } func isExpired(_ content: Content) -> Bool { return false } private var didChangeAccountObserver: NotificationObserver? func configure() { didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in self?.api = Services.api.current _ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in self?.presenter?.view?.present(presentation, animated: true) } } } }
lgpl-2.1
4d129d161730abba6860b638cda99cde
26.930233
153
0.74438
3.861736
false
false
false
false
pendowski/PopcornTimeIOS
Popcorn Time/UI/Table View Controllers/SettingsTableViewController.swift
1
11411
import UIKit import SafariServices class SettingsTableViewController: UITableViewController, TablePickerViewDelegate { let ud = NSUserDefaults.standardUserDefaults() var safariViewController: SFSafariViewController! @IBOutlet weak var switchStreamOnCellular: UISwitch! @IBOutlet weak var removeCacheOnPlayerExit: UISwitch! @IBOutlet weak var segmentedQuality: UISegmentedControl! @IBOutlet weak var languageButton: UIButton! @IBOutlet weak var traktSignInButton: UIButton! @IBOutlet weak var openSubsSignInButton: UIButton! var tablePickerView : TablePickerView? let qualities = ["480p", "720p", "1080p"] var state: String! override func viewDidLoad() { super.viewDidLoad() addTablePicker() showSettings() updateSignedInStatus(traktSignInButton, isSignedIn: ud.boolForKey("AuthorizedTrakt")) updateSignedInStatus(openSubsSignInButton, isSignedIn: ud.boolForKey("AuthorizedOpenSubs")) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(safariLogin(_:)), name: safariLoginNotification, object: nil) } func showSettings() { // Set StreamOnCellular switchStreamOnCellular.on = ud.boolForKey("StreamOnCellular") removeCacheOnPlayerExit.on = ud.boolForKey("removeCacheOnPlayerExit") // Set preferred subtitle language if let preferredSubtitleLanguage = ud.objectForKey("PreferredSubtitleLanguage") as? String { if preferredSubtitleLanguage != "None" { tablePickerView?.setSelected([preferredSubtitleLanguage]) languageButton.setTitle(preferredSubtitleLanguage, forState: .Normal) } else { languageButton.setTitle("None", forState: .Normal) } } else { languageButton.setTitle("None", forState: .Normal) } // Set preferred quality let qualityInSettings = ud.objectForKey("PreferredQuality") as? String var selectedQualityIndex = 0 segmentedQuality.removeAllSegments() for (index, quality) in qualities.enumerate() { segmentedQuality.insertSegmentWithTitle(quality, atIndex: index, animated: true) if let qualityInSettings = qualityInSettings { if quality == qualityInSettings { selectedQualityIndex = index } } } segmentedQuality.selectedSegmentIndex = selectedQualityIndex } func updateSignedInStatus(sender: UIButton, isSignedIn: Bool) { sender.setTitle(isSignedIn ? "Sign Out": "Authorize", forState: .Normal) sender.setTitleColor(isSignedIn ? UIColor(red: 230.0/255.0, green: 46.0/255.0, blue: 37.0/255.0, alpha: 1.0) : view.window?.tintColor!, forState: .Normal) } func addTablePicker() { tablePickerView = TablePickerView(superView: self.view, sourceArray: NSLocale.commonLanguages(), self) self.tabBarController?.view.addSubview(tablePickerView!) } func tablePickerView(tablePickerView: TablePickerView, didChange items: [String]) { if items.count > 0 { ud.setObject(items[0], forKey: "PreferredSubtitleLanguage") languageButton.setTitle(items[0], forState: .Normal) } else { ud.setObject("None", forKey: "PreferredSubtitleLanguage") languageButton.setTitle("None", forState: .Normal) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) tablePickerView?.hide() ud.synchronize() } @IBAction func streamOnCellular(sender: UISwitch) { ud.setBool(sender.on, forKey: "StreamOnCellular") } @IBAction func preferredQuality(control: UISegmentedControl) { let resultAsText = control.titleForSegmentAtIndex(control.selectedSegmentIndex) ud.setObject(resultAsText, forKey: "PreferredQuality") } @IBAction func preferredSubtitleLanguage(sender: AnyObject) { tablePickerView?.toggle() } @IBAction func authorizeTraktTV(sender: UIButton) { if ud.boolForKey("AuthorizedTrakt") { let alert = UIAlertController(title: "Sign Out", message: "Are you sure you want to Sign Out?", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Yes", style: .Destructive, handler: { action in OAuthCredential.deleteCredentialWithIdentifier("trakt") self.ud.setBool(false, forKey: "AuthorizedTrakt") self.updateSignedInStatus(sender, isSignedIn: false) })) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } else { state = randomString(length: 15) openUrl("https://trakt.tv/oauth/authorize?client_id=a3b34d7ce9a7f8c1bb216eed6c92b11f125f91ee0e711207e1030e7cdc965e19&redirect_uri=PopcornTime%3A%2F%2Ftrakt&response_type=code&state=\(state)") } } @IBAction func authorizeOpenSubs(sender: UIButton) { if ud.boolForKey("AuthorizedOpenSubs") { let alert = UIAlertController(title: "Sign Out", message: "Are you sure you want to Sign Out?", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Yes", style: .Destructive, handler: { action in let credential = NSURLCredentialStorage.sharedCredentialStorage().credentialsForProtectionSpace(OpenSubtitles.sharedInstance.protectionSpace)!.values.first! NSURLCredentialStorage.sharedCredentialStorage().removeCredential(credential, forProtectionSpace: OpenSubtitles.sharedInstance.protectionSpace) self.ud.setBool(false, forKey: "AuthorizedOpenSubs") self.updateSignedInStatus(sender, isSignedIn: false) })) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Sign In", message: "VIP account required.", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler({ (textField) in textField.placeholder = "Username" }) alert.addTextFieldWithConfigurationHandler({ (textField) in textField.placeholder = "Password" textField.secureTextEntry = true }) alert.addAction(UIAlertAction(title: "Sign In", style: .Default, handler: { (action) in let credential = NSURLCredential(user: alert.textFields![0].text!, password: alert.textFields![1].text!, persistence: .Permanent) NSURLCredentialStorage.sharedCredentialStorage().setCredential(credential, forProtectionSpace: OpenSubtitles.sharedInstance.protectionSpace) OpenSubtitles.sharedInstance.login({ self.ud.setBool(true, forKey: "AuthorizedOpenSubs") self.updateSignedInStatus(sender, isSignedIn: true) }, error: { error in NSURLCredentialStorage.sharedCredentialStorage().removeCredential(credential, forProtectionSpace: OpenSubtitles.sharedInstance.protectionSpace) alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) })) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } @IBAction func showTwitter(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/popcorntimetv")!) } @IBAction func clearCache(sender: UIButton) { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) do { let size = NSFileManager.defaultManager().folderSizeAtPath(downloadsDirectory) try NSFileManager.defaultManager().removeItemAtURL(NSURL(fileURLWithPath: downloadsDirectory)) controller.title = "Success" if size == 0 { controller.message = "Cache was already empty, no disk space was reclamed." } else { controller.message = "Cleaned \(size) bytes." } } catch { controller.title = "Failed" controller.message = "Error cleanining cache." print("Error: \(error)") } presentViewController(controller, animated: true, completion: nil) } @IBAction func removeCacheOnPlayerExit(sender: UISwitch) { ud.setBool(sender.on, forKey: "removeCacheOnPlayerExit") } @IBAction func showWebsite(sender: AnyObject) { openUrl("http://popcorntime.sh") } func openUrl(url : String) { self.safariViewController = SFSafariViewController(URL: NSURL(string: url)!) self.safariViewController.view.tintColor = UIColor(red:0.37, green:0.41, blue:0.91, alpha:1.0) presentViewController(self.safariViewController, animated: true, completion: nil) } func safariLogin(notification: NSNotification) { safariViewController.dismissViewControllerAnimated(true, completion: nil) let url = notification.object as! NSURL let query = url.query!.urlStringValues() let state = query["state"] guard state != self.state else { dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) { do { let credential = try OAuthCredential(URLString: "https://api-v2launch.trakt.tv/oauth/token", code: query["code"]!, redirectURI: "PopcornTime://trakt", clientID: TraktTVAPI.sharedInstance.clientId, clientSecret: TraktTVAPI.sharedInstance.clientSecret, useBasicAuthentication: false) OAuthCredential.storeCredential(credential, identifier: "trakt") asyncMain { self.ud.setBool(true, forKey: "AuthorizedTrakt") self.updateSignedInStatus(self.traktSignInButton, isSignedIn: true) } } catch {} } return } let error = UIAlertController(title: "Error", message: "Uh Oh! It looks like your connection has been compromised. You may be a victim of Cross Site Request Forgery. If you are on a public WiFi network please disconnect immediately and contact the network administrator.", preferredStyle: .Alert) error.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) error.addAction(UIAlertAction(title: "Learn More", style: .Default, handler: { action in UIApplication.sharedApplication().openURL(NSURL(string: "http://www.veracode.com/security/csrf")!) self.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(error, animated: true, completion: nil) } }
gpl-3.0
584f95545491ac9e41979d652a0d0980
49.941964
304
0.661993
4.927029
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/codegen/Sovereignty.swift
1
8059
import Foundation import Alamofire import Futures public extension ESI { var sovereignty: Sovereignty { return Sovereignty(esi: self) } struct Sovereignty { let esi: ESI @discardableResult public func listSovereigntyCampaigns(ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Sovereignty.Campaign]>> { let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/sovereignty/campaigns/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Sovereignty.Campaign]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Sovereignty.Campaign]>) in promise.set(response: response, cached: 5.0) } return promise.future } @discardableResult public func listSovereigntyStructures(ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Sovereignty.Structure]>> { let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/sovereignty/structures/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Sovereignty.Structure]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Sovereignty.Structure]>) in promise.set(response: response, cached: 120.0) } return promise.future } @discardableResult public func listSovereigntyOfSystems(ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Sovereignty.System]>> { let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/sovereignty/map/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Sovereignty.System]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Sovereignty.System]>) in promise.set(response: response, cached: 3600.0) } return promise.future } public struct System: Codable, Hashable { public var allianceID: Int? public var corporationID: Int? public var factionID: Int? public var systemID: Int public init(allianceID: Int?, corporationID: Int?, factionID: Int?, systemID: Int) { self.allianceID = allianceID self.corporationID = corporationID self.factionID = factionID self.systemID = systemID } enum CodingKeys: String, CodingKey, DateFormatted { case allianceID = "alliance_id" case corporationID = "corporation_id" case factionID = "faction_id" case systemID = "system_id" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct Campaign: Codable, Hashable { public enum GetSovereigntyCampaignsEventType: String, Codable, HTTPQueryable { case ihubDefense = "ihub_defense" case stationDefense = "station_defense" case stationFreeport = "station_freeport" case tcuDefense = "tcu_defense" public var httpQuery: String? { return rawValue } } public struct GetSovereigntyCampaignsParticipants: Codable, Hashable { public var allianceID: Int public var score: Float public init(allianceID: Int, score: Float) { self.allianceID = allianceID self.score = score } enum CodingKeys: String, CodingKey, DateFormatted { case allianceID = "alliance_id" case score var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public var attackersScore: Float? public var campaignID: Int public var constellationID: Int public var defenderID: Int? public var defenderScore: Float? public var eventType: Sovereignty.Campaign.GetSovereigntyCampaignsEventType public var participants: [Sovereignty.Campaign.GetSovereigntyCampaignsParticipants]? public var solarSystemID: Int public var startTime: Date public var structureID: Int64 public init(attackersScore: Float?, campaignID: Int, constellationID: Int, defenderID: Int?, defenderScore: Float?, eventType: Sovereignty.Campaign.GetSovereigntyCampaignsEventType, participants: [Sovereignty.Campaign.GetSovereigntyCampaignsParticipants]?, solarSystemID: Int, startTime: Date, structureID: Int64) { self.attackersScore = attackersScore self.campaignID = campaignID self.constellationID = constellationID self.defenderID = defenderID self.defenderScore = defenderScore self.eventType = eventType self.participants = participants self.solarSystemID = solarSystemID self.startTime = startTime self.structureID = structureID } enum CodingKeys: String, CodingKey, DateFormatted { case attackersScore = "attackers_score" case campaignID = "campaign_id" case constellationID = "constellation_id" case defenderID = "defender_id" case defenderScore = "defender_score" case eventType = "event_type" case participants case solarSystemID = "solar_system_id" case startTime = "start_time" case structureID = "structure_id" var dateFormatter: DateFormatter? { switch self { case .startTime: return DateFormatter.esiDateTimeFormatter default: return nil } } } } public struct Structure: Codable, Hashable { public var allianceID: Int public var solarSystemID: Int public var structureID: Int64 public var structureTypeID: Int public var vulnerabilityOccupancyLevel: Float? public var vulnerableEndTime: Date? public var vulnerableStartTime: Date? public init(allianceID: Int, solarSystemID: Int, structureID: Int64, structureTypeID: Int, vulnerabilityOccupancyLevel: Float?, vulnerableEndTime: Date?, vulnerableStartTime: Date?) { self.allianceID = allianceID self.solarSystemID = solarSystemID self.structureID = structureID self.structureTypeID = structureTypeID self.vulnerabilityOccupancyLevel = vulnerabilityOccupancyLevel self.vulnerableEndTime = vulnerableEndTime self.vulnerableStartTime = vulnerableStartTime } enum CodingKeys: String, CodingKey, DateFormatted { case allianceID = "alliance_id" case solarSystemID = "solar_system_id" case structureID = "structure_id" case structureTypeID = "structure_type_id" case vulnerabilityOccupancyLevel = "vulnerability_occupancy_level" case vulnerableEndTime = "vulnerable_end_time" case vulnerableStartTime = "vulnerable_start_time" var dateFormatter: DateFormatter? { switch self { case .vulnerableEndTime: return DateFormatter.esiDateTimeFormatter case .vulnerableStartTime: return DateFormatter.esiDateTimeFormatter default: return nil } } } } } }
mit
1acec6686244e8a6d845cdb95c94f761
30.728346
318
0.703809
3.731019
false
false
false
false
parkera/swift-corelibs-foundation
Tools/GenerateTestFixtures/GenerateTestFixtures/main.swift
1
3405
// This source file is part of the Swift.org open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors /* This tool generates fixtures from Foundation that can be used by TestFoundation to test cross-platform serialization compatibility. It can generate fixtures either from the Foundation that ships with Apple OSes, or from swift-corelibs-foundation, depending on the OS and linkage. usage: GenerateTestFixtures <OUTPUT ROOT> The fixtures will be generated either in <OUTPUT ROOT>/Darwin or <OUTPUT ROOT>/Swift, depending on whether Darwin Foundation or swift-corelibs-foundation produced the fixtures. */ // 1. Get the right Foundation imported. #if os(iOS) || os(watchOS) || os(tvOS) #error("macOS only, please.") #endif #if os(macOS) && NS_GENERATE_FIXTURES_FROM_SWIFT_CORELIBS_FOUNDATION_ON_DARWIN #if canImport(SwiftFoundation) import SwiftFoundation fileprivate let foundationVariant = "Swift" fileprivate let foundationPlatformVersion = swiftVersionString() #else // A better diagnostic message: #error("You specified NS_GENERATE_FIXTURES_FROM_SWIFT_CORELIBS_FOUNDATION_ON_DARWIN, but the SwiftFoundation module isn't available. Make sure you have set up this project to link with the result of the SwiftFoundation target in the swift-corelibs-foundation workspace") #endif #else import Foundation #if os(macOS) fileprivate let foundationVariant = "macOS" fileprivate let foundationPlatformVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion return version.patchVersion == 0 ? "\(version.majorVersion).\(version.minorVersion)" : "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" }() #else fileprivate let foundationVariant = "Swift" fileprivate let foundationPlatformVersion = swiftVersionString() #endif #endif // 2. Figure out the output path and create it if needed. let arguments = ProcessInfo.processInfo.arguments guard arguments.count > 1 else { let name = arguments.first ?? "GenerateTextFixtures" fatalError("usage: \(name) <OUTPUT PATH>\nSee the comments in main.swift for more information.") } let outputRoot = URL(fileURLWithPath: arguments[1], relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath)) let outputDirectory = outputRoot.appendingPathComponent("\(foundationVariant)-\(foundationPlatformVersion)", isDirectory: true) try! FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true, attributes: nil) // 3. Generate the fixtures. // Fixture objects are defined in TestFoundation/FixtureValues.swift, which needs to be compiled into this module. for fixture in Fixtures.all { let outputFile = outputDirectory.appendingPathComponent(fixture.identifier, isDirectory: false).appendingPathExtension("archive") print(" == Archiving fixture: \(fixture.identifier) to \(outputFile.path)") let value = try! fixture.make() let data = try! NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: fixture.supportsSecureCoding) try! data.write(to: outputFile) }
apache-2.0
cdc9dbfb91a46bcbc95ec8b0c2eba1d9
44.4
274
0.760646
4.613821
false
true
false
false
noppoMan/Slimane
Sources/Slimane/Router/Router.swift
1
625
// // Router.swift // Slimane // // Created by Yuki Takei on 2016/10/05. // // struct Router { var routes = [Route]() public func matchedRoute(for request: Request) -> (Route, Request)? { guard let path = request.path else { return nil } //let request = request for route in routes { if route.regexp.matches(path) && request.method == route.method { var request = request request.params = route.params(request) return (route, request) } } return nil } }
mit
3cb1e9c61074714961ed326702d9bc3b
21.321429
77
0.504
4.340278
false
false
false
false
1985apps/PineKit
Pod/Classes/PineConfig.swift
2
2816
// // KamaConfig.swift // KamaUIKit // // Created by Prakash Raman on 13/02/16. // Copyright © 2016 1985. All rights reserved. // import Foundation import UIKit open class PineConfig { // COLORS public struct Color { public static var blue = UIColor(red:0.153, green:0.290, blue:0.380, alpha:1.00) public static var blueLight = UIColor(red:0.345, green:0.702, blue:0.863, alpha:1.00) public static var red = UIColor(red:0.851, green:0.345, blue:0.341, alpha:1.00) public static var cream = UIColor(red:0.765, green:0.796, blue:0.820, alpha:1.00) public static var purple = UIColor(red:0.196, green:0.188, blue:0.369, alpha:1.00) public static var purpleLight = UIColor(red:0.506, green:0.522, blue:0.839, alpha:1.00) public static var grayLight = UIColor(red:0.957, green:0.961, blue:0.969, alpha:1.00) public static var grayExtraLight = UIColor(red:0.953, green:0.957, blue:0.961, alpha:1.00) // NAMED COLORS public static var primary = blue } public struct Size { public static var icon = CGSize(width: 44, height: 44) } open class Font { open static var REGULAR = "HelveticaNeue" open static var BOLD = "HelveticaNeue-Bold" open static var LIGHT = "HelveticaNeue-Light" open static func get(_ type: String = REGULAR, size: CGFloat = 17.0) -> UIFont { return UIFont(name: type, size: size)! } } public struct Button { public static var height: CGFloat = 56 public struct Hollow { public static var height = 44 public static var borderColor = Color.cream } } public struct TextField { public static var height : CGFloat = 50 public static var width : CGFloat = 200 public static var bottomBorderColor = Color.grayLight } public struct Menu { public static var transitionDuration = 0.5 public struct Transition { public static var duration = Menu.transitionDuration public struct Squeeze { public static var by : CGFloat = 80 public static var x : CGFloat = 150 } } } public struct Switch { public static var onTintColor = PineConfig.Color.blueLight } public struct NavigationBar { public static var height: CGFloat = 44 public static var heightWithStatusBar: CGFloat = 20 + NavigationBar.height } public struct Graph { public static var gridLineColor = Color.grayExtraLight } } /* EXTENTION TO THE UIVIEW */ extension UIView { func addSubviews(_ views: [UIView]){ for view in views { self.addSubview(view) } } }
mit
3fcf6afd4a042cc8df6a0a8d91587e1e
24.36036
98
0.612078
4.015692
false
false
false
false
natecook1000/swift
test/IRGen/objc_bridge.swift
2
11042
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation // CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } { // CHECK: i32 24, // CHECK: i32 17, // CHECK: [17 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC11strRealPropSSvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC11strRealPropSSvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC11strFakePropSSvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC11strFakePropSSvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC13nsstrFakePropSo8NSStringCvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC9strResultSSyFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC6strArg1sySS_tFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$S11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasCACycfcTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasCfDTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0), // CHECK: i8* bitcast (void (%3*, i8*, %4*)* @"$S11objc_bridge3BasC9acceptSetyyShyACSo8NSObjectCSH10ObjectiveCg_GFTo" to i8*) // CHECK: } // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{.*}}, i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$S11objc_bridge3BasCfETo" to i8*) // CHECK: } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } { // CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [11 x i8] c"T@?,N,C,Vx\00" // CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]] func getDescription(_ o: NSObject) -> String { return o.description } func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { f.setFoo(s) } // NSString *bar(int); func callBar() -> String { return bar(0) } // void setBar(NSString *s); func callSetBar(_ s: String) { setBar(s) } var NSS : NSString = NSString() // -- NSString methods don't convert 'self' extension NSString { // CHECK: define internal [[OPAQUE:.*]]* @"$SSo8NSStringC11objc_bridgeE13nsstrFakePropABvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr // CHECK: define internal void @"$SSo8NSStringC11objc_bridgeE13nsstrFakePropABvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr @objc var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$SSo8NSStringC11objc_bridgeE11nsstrResultAByFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr @objc func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @"$SSo8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr @objc func nsstrArg(s s: NSString) { } } class Bas : NSObject { // CHECK: define internal [[OPAQUE:.*]]* @"$S11objc_bridge3BasC11strRealPropSSvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @"$S11objc_bridge3BasC11strRealPropSSvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc var strRealProp : String // CHECK: define internal [[OPAQUE:.*]]* @"$S11objc_bridge3BasC11strFakePropSSvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @"$S11objc_bridge3BasC11strFakePropSSvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc var strFakeProp : String { get { return "" } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$S11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @"$S11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc var nsstrRealProp : NSString // CHECK: define hidden swiftcc %TSo8NSStringC* @"$S11objc_bridge3BasC13nsstrFakePropSo8NSStringCvg"(%T11objc_bridge3BasC* swiftself) {{.*}} { // CHECK: define internal void @"$S11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$S11objc_bridge3BasC9strResultSSyFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { @objc func strResult() -> String { return "" } // CHECK: define internal void @"$S11objc_bridge3BasC6strArg1sySS_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc func strArg(s s: String) { } // CHECK: define internal [[OPAQUE:.*]]* @"$S11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { @objc func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @"$S11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { @objc func nsstrArg(s s: NSString) { } override init() { strRealProp = String() nsstrRealProp = NSString() super.init() } deinit { var x = 10 } override var hashValue: Int { return 0 } @objc func acceptSet(_ set: Set<Bas>) { } } func ==(lhs: Bas, rhs: Bas) -> Bool { return true } class OptionalBlockProperty: NSObject { @objc var x: (([AnyObject]) -> [AnyObject])? }
apache-2.0
0e5164d0b25ea3acb573d4d3394547e0
53.394089
146
0.592556
3.140501
false
false
false
false
Jaelene/PhotoBroswer
PhotoBroswer/PhotoBroswer/Layout/Layout.swift
2
917
// // Layout.swift // PhotoBroswer // // Created by 成林 on 15/7/29. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit extension PhotoBroswer{ class Layout: UICollectionViewFlowLayout { override init(){ super.init() /** 配置 */ layoutSetting() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** 配置 */ func layoutSetting(){ let size = UIScreen.mainScreen().bounds.size self.itemSize = size.sizeWithExtraWidth self.minimumInteritemSpacing = 0 self.minimumLineSpacing = 0 self.sectionInset = UIEdgeInsetsZero self.scrollDirection = UICollectionViewScrollDirection.Horizontal } } }
mit
ffab3da1088b7a603a891344ea7e2320
19.409091
77
0.519509
5.245614
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallengesTests/HeapSortTests.swift
1
831
// // HeapSortTests.swift // WhiteBoardCodingChallenges // // Created by William Boles on 27/06/2016. // Copyright © 2016 Boles. All rights reserved. // import XCTest @testable import WhiteBoardCodingChallenges class HeapSortTests: XCTestCase { // MARK: MaxTests func test_maxHeapSortA() { let input = [6,5,1,7,14,9] let expectedOutput = [1,5,6,7,9,14] let actualOutput = HeapSort.maxHeapSort(input: input) XCTAssertEqual(actualOutput, expectedOutput) } // MARK: MinTests func test_minHeapSortA() { let input = [6,5,1,7,14,9] let expectedOutput = [14,9,7,6,5,1] let actualOutput = HeapSort.minHeapSort(input: input) XCTAssertEqual(actualOutput, expectedOutput) } }
mit
0b20593fcf061594ca536d2864e9c1a7
20.842105
61
0.60241
3.933649
false
true
false
false
Zverik/omim
iphone/Maps/UI/Appearance/ThemeManager.swift
1
1873
@objc(MWMThemeManager) final class ThemeManager: NSObject { private static let autoUpdatesInterval: TimeInterval = 30 * 60 // 30 minutes in seconds private static let instance = ThemeManager() private weak var timer: Timer? private override init() { super.init() } private func update(theme: MWMTheme) { let actualTheme: MWMTheme = { theme in let isVehicleRouting = MWMRouter.isRoutingActive() && (MWMRouter().type == .vehicle) switch theme { case .day: fallthrough case .vehicleDay: return isVehicleRouting ? .vehicleDay : .day case .night: fallthrough case .vehicleNight: return isVehicleRouting ? .vehicleNight : .night case .auto: guard isVehicleRouting else { return .day } switch MWMFrameworkHelper.daytime() { case .day: return .vehicleDay case .night: return .vehicleNight } } }(theme) let nightMode = UIColor.isNightMode() let newNightMode: Bool = { theme in switch theme { case .day: fallthrough case .vehicleDay: return false case .night: fallthrough case .vehicleNight: return true case .auto: assert(false); return false } }(actualTheme) MWMFrameworkHelper.setTheme(actualTheme) if nightMode != newNightMode { UIColor.setNightMode(newNightMode) (UIViewController.topViewController() as! MWMController).mwm_refreshUI() } } static func invalidate() { instance.update(theme: MWMSettings.theme()) } static var autoUpdates: Bool { get { return instance.timer != nil } set { if newValue { instance.timer = Timer.scheduledTimer(timeInterval: autoUpdatesInterval, target: self, selector: #selector(invalidate), userInfo: nil, repeats: true) } else { instance.timer?.invalidate() } invalidate() } } }
apache-2.0
70c032f142a3a187632497908bf166fd
28.730159
157
0.657768
4.427896
false
false
false
false
zachmokahn/SUV
Sources/Spec/IO/Sock/AddrInSpec.swift
1
1150
import SUV import Swiftest class AddrInSpec: Spec { let spec = describe("AddrIn") { describe("initialize") { it("passes the pointer and provided host & port to IP4Addr") { var addrinPointer: UnsafeMutablePointer<SockAddrIn> = nil let ip4Addr: IP4Addr = { host, port, pointer in expect(String.fromCString(host)).to.equal("host") expect(port).to.equal(1000) addrinPointer = pointer return 0 } let addrin = AddrIn("host", 1000, uv_ip4_addr: ip4Addr) expect(addrin.pointer).to.equal(addrinPointer) } it("status is .OK if IP4Addr is successful") { let ip4Addr: IP4Addr = { _,_,_ in return 0 } expect(AddrIn("host", 1000, uv_ip4_addr: ip4Addr).status).to.equal(.OK) } it("status is .Fail with code if IP4Addr is not successful") { let code: Int32 = -1 let ip4Addr: IP4Addr = { _,_,_ in return code } expect(AddrIn("host", 1000, uv_ip4_addr: ip4Addr).status).to.equal(.Fail(code)) } } } }
mit
15977589fc5f800174808582e2de30bb
27.75
89
0.546957
3.721683
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/LinkList/RemoveNthFromEnd.swift
1
600
// // RemoveNthFromEnd.swift // LeetCode // // Created by 黄伯驹 on 2020/3/31. // Copyright © 2020 伯驹 黄. All rights reserved. // import Foundation // https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/ func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { let dummy: ListNode? = ListNode(-1) dummy?.next = head var fast = dummy for _ in 0 ... n { fast = fast?.next } var slow = dummy while fast != nil { slow = slow?.next fast = fast?.next } slow?.next = slow?.next?.next return dummy?.next }
mit
6d80b5db122a56ebbc4a11b3aa4672aa
21.576923
69
0.591141
3.335227
false
false
false
false
ayvazj/BrundleflyiOS
Pod/Classes/Model/BtfyAnimation.swift
1
1634
/* * Copyright (c) 2015 James Ayvaz * * 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 struct BtfyAnimation { enum Property { case Opacity case Position case Scale case Rotation } let id: String? let property: Property let delay: Double let duration: Double let keyframes: [BtfyKeyframe] init(id: String?, property: Property, delay: Double, duration: Double, list: [BtfyKeyframe]) { self.id = id self.property = property self.delay = delay self.duration = duration self.keyframes = list } }
mit
64a5eb69fd6c7bcbaab4a019c98b5a29
34.521739
98
0.718482
4.476712
false
false
false
false
barteljan/VISPER
VISPER-Redux/Classes/CombineLatestClosures.swift
1
2080
// // CallbackPipeline.swift // VISPER-Redux // // Created by bartel on 03.08.18. // import Foundation /// a class which can be filled with some closures of type () -> Void, /// it calls an other completion-closure when all closures are called at least once and /// combineLatest was already called from the outside. public class CombineLatestClosures { public typealias PipelineCallback = () -> Void private var callbackWrappers = [ClosureWrapper]() private var allCallbacksAreCalled: PipelineCallback private var started: Bool = false public init(allCallbacksAreCalled:@escaping PipelineCallback){ self.allCallbacksAreCalled = allCallbacksAreCalled } public func chainClosure(callback:@escaping PipelineCallback) -> PipelineCallback { let wrapper = ClosureWrapper { [weak self] in callback() self?.checkAllClosures() } self.callbackWrappers.append(wrapper) return wrapper.callback } public func combineLatest() { self.started = true checkAllClosures() } private func checkAllClosures() { guard self.started == true else { return } var someWasNotCalled: Bool = false for wrapper in self.callbackWrappers { if wrapper.alreadyCalled == false { someWasNotCalled = true break } } if someWasNotCalled == false { self.allCallbacksAreCalled() } } private class ClosureWrapper { internal var callback: PipelineCallback = { } private var realCallBack: (PipelineCallback)? internal var alreadyCalled: Bool = false init(callback: @escaping PipelineCallback ){ self.callback = { [weak self] in self?.realCallBack = callback self?.alreadyCalled = true self?.realCallBack?() } } } }
mit
75fba68a9d9f08015c7753f3329734ef
26.012987
87
0.586538
5.279188
false
false
false
false
dymx101/Gamers
Gamers/Utilities/NSDateExtensions.swift
1
1096
// // NSDateExtensions.swift // Gamers // // Created by 虚空之翼 on 15/7/14. // Copyright (c) 2015年 Freedom. All rights reserved. // import Foundation extension NSDate { func timeAgo() -> String { let currentDate = NSDate() let calendar = NSCalendar.currentCalendar() calendar.timeZone = NSTimeZone(name: "GMT")! let unitFlags: NSCalendarUnit = .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond let dateComponents = calendar.components(unitFlags, fromDate: self, toDate: currentDate, options: NSCalendarOptions.allZeros) // stackoverflow.com/questions/26277626/nslocalizedstring-with-swift-variable if dateComponents.day != 0 { return "\(dateComponents.day)d" } if dateComponents.hour != 0 { return "\(dateComponents.hour)h" } if dateComponents.minute != 0 { return "\(dateComponents.minute)min" } return "\(dateComponents.second)sec" } }
apache-2.0
715ee81a4365f8128ae810af4cb8d520
27.605263
133
0.606814
4.701299
false
false
false
false
svanimpe/around-the-table
Sources/AroundTheTable/Models/Location.swift
1
2102
import BSON /** The location of a user or activity. */ struct Location: Equatable, Codable { /// The coordinates for this location. let coordinates: Coordinates /// The address that corresponds with this location. let address: String /// The city in which this location is located. let city: String /// The country in which this location is located. let country: String } /** Adds `BSON.Primitive` conformance to `Location`. */ extension Location: Primitive { /// A `Location` is stored as a BSON `Document`. var typeIdentifier: Byte { return Document().typeIdentifier } /// This `Location` as a BSON `Document`. var document: Document { return [ "coordinates": coordinates, "address": address, "city": city, "country": country ] } /** Returns this `Location` as a BSON `Document` in binary form. */ func makeBinary() -> Bytes { return document.makeBinary() } /** Decodes a `Location` from a BSON primitive. - Returns: `nil` when the primitive is not a `Document`. - Throws: a `BSONError` when the document does not contain all required properties. */ init?(_ bson: Primitive?) throws { guard let bson = bson as? Document else { return nil } guard let coordinates = try Coordinates(bson["coordinates"]) else { throw log(BSONError.missingField(name: "coordinates")) } guard let address = String(bson["address"]) else { throw log(BSONError.missingField(name: "address")) } guard let city = String(bson["city"]) else { throw log(BSONError.missingField(name: "city")) } guard let country = String(bson["country"]) else { throw log(BSONError.missingField(name: "country")) } self.init(coordinates: coordinates, address: address, city: city, country: country) } }
bsd-2-clause
a3ff18073630f9068849d4e58ed76d5c
27.026667
88
0.574691
4.640177
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Database/Habitica Database/Models/User/RealmInbox.swift
1
1131
// // RealmInbox.swift // Habitica Database // // Created by Phillip Thelen on 03.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift class RealmInbox: Object, InboxProtocol { @objc dynamic var id: String? @objc dynamic var optOut: Bool = false @objc dynamic var numberNewMessages: Int = 0 override static func primaryKey() -> String { return "id" } @objc dynamic var blocks: [String] { get { if realmBlocks.isInvalidated { return [] } return realmBlocks.map({ (date) in return date }) } set { realmBlocks.removeAll() realmBlocks.append(objectsIn: newValue) } } var realmBlocks = List<String>() convenience init(id: String?, inboxProtocol: InboxProtocol) { self.init() self.id = id self.optOut = inboxProtocol.optOut self.numberNewMessages = inboxProtocol.numberNewMessages self.blocks = inboxProtocol.blocks } }
gpl-3.0
beb83eb1393d811e94ba361ab20b30f0
24.111111
65
0.59115
4.484127
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/NetworkFeeSelection/NetworkFeeSelectionBuilder.swift
1
1092
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import FeatureTransactionDomain import PlatformKit import RIBs // MARK: - Builder protocol NetworkFeeSelectionBuildable: Buildable { func build( withListener listener: NetworkFeeSelectionListener, transactionModel: TransactionModel ) -> NetworkFeeSelectionRouting } final class NetworkFeeSelectionBuilder: NetworkFeeSelectionBuildable { func build( withListener listener: NetworkFeeSelectionListener, transactionModel: TransactionModel ) -> NetworkFeeSelectionRouting { let viewController = NetworkFeeSelectionViewController() let reducer = NetworkFeeSelectionReducer() let presenter = NetworkFeeSelectionPresenter(viewController: viewController, feeSelectionPageReducer: reducer) let interactor = NetworkFeeSelectionInteractor(presenter: presenter, transactionModel: transactionModel) interactor.listener = listener return NetworkFeeSelectionRouter(interactor: interactor, viewController: viewController) } }
lgpl-3.0
323366467e22e2b6f3114434ba629587
35.366667
118
0.774519
5.510101
false
false
false
false
fitomad/FanartTVKit
src/Entities/FanartBasicImage.swift
1
717
// // FanartBasicImage.swift // FanartTV // // Created by Adolfo Vera Blasco on 21/11/15. // Copyright © 2015 Adolfo Vera Blasco. All rights reserved. // import Foundation /// /// Base class for all Fanart.TV images /// public class FanartBasicImage : Equatable { /// Image identifier public internal(set) var imageID: Int! /// The image URL public internal(set) var url: URL! /// How much people like this image public internal(set) var likes: Int! } // MARK: Custom `==` operator implementation /// /// Both objects are equal if their `imageID` property is the same /// public func ==(lhs: FanartBasicImage, rhs: FanartBasicImage) -> Bool { return lhs.imageID == rhs.imageID }
mit
73776a9352ed125d1ebc483ea33458f9
21.375
69
0.677374
3.58
false
false
false
false
ls1intum/ArTEMiS
src/main/resources/templates/swift/test/Tests/${packageNameFolder}Tests/Utilities.swift
1
970
import XCTest import AST import Source import Parser public func classFromString(_ className: String) -> AnyClass! { /// Get 'anyClass' with classname and namespace guard let cls: AnyClass = NSClassFromString("${packageName}Lib.\(className)") else { return nil } /// return AnyClass! return cls } public func getClassSourceFileFor(_ className: String) -> SourceFile? { do { let currentPath = FileManager.default.currentDirectoryPath let filePath = "\(currentPath)/Sources/${packageName}Lib/\(className).swift" return try SourceReader.read(at: filePath) } catch { return nil } } public func getTopLevelDeclarationFor(_ className: String) -> TopLevelDeclaration? { do { if let sourceFile = getClassSourceFileFor(className) { let parser = Parser(source: sourceFile) return try parser.parse() } return nil } catch { return nil } }
mit
e80298b91d33e2217106eb3511e0dd4d
26.714286
88
0.649485
4.754902
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Jetpack Settings/JetpackSettingsViewController.swift
1
17685
import Foundation import CocoaLumberjack import WordPressShared /// The purpose of this class is to render and modify the Jetpack Settings associated to a site. /// open class JetpackSettingsViewController: UITableViewController { // MARK: - Private Properties fileprivate var blog: Blog! fileprivate var service: BlogJetpackSettingsService! fileprivate lazy var handler: ImmuTableViewHandler = { return ImmuTableViewHandler(takeOver: self) }() // MARK: - Computed Properties fileprivate var settings: BlogSettings { return blog.settings! } // MARK: - Static Properties fileprivate static let footerHeight = CGFloat(34.0) fileprivate static let learnMoreUrl = "https://jetpack.com/support/sso/" fileprivate static let wordPressLoginSection = 3 // MARK: - Initializer @objc public convenience init(blog: Blog) { self.init(style: .grouped) self.blog = blog self.service = BlogJetpackSettingsService(managedObjectContext: settings.managedObjectContext!) } // MARK: - View Lifecycle open override func viewDidLoad() { super.viewDidLoad() WPAnalytics.trackEvent(.jetpackSettingsViewed) title = NSLocalizedString("Settings", comment: "Title for the Jetpack Security Settings Screen") ImmuTable.registerRows([SwitchRow.self], tableView: tableView) ImmuTable.registerRows([NavigationItemRow.self], tableView: tableView) WPStyleGuide.configureColors(view: view, tableView: tableView) reloadViewModel() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadSelectedRow() tableView.deselectSelectedRowWithAnimation(true) refreshSettings() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - Model fileprivate func reloadViewModel() { handler.viewModel = tableViewModel() } func tableViewModel() -> ImmuTable { var monitorRows = [ImmuTableRow]() monitorRows.append( SwitchRow(title: NSLocalizedString("Monitor your site's uptime", comment: "Jetpack Monitor Settings: Monitor site's uptime"), value: self.settings.jetpackMonitorEnabled, onChange: self.jetpackMonitorEnabledValueChanged()) ) if self.settings.jetpackMonitorEnabled { monitorRows.append( SwitchRow(title: NSLocalizedString("Send notifications by email", comment: "Jetpack Monitor Settings: Send notifications by email"), value: self.settings.jetpackMonitorEmailNotifications, onChange: self.sendNotificationsByEmailValueChanged()) ) monitorRows.append( SwitchRow(title: NSLocalizedString("Send push notifications", comment: "Jetpack Monitor Settings: Send push notifications"), value: self.settings.jetpackMonitorPushNotifications, onChange: self.sendPushNotificationsValueChanged()) ) } var bruteForceAttackRows = [ImmuTableRow]() bruteForceAttackRows.append( SwitchRow(title: NSLocalizedString("Block malicious login attempts", comment: "Jetpack Settings: Block malicious login attempts"), value: self.settings.jetpackBlockMaliciousLoginAttempts, onChange: self.blockMaliciousLoginAttemptsValueChanged()) ) if self.settings.jetpackBlockMaliciousLoginAttempts { bruteForceAttackRows.append( NavigationItemRow(title: NSLocalizedString("Allowlisted IP addresses", comment: "Jetpack Settings: Allowlisted IP addresses"), action: self.pressedAllowlistedIPAddresses()) ) } var wordPressLoginRows = [ImmuTableRow]() wordPressLoginRows.append( SwitchRow(title: NSLocalizedString("Allow WordPress.com login", comment: "Jetpack Settings: Allow WordPress.com login"), value: self.settings.jetpackSSOEnabled, onChange: self.ssoEnabledChanged()) ) if self.settings.jetpackSSOEnabled { wordPressLoginRows.append( SwitchRow(title: NSLocalizedString("Match accounts using email", comment: "Jetpack Settings: Match accounts using email"), value: self.settings.jetpackSSOMatchAccountsByEmail, onChange: self.matchAccountsUsingEmailChanged()) ) wordPressLoginRows.append( SwitchRow(title: NSLocalizedString("Require two-step authentication", comment: "Jetpack Settings: Require two-step authentication"), value: self.settings.jetpackSSORequireTwoStepAuthentication, onChange: self.requireTwoStepAuthenticationChanged()) ) } var manageConnectionRows = [ImmuTableRow]() manageConnectionRows.append( NavigationItemRow(title: NSLocalizedString("Manage Connection", comment: "Jetpack Settings: Manage Connection"), action: self.pressedManageConnection()) ) return ImmuTable(sections: [ ImmuTableSection( headerText: "", rows: monitorRows, footerText: nil), ImmuTableSection( headerText: NSLocalizedString("Brute Force Attack Protection", comment: "Jetpack Settings: Brute Force Attack Protection Section"), rows: bruteForceAttackRows, footerText: nil), ImmuTableSection( headerText: "", rows: manageConnectionRows, footerText: nil), ImmuTableSection( headerText: NSLocalizedString("WordPress.com login", comment: "Jetpack Settings: WordPress.com Login settings"), rows: wordPressLoginRows, footerText: nil) ]) } // MARK: Learn More footer open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == JetpackSettingsViewController.wordPressLoginSection { return JetpackSettingsViewController.footerHeight } return 0.0 } open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == JetpackSettingsViewController.wordPressLoginSection { let footer = UITableViewHeaderFooterView(frame: CGRect(x: 0.0, y: 0.0, width: tableView.frame.width, height: JetpackSettingsViewController.footerHeight)) footer.textLabel?.text = NSLocalizedString("Learn more...", comment: "Jetpack Settings: WordPress.com Login WordPress login footer text") footer.textLabel?.font = UIFont.preferredFont(forTextStyle: .footnote) footer.textLabel?.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(handleLearnMoreTap(_:))) footer.addGestureRecognizer(tap) return footer } return nil } // MARK: - Row Handlers fileprivate func jetpackMonitorEnabledValueChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackMonitorEnabled = newValue self.reloadViewModel() self.service.updateJetpackSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func sendNotificationsByEmailValueChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackMonitorEmailNotifications = newValue self.service.updateJetpackMonitorSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func sendPushNotificationsValueChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackMonitorPushNotifications = newValue self.service.updateJetpackMonitorSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func blockMaliciousLoginAttemptsValueChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackBlockMaliciousLoginAttempts = newValue self.reloadViewModel() self.service.updateJetpackSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } func pressedAllowlistedIPAddresses() -> ImmuTableAction { return { [unowned self] row in let allowListedIPs = self.settings.jetpackLoginAllowListedIPAddresses let settingsViewController = SettingsListEditorViewController(collection: allowListedIPs) settingsViewController.title = NSLocalizedString("Allowlisted IP Addresses", comment: "Allowlisted IP Addresses Title") settingsViewController.insertTitle = NSLocalizedString("New IP or IP Range", comment: "IP Address or Range Insertion Title") settingsViewController.editTitle = NSLocalizedString("Edit IP or IP Range", comment: "IP Address or Range Edition Title") settingsViewController.footerText = NSLocalizedString("You may allowlist an IP address or series of addresses preventing them from ever being blocked by Jetpack. IPv4 and IPv6 are acceptable. To specify a range, enter the low value and high value separated by a dash. Example: 12.12.12.1-12.12.12.100.", comment: "Text rendered at the bottom of the Allowlisted IP Addresses editor, should match Calypso.") settingsViewController.onChange = { [weak self] (updated: Set<String>) in self?.settings.jetpackLoginAllowListedIPAddresses = updated guard let blog = self?.blog else { return } self?.service.updateJetpackSettingsForBlog(blog, success: { [weak self] in // viewWillAppear will trigger a refresh, maybe before // the new IPs are saved, so lets refresh again here self?.refreshSettings() WPAnalytics.track(.jetpackAllowlistedIpsChanged) }, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } self.navigationController?.pushViewController(settingsViewController, animated: true) WPAnalytics.track(.jetpackAllowlistedIpsViewed) } } fileprivate func ssoEnabledChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackSSOEnabled = newValue self.reloadViewModel() self.service.updateJetpackSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func matchAccountsUsingEmailChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackSSOMatchAccountsByEmail = newValue self.service.updateJetpackSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func requireTwoStepAuthenticationChanged() -> (_ newValue: Bool) -> Void { return { [unowned self] newValue in self.settings.jetpackSSORequireTwoStepAuthentication = newValue self.service.updateJetpackSettingsForBlog(self.blog, success: {}, failure: { [weak self] (_) in self?.refreshSettingsAfterSavingError() }) } } fileprivate func pressedManageConnection() -> ImmuTableAction { return { [unowned self] row in WPAnalytics.trackEvent(.jetpackManageConnectionViewed) let jetpackConnectionVC = JetpackConnectionViewController(blog: blog) jetpackConnectionVC.delegate = self self.navigationController?.pushViewController(jetpackConnectionVC, animated: true) } } // MARK: - Footer handler @objc fileprivate func handleLearnMoreTap(_ sender: UITapGestureRecognizer) { guard let url = URL(string: JetpackSettingsViewController.learnMoreUrl) else { return } let webViewController = WebViewControllerFactory.controller(url: url) if presentingViewController != nil { navigationController?.pushViewController(webViewController, animated: true) } else { let navController = UINavigationController(rootViewController: webViewController) present(navController, animated: true) } } // MARK: - Persistance fileprivate func refreshSettings() { service.syncJetpackSettingsForBlog(blog, success: { [weak self] in self?.reloadViewModel() DDLogInfo("Reloaded Jetpack Settings") }, failure: { (error: Error?) in DDLogError("Error while syncing blog Jetpack Settings: \(String(describing: error))") }) } fileprivate func refreshSettingsAfterSavingError() { let errorTitle = NSLocalizedString("Error updating Jetpack settings", comment: "Title of error dialog when updating jetpack settins fail.") let errorMessage = NSLocalizedString("Please contact support for assistance.", comment: "Message displayed on an error alert to prompt the user to contact support") WPError.showAlert(withTitle: errorTitle, message: errorMessage, withSupportButton: true) refreshSettings() } } extension JetpackSettingsViewController: JetpackConnectionDelegate { func jetpackDisconnectedForBlog(_ blog: Blog) { if blog == self.blog { navigationController?.popToRootViewController(animated: true) } } }
gpl-2.0
a0fbbeb82990e80a529d57366504b639
48.399441
315
0.532711
6.696327
false
false
false
false
Kawoou/FlexibleImage
Sources/Filter/LinearBurnFilter.swift
1
2933
// // LinearBurnFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(watchOS) import Metal #endif internal class LinearBurnFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "LinearBurnFilter" } } internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0) // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { let factors: [Float] = [color.r, color.g, color.b, color.a] for i in 0..<factors.count { var factor = factors[i] let size = max(MemoryLayout<Float>.size, 16) let options: MTLResourceOptions if #available(iOS 9.0, *) { options = [.storageModeShared] } else { options = [.cpuCacheModeWriteCombined] } let buffer = device.device.makeBuffer( bytes: &factor, length: size, options: options ) #if swift(>=4.0) commandEncoder.setBuffer(buffer, offset: 0, index: i) #else commandEncoder.setBuffer(buffer, offset: 0, at: i) #endif } return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { let memoryPool = device.memoryPool! let width = Int(device.drawRect!.width) let height = Int(device.drawRect!.height) func subtract(_ a: UInt16, _ b: UInt16) -> UInt8 { if a + b < 255 { return 0 } else { return UInt8((a + b) - 255) } } var index = 0 for _ in 0..<height { for _ in 0..<width { let r = UInt16(memoryPool[index + 0]) let g = UInt16(memoryPool[index + 1]) let b = UInt16(memoryPool[index + 2]) let a = UInt16(memoryPool[index + 3]) memoryPool[index + 0] = subtract(r, UInt16(color.r * 255)) memoryPool[index + 1] = subtract(g, UInt16(color.g * 255)) memoryPool[index + 2] = subtract(b, UInt16(color.b * 255)) memoryPool[index + 3] = subtract(a, UInt16(color.a * 255)) index += 4 } } return super.processNone(device) } }
mit
f6b92b70e2e37927aedd54013f0edf35
30.505376
160
0.48157
4.473282
false
false
false
false
MichelKansou/Vapor-Blog
Sources/App/Seeds/Database.swift
1
407
import Vapor import Fluent extension Database { func seed<T: Entity, S: Sequence>(_ data: S) throws where S.Iterator.Element == T { let context = DatabaseContext(self) try data.forEach { model in let query = Query<T>(self) query.action = .create query.data = try model.makeNode(context: context) try driver.query(query) } } }
mit
c3df687a639aabc7ce8ef03a6ec5514b
28.071429
87
0.589681
4.111111
false
false
false
false
RobotRebels/SwiftLessons
chapter1/lesson3/31_03_2017.playground/Contents.swift
1
11620
//: Playground - noun: a place where people can play import Foundation /* Будет собираться класс Plane из частей, написанных каждым студентом дома (задание предыдущего урока) - наследование - модификатор protected - апкастинг\даункастинг Задание: (ВНИМАНИЕ: все сценарии с нуля) 1) запуск самолёта, загрузка бомб и бомбардировка (Дэн) 2) попытка бомбардировки, при фейле возврат на базу (Паша) 3) посадить одного пилота, запуск самолёта, понять что он не дорос, заглушить, посадить другого и взлететь (Паша) 4) поднять самолёт, опустить самолёт, заменить двигатель, загрузить бомбы, улететь в закат (Слава) */ class Rumpf { // все что их объединяет - одна фабрика изготовления в истино лучшей стране - III Рейхе static var factory = "Junkers" // общий метод получения фабрики изготовления static func getFactory() -> String { return self.factory } // общий метод изменения фабрики изготовления static func setFactory(newname: String) { self.factory = newname } // свойства фюзеляжа, которые можно безвозбранно менять (кол-во бомб, цвет) var color = "White" private var bombNumber = 0 // свойства фюзеляжа, которые недоступны для редактированию извне. Любые поптыки будут пресекаться анальной карой private var model = "U2" private var fabric = "Steel" private var length = 0.0 private var width = 0.0 private var weight = 0 private var maxBombNumber = 1 // закрытые методы работы c фюзеляжеv (нихуя лезть всем поряд и делать в моем фюзеляже дырки) private func openDoor() { print ("Door is open") } private func closeDoor() { print ("Door is closed") } // Публичный метод установки аварийности в самолете func setAlarmIn () { openDoor() print ("Ahtung!!! Hi Hitler") } // Публичная загрузка бомб для установки нового порядка в мире func downloadBombs(number: Int) { openDoor() if (number + bombNumber >= maxBombNumber) { print ("\(maxBombNumber - bombNumber) bombs downloaded!") bombNumber = maxBombNumber } else { bombNumber = bombNumber + number print ("\(number) bombs downloaded!") } closeDoor() } func getBombCount() -> Int { return bombNumber } // Публичная бомбардировка!!! func bombardment () { openDoor() bombNumber = 0; print("Hi Hitler!!!") closeDoor() } // публичнй метод покраски. Гитлер разрешал красить в любой кроме розового! Ибо розовый - цвет самого фюррера! func setColor(color: String){ if color == "Pink" { print ("You will be died!!! Pink is Hitler color!!!") } else { self.color = color } } // Инициализатор init(model: String, fabric: String, length: Double, width: Double, weight: Int, bombNumber: Int) { self.model = model self.fabric = fabric self.length = length self.weight = weight self.width = width self.maxBombNumber = bombNumber } init(length: Double, weight: Int) { self.length = length self.weight = weight } } class Shassi { // static - все такие параметры применимы к классу как таковому static var sertifacateInCompany: String = "Sert 36/1" static var maxExplutationTime: Int = 6 //private - все такие параметры экземпляра класса недоступны извне private var wheelWeight: Float { get { return Float(count) * diametr / 10.0 } } private var tireWeight: Float { get { return self.tireWeight //return tireRadius * 10 } set { //print(newValue) } } private var tireRadius: Float private var openPosition: Bool = true private var diametr: Float private var brand: String private var yearsOld: Int private var count: Int //метод, который относится к классу как таковому static func companyStandarts() { print("Our actualy standarts for Shassi: Sertificated - \(sertifacateInCompany) and max explutation time - \(maxExplutationTime) years") } private func canUseThisShassi() -> Bool { if (Shassi.maxExplutationTime < yearsOld) { return false } else { return true } } //исходим из того, что эти данные мы сможем где то использовать func weightCalculate() -> Float { return tireWeight + wheelWeight } func isShassiOpen() -> Bool { print(openPosition) return openPosition } func changeOpenPosition() { if (openPosition == true) { openPosition = false print("shassi is closed!") } else { openPosition = true print("shassi is opened!") } } func maxWeight() -> Float { return (Float(diametr) * wheelWeight * Float(count)) / (Float((yearsOld)+1) / 10.0) } /*func ageRisk() { switch yearsOld { case 0 ..< Shassi.maxExplutationTime: print("We can use it!") case Shassi.maxExplutationTime: print("Oh no, we must replace this soon!") default: print("Whats a holly shit!!!") } }*/ func ageRisk() -> Bool { let ageRisk = canUseThisShassi() if ageRisk == true { print("We can use it!") return ageRisk } else { print("Oh no, we must replace this soon!") return ageRisk } } init(_brand: String) { diametr = 10.0 count = 2 yearsOld = 0 brand = "Standart wheel" + _brand tireRadius = diametr + 4.2 } init(_diametr: Float, _count: Int, _type: String, _yearsOld: Int) { diametr = _diametr count = _count brand = _type yearsOld = _yearsOld tireRadius = diametr + 4.2 } } class Pilot { //переменные для всего класса static var pilotRasa: String = "Human" // пилоты у нас пипл с планеты Земля static var gender: String = "Male" // Все пилоты мужики, феминистки негодуют static let minimalAge:Int = 18 // даже если гуманоид, то пилотом может быть с 18-ти static let maximumAge: Int = 75 // переменные доступные только внутри класса private var flightHours: Float = 0.0 private var aviationTye: String = "commercial aviation" // все пилоты не только мужики, но и только гражданская авиация. Девочки рыдают private static var licens: String = "PPL" //тип лицензии. изменять вне класса нельзя. Параметр применяется для всего класса //Публичные переменные, которые можно изменить за рамками класса private var fullName: String = "" private var educationDegree: String = "" private var universityName: String = "" init(_fullName: String, education: String, university: String) { fullName = _fullName educationDegree = education universityName = university } func getPilotFlightHours() -> Float { return flightHours } // Функция проверят может ли кто-то быть пилотом. Доступна и вне класса. Вопрос должна ли что-то еще возвращать данная функция. func checkCanBePilot(race: String, pilotAge: Int) { if (race == "German") { print("Hi Gidra!") } if ((pilotAge > Pilot.minimalAge) && (pilotAge < Pilot.maximumAge)) { print ("Пилот не малорик, можно доверить самолет!") } else { print ("Пилот еще не дорос до больших игрушек, сорян :(") } } // Функфия доступна в рамках класса и возвращает общее количество часов кторое налетал пилот func addNewHours(pilotNewHours: Float) { flightHours += pilotNewHours } /* // функция возвращает обновленное количество часов полета func addFlighthours (flightHours:Float, hoursvalue: Float) -> Float { return print( self.flightHours + hoursvalue) } */ } var rumpf = Rumpf(model: "F-15", fabric: "metal", length: 100.0, width: 10.0, weight: 1000, bombNumber: 10) rumpf.color = "Black" //print(rumpf.color) rumpf.downloadBombs(number: 1) rumpf.bombardment() //print(rumpf.getBombCount()) var newShassi = Shassi(_brand: "Mochlen") newShassi.maxWeight() newShassi.changeOpenPosition() class Engine { private var power: Int = 0 private var isRun: Bool = false var serialNumber: String init(_serialNumer: String, _power: Int) { power = _power serialNumber = _serialNumer } func turnOn() { isRun = true } func turnOff() { isRun = false } } class RollsRoysEngine: Engine { var garanteeAge: Int = 20 } var newRRengine = RollsRoysEngine(_serialNumer: "111", _power: 1000) var engine = Engine(_serialNumer: "111", _power: 1000) class Plane { // композиция (более строгая компоновка объектов) var fusilage: Rumpf = Rumpf(length: 100.0, weight: 10) // апкастинг (даункастинг запрещен) var engine: Engine = RollsRoysEngine(_serialNumer: "123", _power: 100) var shassi: Shassi = Shassi(_brand: "BMW") // аггрегация (менее строгая. Объект внедренный может сууществовать независимо) var pilot: Pilot? func setPilot(newPilot: Pilot) { pilot = newPilot } init(dict: [String: AnyObject]) { fusilage = dict["fusilage"] as? Rumpf ?? Rumpf(length: 100.0, weight: 10) engine = dict["engine"] as? Engine ?? Engine(_serialNumer: "123", _power: 100) shassi = dict["shassi"] as? Shassi ?? Shassi(_brand: "BMW") } } var pilot1 = Pilot(_fullName: "", education: "", university: "") var plane1: Plane? = Plane(dict: [:]) plane1!.pilot = pilot1 print(plane1!.pilot?.getPilotFlightHours()) plane1 = nil print(pilot1) //var fus = Rumpf(length: 100.0, weight: 100) var paramsDict: [String: AnyObject] = [ "engine": Engine(_serialNumer: "321", _power: 15) ] var plane: Plane = Plane(dict: paramsDict) var pilot = Pilot(_fullName: "Gans Anderson", education: "Master", university: "NIAU MEPHI") plane.setPilot(newPilot: pilot) print(plane.engine.serialNumber)
mit
7d91d0f3679629f5884223207f2e2dc7
21.440835
141
0.661394
2.986107
false
false
false
false
quran/quran-ios
Sources/TranslationService/DatabaseVersionPersistence.swift
1
1608
// // DatabaseVersionPersistence.swift // Quran // // Created by Mohamed Afifi on 3/12/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import SQLite import SQLitePersistence protocol DatabaseVersionPersistence { func getTextVersion() throws -> Int } struct SQLiteDatabaseVersionPersistence: DatabaseVersionPersistence, ReadonlySQLitePersistence { private struct Properties { static let table = Table("properties") static let property = Expression<String>("property") static let value = Expression<String>("value") } let filePath: String func getTextVersion() throws -> Int { try run { connection in let query = Properties.table.filter(Properties.property == "text_version") let rows = try connection.prepare(query) guard let first = rows.first(where: { _ in true }) else { throw PersistenceError.general("Cannot find any records for text_version") } return Int(first[Properties.value])! } } }
apache-2.0
71fcd02862e6a6dd83893a8bc87a09d8
32.5
96
0.687189
4.466667
false
false
false
false
Beefycoder/iOS-Swift-Projects
NoteTaker/NewNoteViewController.swift
1
12056
// // NewNoteViewController.swift // NoteTaker // // Created by Pat Butler on 2015-10-01. // Copyright © 2015 RPG Ventures. All rights reserved. // import UIKit import AVFoundation import CoreData class NewNoteViewController: UIViewController { //*** required *** init now requires an optional question mark ? at the start of the init declaration // Setting up an audio recorder takes a little bit more work than setting up an audio player // we need to initialize the recorder components before we can use them // 1. create a baseString, which is just accessing the users home directory path and storing it in baseString // 2. the NSUUID().UUIDString call is a string formatter that creates unique strings, we assign it to the audioURL so the audio files are unique, and just add the file type to the end of it // 3. create a pathComponents var, that contains the baseString (users home director), and the audioURL // 4. create an NSURL object, and put in it the pathComponents var (which has the baseString and audioURL) // 5. create a session var to hold the audio context of the app, which means we are going assign certain settings for recording // 6. create a recordSettings var that will hold our recoding settings that we choose for the recorder, like the sampleRateKey, the number of channels we want the recorder to have, and the audio quailty as well, all that gets stored into the recordettings variable // 7. add to the session var the type of recording session we want..here its PlayAndRecord, and we try to set that setting in the do catch construct, because creating an audio session can throw an error, so we need to handle that using the keyword "try", and if there is an error, we print out its description in the catch block so we know what went wrong // And we store into the audioRecorder, the audioNSURL, which has the path of the recording, and the record settings we just set in the recordSettings variable (so all the info we created above gets put into the audioRecorder)... And we try to do that in the do catch construct again, because grabbing an audio file from a path can throw an error if the file is not there for some reason. // 8. set the audio metering to true, which enables a metering scale of the audio input, that we will access later to show the audio level input and display that in a percentage to the user // 9. we call the prepareToRecord() which creates an audio file and prepares the system for recording. // 10. this Super init gets set last here...we call the inits super class to access its functionality here (has to do with subclassing) //Apple introduced failable initializers.. which are, initializers that can return nil instead of an instance. You define a failable initializer by putting a question mark ? after the init declaration required init?(coder aDecoder: NSCoder) { let baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String //1 self.audioURL = NSUUID().UUIDString + ".m4a" //2 let pathComponents = [baseString, self.audioURL] //3 let audioNSURL = NSURL.fileURLWithPathComponents(pathComponents)! //4 let session = AVAudioSession.sharedInstance() //5 let recordSettings = [ //6 AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000.0, AVNumberOfChannelsKey: 2 as NSNumber, AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue] do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord) //7 self.audioRecorder = try AVAudioRecorder(URL: audioNSURL, settings: recordSettings) } catch let initError as NSError { print("Initialization error: \(initError.localizedDescription)") } self.audioRecorder.meteringEnabled = true //8 self.audioRecorder.prepareToRecord() //9 super.init(coder: aDecoder) //10 } @IBOutlet weak var noteTextField: UITextField! @IBOutlet weak var recordOutlet: UIButton! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var peakImageView: UIImageView! @IBOutlet weak var averageImageView: UIImageView! var audioRecorder: AVAudioRecorder! var audioURL: String var audioPlayer = AVAudioPlayer() let timeInterval: NSTimeInterval = 0.5 override func viewDidLoad() { super.viewDidLoad() recordOutlet.layer.shadowOpacity = 1.0 recordOutlet.layer.shadowOffset = CGSize(width: 5.0, height: 4.0) recordOutlet.layer.shadowRadius = 5.0 recordOutlet.layer.shadowColor = UIColor.blackColor().CGColor } @IBAction func cancel(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } //HOW TO SAVE THE SOUND AND LABEL TEXT TO CORE DATA // 1. the first line we create a context var and then go to the the App delegate class, and grab from that class the managedObjectContext object…this is the the managed object context for the application (which is bound to the persistent store coordinator, which means its the main var we use to manage the variables in core data.) we use the context var to let us save and retrieve the data...in this case, save data // 2. we create the new core data note variable, which will hold the users recordings and titles for us, and pass in the context var, to manage the data.. (the "Note" entity name has to match exactly to what we created in the core data file) // 3. store the users typed text into the core data name property of the newly created note var (and again, core data calls properties attributes) // 4. set the audioURL string we created above to the core data url attribute (attribute and property are synomonous) // 5. try to save sound url and name to core data using the do catch, if theres a problem saving, we handle the error…here well print out the type of error we get // 6. Then Dismiss ViewController @IBAction func save(sender: AnyObject) { if noteTextField.text != "" { let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext //1 let note = NSEntityDescription.insertNewObjectForEntityForName("Note", inManagedObjectContext: context) as! Note //2 note.name = noteTextField.text! //3 note.url = audioURL //4 do { //5 try context.save() } catch let saveError as NSError { print("Saving error: \(saveError.localizedDescription)") } } self.dismissViewControllerAnimated(true, completion: nil) //6 } @IBAction func record(sender: AnyObject) { let mic = UIImage(named: "record button.png") as UIImage! recordOutlet.setImage(mic, forState: .Normal) recordOutlet.layer.shadowOpacity = 1.0 recordOutlet.layer.shadowOffset = CGSize(width: 5.0, height: 4.0) recordOutlet.layer.shadowRadius = 5.0 recordOutlet.layer.shadowColor = UIColor.blackColor().CGColor if audioRecorder.recording { audioRecorder.stop() let mic = UIImage(named: "Mic button.png") as UIImage! recordOutlet.setImage(mic, forState: .Normal) } else { let session = AVAudioSession.sharedInstance() do { try session.setActive(true) audioRecorder.record() } catch let recordError as NSError { print("Recording Error: \(recordError.localizedDescription)") } } } @IBAction func touchDownRecord(sender: AnyObject) { audioPlayer = getAudioPlayerFile("startRecordSound", type: "m4a") audioPlayer.play() let timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "updateAudioMeter:", userInfo: nil, repeats: true) timer.fire() recordOutlet.layer.shadowOpacity = 0.9 recordOutlet.layer.shadowOffset = CGSize(width: -2.0, height: -2.0) recordOutlet.layer.shadowRadius = 5.0 recordOutlet.layer.shadowColor = UIColor.blackColor().CGColor } // A function to update the meters and to update the label too func updateAudioMeter(timer: NSTimer) { if audioRecorder.recording { let dFormat = "%02d" let min:Int = Int(audioRecorder.currentTime / 60) let sec:Int = Int(audioRecorder.currentTime % 60) let timeString = "\(String(format: dFormat, min)):\(String(format: dFormat, sec))" timeLabel.text = timeString audioRecorder.updateMeters() let averageAudio = audioRecorder.averagePowerForChannel(0) * -1 let peakAudio = audioRecorder.peakPowerForChannel(0) * -1 let progressViewAverage = Int(averageAudio) // /100 if using a float let peakViewAverage = Int(peakAudio) // /100 if using float averageRadial(progressViewAverage, peak: peakViewAverage) } else if !audioRecorder.recording { averageImageView.image = UIImage(named: "average0radial.png") peakImageView.image = UIImage(named: "peak0value.png") crossfadeTransition() } } // A function that grabs any audio file path and creates the audio player func getAudioPlayerFile(file: String, type: String) -> AVAudioPlayer { let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String) let url = NSURL.fileURLWithPath(path!) var audioPlayer:AVAudioPlayer? do { try audioPlayer = AVAudioPlayer(contentsOfURL: url) } catch let audioPlayerError as NSError { print("Failed to initialize player error: \(audioPlayerError.localizedDescription)") } return audioPlayer! } func averageRadial (average: Int, peak: Int) { switch average { case average: averageImageView.image = UIImage(named: "average\(String(average))radial") crossfadeTransition() default: averageImageView.image = UIImage(named: "average10radial.png") crossfadeTransition() } switch peak { case peak: peakImageView.image = UIImage(named: "peak\(String(peak))value") crossfadeTransition() default: peakImageView.image = UIImage(named: "peak10value.png") crossfadeTransition() } } func crossfadeTransition() { let transition = CATransition() transition.type = kCATransitionFade transition.duration = 0.2 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) view.layer.addAnimation(transition, forKey: nil) } }
gpl-2.0
8fa0874a993463f878968163f479fb68
49.004149
421
0.623102
5.353621
false
false
false
false
sketchytech/SwiftPlaygrounds
AutoLayoutProgrammaticConstraints.playground/Pages/Anchors_iOS9.xcplaygroundpage/Contents.swift
1
2268
//: [Previous](@previous) import UIKit import XCPlayground /*: # Anchors iOS 9 Using anchors to create constraints is new to iOS 9. */ if #available(iOS 9,*) { class ViewController: UIViewController { func buildConstraints() -> Void { // Initialize let subView = UIView() // Add to the view self.view.addSubview(subView) //Recognize Auto Layout subView.translatesAutoresizingMaskIntoConstraints = false //Coloring subView.backgroundColor = UIColor(red: 135/255, green: 222/255, blue: 212/255, alpha: 1) //: Here view anchors (introduced in iOS 9) control constraints. The shorthand .active is used. This is supported with reqular constraints as well (from iOS 8 forwards). subView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true subView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true subView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true subView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true //: **Important Note**: In real use I would replace view.topAnchor with topLayoutGuide.bottomAnchor and view.bottomAnchor with bottomLayoutGuide.topAnchor to avoid the view going under the status bar. However, to do so here prevents the view from currently rendering correctly. It might be that } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Do any additional setup after loading the view, typically from a nib. buildConstraints() self.view.backgroundColor = UIColor.whiteColor() } } let aVC = ViewController() XCPShowView("myAnchorView", view: aVC.view) } //: **Note**: To see the view you must have the timeline file open. If it is not displayed, tap on the two interlinking circles icon along the top right row of buttons. To the right you should see the view. And if you have problems loading then close the pane and open again. //: [Next](@next)
mit
e5278be9ecf351c661c110ab76ac6a5e
42.615385
302
0.648148
5.336471
false
false
false
false
vbudhram/firefox-ios
Client/Application/NavigationRouter.swift
1
8284
/* 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 struct FxALaunchParams { var query: [String: String] } // An enum to route to HomePanels enum HomePanelPath: String { case bookmarks case topsites case readingList case history } // An enum to route to a settings page. // This could be extended to provide default values to pass to fxa enum SettingsPage: String { case newTab case homePage case mailto case search case clearData = "clear-private-data" case fxa } // Used by the App to navigate to different views. // To open a URL use /open-url or to open a blank tab use /open-url with no params enum DeepLink { case settings(SettingsPage) case homePanel(HomePanelPath) init?(urlString: String) { let paths = urlString.split(separator: "/") guard let component = paths[safe: 0], let componentPath = paths[safe: 1] else { return nil } if component == "settings", let link = SettingsPage(rawValue: String(componentPath)) { self = .settings(link) } else if component == "homepanel", let link = HomePanelPath(rawValue: String(componentPath)) { self = .homePanel(link) } else { return nil } } } extension URLComponents { // Return the first query parameter that matches func valueForQuery(_ param: String) -> String? { return self.queryItems?.first { $0.name == param }?.value } } // The root navigation for the Router. Look at the tests to see a complete URL enum NavigationPath { case url(webURL: URL?, isPrivate: Bool) case fxa(params: FxALaunchParams) case deepLink(DeepLink) init?(url: URL) { let urlString = url.absoluteString guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject], let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Client should be the zeroeth URL type. return nil } guard let scheme = components.scheme, urlSchemes.contains(scheme) else { return nil } if urlString.starts(with: "\(scheme)://deep-link"), let deepURL = components.valueForQuery("url"), let link = DeepLink(urlString: deepURL) { self = .deepLink(link) } else if urlString.starts(with: "\(scheme)://fxa-signin"), components.valueForQuery("signin") != nil { self = .fxa(params: FxALaunchParams(query: url.getQuery())) } else if urlString.starts(with: "\(scheme)://open-url") { let url = components.valueForQuery("url")?.unescape()?.asURL let isPrivate = Bool(components.valueForQuery("private") ?? "") ?? false self = .url(webURL: url, isPrivate: isPrivate) } else { return nil } } static func handle(nav: NavigationPath, with bvc: BrowserViewController) { switch nav { case .fxa(let params): NavigationPath.handleFxA(params: params, with: bvc) case .deepLink(let link): NavigationPath.handleDeepLink(link, with: bvc) case .url(let url, let isPrivate): NavigationPath.handleURL(url: url, isPrivate: isPrivate, with: bvc) } } private static func handleDeepLink(_ link: DeepLink, with bvc: BrowserViewController) { switch link { case .homePanel(let panelPath): NavigationPath.handleHomePanel(panel: panelPath, with: bvc) case .settings(let settingsPath): guard let rootVC = bvc.navigationController else { return } let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = bvc.profile settingsTableViewController.tabManager = bvc.tabManager settingsTableViewController.settingsDelegate = bvc NavigationPath.handleSettings(settings: settingsPath, with: rootVC, baseSettingsVC: settingsTableViewController, and: bvc) } } private static func handleFxA(params: FxALaunchParams, with bvc: BrowserViewController) { if AppConstants.MOZ_FXA_DEEP_LINK_FORM_FILL { bvc.presentSignInViewController(params) } } private static func handleHomePanel(panel: HomePanelPath, with bvc: BrowserViewController) { switch panel { case .bookmarks: bvc.openURLInNewTab(HomePanelType.bookmarks.localhostURL, isPrivileged: true) case .history: bvc.openURLInNewTab(HomePanelType.history.localhostURL, isPrivileged: true) case .readingList:bvc.openURLInNewTab(HomePanelType.readingList.localhostURL, isPrivileged: true) case .topsites: bvc.openURLInNewTab(HomePanelType.topSites.localhostURL, isPrivileged: true) } } private static func handleURL(url: URL?, isPrivate: Bool, with bvc: BrowserViewController) { if let newURL = url { bvc.switchToTabForURLOrOpen(newURL, isPrivate: isPrivate, isPrivileged: false) } else { bvc.openBlankNewTab(focusLocationField: true, isPrivate: isPrivate) } LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "External App or Extension" as AnyObject]) } private static func handleSettings(settings: SettingsPage, with rootNav: UINavigationController, baseSettingsVC: AppSettingsTableViewController, and bvc: BrowserViewController) { guard let profile = baseSettingsVC.profile, let tabManager = baseSettingsVC.tabManager else { return } let controller = SettingsNavigationController(rootViewController: baseSettingsVC) controller.popoverDelegate = bvc controller.modalPresentationStyle = UIModalPresentationStyle.formSheet rootNav.present(controller, animated: true, completion: nil) switch settings { case .newTab: let viewController = NewTabChoiceViewController(prefs: baseSettingsVC.profile.prefs) controller.pushViewController(viewController, animated: true) case .homePage: let viewController = HomePageSettingsViewController() viewController.profile = profile viewController.tabManager = tabManager controller.pushViewController(viewController, animated: true) case .mailto: let viewController = OpenWithSettingsViewController(prefs: profile.prefs) controller.pushViewController(viewController, animated: true) case .search: let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile controller.pushViewController(viewController, animated: true) case .clearData: let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager controller.pushViewController(viewController, animated: true) case .fxa: bvc.presentSignInViewController() } } } extension NavigationPath: Equatable {} func == (lhs: NavigationPath, rhs: NavigationPath) -> Bool { switch (lhs, rhs) { case let (.url(lhsURL, lhsPrivate), .url(rhsURL, rhsPrivate)): return lhsURL == rhsURL && lhsPrivate == rhsPrivate case let (.fxa(lhs), .fxa(rhs)): return lhs.query == rhs.query case let (.deepLink(lhs), .deepLink(rhs)): return lhs == rhs default: return false } } extension DeepLink: Equatable {} func == (lhs: DeepLink, rhs: DeepLink) -> Bool { switch (lhs, rhs) { case let (.settings(lhs), .settings(rhs)): return lhs == rhs case let (.homePanel(lhs), .homePanel(rhs)): return lhs == rhs default: return false } }
mpl-2.0
1313b08bdb683e66c69c994cf5d0ea7e
39.213592
182
0.660309
4.984356
false
false
false
false
ngageoint/mage-ios
Mage/ObservationImportantView.swift
1
3355
// // ObservationImportantView.swift // MAGE // // Created by Daniel Barela on 12/16/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import PureLayout class ObservationImportantView: UIView { weak var observation: Observation?; var scheme: MDCContainerScheming?; var flaggedByLabel: UILabel = UILabel(forAutoLayout: ()); private lazy var reasonLabel: UILabel = { var reasonLabel: UILabel = UILabel(forAutoLayout: ()); reasonLabel.numberOfLines = 0; return reasonLabel; }() private lazy var flagImage: UIImageView = { let flag = UIImage(systemName: "flag.fill", withConfiguration: UIImage.SymbolConfiguration(weight: .semibold)); let flagView = UIImageView(image: flag); return flagView; }() func applyTheme(withScheme scheme: MDCContainerScheming?) { reasonLabel.textColor = UIColor.black.withAlphaComponent(0.87); reasonLabel.font = scheme?.typographyScheme.body2; flaggedByLabel.textColor = UIColor.black.withAlphaComponent(0.6); flaggedByLabel.font = scheme?.typographyScheme.overline; flagImage.tintColor = UIColor.black.withAlphaComponent(0.87); } public convenience init(observation: Observation?, cornerRadius: CGFloat, scheme: MDCContainerScheming? = nil) { self.init(frame: CGRect.zero); layer.cornerRadius = cornerRadius; layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]; self.observation = observation; self.scheme = scheme; self.configureForAutoLayout(); layoutView(); self.backgroundColor = MDCPalette.orange.accent400; if let observation = observation { populate(observation: observation); } applyTheme(withScheme: scheme); } func layoutView() { self.addSubview(flagImage); self.addSubview(flaggedByLabel); self.addSubview(reasonLabel); reasonLabel.accessibilityLabel = "important reason"; flagImage.autoPinEdge(toSuperviewEdge: .top, withInset: 8, relation: .greaterThanOrEqual); flagImage.autoPinEdge(toSuperviewEdge: .bottom, withInset: 8, relation: .greaterThanOrEqual); flagImage.autoPinEdge(toSuperviewEdge: .left, withInset: 16); flagImage.autoSetDimensions(to: CGSize(width: 32, height: 32)); flagImage.autoAlignAxis(toSuperviewAxis: .horizontal); flaggedByLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 56, bottom: 0, right: 8), excludingEdge: .bottom); reasonLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 56, bottom: 8, right: 8), excludingEdge: .top); reasonLabel.autoPinEdge(.top, to: .bottom, of: flaggedByLabel, withOffset: 8); } public func populate(observation: Observation) { self.observation = observation; let important: ObservationImportant? = observation.observationImportant; if let userId = important?.userId { let user = User.mr_findFirst(byAttribute: "remoteId", withValue: userId); flaggedByLabel.text = "Flagged By \(user?.name ?? "")".uppercased() } if let reason = important?.reason { reasonLabel.text = reason; } } }
apache-2.0
6c2fcb4b3751fccd499b93761d5e7e1f
41.455696
135
0.677102
4.882096
false
false
false
false
AbelSu131/ios-charts
Charts/Classes/Renderers/ChartRendererBase.swift
2
1804
// // ChartRendererBase.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class ChartRendererBase: NSObject { /// the component that handles the drawing area of the chart and it's offsets public var viewPortHandler: ChartViewPortHandler!; /// the minimum value on the x-axis that should be plotted internal var _minX: Int = 0; /// the maximum value on the x-axis that should be plotted internal var _maxX: Int = 0; public override init() { super.init(); } public init(viewPortHandler: ChartViewPortHandler) { super.init(); self.viewPortHandler = viewPortHandler; } /// Returns true if the specified value fits in between the provided min and max bounds, false if not. internal func fitsBounds(val: Double, min: Double, max: Double) -> Bool { if (val < min || val > max) { return false; } else { return true; } } /// Calculates the minimum and maximum x-value the chart can currently display (with the given zoom level). public func calcXBounds(#chart: BarLineChartViewBase, xAxisModulus: Int) { let low = chart.lowestVisibleXIndex; let high = chart.highestVisibleXIndex; let subLow = (low % xAxisModulus == 0) ? xAxisModulus : 0; _minX = max((low / xAxisModulus) * (xAxisModulus) - subLow, 0); _maxX = min((high / xAxisModulus) * (xAxisModulus) + xAxisModulus, Int(chart.chartXMax)); } }
apache-2.0
31f3ffaf2b3b21a8cca534c87538b709
27.203125
111
0.624169
4.476427
false
false
false
false
glaurent/MessagesHistoryBrowser
MessagesHistoryBrowser/ContactsMap.swift
1
11573
// // ContactsPhoneNumberList.swift // MessagesHistoryBrowser // // Created by Guillaume Laurent on 26/09/15. // Copyright © 2015 Guillaume Laurent. All rights reserved. // import Cocoa import Contacts class ContactsMap { // let countryPhonePrefix = "+33" var countryPhonePrefix:String static let sharedInstance = ContactsMap() var phoneNumbersMap = [String : String]() // maps contact phone numbers (as found in Messages.app chats) to contact identifiers (as used by the Contacts framework) let contactStore = CNContactStore() let contactIMFetchRequest = CNContactFetchRequest(keysToFetch: [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey, CNContactInstantMessageAddressesKey] as [CNKeyDescriptor]) let contactEmailFetchRequest = CNContactFetchRequest(keysToFetch: [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey, CNContactEmailAddressesKey] as [CNKeyDescriptor]) var progress:Progress? let contactFormatter = CNContactFormatter() init() { countryPhonePrefix = "+1" contactFormatter.style = .fullName } func populate(withCountryPhonePrefix phonePrefix:String) -> Bool { guard CNContactStore.authorizationStatus(for: .contacts) == .authorized else { return false } if #available(OSX 10.13, *) { NSLog("\(#function) macOS >10.13 detected - no need to populate the ContactsMap, using Contacts framework phone number search instead") return true } // ensure countryPhonePrefix has a leading "+" // if phonePrefix.first != "+" { countryPhonePrefix = "+" + phonePrefix } else { countryPhonePrefix = phonePrefix } // get number of contacts so we can set the totalUnitCount of this NSProgress // let predicate = CNContact.predicateForContactsInContainer(withIdentifier: contactStore.defaultContainerIdentifier()) if let allContactsForCount = try? contactStore.unifiedContacts(matching: predicate, keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor]) { progress = Progress(totalUnitCount: Int64(allContactsForCount.count)) // NSLog("\(#function) : nb of contacts : \(allContactsForCount.count)") } DispatchQueue.global(qos: .background).sync { () -> Void in let keysToFetch = [CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey] as [CNKeyDescriptor] let contactFetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch) do { try self.contactStore.enumerateContacts(with: contactFetchRequest) { (contact, stop) -> Void in NSLog("\(#function) contact : \(contact.givenName)") let phoneNumbers = contact.phoneNumbers if phoneNumbers.count > 0 { for index in 0..<phoneNumbers.count { let phoneNb = phoneNumbers[index].value let canonPhoneNb = self.canonicalizePhoneNumber(phoneNb.stringValue) NSLog("\(#function) phoneNb : \(canonPhoneNb) for contact \(contact.givenName)") self.phoneNumbersMap[canonPhoneNb] = contact.identifier DispatchQueue.main.async { self.progress?.completedUnitCount = Int64(index) } } } } } catch let e { NSLog("\(#function) error while enumerating contacts : \(e)") } } self.progress = nil return true } func canonicalizePhoneNumber(_ rawPhoneNumber:String) -> String { var res = "" for ch in rawPhoneNumber { switch ch { case "0"..."9", "+": res.append(ch) default: break // skip character } } // This really works for French numbers only // if res.hasPrefix("0") { let skip0Index = res.index(res.startIndex, offsetBy: 1) // res = countryPhonePrefix + res.substring(from: skip0Index) res = countryPhonePrefix + res[skip0Index...] } return res } func nameForPhoneNumber(_ phoneNumber:String) -> (String, String)? { if #available(OSX 10.13, *) { let cnPhoneNumber = CNPhoneNumber(stringValue: phoneNumber) let predicateForPhoneNumber = CNContact.predicateForContacts(matching: cnPhoneNumber) let keyDescriptors = [CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey] as [CNKeyDescriptor] do { let contacts = try contactStore.unifiedContacts(matching: predicateForPhoneNumber, keysToFetch: keyDescriptors) if let contact = contacts.first { let contactIdentifier = contact.identifier let contactName = formattedContactName(contactIdentifier) ?? "<unknown> \(phoneNumber)" return (contactName, contactIdentifier) } else { NSLog("\(#function) : couldn't find contact for this phone number \(phoneNumber))") return nil } } catch let error { NSLog("\(#function) : error while searching for \(phoneNumber)) - error \(error.localizedDescription)") return nil } } else { // Fallback on earlier versions if let contactIdentifier = phoneNumbersMap[phoneNumber] { let contactName = formattedContactName(contactIdentifier) ?? "<unknown> \(phoneNumber)" return (contactName, contactIdentifier) // return (contactName(contactIdentifier), contact.identifier) } else { // try matching the last 5 digits of the phone number let phoneNumberLength = phoneNumber.count let tailMatchLength = min(5, phoneNumberLength - 1) // match the last 5 nb or (length - 1) if less than 5 chars let tailStartIndex = phoneNumber.index(phoneNumber.endIndex, offsetBy: -tailMatchLength) let numberLast5Digits = phoneNumber[tailStartIndex...] // get the contacts whose phone number match the last 5 digits of the input phone number // let contactPhoneNumberMatchingLast5Digits = phoneNumbersMap.filter { (key:String, value:String) -> Bool in guard key.count > tailMatchLength else { return false } let keyTailStartIndex = key.index(key.endIndex, offsetBy: -tailMatchLength) let keyTail = key[keyTailStartIndex...] return keyTail == numberLast5Digits } if let firstPair = contactPhoneNumberMatchingLast5Digits.first { let contactIdentifier = firstPair.value let contactName = formattedContactName(contactIdentifier) ?? "<unknown> \(phoneNumber)" return (contactName, contactIdentifier) } else { return nil } } } // return nil } func nameForInstantMessageAddress(_ imAddressToSearch:String) -> (String, String)? { var res:(String, String)? do { try contactStore.enumerateContacts(with: contactIMFetchRequest) { (contact, stop) -> Void in let imAddresses = contact.instantMessageAddresses for labeledValue in imAddresses { let imAddress = labeledValue.value if imAddress.username == imAddressToSearch { res = (self.formattedContactName(contact.identifier) ?? imAddressToSearch, contact.identifier) stop.pointee = true } } } } catch { } return res } func nameForEmailAddress(_ emailAddressToSearch:String) -> (String, String)? { var res:(String, String)? do { try contactStore.enumerateContacts(with: contactEmailFetchRequest) { (contact, stop) -> Void in let emailAddresses = contact.emailAddresses for labeledValue in emailAddresses { let emailAddress = labeledValue.value as String if emailAddress == emailAddressToSearch { res = (self.formattedContactName(contact.identifier) ?? emailAddressToSearch, contact.identifier) stop.pointee = true } } } } catch { } return res } private func formattedContactName(_ contactIdentifier:String) -> String? { if let contact = try? contactStore.unifiedContact(withIdentifier: contactIdentifier, keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactNicknameKey as CNKeyDescriptor]) { if contact.nickname != "" { return contact.nickname } return contactFormatter.string(from: contact) } else { return nil } // let firstName = contact.givenName // let lastName = contact.familyName // return "\(firstName) \(lastName)" } // returns contact image or pair of initials if no image is found, or nil if contact is unknown // func contactImage(_ contactIdentifier:String) -> (NSImage?, (String, String)?) { do { let contact = try contactStore.unifiedContact(withIdentifier: contactIdentifier, keysToFetch:[CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor]) if let imageData = contact.imageData { return (NSImage(data: imageData), nil) // thumbnailImageData is nil, why ? } else { let firstNameInitial = String(contact.givenName.first ?? Character(" ")) let lastNameInitial = String(contact.familyName.first ?? Character(" ")) return (nil, (firstNameInitial, lastNameInitial)) // // get a bitmap of the contact's initials (like in Contacts.app) // let firstName = contact.givenName // let lastName = contact.familyName // // var initials = "" // // if firstName.count > 0 { // initials = initials + "\(firstName.first!)" // } // if lastName.count > 0 { // initials = initials + "\(lastName.first!)" // } // // if let imageLabel = LabelToImage.stringToImage(initials) { // return imageLabel // } } } catch { NSLog("\(#function) : Couldn't get contact with identifier \"\(contactIdentifier)\"") return (nil, nil) // return LabelToImage.stringToImage("?") } } }
gpl-3.0
16f18b472e8354a66bdfd879ebe3e37d
37.573333
284
0.580021
5.560788
false
false
false
false
bomjkolyadun/goeuro-test
GoEuro/GoEuro/ViewControllers/GEDirectionViewController.swift
1
1019
// // GEDirectionViewController.swift // GoEuro // // Created by Dmitry Osipa on 7/31/17. // Copyright © 2017 Dmitry Osipa. All rights reserved. // import UIKit class GEDirectionViewController: UIViewController { @IBOutlet weak var directionDateLabel: UILabel? @IBOutlet weak var directionLabel: UILabel? static let dateFormatter = { () -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = "dd MMM" return formatter }() public var direction: GEDirection! { didSet { self.setupLabels() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setupLabels() } func setupLabels() { let text = (direction.fromLocation as String) + " → " + (direction.toLocation as String) self.directionLabel?.text = text self.directionDateLabel?.text = GEDirectionViewController.dateFormatter.string(from: direction.date as Date) } }
apache-2.0
ae11c8c7b2864b06087a86bd7c14613a
25.051282
116
0.654528
4.475771
false
false
false
false
shvets/WebAPI
Sources/WebAPI/GidOnline2API.swift
1
32984
import Foundation import SwiftSoup // import SwiftyJSON import Alamofire open class GidOnline2API: HttpService { // public static let SiteUrl = "http://gidonline-kino.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(GidOnline2API.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(GidOnline2API.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 = GidOnline2API.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 = name[index1..<index2] // // var episode = [String: String]() // // episode["name"] = name // episode["id"] = url // episode["type"] = "episode" // episode["seasonNumber"] = seasonNumber // episode["episodeNumber"] = String(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 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://") // } // // print(movieUrl) // // if let response = httpRequest(movieUrl, headers: getHeaders(url)) { // print(response.response!.statusCode) // // if response.response!.statusCode == 302 { // print("2") // let newGatewayUrl = response.response!.allHeaderFields["Location"] as! String // print(newGatewayUrl) // // let response2 = httpRequest(movieUrl, headers: getHeaders(newGatewayUrl))! // // data = response2.data // } // else { // data = response.data // // let document2 = try toDocument(data)! // // let iframeBlock = try document2.select("iframe") // // let url2 = try iframeBlock.attr("src") // // //print(url2) // // if let response3 = httpRequest(url2, headers: getHeaders(url)) { // data = response3.data! // } // } // } // } // // return data // } // // func getJsonData(_ content: String) -> [String] { // let items = [String]() // // var dataSection = false // // content.enumerateLines { (line, _) in // if line.find("new VideoBalancer({") != nil { // dataSection = true // print("alex") // } // else if dataSection == true { // if line.find("};") != nil { // dataSection = false // } // else if !line.isEmpty { // //print(line) // if line.find("media: ") != nil { // let index1 = line.find("media:") // let index2 = line.find("]") // // let index11 = line.index(index1!, offsetBy: 8) // let index21 = line.index(index2!, offsetBy: -1) // let urls = line[index11 ... index21] // //// let json = JSON(urls) //// //// //print("[ " + urls + " ]") //// //print(json) //// //// for (_, _) in json { //// //print(key) //// //print(value) //// } // // } // } // } // } // // return items // } //// //// 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[class=ifram]").attr("src") //// //// if !urls.isEmpty { //// gatewayUrl = urls //// } //// else { //// let url = "\(GidOnline2API.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 //// } // // func getGatewayUrl(_ document: Document) throws -> String? { // var gatewayUrl: String? // // let frameBlock = try document.select("div[class=tray]").array()[0] // // let iframeBlock = try frameBlock.select("iframe") // // var urls: [String] = [] // // for item in iframeBlock { // urls.append(try item.attr("src")) // } // // //print(urls) // // if !urls.isEmpty { // gatewayUrl = urls[0] // } // else { // let url = "\(GidOnline2API.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) // // let iframeBlock2 = try document2!.select("iframe") // // var urls: [String] = [] // // for item in iframeBlock2 { // urls.append(try item.attr("src")) // } // // if !urls[0].trim().isEmpty { // gatewayUrl = urls[0] // } // } // // 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] a[class=mainlink]") // // for item: Element in items.array() { // let href = try item.attr("href") // let name = try item.select("span").text() // let thumb = GidOnline2API.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) // // page = try Int(paginationBlock.select("span[class=current]").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(GidOnline2API.SiteUrl) != nil && url.find("http://") == nil { //// newUrl = GidOnline2API.SiteUrl + url //// } //// //// var baseUrls: [String] = [] //// //// if let data = try getMovieContent(newUrl, season: season, episode: episode) { //// baseUrls = getJsonData(String(data: data, encoding: .utf8)!) //// //// print(baseUrls) //// } //// //// var urls: [[String: String]] = [] // //// for (index, url) in baseUrls.enumerated() { //// // 360, 480, 720, 1080 //// urls.append(["url": url, "bandwidth": String(describing: index+1)]) //// } // //// var headers: [String: String] = [:] //// //// headers["Host"] = "cdn10.hdgo.cc" //// headers["Range"] = "bytes=0-" //// headers["Referer"] = "http://ru.d99q88vn.ru/video/XCwA9HElTOvpj7pXNYrSnWTv7ChXmYqO/2139/" //// headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" //// //// print(urls[0]["url"]!) //// //// let response = httpRequest(urls[0]["url"]!, headers: headers)! //// //// if response.response!.statusCode == 302 { //// let newGatewayUrl = response.response!.allHeaderFields["Location"] as! String //// //// print("3") //// //// print(newGatewayUrl) //// ////// let response2 = httpRequest(movieUrl, headers: getHeaders(newGatewayUrl))! ////// ////// data = response2.data //// } // // //// let html = String(data: content!, encoding: .utf8) //// //// let frameCommit = getRequestTokens(html!) //// //// let parameters = getSessionData(html!) //// //// let headers: HTTPHeaders = [ //// "X-Frame-Commit": frameCommit, //// "X-Requested-With": "XMLHttpRequest" //// ] //// //// let response2 = httpRequest(sessionUrl(), headers: headers, parameters: parameters, method: .post) //// //// let data2 = JSON(data: response2!.data!) //// //// let manifests = data2["mans"] //// //// print(manifests) //// //// let manifestMp4Url = JSON(data: try manifests.rawData())["manifest_mp4"].rawString()! //// //// print(manifestMp4Url) //// //// return try getMp4Urls(manifestMp4Url).reversed() // //// return urls //// } // // public func getUrls(_ url: String, season: String = "", episode: String="") throws -> [[String: String]] { // var newUrl = url // // if url.find(GidOnline2API.SiteUrl) != nil && url.find("http://") == nil { // newUrl = GidOnline2API.SiteUrl + url // } // // var baseUrls: [String] = [] // // if let data = try getMovieContent(newUrl, season: season, episode: episode) { // print(String(data: data, encoding: .utf8)!) // // baseUrls = getJsonData(String(data: data, encoding: .utf8)!) // // print(baseUrls) // } // // let urls: [[String: String]] = [] // //// let html = String(data: content!, encoding: .utf8) //// //// let frameCommit = getRequestTokens(html!) //// //// let parameters = getSessionData(html!) //// //// let headers: HTTPHeaders = [ //// "X-Frame-Commit": frameCommit, //// "X-Requested-With": "XMLHttpRequest" //// ] //// //// let response2 = httpRequest(sessionUrl(), headers: headers, parameters: parameters, method: .post) //// //// let data2 = JSON(data: response2!.data!) //// //// let manifests = data2["mans"] //// //// print(manifests) //// //// let manifestMp4Url = JSON(data: try manifests.rawData())["manifest_mp4"].rawString()! //// //// print(manifestMp4Url) //// //// return try getMp4Urls(manifestMp4Url).reversed() // // return urls // } // // 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':".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) //// let 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 = text1[index1! ..< text1.endIndex] //// //// let index2 = text2.find("']") //// let index3 = text2.find("= '") //// //// let key = text2[text2.index(text2.startIndex, offsetBy: 2) ..< index2!] //// let value = 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(GidOnline2API.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"] = GidOnline2API.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 = GidOnline2API.SiteUrl + "/page/" // } // else { // pattern = GidOnline2API.SiteUrl + path + "page/" // } // } // else { // pattern = GidOnline2API.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: GidOnline2API.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 //// "Upgrade-Insecure-Requests": "1", ////// "Host": "moonwalk.cc" // ] // } // // 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
edc8605580a1a302d86faa40b8dbae21
27.453368
155
0.535828
3.237276
false
false
false
false
cagaray/peek-coding-challenge
PeekCodingChallenge/ViewController.swift
1
7635
// // ViewController.swift // PeekCodingChallenge // // Created by Cristián Garay on 5/13/16. // Copyright © 2016 Cristian Garay. All rights reserved. // import UIKit /* MARK: View controller with UITableView to load twitter mentions of @Peek */ class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //Table view to display twitter mentions of @Peek. @IBOutlet weak var twitterMentionsTableView: UITableView! //Activity indicator to wait for tweets to load into the tableview. @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! //Refresh control for pull to refresh functionality. lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(ViewController.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged) return refreshControl }() //Twitter request objects to interact with Twitter API (search for Tweets and Retweet) and array to save requested tweets. //TwitterRequest objects save parameters from query to query (max_id, etc.), so I use 2 objects one for querys and one for retweets so not to affect those parameters for future queries. //TODO: Query from this call to the API returns different results from query on web. Check if differences only due to advertising and such, or there is a missing parameter (query on the web is constructed the same way as here). Is including account such as @Peek-a-boo, and retweets (web don't). var twitterRequest: TwitterRequest? = TwitterRequest(search: "%40peek", count: 7, .Mixed, nil) var retweetRequest: TwitterRequest? = TwitterRequest("statuses/retweet/") var peekMentionsArray = [Tweet]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. twitterMentionsTableView.delegate = self twitterMentionsTableView.dataSource = self //Start animation of activity indicator when loading tweets. //TODO: Center animation on vertical axis with regard of entire screen. activityIndicatorView.center = self.twitterMentionsTableView.center activityIndicatorView.startAnimating() //First fetch of tweets that mentioned account @peek //TODO: Improve speed of this first query. A LOT. twitterRequest!.fetchTweets{ (tweetArray: [Tweet]) in for tweet in tweetArray { self.peekMentionsArray.append(tweet) } self.twitterMentionsTableView.reloadData() self.activityIndicatorView.stopAnimating() self.twitterMentionsTableView.addSubview(self.refreshControl) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peekMentionsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = twitterMentionsTableView.dequeueReusableCellWithIdentifier("twitterMentionsCell", forIndexPath: indexPath) as! TwitterMentionsTableViewCell cell.userNameLabel?.text = "@" + peekMentionsArray[indexPath.row].user.screenName cell.tweetLabel?.text = peekMentionsArray[indexPath.row].text cell.userAvatarImageView.image = UIImage(data: peekMentionsArray[indexPath.row].user.profileImageData!) //I choose colors that were similar to Peek's website theme. if indexPath.row % 2 == 0 { cell.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 100/100.0) cell.tweetLabel.textColor = UIColor(red: 61/255.0, green: 165/255.0, blue: 217/255.0, alpha: 100/100.0) cell.userNameLabel.textColor = UIColor(red: 61/255.0, green: 165/255.0, blue: 217/255.0, alpha: 100/100.0) } else { cell.backgroundColor = UIColor(red: 61/255.0, green: 165/255.0, blue: 217/255.0, alpha: 100/100.0) cell.tweetLabel.textColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 100/100.0) cell.userNameLabel.textColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 100/100.0) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } //When user sees the last available cell is time to load oldet tweets. func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == peekMentionsArray.count-1{ let twitterRequestForOlder = self.twitterRequest!.requestForOlder if twitterRequestForOlder != nil{ twitterRequest = twitterRequestForOlder twitterRequest!.fetchTweets{ (tweetArray: [Tweet]) in for tweet in tweetArray { self.peekMentionsArray.append(tweet) } self.twitterMentionsTableView.reloadData() } } else{ debugPrint("Infinite scroll - No more tweets to show") } } } //Search for newer tweets in pull-to-refresh functionality func handleRefresh(refreshControl: UIRefreshControl) { let twitterRequestForNewer = self.twitterRequest!.requestForNewer if twitterRequestForNewer != nil { twitterRequest = twitterRequestForNewer twitterRequest!.fetchTweets{ (tweetArray: [Tweet]) in for tweet in tweetArray { self.peekMentionsArray.insert(tweet, atIndex: 0) } self.twitterMentionsTableView.reloadData() refreshControl.endRefreshing() } refreshControl.endRefreshing() } else { debugPrint("No more tweets to show") } refreshControl.endRefreshing() } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } //Implement buttons on each row to delete tweet or retweet. Swipe to the left to see them. func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteClosure = { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in self.peekMentionsArray.removeAtIndex(indexPath.row) self.twitterMentionsTableView.reloadData() } let retweetClosure = { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in let retweetItem = self.peekMentionsArray[indexPath.row] self.retweetRequest?.retweet(retweetItem) self.twitterMentionsTableView.reloadData() } let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: deleteClosure) let retweetAction = UITableViewRowAction(style: .Normal, title: "Retweet", handler: retweetClosure) return [deleteAction, retweetAction] } }
mit
e973505cebf35b36c2d86c4be8c811bf
44.434524
299
0.665924
5.07851
false
false
false
false
groue/GRMustache.swift
Tests/Public/ConfigurationTests/ConfigurationBaseContextTests.swift
2
6716
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class ConfigurationBaseContextTests: XCTestCase { override func tearDown() { super.tearDown() DefaultConfiguration = Configuration() } func testDefaultConfigurationCustomBaseContext() { DefaultConfiguration.baseContext = Context(["foo": "success"]) let template = try! Template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testTemplateBaseContextOverridesDefaultConfigurationBaseContext() { DefaultConfiguration.baseContext = Context(["foo": "failure"]) let template = try! Template(string: "{{foo}}") template.baseContext = Context(["foo": "success"]) let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testDefaultRepositoryConfigurationHasDefaultConfigurationBaseContext() { DefaultConfiguration.baseContext = Context(["foo": "success"]) let repository = TemplateRepository() let template = try! repository.template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testRepositoryConfigurationBaseContextWhenSettingTheWholeConfiguration() { var configuration = Configuration() configuration.baseContext = Context(["foo": "success"]) let repository = TemplateRepository() repository.configuration = configuration let template = try! repository.template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testRepositoryConfigurationBaseContextWhenUpdatingRepositoryConfiguration() { let repository = TemplateRepository() repository.configuration.baseContext = Context(["foo": "success"]) let template = try! repository.template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testRepositoryConfigurationBaseContextOverridesDefaultConfigurationBaseContextWhenSettingTheWholeConfiguration() { DefaultConfiguration.baseContext = Context(["foo": "failure"]) var configuration = Configuration() configuration.baseContext = Context(["foo": "success"]) let repository = TemplateRepository() repository.configuration = configuration let template = try! repository.template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testRepositoryConfigurationBaseContextOverridesDefaultConfigurationBaseContextWhenUpdatingRepositoryConfiguration() { DefaultConfiguration.baseContext = Context(["foo": "failure"]) let repository = TemplateRepository() repository.configuration.baseContext = Context(["foo": "success"]) let template = try! repository.template(string: "{{foo}}") let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testTemplateBaseContextOverridesRepositoryConfigurationBaseContextWhenSettingTheWholeConfiguration() { var configuration = Configuration() configuration.baseContext = Context(["foo": "failure"]) let repository = TemplateRepository() repository.configuration = configuration let template = try! repository.template(string: "{{foo}}") template.baseContext = Context(["foo": "success"]) let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testTemplateBaseContextOverridesRepositoryConfigurationBaseContextWhenUpdatingRepositoryConfiguration() { let repository = TemplateRepository() repository.configuration.baseContext = Context(["foo": "failure"]) let template = try! repository.template(string: "{{foo}}") template.baseContext = Context(["foo": "success"]) let rendering = try! template.render() XCTAssertEqual(rendering, "success") } func testDefaultConfigurationMutationHasNoEffectAfterAnyTemplateHasBeenCompiled() { let repository = TemplateRepository() var rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render() XCTAssertEqual(rendering, "success") DefaultConfiguration.baseContext = Context(["foo": "failure"]) rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render() XCTAssertEqual(rendering, "success") } func testRepositoryConfigurationMutationHasNoEffectAfterAnyTemplateHasBeenCompiled() { let repository = TemplateRepository() var rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render() XCTAssertEqual(rendering, "success") repository.configuration.baseContext = Context(["foo": "failure"]) rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render() XCTAssertEqual(rendering, "success") var configuration = Configuration() configuration.baseContext = Context(["foo": "failure"]) repository.configuration = configuration rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render() XCTAssertEqual(rendering, "success") } }
mit
f05c5727aeca6d2977249da74f90e399
41.5
126
0.676992
5.567993
false
true
false
false
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/Extentions/UITableView+Utility.swift
1
1436
// // UITableView+Fade.swift // GISTFramework // // Created by Shoaib on 5/18/15. // Copyright (c) 2015 Social Cubix. All rights reserved. // import UIKit // MARK: - UITableView extension for Utility Method public extension UITableView { public func reloadData(_ animated:Bool, completion:(()->Void)? = nil) { if (animated) { self.fadeOut({ (finished) -> () in self.reloadData(); self.fadeIn(); completion?(); }) } else { self.reloadData(); completion?(); } } //F.E. public func scrollToBottom(_ animated: Bool = true) { let delay = 0.1 * Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { let numberOfSections = self.numberOfSections let numberOfRows = self.numberOfRows(inSection: numberOfSections-1) if numberOfRows > 0 { let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1)); self.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: animated) } } } //F.E. public func scrollToTop(_ animated: Bool = true) { self.setContentOffset(CGPoint.zero, animated: animated); } //F.E. } //E.E.
gpl-3.0
cb3136573b7bb57e9535f092c7cf87b5
28.306122
105
0.532033
4.802676
false
false
false
false
rmalabuyoc/treehouse-tracks
ios-development-with-swift/Stormy/Stormy/Current.swift
1
2069
// // Current.swift // Stormy // // Created by Ryzan on 2015-05-17. // Copyright (c) 2015 Ryzan. All rights reserved. // import Foundation import UIKit struct Current { var currentTime: String? var temperature: Int var humidity: Double var precipProbability: Double var summary: String var icon: UIImage? init(weatherDictionary: NSDictionary) { let currentWeather = weatherDictionary["currently"] as! NSDictionary let currentTimeValue = currentWeather["time"] as! Int let iconString = currentWeather["icon"] as! String temperature = currentWeather["temperature"] as! Int humidity = currentWeather["humidity"] as! Double precipProbability = currentWeather["precipProbability"] as! Double summary = currentWeather["summary"] as! String currentTime = dateStringFromUnixTime(currentTimeValue) // Set last since it's using an instance method icon = weatherIconFromString(iconString) } func dateStringFromUnixTime(unixTime: Int) -> String { let timeInSeconds = NSTimeInterval(unixTime) let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds) let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = .ShortStyle return dateFormatter.stringFromDate(weatherDate) } func weatherIconFromString(stringIcon: String) -> UIImage { var imageName: String switch stringIcon { case "clear-day": imageName = "clear-day" case "clear-night": imageName = "clear-night" case "rain": imageName = "rain" case "snow": imageName = "snow" case "sleet": imageName = "sleet" case "wind": imageName = "wind" case "fog": imageName = "fog" case "cloudy": imageName = "cloudy" case "partly-cloudy-day": imageName = "partly-cloudy" case "partly-cloudy-night": imageName = "cloudy-night" default: imageName = "default" } let iconImage = UIImage(named: imageName) return iconImage! } }
mit
06020b3e9d2369d207ede68c52231015
25.883117
106
0.656356
4.587583
false
false
false
false
andreamarcolin/NewsAPIClient
NewsAPIClient/Classes/Source.swift
1
2673
// // Source.swift // NewsAPIClient // // Created by Andrea Marcolin (Twitter @andreamarcolin5) on 14/12/16. // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation public extension NewsAPIClient { /// A struct which represents a Source entity from NewsAPI.org APIs public struct Source { public let id: String public let name: String public let description: String public let url: String public let category: String public let language: String public let country: String public let logoUrls: [String : String] public let availableSortBys: [String : String] /// The init method for Source /// /// - Parameters: /// - id: the unique identifier for the news source. This is needed when querying the /articles endpoint to retrieve article metadata /// - name: the display-friendly name of the news source /// - description: a brief description of the news source and what area they specialize in /// - url: the base URL or homepage of the source /// - category: the topic category that the source focuses on /// - language: the 2-letter ISO-639-1 code for the language that the source is written in /// - country: the 2-letter ISO 3166-1 code of the country that the source mainly focuses on /// - logoUrls: an array containing URLs to the source's logo, in different sizes /// - availableSortBys: the available headline lists for the news source /// - Throws: an InitializationError if somthing fails during properties initialization (eg. invalid URLs or unknown languages, categories and countries) init(id: String, name: String, description: String, url: String, category: String, language: String, country: String, logoUrls: [String : String], availableSortBys: [String]) { // Assign the parsed objects to struct properties self.id = id self.name = name self.description = description self.url = url self.category = category self.language = language self.country = country self.logoUrls = logoUrls // Build a dictionary from array values with same key as value, so we can take advantage of access by String var parsedAvailableSortBys = [String : String]() for sortBy in availableSortBys { parsedAvailableSortBys[sortBy] = sortBy } self.availableSortBys = parsedAvailableSortBys } } }
mit
91af9942f61f61d8a753c43061ddb6b0
43.55
184
0.631874
4.82491
false
false
false
false
swift102016team5/mefocus
MeFocus/MeFocus/Auth.swift
1
1821
// // Auth.swift // MeFocus // // Created by Hao on 11/19/16. // Copyright © 2016 Group5. All rights reserved. // import UIKit import Lock import SimpleKeychain class Auth: NSObject { static private var _shared:Auth? static var shared:Auth{ get { if self._shared == nil { self._shared = Auth() } return self._shared! } } var profile:A0UserProfile? { didSet { if let p = profile { keychain.setData( NSKeyedArchiver.archivedData(withRootObject: p), forKey: "profile" ) } } } var token:A0Token? { didSet { if let t = token { keychain.setString(t.idToken, forKey: "idToken") } } } var keychain:A0SimpleKeychain var client:A0APIClient override init() { keychain = A0SimpleKeychain(service: "Auth0") client = A0Lock.shared().apiClient() } func check(completion:@escaping ((Auth)->Void)){ if profile != nil { completion(self) return } guard let idToken = keychain.string(forKey: "idToken") else { completion(self) return } client.fetchUserProfile( withIdToken: idToken, success: { profile in // Our idToken is still valid... // We store the fetched user profile self.profile = profile completion(self) }, failure: { error in self.keychain.clearAll() completion(self) } ) } }
mit
c396844cd5f966a39f51211e17fb0b1f
20.927711
69
0.464835
4.972678
false
false
false
false
sublimter/Meijiabang
KickYourAss/KickYourAss/ZXY_Start/ZXY_ThirdPartyFile/ZXY_SheetView.swift
3
8349
// // ZXY_SheetView.swift // ZXYPrettysHealth // // Created by 宇周 on 15/1/16. // Copyright (c) 2015年 宇周. All rights reserved. // import UIKit protocol ZXY_SheetViewDelegate : class { /** sheet点击代理时间 :param: sheetView 所创建的sheetView 实例 :param: index 非负表示用户点击按钮 ,-1表示点击取消 :returns: 返回空 */ func clickItemAtIndex(sheetView: ZXY_SheetView,index: Int) -> Void } class ZXY_SheetView: UIView { private var titleString : String? private var cancelString: String? private var listString : [String]? private var currentTable : UITableView! private var imgBack : UIImageView? private var tableHeight = 30.0 private var _parentView : UIView? private var backCo = UIColor(red: 218/255.0, green: 214/255.0, blue: 218/255.0, alpha: 1) var delegate : ZXY_SheetViewDelegate? /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ /** 实例化方法 :param: zxyTitle 标题 设置为nil :param: cancelBtn 取消按钮的标题 :param: messages 需要显示的按钮的文字聊表 :returns: 实例 */ init(zxyTitle : String?,cancelBtn: String?,andMessage messages : String...) { super.init(frame: UIScreen.mainScreen().bounds) self.backgroundColor = UIColor.lightGrayColor() self.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 0.0) self.opaque = true self.clipsToBounds = true self.titleString = zxyTitle self.cancelString = cancelBtn self.listString = messages if let isNil = currentTable { } else { currentTable = UITableView() currentTable.backgroundColor = self.backCo currentTable.separatorStyle = UITableViewCellSeparatorStyle.None currentTable.delegate = self currentTable.dataSource = self currentTable.bounces = false currentTable.registerClass(ZXY_SheetViewCell.self, forCellReuseIdentifier: ZXY_SheetViewCellID) currentTable.tableFooterView = UIView(frame: CGRectZero) self.addSubview(currentTable) } } func setBackCo(backCO : UIColor) { self.backCo = backCO } func getTableHeight() -> CGFloat { var currentHeight : CGFloat = 20 if(titleString != nil) { currentHeight += 50 } if(cancelString != nil) { currentHeight += 50 } for var i = 0; i < listString?.count ;i++ { currentHeight += 50 } if(currentHeight > self.frame.size.height) { return 600 } else { return currentHeight } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 显示sheet :param: parentV 父类视图 */ func showSheet(parentV : UIView) -> Void { self._parentView = parentV self.frame = CGRectMake(0, parentV.frame.size.height, parentV.frame.size.width, parentV.frame.size.height) if(imgBack == nil) { imgBack = UIImageView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)) imgBack?.userInteractionEnabled = true } imgBack?.backgroundColor = UIColor.blackColor() imgBack?.alpha = 0 parentV.addSubview(imgBack!) var tapImg = UITapGestureRecognizer(target: self, action: Selector("tapImageMethod")) self.addGestureRecognizer(tapImg) currentTable.frame = CGRectMake(0, self.frame.size.height-self.getTableHeight(), self.frame.size.width, self.getTableHeight()) parentV.addSubview(self) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {[weak self] () -> Void in self?.imgBack?.alpha = 0.4 self?.frame = CGRectMake(0, 0, parentV.frame.size.width, parentV.frame.size.height) }) { (Bool) -> Void in } } func tapImageMethod() -> Void { if let isNil = _parentView { self.hideSheet(self._parentView!) } else { assert({ self._parentView == nil }(), { "Parent view is nil" }()) } } func hideSheet(parentV : UIView?) { if(parentV == nil) { return } UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {[weak self] () -> Void in self?.imgBack?.alpha = 0 if var isNil = self?._parentView { self?.frame = CGRectMake(0, parentV!.frame.size.height, parentV!.frame.size.width, parentV!.frame.size.height) } }) { [weak self](Bool) -> Void in self?.removeFromSuperview() self?.imgBack?.removeFromSuperview() } } } extension ZXY_SheetView :UITableViewDataSource,UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var currentSection = indexPath.section var currentRow = indexPath.row var cell = tableView.dequeueReusableCellWithIdentifier(ZXY_SheetViewCellID) as ZXY_SheetViewCell cell.backgroundColor = backCo if(currentSection == 0) { cell.setBtnString(titleString) cell.setCurrentIndex(-2) } else if(currentSection == 1) { cell.setBtnString(listString![currentRow]) cell.setCurrentIndex(currentRow) } else { cell.setBtnString(cancelString) cell.setCurrentIndex(-1) cell.setBackColor(UIColor.lightGrayColor()) cell.setTxTColor(UIColor.whiteColor()) } cell.delegate = self return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if(section == 1) { return 10 } else if(section == 2) { return 10 } else { return 0 } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(section == 0) { if(titleString == nil) { return 0 } return 1 } else if (section == 1) { if let isNil = listString { return listString!.count } else { return 0 } } else { if(cancelString == nil) { return 0 } return 1 } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var curr: UIView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, 15)) curr.backgroundColor = backCo return curr } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } } extension ZXY_SheetView : SheetViewCellDelegate { func clickButtonWithIndex(index: Int) { if(self.delegate != nil) { self.delegate?.clickItemAtIndex(self, index: index) } self.tapImageMethod() } }
mit
1b2e58f2ad82a4b6cc57b55cb25c0fdd
27.775439
193
0.562492
4.705106
false
false
false
false
GraphQLSwift/GraphQL
Tests/GraphQLTests/LanguageTests/ParserTests.swift
1
15524
@testable import GraphQL import XCTest class ParserTests: XCTestCase { func testErrorMessages() throws { var source: String XCTAssertThrowsError(try parse(source: "{")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssertEqual( error.message, """ Syntax Error GraphQL (1:2) Expected Name, found <EOF> 1: { ^ """ ) XCTAssertEqual(error.positions, [1]) XCTAssertEqual(error.locations[0].line, 1) XCTAssertEqual(error.locations[0].column, 2) } XCTAssertThrowsError(try parse(source: "{ ...MissingOn }\nfragment MissingOn Type\n")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (2:20) Expected \"on\", found Name \"Type\"" )) } XCTAssertThrowsError(try parse(source: "{ field: {} }")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:10) Expected Name, found {" )) } XCTAssertThrowsError(try parse(source: "notanoperation Foo { field }")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:1) Unexpected Name \"notanoperation\"" )) } XCTAssertThrowsError(try parse(source: "...")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:1) Unexpected ..." )) } XCTAssertThrowsError(try parse(source: Source( body: "query", name: "MyQuery.graphql" ))) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error MyQuery.graphql (1:6) Expected {, found <EOF>" )) } source = "query Foo($x: Complex = { a: { b: [ $var ] } }) { field }" XCTAssertThrowsError(try parse(source: source)) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:37) Unexpected $" )) } XCTAssertThrowsError(try parse(source: "fragment on on on { on }")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:10) Unexpected Name \"on\"" )) } XCTAssertThrowsError(try parse(source: "{ ...on }")) { error in guard let error = error as? GraphQLError else { return XCTFail() } XCTAssert(error.message.contains( "Syntax Error GraphQL (1:9) Expected Name, found }" )) } } func testVariableInlineValues() throws { _ = try parse(source: "{ field(complex: { a: { b: [ $var ] } }) }") } func testFieldWithArguments() throws { let query = """ { stringArgField(stringArg: "Hello World") intArgField(intArg: 1) floatArgField(floatArg: 3.14) falseArgField(boolArg: false) trueArgField(boolArg: true) nullArgField(value: null) enumArgField(enumArg: VALUE) multipleArgs(arg1: 1, arg2: false, arg3: THIRD) } """ let expected = Document( definitions: [ OperationDefinition( operation: .query, selectionSet: SelectionSet( selections: [ Field( name: Name(value: "stringArgField"), arguments: [ Argument( name: Name(value: "stringArg"), value: StringValue(value: "Hello World", block: false) ), ] ), Field( name: Name(value: "intArgField"), arguments: [ Argument( name: Name(value: "intArg"), value: IntValue(value: "1") ), ] ), Field( name: Name(value: "floatArgField"), arguments: [ Argument( name: Name(value: "floatArg"), value: FloatValue(value: "3.14") ), ] ), Field( name: Name(value: "falseArgField"), arguments: [ Argument( name: Name(value: "boolArg"), value: BooleanValue(value: false) ), ] ), Field( name: Name(value: "trueArgField"), arguments: [ Argument( name: Name(value: "boolArg"), value: BooleanValue(value: true) ), ] ), Field( name: Name(value: "nullArgField"), arguments: [ Argument( name: Name(value: "value"), value: NullValue() ), ] ), Field( name: Name(value: "enumArgField"), arguments: [ Argument( name: Name(value: "enumArg"), value: EnumValue(value: "VALUE") ), ] ), Field( name: Name(value: "multipleArgs"), arguments: [ Argument( name: Name(value: "arg1"), value: IntValue(value: "1") ), Argument( name: Name(value: "arg2"), value: BooleanValue(value: false) ), Argument( name: Name(value: "arg3"), value: EnumValue(value: "THIRD") ), ] ), ] ) ), ] ) let document = try parse(source: query) XCTAssert(document == expected) } // it('parses multi-byte characters', async () => { // // Note: \u0A0A could be naively interpretted as two line-feed chars. // expect( // parse(` // # This comment has a \u0A0A multi-byte character. // { field(arg: "Has a \u0A0A multi-byte character.") } // `) // ).to.containSubset({ // definitions: [ { // selectionSet: { // selections: [ { // arguments: [ { // value: { // kind: Kind.STRING, // value: 'Has a \u0A0A multi-byte character.' // } // } ] // } ] // } // } ] // }); // }); func testKitchenSink() throws { // let path = "/Users/paulofaria/Development/Zewo/GraphQL/Tests/GraphQLTests/LanguageTests/kitchen-sink.graphql" // let kitchenSink = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) // _ = try parse(source: kitchenSink as String) } func testNonKeywordAsName() throws { let nonKeywords = [ "on", "fragment", "query", "mutation", "subscription", "true", "false", ] for nonKeyword in nonKeywords { var fragmentName = nonKeyword // You can't define or reference a fragment named `on`. if nonKeyword == "on" { fragmentName = "a" } _ = try parse( source: "query \(nonKeyword) {" + "... \(fragmentName)" + "... on \(nonKeyword) { field }" + "}" + "fragment \(fragmentName) on Type {" + "\(nonKeyword)(\(nonKeyword): $\(nonKeyword)) @\(nonKeyword)(\(nonKeyword): \(nonKeyword))" + "}" ) } } func testAnonymousMutationOperation() throws { _ = try parse( source: "mutation {" + " mutationField" + "}" ) } func testAnonymousSubscriptionOperation() throws { _ = try parse( source: "subscription {" + " subscriptionField" + "}" ) } func testNamedMutationOperation() throws { _ = try parse( source: "mutation Foo {" + " mutationField" + "}" ) } func testNamedSubscriptionOperation() throws { _ = try parse( source: "subscription Foo {" + " subscriptionField" + "}" ) } func testCreateAST() throws { let query = "{" + " node(id: 4) {" + " id," + " name" + " }" + "}" let expected = Document( definitions: [ OperationDefinition( operation: .query, selectionSet: SelectionSet( selections: [ Field( name: Name(value: "node"), arguments: [ Argument( name: Name(value: "id"), value: IntValue(value: "4") ), ], selectionSet: SelectionSet( selections: [ Field(name: Name(value: "id")), Field(name: Name(value: "name")), ] ) ), ] ) ), ] ) XCTAssert(try parse(source: query) == expected) } func testNoLocation() throws { let result = try parse(source: "{ id }", noLocation: true) XCTAssertNil(result.loc) } func testLocationSource() throws { let source = Source(body: "{ id }") let result = try parse(source: source) XCTAssertEqual(result.loc?.source, source) } func testLocationTokens() throws { let source = Source(body: "{ id }") let result = try parse(source: source) XCTAssertEqual(result.loc?.startToken.kind, .sof) XCTAssertEqual(result.loc?.endToken.kind, .eof) } func testParseValue() throws { let source = "[123 \"abc\"]" let expected: Value = ListValue( values: [ IntValue(value: "123"), StringValue(value: "abc", block: false), ] ) XCTAssert(try parseValue(source: source) == expected) } func testParseType() throws { var source: String var expected: Type source = "String" expected = NamedType( name: Name(value: "String") ) XCTAssert(try parseType(source: source) == expected) source = "MyType" expected = NamedType( name: Name(value: "MyType") ) XCTAssert(try parseType(source: source) == expected) source = "[MyType]" expected = ListType( type: NamedType( name: Name(value: "MyType") ) ) XCTAssert(try parseType(source: source) == expected) source = "MyType!" expected = NonNullType( type: NamedType( name: Name(value: "MyType") ) ) XCTAssert(try parseType(source: source) == expected) source = "[MyType!]" expected = ListType( type: NonNullType( type: NamedType( name: Name(value: "MyType") ) ) ) XCTAssert(try parseType(source: source) == expected) } func testParseDirective() throws { let source = #""" directive @restricted( """The reason for this restriction""" reason: String = null ) on FIELD_DEFINITION """# let expected = Document(definitions: [ DirectiveDefinition( description: nil, name: Name(value: "restricted"), arguments: [ InputValueDefinition( description: StringValue( value: "The reason for this restriction", block: true ), name: Name(value: "reason"), type: NamedType(name: Name(value: "String")), defaultValue: NullValue() ), ], locations: [ Name(value: "FIELD_DEFINITION"), ] ), ]) let document = try parse(source: source) XCTAssert(document == expected) } }
mit
90d80106203911e47b591fb044a3f54e
31.751055
119
0.391265
5.626676
false
false
false
false
zhwayne/WLReloadPromptView
WLReloadPromptView/ViewController.swift
1
2773
// // ViewController.swift // WLReloadPromptView // // Created by Wayne on 15/12/24. // Copyright © 2015年 ZHWAYNE. All rights reserved. // import UIKit class ViewController: UIViewController, WLReloadPromptViewDelegate, WLReloadPromptViewDataSource { @IBOutlet weak var iamgeView: UIImageView! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! var reloadPromptView: WLReloadPromptView! var shouldReload = true deinit { print("deinit") } override func viewDidLoad() { super.viewDidLoad() reloadPromptView = WLReloadPromptView.init(viewController: self) // 模拟网络不畅 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.activityIndicatorView.isHidden = true; self.reloadPromptView.appear() } } func reloadPromptViewAllowedReload() -> Bool { return shouldReload } func image(in promptView: WLReloadPromptView) -> UIImage { return #imageLiteral(resourceName: "wifi") } func description(in promptView: WLReloadPromptView) -> NSAttributedString { let string = NSAttributedString.init(string: "您的网络环境不太顺畅", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)]) return string } func button(in promptView: WLReloadPromptView) -> UIControl { let button = UIButton.init(type: .system) button.setTitle("点击重试", for: .normal) button.bounds = CGRect.init(origin: .zero, size: .init(width: 128, height: 34)) button.setTitleColor(UIColor.darkGray, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16) button.layer.cornerRadius = 4 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.darkGray.cgColor return button } func didTapedReloadButton(in reloadView: WLReloadPromptView) { activityIndicatorView.isHidden = false; activityIndicatorView.startAnimating(); view.bringSubview(toFront: self.activityIndicatorView) shouldReload = false URLSession.shared.dataTask(with: URL.init(string: "http://img.hb.aicdn.com/363be1dcb8896a5307c0c5149b056929b7e9084618aee-Fcy2rj_fw658")!, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { self.iamgeView.image = UIImage(data: data!) self.activityIndicatorView.isHidden = true self.shouldReload = true self.reloadPromptView.disappear() }) }).resume() } }
mit
613a8c6018d34bd06f66cdebb5159cb1
34.921053
201
0.658608
4.482759
false
false
false
false
jongwonwoo/learningswift
Swift 3 Functional Programming/Dealing with Optionals.playground/Contents.swift
1
566
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let dict = ["One": 1, "Two": 2, "Three": 3] let firstValue = dict["One"] let implictlyUnwrappedFirstValue: Int! = dict["One"] class Residence { var numberOfRooms = 1 } class Person { var residence: Residence? } let residence = Residence() residence.numberOfRooms = 5 let sangeeth = Person() sangeeth.residence = residence if let roomCount = sangeeth.residence?.numberOfRooms { print(roomCount) } //let roomCount = sangeeth.residence!.numberOfRooms
mit
5fa4e68635f9b543b16aed5fe6bc8c89
17.866667
54
0.710247
3.5375
false
false
false
false
gregomni/swift
stdlib/public/Concurrency/ContinuousClock.swift
7
5116
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift /// A clock that measures time that always increments but does not stop /// incrementing while the system is asleep. /// /// `ContinuousClock` can be considered as a stopwatch style time. The frame of /// reference of the `Instant` may be bound to process launch, machine boot or /// some other locally defined reference point. This means that the instants are /// only comparable locally during the execution of a program. /// /// This clock is suitable for high resolution measurements of execution. @available(SwiftStdlib 5.7, *) public struct ContinuousClock { /// A continuous point in time used for `ContinuousClock`. public struct Instant: Codable, Sendable { internal var _value: Swift.Duration internal init(_value: Swift.Duration) { self._value = _value } } public init() { } } @available(SwiftStdlib 5.7, *) extension Clock where Self == ContinuousClock { /// A clock that measures time that always increments but does not stop /// incrementing while the system is asleep. /// /// try await Task.sleep(until: .now + .seconds(3), clock: .continuous) /// @available(SwiftStdlib 5.7, *) public static var continuous: ContinuousClock { return ContinuousClock() } } @available(SwiftStdlib 5.7, *) extension ContinuousClock: Clock { /// The current continuous instant. public var now: ContinuousClock.Instant { ContinuousClock.now } /// The minimum non-zero resolution between any two calls to `now`. public var minimumResolution: Swift.Duration { var seconds = Int64(0) var nanoseconds = Int64(0) _getClockRes( seconds: &seconds, nanoseconds: &nanoseconds, clock: _ClockID.continuous.rawValue) return .seconds(seconds) + .nanoseconds(nanoseconds) } /// The current continuous instant. public static var now: ContinuousClock.Instant { var seconds = Int64(0) var nanoseconds = Int64(0) _getTime( seconds: &seconds, nanoseconds: &nanoseconds, clock: _ClockID.continuous.rawValue) return ContinuousClock.Instant(_value: .seconds(seconds) + .nanoseconds(nanoseconds)) } /// Suspend task execution until a given deadline within a tolerance. /// If no tolerance is specified then the system may adjust the deadline /// to coalesce CPU wake-ups to more efficiently process the wake-ups in /// a more power efficient manner. /// /// If the task is canceled before the time ends, this function throws /// `CancellationError`. /// /// This function doesn't block the underlying thread. public func sleep( until deadline: Instant, tolerance: Swift.Duration? = nil ) async throws { let (seconds, attoseconds) = deadline._value.components let nanoseconds = attoseconds / 1_000_000_000 try await Task._sleep(until:seconds, nanoseconds, tolerance: tolerance, clock: .continuous) } } @available(SwiftStdlib 5.7, *) extension ContinuousClock.Instant: InstantProtocol { public static var now: ContinuousClock.Instant { ContinuousClock.now } public func advanced(by duration: Swift.Duration) -> ContinuousClock.Instant { return ContinuousClock.Instant(_value: _value + duration) } public func duration(to other: ContinuousClock.Instant) -> Swift.Duration { other._value - _value } public func hash(into hasher: inout Hasher) { hasher.combine(_value) } public static func == ( _ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant ) -> Bool { return lhs._value == rhs._value } public static func < ( _ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant ) -> Bool { return lhs._value < rhs._value } @_alwaysEmitIntoClient @inlinable public static func + ( _ lhs: ContinuousClock.Instant, _ rhs: Swift.Duration ) -> ContinuousClock.Instant { lhs.advanced(by: rhs) } @_alwaysEmitIntoClient @inlinable public static func += ( _ lhs: inout ContinuousClock.Instant, _ rhs: Swift.Duration ) { lhs = lhs.advanced(by: rhs) } @_alwaysEmitIntoClient @inlinable public static func - ( _ lhs: ContinuousClock.Instant, _ rhs: Swift.Duration ) -> ContinuousClock.Instant { lhs.advanced(by: .zero - rhs) } @_alwaysEmitIntoClient @inlinable public static func -= ( _ lhs: inout ContinuousClock.Instant, _ rhs: Swift.Duration ) { lhs = lhs.advanced(by: .zero - rhs) } @_alwaysEmitIntoClient @inlinable public static func - ( _ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant ) -> Swift.Duration { rhs.duration(to: lhs) } }
apache-2.0
173798120e208c7710614dda2b33fd67
30.006061
80
0.673378
4.284757
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Main/Controller/WKWebViewController.swift
1
6941
// // WKWebViewController.swift // ProductionReport // // Created by i-Techsys.com on 17/2/16. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import WebKit class WKWebViewController: UIViewController { // MARK: - lazy fileprivate lazy var webView: WKWebView = { [unowned self] in // 创建webveiew let webView = WKWebView(frame: self.view.bounds) webView.navigationDelegate = self webView.uiDelegate = self return webView }() fileprivate lazy var progressView: UIProgressView = { let progressView = UIProgressView(progressViewStyle: .bar) progressView.frame.size.width = self.view.frame.size.width // 这里可以改进度条颜色 progressView.tintColor = UIColor.green return progressView }() // MARK: - 生命周期 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) view.addSubview(webView) view.insertSubview(progressView, aboveSubview: webView) } convenience init(navigationTitle: String, urlStr: String) { self.init(nibName: nil, bundle: nil) navigationItem.title = navigationTitle webView.load(URLRequest(url: URL(string: urlStr)!)) } convenience init(navigationTitle: String, url: URL) { self.init(nibName: nil, bundle: nil) navigationItem.title = navigationTitle webView.load(URLRequest(url: url)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge() webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "v2_refresh"), style: .plain, target: self, action: #selector(self.refreshClick)) } // MARK: - Action @objc fileprivate func refreshClick() { if webView.url != nil && webView.url!.absoluteString.count > 1 { webView.reload() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "loading" { // print("loading") } else if keyPath == "title" { // title = self.webView.title } else if keyPath == "estimatedProgress" { print(webView.estimatedProgress) progressView.setProgress(Float(webView.estimatedProgress), animated: false) } self.progressView.isHidden = (self.progressView.progress == 1) if webView.isLoading == true { // 手动调用JS代码 let js = "callJsAlert()" webView.evaluateJavaScript(js, completionHandler: { (any, err) in debugPrint(any) }) } } // 移除观察者 deinit { webView.removeObserver(self, forKeyPath: "loading") webView.removeObserver(self, forKeyPath: "title") webView.removeObserver(self, forKeyPath: "estimatedProgress") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - WKScriptMessageHandler extension WKWebViewController: WKScriptMessageHandler { // WKScriptMessageHandler:必须实现的函数,是APP与js交互,提供从网页中收消息的回调方法 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.body) print(message.webView) } } // MARK: - WKNavigationDelegate extension WKWebViewController: WKNavigationDelegate { // 决定导航的动作,通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制,不允许跨域,因此我们要对不能跨域的链接 // 单独处理。但是,对于Safari是允许跨域的,不用这么处理。 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let hostname = (navigationAction.request as NSURLRequest).url?.host?.lowercased() debugPrint(hostname ?? "http://baidu.com") debugPrint(navigationAction.navigationType) // if hostname != nil ,hostname!.hasPrefix("http") { // hostname = "http:" + hostname! // } // 处理跨域问题 if navigationAction.navigationType == .linkActivated && hostname!.contains(".baidu.com") { // 手动跳转 UIApplication.shared.openURL(navigationAction.request.url!) // 不允许导航 decisionHandler(.cancel) } else { decisionHandler(.allow) } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print(#function) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { print(#function) decisionHandler(.allow) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print(#function) completionHandler(.performDefaultHandling, nil) } } // MARK: - WKUIDelegate extension WKWebViewController: WKUIDelegate { func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: "tip", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (_) -> Void in // We must call back js completionHandler() })) self.present(alert, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { completionHandler(true) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { completionHandler("woqu") } func webViewDidClose(_ webView: WKWebView) { print("close") } }
mit
7f8959d715a9930c9631af9e39fa8a78
37.593023
201
0.660892
4.917037
false
false
false
false
HPE-Haven-OnDemand/havenondemand-ios-swift
HODClient/lib/HODResponseParser.swift
1
43880
// // HODResponseParser.swift // Parse HOD API Responses // // Created by MAC_USER on 9/25/15. // Copyright (c) 2015 PhongVu. All rights reserved. // import Foundation public struct HODErrorCode { static let IN_PROGRESS = 1610 static let QUEUED = 1620 static let NONSTANDARD_RESPONSE = 1630 static let INVALID_PARAM = 1640 static let INVALID_HOD_RESPONSE = 1650 static let UNKNOWN_ERROR = 1660 } public class HODResponseParser { var hodErrors : NSMutableArray = [] public init() { } public func GetLastError() -> NSMutableArray { return hodErrors } private func resetErrors() { hodErrors.removeAllObjects() } private func addError(error : HODErrorObject) { hodErrors.addObject(error) } public func ParseJobID(jsonStr:String) -> String? { var jobID : String? if (jsonStr.characters.count != 0) { let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding) do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) guard let _ :NSDictionary = json as? NSDictionary else { return jobID } jobID = json.valueForKey("jobID") as? String } catch { return jobID } } return jobID } public func getResult(inout jsonStr:String) -> String? { resetErrors() var result = jsonStr if (jsonStr.characters.count == 0) { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Empty response.\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: jsonObj) addError(hodError) return nil } let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding) do { let jsonObj = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) guard let _ :NSDictionary = jsonObj as? NSDictionary else { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response.\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: jsonObj) addError(hodError) return nil } if let actions = jsonObj["actions"] as? NSArray { let status = actions[0].valueForKey("status") as? String if status == "finished" || status == "FINISHED" { let jsonData: NSData? do { jsonData = try NSJSONSerialization.dataWithJSONObject((actions[0].valueForKey("result") as? NSDictionary)!, options: []) result = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)! as String } catch let error as NSError { let err = String(format: "%@%d%@%@%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"", error.localizedDescription, "\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } } else if status == "failed" { let errors = actions[0].valueForKey("errors") as! NSArray for item in errors { let hodError = HODErrorObject(json: item as! NSDictionary) addError(hodError) } return nil } else if status == "queued" { var jobID = jsonObj.valueForKey("jobID") as? String jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let err = String(format: "%@%d%@%@%@", "{\"error\":", HODErrorCode.QUEUED,",\"reason\":\"Task is in queue\",\"jobID\":\"", jobID!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } else if status == "in progress" { var jobID = jsonObj.valueForKey("jobID") as? String jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let err = String(format: "%@%d%@%@%@", "{\"error\":",HODErrorCode.IN_PROGRESS,",\"reason\":\"Task is in progress\",\"jobID\":\"", jobID!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } else { let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.UNKNOWN_ERROR,",\"reason\":\"", status!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } } else { // handle error for sync mode var isError = false for (key, _) in jsonObj as! NSDictionary { if key as! String == "error" { let hodError = HODErrorObject(json: jsonObj as! NSDictionary) addError(hodError) isError = true } } if isError == true { return nil } } } catch { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } return result } private func logParserError(error:NSError) { let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.INVALID_HOD_RESPONSE,",\"reason\":\"", error.localizedDescription, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) } public func ParseSpeechRecognitionResponse(inout jsonStr:String) -> SpeechRecognitionResponse? { var obj : SpeechRecognitionResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = SpeechRecognitionResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseCancelConnectorScheduleResponse(inout jsonStr:String) -> CancelConnectorScheduleResponse? { var obj : CancelConnectorScheduleResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = CancelConnectorScheduleResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseConnectorHistoryResponse(inout jsonStr:String) -> ConnectorHistoryResponse? { var obj : ConnectorHistoryResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ConnectorHistoryResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseConnectorStatusResponse(inout jsonStr:String) -> ConnectorStatusResponse? { var obj : ConnectorStatusResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ConnectorStatusResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseCreateConnectorResponse(inout jsonStr:String) -> CreateConnectorResponse? { var obj : CreateConnectorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = CreateConnectorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseDeleteConnectorResponse(inout jsonStr:String) -> DeleteConnectorResponse? { var obj : DeleteConnectorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = DeleteConnectorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRetrieveConnectorConfigurationAttrResponse(inout jsonStr:String) -> RetrieveConnectorConfigurationAttrResponse? { var obj : RetrieveConnectorConfigurationAttrResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RetrieveConnectorConfigurationAttrResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRetrieveConnectorConfigurationFileResponse(inout jsonStr:String) -> RetrieveConnectorConfigurationFileResponse? { var obj : RetrieveConnectorConfigurationFileResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RetrieveConnectorConfigurationFileResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseStartConnectorResponse(inout jsonStr:String) -> StartConnectorResponse? { var obj : StartConnectorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = StartConnectorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseStopConnectorResponse(inout jsonStr:String) -> StopConnectorResponse? { var obj : StopConnectorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = StopConnectorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseUpdateConnectorResponse(inout jsonStr:String) -> UpdateConnectorResponse? { var obj : UpdateConnectorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = UpdateConnectorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseExpandContainerResponse(inout jsonStr:String) -> ExpandContainerResponse? { var obj : ExpandContainerResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ExpandContainerResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseStoreObjectResponse(inout jsonStr:String) -> StoreObjectResponse? { var obj : StoreObjectResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = StoreObjectResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseViewDocumentResponse(inout jsonStr:String) -> ViewDocumentResponse? { var obj : ViewDocumentResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ViewDocumentResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseGetCommonNeighborsResponse(inout jsonStr:String) -> GetCommonNeighborsResponse? { var obj : GetCommonNeighborsResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = GetCommonNeighborsResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseGetNeighborsResponse(inout jsonStr:String) -> GetNeighborsResponse? { var obj : GetNeighborsResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = GetNeighborsResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseGetNodesResponse(inout jsonStr:String) -> GetNodesResponse? { var obj : GetNodesResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = GetNodesResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseGetShortestPathResponse(inout jsonStr:String) -> GetShortestPathResponse? { var obj : GetShortestPathResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = GetShortestPathResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseGetSubgraphResponse(inout jsonStr:String) -> GetSubgraphResponse? { var obj : GetSubgraphResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = GetSubgraphResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseSuggestLinksResponse(inout jsonStr:String) -> SuggestLinksResponse? { var obj : SuggestLinksResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = SuggestLinksResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseSummarizeGraphResponse(inout jsonStr:String) -> SummarizeGraphResponse? { var obj : SummarizeGraphResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = SummarizeGraphResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseOCRDocumentResponse(inout jsonStr:String) -> OCRDocumentResponse? { var obj : OCRDocumentResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = OCRDocumentResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRecognizeBarcodesResponse(inout jsonStr:String) -> RecognizeBarcodesResponse? { var obj : RecognizeBarcodesResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RecognizeBarcodesResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseDetectFacesResponse(inout jsonStr:String) -> DetectFacesResponse? { var obj : DetectFacesResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = DetectFacesResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRecognizeImagesResponse(inout jsonStr:String) -> RecognizeImagesResponse? { var obj : RecognizeImagesResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RecognizeImagesResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParsePredictResponse(inout jsonStr:String) -> PredictResponse? { var obj : PredictResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = PredictResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRecommendResponse(inout jsonStr:String) -> RecommendResponse? { var obj : RecommendResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RecommendResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseTrainPredictorResponse(inout jsonStr:String) -> TrainPredictorResponse? { var obj : TrainPredictorResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = TrainPredictorResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseCreateQueryProfileResponse(inout jsonStr:String) -> CreateQueryProfileResponse? { var obj : CreateQueryProfileResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = CreateQueryProfileResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseDeleteQueryProfileResponse(inout jsonStr:String) -> DeleteQueryProfileResponse? { var obj : DeleteQueryProfileResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = DeleteQueryProfileResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRetrieveQueryProfileResponse(inout jsonStr:String) -> RetrieveQueryProfileResponse? { var obj : RetrieveQueryProfileResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RetrieveQueryProfileResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseUpdateQueryProfileResponse(inout jsonStr:String) -> UpdateQueryProfileResponse? { var obj : UpdateQueryProfileResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = UpdateQueryProfileResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseFindRelatedConceptsResponse(inout jsonStr:String) -> FindRelatedConceptsResponse? { var obj : FindRelatedConceptsResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = FindRelatedConceptsResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseAutoCompleteResponse(inout jsonStr:String) -> AutoCompleteResponse? { var obj : AutoCompleteResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = AutoCompleteResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseExtractConceptsResponse(inout jsonStr:String) -> ExtractConceptsResponse? { var obj : ExtractConceptsResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ExtractConceptsResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseExpandTermsResponse(inout jsonStr:String) -> ExpandTermsResponse? { var obj : ExpandTermsResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ExpandTermsResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseHighlightTextResponse(inout jsonStr:String) -> HighlightTextResponse? { var obj : HighlightTextResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = HighlightTextResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseIdentifyLanguageResponse(inout jsonStr:String) -> IdentifyLanguageResponse? { var obj : IdentifyLanguageResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = IdentifyLanguageResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseSentimentAnalysisResponse(inout jsonStr:String) -> SentimentAnalysisResponse? { var obj : SentimentAnalysisResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = SentimentAnalysisResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseTokenizeTextResponse(inout jsonStr:String) -> TokenizeTextResponse? { var obj : TokenizeTextResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = TokenizeTextResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseAddToTextIndexResponse(inout jsonStr:String) -> AddToTextIndexResponse? { var obj : AddToTextIndexResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = AddToTextIndexResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseCreateTextIndexResponse(inout jsonStr:String) -> CreateTextIndexResponse? { var obj : CreateTextIndexResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = CreateTextIndexResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseDeleteTextIndexResponse(inout jsonStr:String) -> DeleteTextIndexResponse? { var obj : DeleteTextIndexResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = DeleteTextIndexResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseDeleteFromTextIndexResponse(inout jsonStr:String) -> DeleteFromTextIndexResponse? { var obj : DeleteFromTextIndexResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = DeleteFromTextIndexResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseIndexStatusResponse(inout jsonStr:String) -> IndexStatusResponse? { var obj : IndexStatusResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = IndexStatusResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseListResourcesResponse(inout jsonStr:String) -> ListResourcesResponse? { var obj : ListResourcesResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = ListResourcesResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseRestoreTextIndexResponse(inout jsonStr:String) -> RestoreTextIndexResponse? { var obj : RestoreTextIndexResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = RestoreTextIndexResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseAnomalyDetectionResponse(inout jsonStr:String) -> AnomalyDetectionResponse? { var obj : AnomalyDetectionResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = AnomalyDetectionResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseTrendAnalysisResponse(inout jsonStr:String) -> TrendAnalysisResponse? { var obj : TrendAnalysisResponse! if let result = getResult(&jsonStr) { do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary obj = TrendAnalysisResponse(json:dic) } catch let error as NSError { logParserError(error) } } return obj } public func ParseCustomResponse(inout jsonStr:String) -> NSDictionary? { resetErrors() var obj : NSDictionary! if (jsonStr.characters.count == 0) { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Empty response.\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: jsonObj) addError(hodError) return nil } let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding) do { let jsonObj = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) guard let _ :NSDictionary = jsonObj as? NSDictionary else { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response.\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: jsonObj) addError(hodError) return nil } var result = jsonStr if let actions = jsonObj["actions"] as? NSArray { let status = actions[0].valueForKey("status") as? String if status == "finished" || status == "FINISHED" { let jsonData: NSData? do { jsonData = try NSJSONSerialization.dataWithJSONObject((actions[0].valueForKey("result") as? NSDictionary)!, options: []) result = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)! as String } catch let error as NSError { let err = String(format: "%@%d%@%@%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"", error.localizedDescription, "\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } } else if status == "failed" { let errors = actions[0].valueForKey("errors") as! NSArray for item in errors { let hodError = HODErrorObject(json: item as! NSDictionary) addError(hodError) } return nil } else if status == "queued" { var jobID = jsonObj.valueForKey("jobID") as? String jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let err = String(format: "%@%d%@%@%@", "{\"error\":", HODErrorCode.QUEUED,",\"reason\":\"Task is in queue\",\"jobID\":\"", jobID!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } else if status == "in progress" { var jobID = jsonObj.valueForKey("jobID") as? String jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let err = String(format: "%@%d%@%@%@", "{\"error\":",HODErrorCode.IN_PROGRESS,",\"reason\":\"Task is in progress\",\"jobID\":\"", jobID!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } else { let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.UNKNOWN_ERROR,",\"reason\":\"", status!, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } } else { // handle error for sync mode var isError = false for (key, _) in jsonObj as! NSDictionary { if key as! String == "error" { let hodError = HODErrorObject(json: jsonObj as! NSDictionary) addError(hodError) isError = true } } if isError { return nil } } do { let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) obj = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary } catch let error as NSError { let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.INVALID_HOD_RESPONSE,",\"reason\":\"", error.localizedDescription, "\"}") let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } } catch { let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response\"}"]) let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding) let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary let hodError = HODErrorObject(json: errorObj) addError(hodError) return nil } return obj } }
mit
f8a0f0c2ac80bdcd9814a7e252952334
44.425466
178
0.582065
5.262022
false
false
false
false
nitinhayaran/ios_google_places_autocomplete
GooglePlacesAutocomplete/GooglePlacesAutocomplete.swift
1
11470
// // GooglePlacesAutocomplete.swift // GooglePlacesAutocomplete // // Created by Howard Wilson on 10/02/2015. // Copyright (c) 2015 Howard Wilson. All rights reserved. // import UIKit public struct LocationBias { public let latitude: Double public let longitude: Double public let radius: Int public init(latitude: Double = 0, longitude: Double = 0, radius: Int = 20000000) { self.latitude = latitude self.longitude = longitude self.radius = radius } public var location: String { return "\(latitude),\(longitude)" } } public enum PlaceType: CustomStringConvertible { case All case Geocode case Address case Establishment case Regions case Cities public var description : String { switch self { case .All: return "" case .Geocode: return "geocode" case .Address: return "address" case .Establishment: return "establishment" case .Regions: return "(regions)" case .Cities: return "(cities)" } } } public class Place: NSObject { public let id: String public let desc: String public var apiKey: String? override public var description: String { get { return desc } } public init(id: String, description: String) { self.id = id self.desc = description } public convenience init(prediction: [String: AnyObject], apiKey: String?) { self.init( id: prediction["place_id"] as! String, description: prediction["description"] as! String ) self.apiKey = apiKey } /** Call Google Place Details API to get detailed information for this place Requires that Place#apiKey be set - parameter result: Callback on successful completion with detailed place information */ public func getDetails(result: PlaceDetails -> ()) { GooglePlaceDetailsRequest(place: self).request(result) } } public class PlaceDetails: CustomStringConvertible { public let name: String public let latitude: Double public let longitude: Double public let raw: [String: AnyObject] public init(json: [String: AnyObject]) { let result = json["result"] as! [String: AnyObject] let geometry = result["geometry"] as! [String: AnyObject] let location = geometry["location"] as! [String: AnyObject] self.name = result["name"] as! String self.latitude = location["lat"] as! Double self.longitude = location["lng"] as! Double self.raw = json } public var description: String { return "PlaceDetails: \(name) (\(latitude), \(longitude))" } } @objc public protocol GooglePlacesAutocompleteDelegate { optional func placesFound(places: [Place]) optional func placeSelected(place: Place) optional func placeViewClosed() } // MARK: - GooglePlacesAutocomplete public class GooglePlacesAutocomplete: UINavigationController { public var gpaViewController: GooglePlacesAutocompleteContainer! public var closeButton: UIBarButtonItem! // Proxy access to container navigationItem public override var navigationItem: UINavigationItem { get { return gpaViewController.navigationItem } } public var placeDelegate: GooglePlacesAutocompleteDelegate? { get { return gpaViewController.delegate } set { gpaViewController.delegate = newValue } } public var locationBias: LocationBias? { get { return gpaViewController.locationBias } set { gpaViewController.locationBias = newValue } } public convenience init(apiKey: String, placeType: PlaceType = .All) { let gpaViewController = GooglePlacesAutocompleteContainer( apiKey: apiKey, placeType: placeType ) self.init(rootViewController: gpaViewController) self.gpaViewController = gpaViewController closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "close") closeButton.style = UIBarButtonItemStyle.Done gpaViewController.navigationItem.leftBarButtonItem = closeButton gpaViewController.navigationItem.title = "Enter Address" } func close() { placeDelegate?.placeViewClosed?() } public func reset() { gpaViewController.searchBar.text = "" gpaViewController.searchBar(gpaViewController.searchBar, textDidChange: "") } } // MARK: - GooglePlacesAutocompleteContainer public class GooglePlacesAutocompleteContainer: UIViewController { @IBOutlet public weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var topConstraint: NSLayoutConstraint! var delegate: GooglePlacesAutocompleteDelegate? var apiKey: String? var places = [Place]() var placeType: PlaceType = .All var locationBias: LocationBias? convenience init(apiKey: String, placeType: PlaceType = .All) { let bundle = NSBundle(forClass: GooglePlacesAutocompleteContainer.self) self.init(nibName: "GooglePlacesAutocomplete", bundle: bundle) self.apiKey = apiKey self.placeType = placeType } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override public func viewWillLayoutSubviews() { topConstraint.constant = topLayoutGuide.length } override public func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) searchBar.becomeFirstResponder() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") } func keyboardWasShown(notification: NSNotification) { if isViewLoaded() && view.window != nil { let info: Dictionary = notification.userInfo! let keyboardSize: CGSize = (info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size)! let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0) tableView.contentInset = contentInsets; tableView.scrollIndicatorInsets = contentInsets; } } func keyboardWillBeHidden(notification: NSNotification) { if isViewLoaded() && view.window != nil { self.tableView.contentInset = UIEdgeInsetsZero self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero } } } // MARK: - GooglePlacesAutocompleteContainer (UITableViewDataSource / UITableViewDelegate) extension GooglePlacesAutocompleteContainer: UITableViewDataSource, UITableViewDelegate { public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return places.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // Get the corresponding candy from our candies array let place = self.places[indexPath.row] // Configure the cell cell.textLabel!.text = place.description cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { delegate?.placeSelected?(self.places[indexPath.row]) } } // MARK: - GooglePlacesAutocompleteContainer (UISearchBarDelegate) extension GooglePlacesAutocompleteContainer: UISearchBarDelegate { public func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if (searchText == "") { self.places = [] tableView.hidden = true } else { getPlaces(searchText) } } /** Call the Google Places API and update the view with results. - parameter searchString: The search query */ private func getPlaces(searchString: String) { var params = [ "input": searchString, "types": placeType.description, "key": apiKey ?? "" ] if let bias = locationBias { params["location"] = bias.location params["radius"] = bias.radius.description } GooglePlacesRequestHelpers.doRequest( "https://maps.googleapis.com/maps/api/place/autocomplete/json", params: params ) { json in if let predictions = json["predictions"] as? Array<[String: AnyObject]> { self.places = predictions.map { (prediction: [String: AnyObject]) -> Place in return Place(prediction: prediction, apiKey: self.apiKey) } self.tableView.reloadData() self.tableView.hidden = false self.delegate?.placesFound?(self.places) } } } } // MARK: - GooglePlaceDetailsRequest class GooglePlaceDetailsRequest { let place: Place init(place: Place) { self.place = place } func request(result: PlaceDetails -> ()) { GooglePlacesRequestHelpers.doRequest( "https://maps.googleapis.com/maps/api/place/details/json", params: [ "placeid": place.id, "key": place.apiKey ?? "" ] ) { json in result(PlaceDetails(json: json as! [String: AnyObject])) } } } // MARK: - GooglePlacesRequestHelpers class GooglePlacesRequestHelpers { /** Build a query string from a dictionary - parameter parameters: Dictionary of query string parameters - returns: The properly escaped query string */ private class func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += [(escape(key), escape("\(value)"))] } return (components.map{"\($0)=\($1)"} as [String]).joinWithSeparator("&") } private class func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } private class func doRequest(url: String, params: [String: String], success: NSDictionary -> ()) { let request = NSMutableURLRequest( URL: NSURL(string: "\(url)?\(query(params))")! ) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in self.handleResponse(data, response: response as? NSHTTPURLResponse, error: error, success: success) } task.resume() } private class func handleResponse(data: NSData!, response: NSHTTPURLResponse!, error: NSError!, success: NSDictionary -> ()) { if let error = error { print("GooglePlaces Error: \(error.localizedDescription)") return } if response == nil { print("GooglePlaces Error: No response from API") return } if response.statusCode != 200 { print("GooglePlaces Error: Invalid status code \(response.statusCode) from API") return } guard let response = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) else { print("GooglePlaces Error: \(error.localizedDescription)") return } guard let json = response as? NSDictionary else { print("Not a dictionary") return } guard let status = json["status"] as? String where status == "OK" else { print("GooglePlaces API Error") return } // Perform table updates on UI thread dispatch_async(dispatch_get_main_queue(), { UIApplication.sharedApplication().networkActivityIndicatorVisible = false success(json) }) } }
mit
37b745ac51ce7139e0a5664d230dc3d3
29.424403
149
0.706103
4.827441
false
false
false
false
SwiftKit/Lipstick
LipstickTests/CGRect+InitTest.swift
1
2724
// // CGRect+InitTest.swift // Lipstick // // Created by Filip Dolnik on 18.10.16. // Copyheight © 2016 Bheightify. All heights reserved. // import Quick import Nimble import Lipstick class CGRectInitTest: QuickSpec { override func spec() { describe("CGRect init") { it("creates CGRect") { expect(CGRect(x: 0, y: 0, width: 0, height: 0)) == CGRect() expect(CGRect(x: 1, y: 1, width: 2, height: 2)) == CGRect(origin: CGPoint(1), size: CGSize(2)) expect(CGRect(x: 1, y: 1, width: 0, height: 0)) == CGRect(origin: CGPoint(1)) expect(CGRect(x: 1, y: 1, width: 1, height: 0)) == CGRect(origin: CGPoint(1), width: 1) expect(CGRect(x: 1, y: 1, width: 0, height: 1)) == CGRect(origin: CGPoint(1), height: 1) expect(CGRect(x: 1, y: 1, width: 1, height: 1)) == CGRect(origin: CGPoint(1), width: 1, height: 1) expect(CGRect(x: 0, y: 0, width: 1, height: 1)) == CGRect(size: CGSize(1)) expect(CGRect(x: 1, y: 0, width: 1, height: 1)) == CGRect(x: 1, size: CGSize(1)) expect(CGRect(x: 0, y: 1, width: 1, height: 1)) == CGRect(y: 1, size: CGSize(1)) expect(CGRect(x: 1, y: 1, width: 1, height: 1)) == CGRect(x: 1, y: 1, size: CGSize(1)) expect(CGRect(x: 1, y: 0, width: 0, height: 0)) == CGRect(x: 1) expect(CGRect(x: 1, y: 1, width: 0, height: 0)) == CGRect(x: 1, y: 1) expect(CGRect(x: 1, y: 0, width: 1, height: 0)) == CGRect(x: 1, width: 1) expect(CGRect(x: 1, y: 0, width: 0, height: 1)) == CGRect(x: 1, height: 1) expect(CGRect(x: 1, y: 1, width: 1, height: 0)) == CGRect(x: 1, y: 1, width: 1) expect(CGRect(x: 1, y: 1, width: 0, height: 1)) == CGRect(x: 1, y: 1, height: 1) expect(CGRect(x: 1, y: 0, width: 1, height: 1)) == CGRect(x: 1, width: 1, height: 1) expect(CGRect(x: 0, y: 1, width: 0, height: 0)) == CGRect(y: 1) expect(CGRect(x: 0, y: 1, width: 1, height: 0)) == CGRect(y: 1, width: 1) expect(CGRect(x: 0, y: 1, width: 0, height: 1)) == CGRect(y: 1, height: 1) expect(CGRect(x: 0, y: 1, width: 1, height: 1)) == CGRect(y: 1, width: 1, height: 1) expect(CGRect(x: 0, y: 0, width: 1, height: 0)) == CGRect(width: 1) expect(CGRect(x: 0, y: 0, width: 1, height: 1)) == CGRect(width: 1, height: 1) expect(CGRect(x: 0, y: 0, width: 0, height: 1)) == CGRect(height: 1) } } } }
mit
fabb5bc35d4b207168d3fbfbf0155f21
52.392157
114
0.488065
3.104903
false
false
false
false
OscarSwanros/swift
test/DebugInfo/guard-let.swift
8
1471
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s --check-prefix=CHECK2 // UNSUPPORTED: OS=watchos func use<T>(_ t: T) {} public func f(_ i : Int?) { // CHECK: define {{.*}}@_T04main1fySiSgF // The shadow copy store should not have a location. // Note that the store must be in the same scope or else it might defeat // livedebugvalues. // CHECK1: @llvm.dbg.declare(metadata {{(i32|i64)}}* %val.addr, {{.*}}, !dbg ![[DBG0:.*]] // CHECK1: %[[PHI:.*]] = phi // CHECK1: store {{(i32|i64)}} %[[PHI]], {{(i32|i64)}}* %val.addr, align {{(4|8)}}, !dbg ![[DBG1:.*]] // CHECK1: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK1: ![[BLK:.*]] = distinct !DILexicalBlock(scope: ![[F]], // CHECK1: ![[DBG0]] = !DILocation(line: [[@LINE+2]], // CHECK1: ![[DBG1]] = !DILocation(line: 0, scope: ![[BLK]]) guard let val = i else { return } use(val) } // With large type optimizations the string is passed indirectly on i386 so // there is no shadow copy happening. // UNSUPPORTED: CPU=i386 public func g(_ s : String?) { // CHECK2: define {{.*}}@_T04main1gySSSgF // The shadow copy store should not have a location. // CHECK2: getelementptr inbounds {{.*}} %s.debug, {{.*}}, !dbg ![[DBG0:.*]] // CHECK2: ![[G:.*]] = distinct !DISubprogram(name: "g" // CHECK2: ![[DBG0]] = !DILocation(line: 0, scope: ![[G]]) guard let val = s else { return } use(val) }
apache-2.0
0035cc2841105128ce7e8156a298c819
37.710526
103
0.590755
3.116525
false
false
false
false
JohnEstropia/CoreStore
Demo/Sources/Demos/Modern/PokedexDemo/Modern.PokedexDemo.Form.swift
1
2047
// // Demo // Copyright © 2020 John Rommel Estropia, Inc. All rights reserved. import CoreStore import UIKit // MARK: - Modern.PokedexDemo extension Modern.PokedexDemo { // MARK: - Modern.PokedexDemo.Form /** ⭐️ Sample 1: This sample shows how to declare `CoreStoreObject` subclasses that implement `ImportableUniqueObject`. For this class the `ImportSource` is a JSON `Dictionary`. */ final class Form: CoreStoreObject, ImportableUniqueObject { // MARK: Internal @Field.Stored("id") var id: Int = 0 @Field.Stored("name") var name: String? @Field.Stored("spriteURL") var spriteURL: URL? @Field.Relationship("details", inverse: \.$forms) var details: Modern.PokedexDemo.Details? // MARK: ImportableObject typealias ImportSource = Dictionary<String, Any> // MARK: ImportableUniqueObject typealias UniqueIDType = Int static let uniqueIDKeyPath: String = String(keyPath: \Modern.PokedexDemo.Form.$id) var uniqueIDValue: UniqueIDType { get { return self.id } set { self.id = newValue } } static func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -> UniqueIDType? { let json = source return try Modern.PokedexDemo.Service.parseJSON(json["id"]) } func update(from source: ImportSource, in transaction: BaseDataTransaction) throws { typealias Service = Modern.PokedexDemo.Service let json = source self.name = try Service.parseJSON(json["name"]) self.spriteURL = try? Service.parseJSON( json["sprites"], transformer: { (json: Dictionary<String, Any>) in try Service.parseJSON(json["front_default"], transformer: URL.init(string:)) } ) } } }
mit
d424552b4f18c06e896b79832d1186e4
27.361111
178
0.583741
4.94431
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Vendor/Alamofire/Validation.swift
1
11845
// // Validation.swift // // Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Request { // MARK: Helper Types fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason /// Used to represent whether validation was successful or encountered an error resulting in a failure. /// /// - success: The validation was successful. /// - failure: The validation failed encountering the provided error. enum ValidationResult { case success case failure(Error) } fileprivate struct MIMEType { let type: String let subtype: String var isWildcard: Bool { return type == "*" && subtype == "*" } init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) #if swift(>=3.2) let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] #else let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) #endif return split.components(separatedBy: "/") }() if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false } } } // MARK: Properties fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { return accept.components(separatedBy: ",") } return ["*/*"] } // MARK: Status Code fileprivate func validate<S: Sequence>( statusCode acceptableStatusCodes: S, response: HTTPURLResponse) -> ValidationResult where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { return .success } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(AFError.responseValidationFailed(reason: reason)) } } // MARK: Content Type fileprivate func validate<S: Sequence>( contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, data.count > 0 else { return .success } guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .success } } let error: AFError = { let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { return .success } } let error: AFError = { let reason: ErrorReason = .unacceptableContentType( acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType ) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } } // MARK: - extension DataRequest { /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the /// request was valid. typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(self.request, response, self.delegate.data) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in return self.validate(contentType: acceptableContentTypes, response: response, data: data) } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult func validate() -> Self { let contentTypes = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } } // MARK: - extension DownloadRequest { /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a /// destination URL, and returns whether the request was valid. typealias Validation = ( _ request: URLRequest?, _ response: HTTPURLResponse, _ temporaryURL: URL?, _ destinationURL: URL?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in let request = self.request let temporaryURL = self.downloadDelegate.temporaryURL let destinationURL = self.downloadDelegate.destinationURL if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(request, response, temporaryURL, destinationURL) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, _, _ in let fileURL = self.downloadDelegate.fileURL guard let validFileURL = fileURL else { return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) } do { let data = try Data(contentsOf: validFileURL) return self.validate(contentType: acceptableContentTypes, response: response, data: data) } catch { return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) } } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult func validate() -> Self { let contentTypes = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } }
apache-2.0
5aed560a5d4fbc1157629fcb6acd665b
35.900312
120
0.630055
5.285587
false
false
false
false
lllyyy/LY
U17-master/U17/U17/Extension/DictionaryExtension.swift
1
5061
// // DictionaryExtension.swift // U17 // // Created by charles on 2017/10/27. // Copyright © 2017年 None. All rights reserved. // import Foundation extension Dictionary { /// EZSE: Returns the value of a random Key-Value pair from the Dictionary public func random() -> Value? { return Array(values).random() } /// EZSE: Union of self and the input dictionaries. public func union(_ dictionaries: Dictionary...) -> Dictionary { var result = self dictionaries.forEach { (dictionary) -> Void in dictionary.forEach { (arg) -> Void in let (key, value) = arg result[key] = value } } return result } /// EZSE: Checks if a key exists in the dictionary. public func has(_ key: Key) -> Bool { return index(forKey: key) != nil } /// EZSE: Creates an Array with values generated by running /// each [key: value] of self through the mapFunction. public func toArray<V>(_ map: (Key, Value) -> V) -> [V] { return self.map(map) } /// EZSE: Creates a Dictionary with the same keys as self and values generated by running /// each [key: value] of self through the mapFunction. public func mapValues<V>(_ map: (Key, Value) -> V) -> [Key: V] { var mapped: [Key: V] = [:] forEach { mapped[$0] = map($0, $1) } return mapped } /// EZSE: Creates a Dictionary with the same keys as self and values generated by running /// each [key: value] of self through the mapFunction discarding nil return values. public func mapFilterValues<V>(_ map: (Key, Value) -> V?) -> [Key: V] { var mapped: [Key: V] = [:] forEach { if let value = map($0, $1) { mapped[$0] = value } } return mapped } /// EZSE: Creates a Dictionary with keys and values generated by running /// each [key: value] of self through the mapFunction discarding nil return values. public func mapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] { var mapped: [K: V] = [:] forEach { if let value = map($0, $1) { mapped[value.0] = value.1 } } return mapped } /// EZSE: Creates a Dictionary with keys and values generated by running /// each [key: value] of self through the mapFunction. public func map<K, V>(_ map: (Key, Value) -> (K, V)) -> [K: V] { var mapped: [K: V] = [:] forEach { let (_key, _value) = map($0, $1) mapped[_key] = _value } return mapped } /// EZSE: Constructs a dictionary containing every [key: value] pair from self /// for which testFunction evaluates to true. public func filter(_ test: (Key, Value) -> Bool) -> Dictionary { var result = Dictionary() for (key, value) in self { if test(key, value) { result[key] = value } } return result } /// EZSE: Checks if test evaluates true for all the elements in self. public func testAll(_ test: (Key, Value) -> (Bool)) -> Bool { return !contains { !test($0, $1) } } /// EZSE: Unserialize JSON string into Dictionary public static func constructFromJSON (json: String) -> Dictionary? { if let data = (try? JSONSerialization.jsonObject( with: json.data(using: String.Encoding.utf8, allowLossyConversion: true)!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? Dictionary { return data } else { return nil } } /// EZSE: Serialize Dictionary into JSON string public func formatJSON() -> String? { if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) { let jsonStr = String(data: jsonData, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) return String(jsonStr ?? "") } return nil } } extension Dictionary where Value: Equatable { /// EZSE: Difference of self and the input dictionaries. /// Two dictionaries are considered equal if they contain the same [key: value] pairs. public func difference(_ dictionaries: [Key: Value]...) -> [Key: Value] { var result = self for dictionary in dictionaries { for (key, value) in dictionary { if result.has(key) && result[key] == value { result.removeValue(forKey: key) } } } return result } } /// EZSE: Combines the first dictionary with the second and returns single dictionary public func += <KeyType, ValueType> (left: inout [KeyType: ValueType], right: [KeyType: ValueType]) { for (k, v) in right { left.updateValue(v, forKey: k) } }
mit
6f323f713cc7794f6068ec9c0932029f
32.946309
122
0.561091
4.367876
false
false
false
false
rtoal/polyglot
swift/shape_extensions.swift
2
957
protocol Shape { func area() -> Double } struct Square: Shape { var side: Double func area() -> Double {return side * side} } let s = Square(side: 10) assert(s.area() == 100) protocol Boundaried { func perimeter() -> Double } extension Square: Boundaried { func perimeter() -> Double {return side * 4} } assert(s.perimeter() == 40) import Foundation struct Circle: Shape, Boundaried { var radius: Double func area() -> Double {return Double.pi * radius * radius} func perimeter() -> Double {return 2 * Double.pi * radius} } let c = Circle(radius: 8) assert(c.area() == 64 * Double.pi) assert(c.perimeter() == 16 * Double.pi) extension Shape { var json: String { return "{\"area\": \(area())}" } } assert(s.json == "{\"kind\": \"square\", \"side\": 10.0}") extension Square { var json: String {return "{\"kind\": \"square\", \"side\": \(side)}"} } assert(s.json == "{\"kind\": \"square\", \"side\": 10.0}")
mit
f2984386fc9ea794ea5a7e67de74fd50
20.75
73
0.601881
3.28866
false
false
false
false
codepgq/WeiBoDemo
PQWeiboDemo/PQWeiboDemo/classes/DIYModalAnimation/PQModalAnimation.swift
1
4836
// // PQModalAnimation.swift // PQWeiboDemo // // Created by ios on 16/10/9. // Copyright © 2016年 ios. All rights reserved. // import UIKit /// 页面将要出现 public let PQModalAnimationWillShowKey = "PQModalAnimationWillShowKey" /// 页面将要消失 public let PQModalAnimationWillCloseKey = "PQModalAnimationWillCloseKey" class PQModalAnimation: NSObject, UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning { /// 记录当前是否展开 var isPresent: Bool = false /// 显示视图的大小 var presentFrame = UIScreen.main.bounds /// 动画时长 var animaDuration : TimeInterval = 0.5 /// 动画方向 var modalDirectionType : PQAnimationDirection = PQAnimationDirection.top /// 展示视图 private var presented : UIViewController? /// 图层遮罩 lazy var backView : UIView = { let back = UIView(frame: UIScreen.main.bounds) back.backgroundColor = UIColor(white: 0, alpha: 0.2) let tap = UITapGestureRecognizer(target: self, action: #selector(PQModalAnimation.dismiss)) back.addGestureRecognizer(tap) return back }() /** dismiss */ @objc private func dismiss(){ presented?.dismiss(animated: true, completion: nil) } init(direction : PQAnimationDirection?) { super.init() modalDirectionType = direction ?? PQAnimationDirection.top } /** 告诉系统谁来负责modal动画 - parameter presented: 被展现的视图 - parameter presenting: 发起的视图 - parameter source: - returns: 谁来负责 */ func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presented = presented isPresent = true //发送将要显示通知 NotificationCenter.default.post(name : NSNotification.Name(rawValue: PQModalAnimationWillShowKey), object: nil) return self } /** 谁来负责dissmiss动画 - parameter dismissed: 被关闭的视图 - returns: 谁来负责 */ func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false //发送将要消失通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: PQModalAnimationWillCloseKey), object: nil) return self } } // MARK: - 动画处理 extension PQModalAnimation{ /** 设置动画时长,默认0.5秒 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 - returns: 动画时长 */ @objc(transitionDuration:) func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{ return animaDuration } /** 告诉系统如何动画,消失、出现都会调用这个方法 - parameter transitionContext: 上下文,保存了动画需要的所有参数 */ @objc(animateTransition:) func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ // 1、获取到要展现的视图 let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) ?? transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)?.view let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) ?? transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view // 2、把视图添加到容器上 if isPresent { toView?.frame = presentFrame transitionContext.containerView.addSubview(backView) transitionContext.containerView.addSubview(toView!) } // 3、获取动画 let animations = PQAnimation.createAnimation(isShow: isPresent, direction: modalDirectionType, fromView: fromView!, toView: toView!, frame : presentFrame) // 4、执行动画 UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear, animations:animations.startAnimation!, completion: { (_) in // 6、动画执行完成后一定要记得通知系统 transitionContext.completeTransition(true) }) // 消失 if self.isPresent == false { UIView.animate(withDuration: transitionDuration(using: transitionContext)) { self.backView.removeFromSuperview() } } } }
mit
bbd960872890b9a5f7db55aa9781f1fa
31.272059
231
0.666211
4.993174
false
false
false
false
krzyzanowskim/Natalie
Sources/natalie/ViewController.swift
1
1311
// // ViewController.swift // Natalie // // Created by Marcin Krzyzanowski on 07/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // class ViewController: XMLObject { lazy var customClass: String? = self.xml.element?.attribute(by: "customClass")?.text lazy var customModuleProvider: String? = self.xml.element?.attribute(by: "customModuleProvider")?.text lazy var storyboardIdentifier: String? = self.xml.element?.attribute(by: "storyboardIdentifier")?.text lazy var customModule: String? = self.xml.element?.attribute(by: "customModule")?.text lazy var id: String? = self.xml.element?.attribute(by: "id")?.text lazy var userLabel: String? = self.xml.element?.attribute(by: "userLabel")?.text lazy var reusables: [Reusable]? = { if let reusables = self.searchAll(root: self.xml, attributeKey: "reuseIdentifier") { return reusables.map { Reusable(xml: $0) } } return nil }() lazy var customClassWithModule: String? = { if let className = self.customClass { if let moduleName = self.customModule, customModuleProvider != "target" { return "\(moduleName).\(className)" } else { return className } } return nil }() }
mit
cb4e752cdd9f647b55d8cf819bc0f60a
35.388889
106
0.639695
4.381271
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/OperatorUsageWhitespaceRule.swift
1
7480
import Foundation import SourceKittenFramework public struct OperatorUsageWhitespaceRule: OptInRule, CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "operator_usage_whitespace", name: "Operator Usage Whitespace", description: "Operators should be surrounded by a single whitespace " + "when they are being used.", kind: .style, nonTriggeringExamples: [ "let foo = 1 + 2\n", "let foo = 1 > 2\n", "let foo = !false\n", "let foo: Int?\n", "let foo: Array<String>\n", "let foo: [String]\n", "let foo = 1 + \n 2\n", "let range = 1...3\n", "let range = 1 ... 3\n", "let range = 1..<3\n", "#if swift(>=3.0)\n foo()\n#endif\n", "array.removeAtIndex(-200)\n", "let name = \"image-1\"\n", "button.setImage(#imageLiteral(resourceName: \"image-1\"), for: .normal)\n", "let doubleValue = -9e-11\n" ], triggeringExamples: [ "let foo = 1↓+2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo↓=1↓+2\n", "let foo↓=1 + 2\n", "let foo↓=bar\n", "let range = 1↓ ..< 3\n", "let foo = bar↓ ?? 0\n", "let foo = bar↓??0\n", "let foo = bar↓ != 0\n", "let foo = bar↓ !== bar2\n", "let v8 = Int8(1)↓ << 6\n", "let v8 = 1↓ << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n" ], corrections: [ "let foo = 1↓+2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo↓=1↓+2\n": "let foo = 1 + 2\n", "let foo↓=1 + 2\n": "let foo = 1 + 2\n", "let foo↓=bar\n": "let foo = bar\n", "let range = 1↓ ..< 3\n": "let range = 1..<3\n", "let foo = bar↓ ?? 0\n": "let foo = bar ?? 0\n", "let foo = bar↓??0\n": "let foo = bar ?? 0\n", "let foo = bar↓ != 0\n": "let foo = bar != 0\n", "let foo = bar↓ !== bar2\n": "let foo = bar !== bar2\n", "let v8 = Int8(1)↓ << 6\n": "let v8 = Int8(1) << 6\n", "let v8 = 1↓ << (6)\n": "let v8 = 1 << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n": "let v8 = 1 << (6)\n let foo = 1 > 2\n" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(file: file).map { range, _ in StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: range.location)) } } private func violationRanges(file: File) -> [(NSRange, String)] { let escapedOperators = ["/", "=", "-", "+", "*", "|", "^", "~"].map({ "\\\($0)" }).joined() let rangePattern = "\\.\\.(?:\\.|<)" // ... or ..< let notEqualsPattern = "\\!\\=\\=?" // != or !== let coalescingPattern = "\\?{2}" let operators = "(?:[\(escapedOperators)%<>&]+|\(rangePattern)|\(coalescingPattern)|" + "\(notEqualsPattern))" let oneSpace = "[^\\S\\r\\n]" // to allow lines ending with operators to be valid let zeroSpaces = oneSpace + "{0}" let manySpaces = oneSpace + "{2,}" let leadingVariableOrNumber = "(?:\\b|\\))" let trailingVariableOrNumber = "(?:\\b|\\()" let spaces = [(zeroSpaces, zeroSpaces), (oneSpace, manySpaces), (manySpaces, oneSpace), (manySpaces, manySpaces)] let patterns = spaces.map { first, second in leadingVariableOrNumber + first + operators + second + trailingVariableOrNumber } let pattern = "(?:\(patterns.joined(separator: "|")))" let genericPattern = "<(?:\(oneSpace)|\\S)+?>" // not using dot to avoid matching new line let validRangePattern = leadingVariableOrNumber + zeroSpaces + rangePattern + zeroSpaces + trailingVariableOrNumber let excludingPattern = "(?:\(genericPattern)|\(validRangePattern))" let excludingKinds = SyntaxKind.commentAndStringKinds.union([.objectLiteral]) return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds, excludingPattern: excludingPattern).compactMap { range in // if it's only a number (i.e. -9e-11), it shouldn't trigger guard kinds(in: range, file: file) != [.number] else { return nil } let spacesPattern = oneSpace + "*" let rangeRegex = regex(spacesPattern + rangePattern + spacesPattern) // if it's a range operator, the correction shouldn't have spaces if let matchRange = rangeRegex.firstMatch(in: file.contents, options: [], range: range)?.range { let correction = operatorInRange(file: file, range: matchRange) return (matchRange, correction) } let pattern = spacesPattern + operators + spacesPattern let operatorsRegex = regex(pattern) guard let matchRange = operatorsRegex.firstMatch(in: file.contents, options: [], range: range)?.range else { return nil } let operatorContent = operatorInRange(file: file, range: matchRange) let correction = " " + operatorContent + " " return (matchRange, correction) } } private func kinds(in range: NSRange, file: File) -> [SyntaxKind] { let contents = file.contents.bridge() guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else { return [] } return file.syntaxMap.kinds(inByteRange: byteRange) } private func operatorInRange(file: File, range: NSRange) -> String { return file.contents.bridge().substring(with: range).trimmingCharacters(in: .whitespaces) } public func correct(file: File) -> [Correction] { let violatingRanges = violationRanges(file: file).filter { range, _ in return !file.ruleEnabled(violatingRanges: [range], for: self).isEmpty } var correctedContents = file.contents var adjustedLocations = [Int]() for (violatingRange, correction) in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: correction) adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
mit
1056f079672207f8ee90f1138bfe10d1
41.62069
109
0.522384
4.010817
false
false
false
false
GalinaCode/Nutriction-Cal
NutritionCal/Nutrition Cal/ImageCache.swift
1
2408
// // ImageCache.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // // Source code from FavoriteActors App by Jason on 1/31/15. Copyright (c) 2015 Udacity. All rights reserved. import UIKit class ImageCache { class func sharedInstance() -> ImageCache { struct Singleton { static var sharedInstance = ImageCache() } return Singleton.sharedInstance } // MARK: - Shared Image Cache struct Caches { static let imageCache = ImageCache() } private var inMemoryCache = NSCache() // MARK: - Retreiving images func imageWithIdentifier(identifier: String?) -> UIImage? { // If the identifier is nil, or empty, return nil if identifier == nil || identifier! == "" { return nil } let path = pathForIdentifier(identifier!) // First try the memory cache if let image = inMemoryCache.objectForKey(path) as? UIImage { return image } // Next Try the hard drive if let data = NSData(contentsOfFile: path) { return UIImage(data: data) } return nil } // MARK: - Saving images func storeImage(image: UIImage?, withIdentifier identifier: String) { let path = pathForIdentifier(identifier) // If the image is nil, remove images from the cache if image == nil { inMemoryCache.removeObjectForKey(path) do { try NSFileManager.defaultManager().removeItemAtPath(path) } catch {} return } // Otherwise, keep the image in memory inMemoryCache.setObject(image!, forKey: path) // And in documents directory let data = UIImagePNGRepresentation(image!)! data.writeToFile(path, atomically: true) } // MARK: - Deleting an image func deleteImageWithIdentifier(identifier: String) { let fileManager = NSFileManager.defaultManager() let path = pathForIdentifier(identifier) if fileManager.fileExistsAtPath(path) { do { try fileManager.removeItemAtPath(path) print("\(identifier) image deleted") } catch { print("\(identifier) couldn't be deleted") } } } // MARK: - Helper func pathForIdentifier(identifier: String) -> String { let documentsDirectoryURL: NSURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! let fullURL = documentsDirectoryURL.URLByAppendingPathComponent(identifier) return fullURL.path! } }
apache-2.0
1a0ab0d82bd92159ac359d29b1c66bb6
22.144231
139
0.697964
3.991708
false
false
false
false
OAuthSwift/OAuthSwift
Sources/OAuthSwiftMultipartData.swift
4
1460
// // OAuthSwiftMultipartData.swift // OAuthSwift // // Created by Tomohiro Kawaji on 12/18/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation public struct OAuthSwiftMultipartData { public var name: String public var data: Data public var fileName: String? public var mimeType: String? public init(name: String, data: Data, fileName: String?, mimeType: String?) { self.name = name self.data = data self.fileName = fileName self.mimeType = mimeType } } extension Data { public mutating func append(_ multipartData: OAuthSwiftMultipartData, encoding: String.Encoding, separatorData: Data) { var filenameClause = "" if let filename = multipartData.fileName { filenameClause = "; filename=\"\(filename)\"" } let contentDispositionString = "Content-Disposition: form-data; name=\"\(multipartData.name)\"\(filenameClause)\r\n" let contentDispositionData = contentDispositionString.data(using: encoding)! self.append(contentDispositionData) if let mimeType = multipartData.mimeType { let contentTypeString = "Content-Type: \(mimeType)\r\n" let contentTypeData = contentTypeString.data(using: encoding)! self.append(contentTypeData) } self.append(separatorData) self.append(multipartData.data) self.append(separatorData) } }
mit
ba2dd3dbec55a368b0cfc0050aea567c
29.416667
124
0.663014
4.534161
false
false
false
false
Trevi-Swift/Trevi
Sources/Json.swift
1
2397
// // Json.swift // Trevi // // Created by LeeYoseob on 2015. 12. 9.. // Copyright © 2015 Trevi Community. All rights reserved. // import Foundation public enum JSON { case Array( [JSON] ) case Dictionary( [Swift.String:JSON] ) case String( Swift.String ) case Number( Float ) case Null } extension JSON { public var string: Swift.String? { switch self { case .String(let s): return s default: return nil } } public var int: Int? { switch self { case .Number(let d): return Int ( d ) default: return nil } } public var float: Float? { switch self { case .Number(let d): return d default: return nil } } public var bool: Bool? { switch self { case .Number(let d): return (d != 0) default: return nil } } public var isNull: Bool { switch self { case Null: return true default: return false } } public func wrap ( json: AnyObject ) -> JSON { if let str = json as? Swift.String { return .String ( str ) } if let num = json as? NSNumber { return .Number ( num.floatValue ) } if let dictionary = json as? [Swift.String:AnyObject] { return .Dictionary ( internalConvertDictionary ( dictionary ) ) } if let array = json as? [AnyObject] { return .Array ( internalConvertArray ( array ) ) } assert ( json is NSNull, "Unsupported Type" ) return .Null } private func internalConvertDictionary ( dic: [Swift.String:AnyObject] ) -> [Swift.String:JSON]! { // var newDictionary = [:] // for (k,v) in dic{ // switch v{ // case let arr as [AnyObject]: // var newarr = internalConvertArray(arr) // // print(arr) // case let dic as [Swift.String: AnyObject]: // internalConvertDictionary(dic) // default: // wrap(v) // break // // } // } return nil; } private func internalConvertArray ( arr: [AnyObject] ) -> [JSON]! { return nil } }
apache-2.0
05d136ee2c11d8eb599cc26105d6384c
21.392523
102
0.489149
4.293907
false
false
false
false
darofar/lswc
parcial1-javier/Examen/Examen/SquareView.swift
1
1562
// // TrajectoryView.swift // Angry Birds // // Created by Javier De La Rubia on 15/3/15. // Copyright (c) 2015 Javier De La Rubia. All rights reserved. // import UIKit import Darwin @IBDesignable class SquareView: UIView { var dataSource: SquareViewDataSource! @IBInspectable var stroke: UIColor = UIColor.redColor() @IBInspectable var fill: UIColor = UIColor.redColor() @IBInspectable var background: UIColor = UIColor.redColor() @IBInspectable var side: Double = 50; @IBInspectable var width: Double = 3; override func drawRect(rect: CGRect) { if(dataSource == nil) { return; } background.setFill(); UIRectFill(rect); dataSource.setSide(side); let ctx = UIGraphicsGetCurrentContext(); let path = UIBezierPath() let values : SquareValues = dataSource.corners(); path.moveToPoint(CGPointMake(CGFloat(values.corners[3].positionX), CGFloat(values.corners[3].positionY))); for corner in values.corners { path.addLineToPoint(CGPointMake(CGFloat(corner.positionX), CGFloat(corner.positionY))); } path.addLineToPoint(CGPointMake(CGFloat(values.corners[0].positionX), CGFloat(values.corners[0].positionY))); stroke.setStroke(); fill.setFill(); path.lineWidth = CGFloat(width); path.fill(); path.stroke(); } }
apache-2.0
b6571e91cb6838fed8afc087c8f94da1
22.666667
117
0.588348
4.866044
false
false
false
false
frootloops/swift
tools/SwiftSyntax/SyntaxCollection.swift
1
5489
//===-------------- SyntaxCollection.swift - Syntax Collection ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation /// Represents a collection of Syntax nodes of a specific type. SyntaxCollection /// behaves as a regular Swift collection, and has accessors that return new /// versions of the collection with different children. public class SyntaxCollection<SyntaxElement: Syntax>: Syntax { /// Creates a new SyntaxCollection by replacing the underlying layout with /// a different set of raw syntax nodes. /// /// - Parameter layout: The new list of raw syntax nodes underlying this /// collection. /// - Returns: A new SyntaxCollection with the new layout underlying it. internal func replacingLayout( _ layout: [RawSyntax]) -> SyntaxCollection<SyntaxElement> { let newRaw = data.raw.replacingLayout(layout) let (newRoot, newData) = data.replacingSelf(newRaw) return SyntaxCollection<SyntaxElement>(root: newRoot, data: newData) } /// Creates a new SyntaxCollection by appending the provided syntax element /// to the children. /// /// - Parameter syntax: The element to append. /// - Returns: A new SyntaxCollection with that element appended to the end. public func appending( _ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.append(syntax.raw) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by prepending the provided syntax element /// to the children. /// /// - Parameter syntax: The element to prepend. /// - Returns: A new SyntaxCollection with that element prepended to the /// beginning. public func prepending( _ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> { return inserting(syntax, at: 0) } /// Creates a new SyntaxCollection by inserting the provided syntax element /// at the provided index in the children. /// /// - Parameters: /// - syntax: The element to insert. /// - index: The index at which to insert the element in the collection. /// /// - Returns: A new SyntaxCollection with that element appended to the end. public func inserting(_ syntax: SyntaxElement, at index: Int) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout /// Make sure the index is a valid insertion index (0 to 1 past the end) precondition((newLayout.startIndex...newLayout.endIndex).contains(index), "inserting node at invalid index \(index)") newLayout.insert(syntax.raw, at: index) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the syntax element at the /// provided index. /// /// - Parameter index: The index of the element to remove from the collection. /// - Returns: A new SyntaxCollection with the element at the provided index /// removed. public func removing(childAt index: Int) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.remove(at: index) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the first element. /// /// - Returns: A new SyntaxCollection with the first element removed. public func removingFirst() -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.removeFirst() return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the last element. /// /// - Returns: A new SyntaxCollection with the last element removed. public func removingLast() -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.removeLast() return replacingLayout(newLayout) } /// Returns an iterator over the elements of this syntax collection. public func makeIterator() -> SyntaxCollectionIterator<SyntaxElement> { return SyntaxCollectionIterator(collection: self) } } /// Conformance for SyntaxCollection to the Collection protocol. extension SyntaxCollection: Collection { public var startIndex: Int { return data.childCaches.startIndex } public var endIndex: Int { return data.childCaches.endIndex } public func index(after i: Int) -> Int { return data.childCaches.index(after: i) } public subscript(_ index: Int) -> SyntaxElement { return child(at: index)! as! SyntaxElement } } /// A type that iterates over a syntax collection using its indices. public struct SyntaxCollectionIterator<Element: Syntax>: IteratorProtocol { private let collection: SyntaxCollection<Element> private var index: SyntaxCollection<Element>.Index fileprivate init(collection: SyntaxCollection<Element>) { self.collection = collection self.index = collection.startIndex } public mutating func next() -> Element? { guard !(self.collection.isEmpty || self.index == self.collection.endIndex) else { return nil } let result = collection[index] collection.formIndex(after: &index) return result } }
apache-2.0
28ecbfa663de87299ce7a6c9c31ac912
35.593333
80
0.695755
4.63598
false
false
false
false
ochococo/Design-Patterns-In-Swift
Design-Patterns-CN.playground/Pages/Creational.xcplaygroundpage/Contents.swift
2
6613
/*: 创建型模式 ======== > 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。 > >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F) ## 目录 * [行为型模式](Behavioral) * [创建型模式](Creational) * [结构型模式](Structural) */ import Foundation /*: 🌰 抽象工厂(Abstract Factory) ------------- 抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。 ### 示例: 协议 */ protocol BurgerDescribing { var ingredients: [String] { get } } struct CheeseBurger: BurgerDescribing { let ingredients: [String] } protocol BurgerMaking { func make() -> BurgerDescribing } // 工厂方法实现 final class BigKahunaBurger: BurgerMaking { func make() -> BurgerDescribing { return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"]) } } final class JackInTheBox: BurgerMaking { func make() -> BurgerDescribing { return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"]) } } /*: 抽象工厂 */ enum BurgerFactoryType: BurgerMaking { case bigKahuna case jackInTheBox func make() -> BurgerDescribing { switch self { case .bigKahuna: return BigKahunaBurger().make() case .jackInTheBox: return JackInTheBox().make() } } } /*: ### 用法 */ let bigKahuna = BurgerFactoryType.bigKahuna.make() let jackInTheBox = BurgerFactoryType.jackInTheBox.make() /*: 👷 生成器(Builder) -------------- 一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。 ### 示例: */ final class DeathStarBuilder { var x: Double? var y: Double? var z: Double? typealias BuilderClosure = (DeathStarBuilder) -> () init(buildClosure: BuilderClosure) { buildClosure(self) } } struct DeathStar : CustomStringConvertible { let x: Double let y: Double let z: Double init?(builder: DeathStarBuilder) { if let x = builder.x, let y = builder.y, let z = builder.z { self.x = x self.y = y self.z = z } else { return nil } } var description:String { return "Death Star at (x:\(x) y:\(y) z:\(z))" } } /*: ### 用法 */ let empire = DeathStarBuilder { builder in builder.x = 0.1 builder.y = 0.2 builder.z = 0.3 } let deathStar = DeathStar(builder:empire) /*: 🏭 工厂方法(Factory Method) ----------------------- 定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。 ### 示例: */ protocol CurrencyDescribing { var symbol: String { get } var code: String { get } } final class Euro: CurrencyDescribing { var symbol: String { return "€" } var code: String { return "EUR" } } final class UnitedStatesDolar: CurrencyDescribing { var symbol: String { return "$" } var code: String { return "USD" } } enum Country { case unitedStates case spain case uk case greece } enum CurrencyFactory { static func currency(for country: Country) -> CurrencyDescribing? { switch country { case .spain, .greece: return Euro() case .unitedStates: return UnitedStatesDolar() default: return nil } } } /*: ### 用法 */ let noCurrencyCode = "No Currency Code Available" CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode /*: 🔂 单态(Monostate) ------------ 单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。 因此,在这种情况下,单态会将状态保存为静态,而不是将整个实例保存为单例。 [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf) ### 示例: */ class Settings { enum Theme { case `default` case old case new } private static var theme: Theme? var currentTheme: Theme { get { Settings.theme ?? .default } set(newTheme) { Settings.theme = newTheme } } } /*: ### 用法: */ import SwiftUI // 改变主题 let settings = Settings() // 开始使用主题 .old settings.currentTheme = .new // 改变主题为 .new // 界面一 let screenColor: Color = Settings().currentTheme == .old ? .gray : .white // 界面二 let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect" /*: 🃏 原型(Prototype) -------------- 通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。 ### 示例: */ class MoonWorker { let name: String var health: Int = 100 init(name: String) { self.name = name } func clone() -> MoonWorker { return MoonWorker(name: name) } } /*: ### 用法 */ let prototype = MoonWorker(name: "Sam Bell") var bell1 = prototype.clone() bell1.health = 12 var bell2 = prototype.clone() bell2.health = 23 var bell3 = prototype.clone() bell3.health = 0 /*: 💍 单例(Singleton) -------------- 单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为 ### 示例: */ final class ElonMusk { static let shared = ElonMusk() private init() { // Private initialization to ensure just one instance is created. } } /*: ### 用法 */ let elon = ElonMusk.shared // There is only one Elon Musk folks.
gpl-3.0
6b8486f1a1ce4214905ef377e6339548
17.785211
104
0.619119
3.085599
false
false
false
false
soniccat/GAPageViewController
GAPagerViewController/PagerController/GAPagerViewController.swift
1
8144
// // GAPagerViewController.swift // CollectionPager // // Created by Alexey Glushkov on 04.03.17. // Copyright © 2017 Alexey Glushkov. All rights reserved. // import UIKit @objc public protocol PagerConrollerViewControllerDataSrouce { func pagerControllerNumberOfPages() -> Int func pagerControllerBindPage(controller: UIViewController, index: Int) func pagerControllerPageIndentifier(index: Int) -> String func pagerControllerCreateController(identifier: String) -> UIViewController } @objc public protocol PagerConrollerViewControllerDelegate { func pagerControllerPageDidChange() func pagerControllerWillAppearPage(controller: UIViewController, index: Int) func pagerControllerWillDisappearPage(controller: UIViewController, index: Int) func pagerControllerDidAppearPage(controller: UIViewController, index: Int) func pagerControllerDidDisappearPage(controller: UIViewController, index: Int) } open class GAPagerViewController: GABasePagerViewController, GAReuseQueueDelegate { private let CellIdentifier = "PagerCell" private var queue = GAReuseQueue() private var bindedControllers:[Int:UIViewController] = [:] // Define how many additional controllers we want to keep in the memory public var bindControllerRange = 1 { didSet { updateBindedControllers() } } public var datasource: PagerConrollerViewControllerDataSrouce! public var delegate: PagerConrollerViewControllerDelegate? override open func awakeFromNib() { super.awakeFromNib() baseInit() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) baseInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) baseInit() } private func baseInit() { bindDelegate() } private func bindDelegate() { queue.delegate = self } override open func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) var i = 0; for controller in bindedControllers.values { controller.restorationIdentifier = String(format: "%d", i) i += 1 } coder.encode(bindedControllers, forKey: "bindedControllers") } override open func decodeRestorableState(with coder: NSCoder) { super.decodeRestorableState(with: coder) bindedControllers = coder.decodeObject(forKey: "bindedControllers") as! [Int : UIViewController] } // force controller binding private func prebindControllers() { let minIndex = max(0, currentIndex - bindControllerRange) let maxIndex = min(collectionView.numberOfItems(inSection: 0) - 1, currentIndex + bindControllerRange) for i in minIndex ... maxIndex { if bindedControllers[i] == nil { bindController(index: i) } } } // MARK: Overrides open override func registerCells() { collectionView.register(GAPagerCell.self, forCellWithReuseIdentifier: CellIdentifier) } open override func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) } override open func onPageChange() { updateBindedControllers() prebindControllers() delegate?.pagerControllerPageDidChange() } override open func numberOfPage() -> Int { return datasource.pagerControllerNumberOfPages() } override open func bindPage(cell: UICollectionViewCell, index: Int) { prebindControllers() // we set controller for the cell in startAddingController } private func bindController(index: Int) { let controller = ensuredPageController(index: index) prepareController(controller: controller) datasource.pagerControllerBindPage(controller: controller, index: index) addBindedController(index: index, controller: controller) } override open func pageWillAppear(cell: UICollectionViewCell, index: Int) { let pagerCell = cell as! GAPagerCell startAddingControllerIfNeeded(cell: pagerCell, index: index) delegate?.pagerControllerWillAppearPage(controller: pagerCell.controller!, index: index) } override open func pageDidAppear(cell: UICollectionViewCell, index: Int) { let pagerCell = cell as! GAPagerCell finishAddingController(cell: pagerCell, index: index) delegate?.pagerControllerDidAppearPage(controller: pagerCell.controller!, index: index) } override open func pageWillDisappear(cell: UICollectionViewCell, index: Int) { let pagerCell = cell as! GAPagerCell startRemovingController(cell: pagerCell, index: index) delegate?.pagerControllerWillDisappearPage(controller: pagerCell.controller!, index: index) } override open func pageDidDisappear(cell: UICollectionViewCell, index: Int) { let pagerCell = cell as! GAPagerCell delegate?.pagerControllerDidDisappearPage(controller: pagerCell.controller!, index: index) finishRemovingController(cell: pagerCell, index: index) } // MARK: work with bindedControllers private func updateBindedControllers() { for (index, v) in bindedControllers { if abs(currentIndex - index) > bindControllerRange { queue.enqueue(obj: v) gaLog("queue size %d", queue.count) clearBindedController(index: index) } } } private func addBindedController(index:Int, controller: UIViewController) { bindedControllers[index] = controller gaLog("binded size %d after add", bindedControllers.count) } private func clearBindedController(index:Int) { bindedControllers[index] = nil gaLog("binded size %d after clear", bindedControllers.count) } // func startAddingControllerIfNeeded(cell: GAPagerCell, index:Int) { if cell.controller == nil { startAddingController(cell: cell, index: index) } else { cell.startAddingController(ct: cell.controller!, animated: true) } } func startAddingController(cell: GAPagerCell, index:Int) { let controller = ensuredPageController(index: index) addChildViewController(controller) cell.startAddingController(ct: controller, animated: true) controller.didMove(toParentViewController: self) } func finishAddingController(cell: GAPagerCell, index:Int) { cell.finishAddingController() } func startRemovingController(cell: GAPagerCell, index:Int) { cell.startRemovingController(animated: true) } func finishRemovingController(cell: GAPagerCell, index:Int) { let ctrl = cell.controller ctrl?.willMove(toParentViewController: nil) cell.finishRemovingController() // we enque the controller in updateBindedControllers } func ensuredPageController(index: Int) -> UIViewController { var controller = bindedControllers[index] let identifier = datasource.pagerControllerPageIndentifier(index: index) if controller == nil || controller?.reuseIdentifier != identifier { controller = queue.dequeue(reuseIdentifier: identifier) as? UIViewController gaLog("queue size %d %@", queue.count, controller!) } return controller! } func prepareController(controller: UIViewController) { controller.view.frame = view.bounds } public func createObject(reuseIdentifier: String) -> GAReusableObject { return datasource.pagerControllerCreateController(identifier: reuseIdentifier) } }
mit
7e6e312ebe549eb7f0903b7b16be9b59
34.251082
110
0.673585
5.121384
false
false
false
false
Higgcz/Buildasaur
BuildaKit/SyncerBotManipulation.swift
2
4790
// // GitHubXCBotUtils.swift // Buildasaur // // Created by Honza Dvorsky on 16/05/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK import BuildaGitServer import BuildaUtils extension HDGitHubXCBotSyncer { //MARK: Bot manipulation utils func cancelIntegrations(integrations: [Integration], completion: () -> ()) { integrations.mapVoidAsync({ (integration, itemCompletion) -> () in self.xcodeServer.cancelIntegration(integration.id, completion: { (success, error) -> () in if error != nil { self.notifyError(error, context: "Failed to cancel integration \(integration.number)") } else { Log.info("Successfully cancelled integration \(integration.number)") } itemCompletion() }) }, completion: completion) } func deleteBot(bot: Bot, completion: () -> ()) { self.xcodeServer.deleteBot(bot.id, revision: bot.rev, completion: { (success, error) -> () in if error != nil { self.notifyError(error, context: "Failed to delete bot with name \(bot.name)") } else { Log.info("Successfully deleted bot \(bot.name)") } completion() }) } private func createBotFromName(botName: String, branch: String, repo: Repo, completion: () -> ()) { /* synced bots must have a manual schedule, Builda tells the bot to reintegrate in case of a new commit. this has the advantage in cases when someone pushes 10 commits. if we were using Xcode Server's "On Commit" schedule, it'd schedule 10 integrations, which could take ages. Builda's logic instead only schedules one integration for the latest commit's SHA. even though this is desired behavior in this syncer, technically different syncers can have completely different logic. here I'm just explaining why "On Commit" schedule isn't generally a good idea for when managed by Builda. */ let schedule = BotSchedule.manualBotSchedule() let template = self.currentBuildTemplate() //to handle forks let headOriginUrl = repo.repoUrlSSH let localProjectOriginUrl = self.project.workspaceMetadata!.projectURL.absoluteString let project: Project if headOriginUrl != localProjectOriginUrl { //we have a fork, duplicate the metadata with the fork's origin do { let source = try self.project.duplicateForForkAtOriginURL(headOriginUrl) project = source } catch { self.notifyError(Error.withInfo("Couldn't create a Project for fork with origin at url \(headOriginUrl), error \(error)"), context: "Creating a bot from a PR") completion() return } } else { //a normal PR in the same repo, no need to duplicate, just use the existing project project = self.project } let xcodeServer = self.xcodeServer XcodeServerSyncerUtils.createBotFromBuildTemplate(botName, template: template, project: project, branch: branch, scheduleOverride: schedule, xcodeServer: xcodeServer) { (bot, error) -> () in if error != nil { self.notifyError(error, context: "Failed to create bot with name \(botName)") } completion() } } func createBotFromPR(pr: PullRequest, completion: () -> ()) { let branchName = pr.head.ref let botName = BotNaming.nameForBotWithPR(pr, repoName: self.repoName()!) self.createBotFromName(botName, branch: branchName, repo: pr.head.repo, completion: completion) } func createBotFromBranch(branch: Branch, repo: Repo, completion: () -> ()) { let branchName = branch.name let botName = BotNaming.nameForBotWithBranch(branch, repoName: self.repoName()!) self.createBotFromName(botName, branch: branchName, repo: repo, completion: completion) } private func currentBuildTemplate() -> BuildTemplate! { if let preferredTemplateId = self.project.preferredTemplateId, let template = StorageManager.sharedInstance.buildTemplates.filter({ $0.uniqueId == preferredTemplateId }).first { return template } assertionFailure("Couldn't get the current build template, this syncer should NOT be running!") return nil } }
mit
2ac9531f3d9d13f6602a7c642150573c
38.916667
198
0.604802
5.074153
false
false
false
false
abelondev/JSchemaForm
Source/JScope.swift
1
2228
// // JScope.swift // Pods // // Created by Andrey Belonogov on 11/24/15. // // import Foundation @objc public class JScope : NSObject { public var scopeDictionary:[String:AnyObject]? public var schema:JSchema? public var form:JForm? public var model:[String:AnyObject]? public lazy var dateTimeFormatter:NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" dateFormatter.locale = .currentLocale() return dateFormatter; }() public init(schema:JSchema, form:JForm, model:[String:AnyObject]) { self.schema = schema; self.form = form; self.model = model; } public init(schemaDictionary:[String:AnyObject]?, formArray:[AnyObject]?, modelDictionary:[String:AnyObject]?) { if let schemaDict = schemaDictionary { self.schema = JSchema(dictionary: schemaDict); } if let formArray = formArray { self.form = JForm(array: formArray); } if let modelDictionary = modelDictionary { self.model = modelDictionary; } } public convenience init?(scopeDictionary ascopeDictionary:[String:AnyObject]) throws { let expandedScopeDictionary = try ReferenceExpander(rootDictionary:ascopeDictionary).expand() var vformArray:[AnyObject]?; var vmodelDict:[String: AnyObject]?; var vschemaDict:[String: AnyObject]?; if let formArray = expandedScopeDictionary["form"] as! [AnyObject]? { vformArray = formArray; } if let modelDict = expandedScopeDictionary["model"] as! [String: AnyObject]? { vmodelDict = modelDict; } if let schemaDict = expandedScopeDictionary["schema"] as! [String: AnyObject]? { vschemaDict = schemaDict; } self.init(schemaDictionary:vschemaDict, formArray:vformArray, modelDictionary:vmodelDict); scopeDictionary = expandedScopeDictionary; } /*public convenience init(dictionary: [String: AnyObject]) throws { self.init(schema:JSchema(dictionary: dictionary)); } */ }
apache-2.0
f9da3d3f0063af14016717f8c4c8e415
29.958333
116
0.62702
4.528455
false
false
false
false
fousa/trackkit
Example/Tests/Tests/GPX/1.1/GPXWaypointSpecs.swift
1
12814
// // TrackKit // // Created by Jelle Vandebeeck on 30/12/2016. // import Quick import Nimble import TrackKit class GPXWaypointSpec: QuickSpec { override func spec() { describe("waypoints") { it("should not have waypoints") { let content = "<gpx version='1.1'></gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.waypoints).to(beNil()) } it("should not have waypoints without a coordinate") { let content = "<gpx version='1.1'>" + "<wpt></wpt>" + "<wpt></wpt>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.waypoints).to(beNil()) } it("should have waypoints") { let content = "<gpx version='1.1'>" + "<wpt lat='10' lon='10'></wpt>" + "<wpt lat='11' lon='11'></wpt>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.waypoints?.count) == 2 } } describe("waypoint data") { var point: Point! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<wpt lat='41.2' lon='-71.3'>" + "<ele>1001</ele>" + "<magvar>300</magvar>" + "<name>A waypoint</name>" + "<time>2016-03-10T10:05:12+02:00</time>" + "<geoidheight>56</geoidheight>" + "<cmt>A comment</cmt>" + "<desc>A description</desc>" + "<src>A source</src>" + "<sym>A symbol</sym>" + "<type>A type</type>" + "<fix>dgps</fix>" + "<sat>9</sat>" + "<hdop>1.3</hdop>" + "<vdop>2.2</vdop>" + "<pdop>3.1</pdop>" + "<ageofdgpsdata>0.4</ageofdgpsdata>" + "<dgpsid>400</dgpsid>" // Link + "<link href='http://fousa.be'>" + "<text>Fousa</text>" + "<type>text/html</type>" + "</link>" + "</wpt>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() point = file.waypoints?.first! } it("should have a coordinate") { expect(point.coordinate?.latitude) == 41.2 expect(point.coordinate?.longitude) == -71.3 } it("should have an elevation") { expect(point.elevation) == 1001 } it("should have a magnetic variation") { expect(point.magneticVariation) == 300 } it("should have a time") { expect(point.time?.description) == "2016-03-10 08:05:12 +0000" } it("should have a mean sea level height") { expect(point.meanSeaLevelHeight) == 56 } it("should have a name") { expect(point.name) == "A waypoint" } it("should have a comment") { expect(point.comment) == "A comment" } it("should have a description") { expect(point.description) == "A description" } it("should have a source") { expect(point.source) == "A source" } it("should have a link") { expect(point.link?.link) == "http://fousa.be" expect(point.link?.text) == "Fousa" expect(point.link?.mimeType) == "text/html" } it("should have a symbol") { expect(point.source) == "A source" } it("should have satelites") { expect(point.satelites) == 9 } it("should have a horizontal dilution of precision") { expect(point.horizontalDilutionOfPrecision) == 1.3 } it("should have a vertical dilution of precision") { expect(point.verticalDilutionOfPrecision) == 2.2 } it("should have a position dilution of precision") { expect(point.positionDilutionOfPrecision) == 3.1 } it("should have an age of gpx data") { expect(point.ageOfTheGpxData) == 0.4 } it("should have a gps station type") { expect(point.dgpsStationType) == 400 } it("should have a type") { expect(point.type) == "A type" } it("should have a fix") { expect(point.fix) == .dgps } it("should not have an air temperature") { expect(point.airTemperature).to(beNil()) } it("should not have a water temperature") { expect(point.waterTemperature).to(beNil()) } it("should not have a depth") { expect(point.depth).to(beNil()) } it("should not have a heart rate") { expect(point.heartRate).to(beNil()) } it("should not have a cadence") { expect(point.cadence).to(beNil()) } it("should not have a speed") { expect(point.speed).to(beNil()) } it("should not have a course") { expect(point.course).to(beNil()) } it("should not have a bearing") { expect(point.bearing).to(beNil()) } } describe("extensions") { context("TrackPointExtensions") { var point: Point! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<wpt lat='41.2' lon='-71.3'>" // Extensions + "<extensions>" + "<gpxtpx:TrackPointExtension>" + "<gpxtpx:atemp>11</gpxtpx:atemp>" + "<gpxtpx:wtemp>20</gpxtpx:wtemp>" + "<gpxtpx:depth>15</gpxtpx:depth>" + "<gpxtpx:hr>116</gpxtpx:hr>" + "<gpxtpx:cad>87</gpxtpx:cad>" + "<gpxtpx:speed>4</gpxtpx:speed>" + "<gpxtpx:course>120</gpxtpx:course>" + "<gpxtpx:bearing>130</gpxtpx:bearing>" + "</gpxtpx:TrackPointExtension>" + "</extensions>" + "</wpt>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() point = file.waypoints?.first! } it("should have an air temperature") { expect(point.airTemperature) == 11 } it("should have a water temperature") { expect(point.waterTemperature) == 20 } it("should have a depth") { expect(point.depth) == 15 } it("should have a heart rate") { expect(point.heartRate) == 116 } it("should have a cadence") { expect(point.cadence) == 87 } it("should have a speed") { expect(point.speed) == 4 } it("should have a course") { expect(point.course) == 120 } it("should have a bearing") { expect(point.bearing) == 130 } } } describe("empty waypoint") { var point: Point! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<wpt lat='41.2' lon='-71.3'>" + "</wpt>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() point = file.waypoints?.first! } it("should not have an elevation") { expect(point.elevation).to(beNil()) } it("should not have a magnetic variation") { expect(point.magneticVariation).to(beNil()) } it("should not have a time") { expect(point.time?.description).to(beNil()) } it("should not have a mean sea level height") { expect(point.meanSeaLevelHeight).to(beNil()) } it("should not have a name") { expect(point.name).to(beNil()) } it("should not have a comment") { expect(point.comment).to(beNil()) } it("should not have a description") { expect(point.description).to(beNil()) } it("should not have a source") { expect(point.source).to(beNil()) } it("should not have a link") { expect(point.link).to(beNil()) } it("should not have a type") { expect(point.type).to(beNil()) } it("should not have a fix") { expect(point.fix).to(beNil()) } it("should not have a symbol") { expect(point.source).to(beNil()) } it("should not have satelites") { expect(point.satelites).to(beNil()) } it("should not have a horizontal dilution of precision") { expect(point.horizontalDilutionOfPrecision).to(beNil()) } it("should not have a vertical dilution of precision") { expect(point.verticalDilutionOfPrecision).to(beNil()) } it("should not have a position dilution of precision") { expect(point.positionDilutionOfPrecision).to(beNil()) } it("should not have an age of gpx data") { expect(point.ageOfTheGpxData).to(beNil()) } it("should have a gps station type") { expect(point.dgpsStationType).to(beNil()) } it("should not have an air temperature") { expect(point.airTemperature).to(beNil()) } it("should not have a water temperature") { expect(point.waterTemperature).to(beNil()) } it("should not have a depth") { expect(point.depth).to(beNil()) } it("should not have a heart rate") { expect(point.heartRate).to(beNil()) } it("should not have a cadence") { expect(point.cadence).to(beNil()) } it("should not have a speed") { expect(point.speed).to(beNil()) } it("should not have a course") { expect(point.course).to(beNil()) } it("should not have a bearing") { expect(point.bearing).to(beNil()) } } } }
mit
7572a6b658c5d54eda19e3b16c24d3e6
33.079787
88
0.401826
4.930358
false
false
false
false
joerocca/GitHawk
Classes/Systems/WebviewCellHeightCache.swift
2
1337
// // WebviewCellHeightCache.swift // Freetime // // Created by Ryan Nystrom on 7/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class WebviewCellHeightCache: IssueCommentHtmlCellDelegate { private static let cache = WidthCache<String, CGSize>() private weak var sectionController: ListSectionController? init(sectionController: ListSectionController) { self.sectionController = sectionController } // MARK: Public API func height(model: IssueCommentHtmlModel, width: CGFloat) -> CGFloat { return WebviewCellHeightCache.cache.data(key: model.html, width: width)?.height ?? Styles.Sizes.tableCellHeight } // MARK: IssueCommentHtmlCellDelegate func webViewDidResize(cell: IssueCommentHtmlCell, html: String, cellWidth: CGFloat, size: CGSize) { guard let sectionController = self.sectionController, sectionController.section != NSNotFound, size != WebviewCellHeightCache.cache.data(key: html, width: cellWidth) else { return } WebviewCellHeightCache.cache.set(data: size, key: html, width: cellWidth) UIView.performWithoutAnimation { sectionController.collectionContext?.invalidateLayout(for: sectionController) } } }
mit
66bfcf86852f2ba90ae6ca09b66f7dd1
30.069767
103
0.705838
4.893773
false
false
false
false
Sharelink/Bahamut
Bahamut/UIImagePlayerController.swift
1
13305
// // UIImagePlayerController.swift // Bahamut // // Created by AlexChow on 15/9/6. // Copyright © 2015年 GStudio. All rights reserved. // import UIKit protocol ImageProvider { func getImageCount() -> Int func startLoad(index:Int) func getThumbnail(index:Int) -> UIImage? func registImagePlayerObserver(observer:LoadImageObserver) } class UIFetchImageView: UIScrollView,UIScrollViewDelegate { private var progress:KDCircularProgress!{ didSet{ progress.trackColor = UIColor.blackColor() progress.IBColor1 = UIColor.whiteColor() progress.IBColor2 = UIColor.whiteColor() progress.IBColor3 = UIColor.whiteColor() } } private var refreshButton:UIButton!{ didSet{ refreshButton.titleLabel?.text = "LOAD_IMG_ERROR".localizedString() refreshButton.hidden = true refreshButton.addTarget(self, action: #selector(UIFetchImageView.refreshButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(refreshButton) } } private var imageView:UIImageView! func refreshButtonClick(_:UIButton) { startLoadImage() } func startLoadImage() { canScale = false refreshButton.hidden = true self.progress.setProgressValue(0) } func imageLoaded(image:UIImage) { self.progress.setProgressValue(0) dispatch_async(dispatch_get_main_queue()){ self.imageView.image = image self.canScale = true self.refreshUI() } } func imageLoadError() { self.progress.setProgressValue(0) dispatch_async(dispatch_get_main_queue()){ self.refreshButton.hidden = false self.canScale = false self.refreshUI() } } func loadImageProgress(progress:Float) { self.progress.setProgressValue(0) } func setThumbnail(thumbnail:UIImage) { self.canScale = false self.imageView.image = thumbnail } private func initImageView() { imageView = UIImageView() imageView.contentMode = .ScaleAspectFit self.addSubview(imageView) } private func initErrorButton() { self.refreshButton = UIButton(type: UIButtonType.InfoDark) } private func initGesture() { self.minimumZoomScale = 1 self.maximumZoomScale = 2 self.userInteractionEnabled = true let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(UIFetchImageView.doubleTap(_:))) doubleTapGesture.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTapGesture) } private func initProgress() { progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) progress.startAngle = -90 progress.progressThickness = 0.2 progress.trackThickness = 0.6 progress.clockwise = true progress.gradientRotateSpeed = 2 progress.roundedCorners = false progress.glowMode = .Forward progress.glowAmount = 0.9 progress.setColors(UIColor.cyanColor() ,UIColor.whiteColor(), UIColor.magentaColor(), UIColor.whiteColor(), UIColor.orangeColor()) self.addSubview(progress) progress.hidden = true } private func refreshUI() { self.setZoomScale(self.minimumZoomScale, animated: true) progress.center = CGPoint(x: self.center.x, y: self.center.y) refreshButton.center = CGPoint(x: self.center.x, y: self.center.y) imageView.frame = UIApplication.sharedApplication().keyWindow!.bounds imageView.layoutIfNeeded() } private var isScale:Bool = false private var isScrollling:Bool = false private var canScale:Bool = false func doubleTap(ges:UITapGestureRecognizer) { if !canScale{return} let touchPoint = ges.locationInView(self) if (self.zoomScale != self.minimumZoomScale) { self.setZoomScale(self.minimumZoomScale, animated: true) } else { let newZoomScale = CGFloat(2.0) let xsize = self.bounds.size.width / newZoomScale let ysize = self.bounds.size.height / newZoomScale self.zoomToRect(CGRectMake(touchPoint.x - xsize / 2, touchPoint.y - ysize / 2, xsize, ysize), animated: true) } } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return self.imageView } func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) { self.scrollEnabled = true } func scrollViewDidZoom(scrollView: UIScrollView) { self.setNeedsLayout() self.setNeedsDisplay() } convenience init() { self.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) initScrollView() initImageView() initProgress() initErrorButton() initGesture() } private func initScrollView() { self.delegate = self self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.decelerationRate = UIScrollViewDecelerationRateFast self.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } protocol LoadImageObserver { func imageLoaded(index:Int,image:UIImage) func imageLoadError(index:Int) func imageLoadingProgress(index:Int,progress:Float) } class UIImagePlayerController: UIViewController,UIScrollViewDelegate,LoadImageObserver { private var imageCount:Int = 0 private let spaceOfItem:CGFloat = 23 var imageProvider:ImageProvider!{ didSet{ imageProvider.registImagePlayerObserver(self) imageCount = imageProvider.getImageCount() } } var images = [UIFetchImageView]() func supportedViewOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.All } @IBOutlet weak var scrollView: UIScrollView!{ didSet{ scrollView.backgroundColor = UIColor.blackColor() scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.pagingEnabled = false scrollView.delegate = self } } var currentIndex:Int = -1{ didSet{ if currentIndex >= 0 && currentIndex != oldValue && currentIndex < imageCount { images[currentIndex].startLoadImage() if let thumb = imageProvider.getThumbnail(currentIndex) { images[currentIndex].setThumbnail(thumb) } self.imageProvider.startLoad(currentIndex) } } } private func scrollToCurrentIndex() { let x:CGFloat = CGFloat(integerLiteral: currentIndex) * (self.scrollView.frame.width + spaceOfItem); self.scrollView.contentOffset = CGPointMake(x, 0); } private func getNearestTargetPoint(offset:CGPoint) -> CGPoint{ let pageSize = self.scrollView.frame.width + spaceOfItem let targetIndex = Int(roundf(Float(offset.x / pageSize))) currentIndex += targetIndex == currentIndex ? 0 : targetIndex > currentIndex ? 1 : -1 let targetX = pageSize * CGFloat(currentIndex); return CGPointMake(targetX, offset.y); } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let offset = getNearestTargetPoint(targetContentOffset.memory) targetContentOffset.memory.x = offset.x } func imageLoaded(index: Int, image: UIImage) { if images.count > index{ images[index].imageLoaded(image) } } func imageLoadError(index: Int) { if images.count > index{ images[index].imageLoadError() } } func imageLoadingProgress(index: Int, progress: Float) { if images.count > index{ images[index].loadImageProgress(progress) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return [UIInterfaceOrientationMask.Portrait,UIInterfaceOrientationMask.Landscape] } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) initImageViews() initPageControl() initObserver() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) deinitObserver() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() resizeScrollView() } private func initPageControl() { self.pageControl.numberOfPages = imageCount } @IBOutlet weak var pageControl: UIPageControl!{ didSet{ if pageControl != nil { pageControl.hidden = imageCount <= 1 } } } func initImageViews() { for _ in 0..<imageCount { let uiImageView = UIFetchImageView() scrollView.addSubview(uiImageView) images.append(uiImageView) } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(UIImagePlayerController.tapScollView(_:))) let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(UIImagePlayerController.doubleTapScollView(_:))) doubleTapGesture.numberOfTapsRequired = 2 tapGesture.requireGestureRecognizerToFail(doubleTapGesture) tapGesture.delaysTouchesBegan = true self.view.addGestureRecognizer(tapGesture) self.view.addGestureRecognizer(doubleTapGesture) } private func initObserver() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIImagePlayerController.didChangeStatusBarOrientation(_:)), name: UIApplicationDidChangeStatusBarOrientationNotification, object: UIApplication.sharedApplication()) } private func deinitObserver() { NSNotificationCenter.defaultCenter().removeObserver(self) } func didChangeStatusBarOrientation(_: NSNotification) { resizeScrollView() } func resizeScrollView() { let svFrame = UIApplication.sharedApplication().keyWindow!.bounds let imageWidth = svFrame.width let imageHeight = svFrame.height let pageSize = imageWidth + spaceOfItem for i:Int in 0 ..< images.count { let imageX = CGFloat(integerLiteral: i) * pageSize let frame = CGRectMake( imageX , 0, imageWidth, imageHeight) images[i].frame = frame images[i].refreshUI() } scrollView.frame = svFrame scrollView.contentSize = CGSizeMake(CGFloat(integerLiteral:imageCount) * pageSize, imageHeight) } enum OrientationAngle:CGFloat { case Portrait = 0.0 case LandscapeLeft = 270.0 case LandscapeRight = 90.0 case PortraitUpsideDown = 180.0 } func getRotationAngle() -> OrientationAngle { switch UIApplication.sharedApplication().statusBarOrientation { case .Portrait: return OrientationAngle.Portrait case .LandscapeLeft: return OrientationAngle.LandscapeLeft case .LandscapeRight: return OrientationAngle.LandscapeRight case .PortraitUpsideDown: return OrientationAngle.PortraitUpsideDown case .Unknown: return OrientationAngle.Portrait } } func scrollViewDidScroll(scrollView: UIScrollView) { let scrollviewW:CGFloat = scrollView.frame.width; let x = scrollView.contentOffset.x; let page:Int = Int((x + scrollviewW / 2) / scrollviewW); if pageControl != nil { self.pageControl.currentPage = page } } func doubleTapScollView(_:UIGestureRecognizer) { } func tapScollView(_:UIGestureRecognizer) { self.dismissViewControllerAnimated(false) { () -> Void in } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } static func showImagePlayer(currentController:UIViewController,imageProvider:ImageProvider,imageIndex:Int = 0) { let controller = instanceFromStoryBoard("Component", identifier: "imagePlayerController",bundle: Sharelink.mainBundle()) as!UIImagePlayerController controller.imageProvider = imageProvider currentController.presentViewController(controller, animated: true, completion: { () -> Void in controller.currentIndex = imageIndex controller.scrollToCurrentIndex() }) } }
mit
a35471ffb55af8cbb74f6f86951996b6
30.521327
247
0.639829
5.337881
false
false
false
false
linchaosheng/CSSwiftWB
SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBQRCodeCardViewController.swift
1
3934
// // QRCodeCardViewController.swift // DSWeibo // // Created by xiaomage on 15/9/9. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit class WBQRCodeCardViewController: UIViewController { // MARK: - 懒加载 fileprivate lazy var iconView: UIImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() // 1.设置标题 navigationItem.title = "我的名片" // 2.添加图片容器 view.addSubview(iconView) // 3.布局图片容器 iconView.bounds = CGRect(x: 0, y: 0, width: 300, height: 300) iconView.center = view.center // iconView.backgroundColor = UIColor.redColor() // 4.生成二维码 let qrcodeImage = creatQRCodeImage() // 5.将生成好的二维码添加到图片容器上 iconView.image = qrcodeImage } fileprivate func creatQRCodeImage() -> UIImage{ // 1.创建滤镜 let filter = CIFilter(name: "CIQRCodeGenerator") // 2.还原滤镜的默认属性 filter?.setDefaults() // 3.设置需要生成二维码的数据 filter?.setValue("安人多梦".data(using: String.Encoding.utf8), forKey: "inputMessage") // 4.从滤镜中取出生成好的图片 let ciImage = filter?.outputImage // 创建高清二维码 let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!, size: 300) // 5.创建一个头像 let icon = UIImage(named: "avatar_vip") // 6.合成图片(将二维码和头像进行合并) let newImage = creteImage(bgImage, iconImage: icon!) // 7.返回生成好的二维码 return newImage } /** 合成图片 :param: bgImage 背景图片 :param: iconImage 头像 */ fileprivate func creteImage(_ bgImage: UIImage, iconImage: UIImage) -> UIImage { // 1.开启图片上下文 UIGraphicsBeginImageContext(bgImage.size) // 2.绘制背景图片 bgImage.draw(in: CGRect(origin: CGPoint.zero, size: bgImage.size)) // 3.绘制头像 let W : CGFloat = 50 let H : CGFloat = W let X = (bgImage.size.width - W) * 0.5 let Y = (bgImage.size.height - H) * 0.5 iconImage.draw(in: CGRect(x: X, y: Y, width: W, height: H)) // 4.取出绘制号的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 5.关闭上下文 UIGraphicsEndImageContext() // 6.返回合成号的图片 return newImage! } /** 根据CIImage生成指定大小的高清UIImage :param: image 指定CIImage :param: size 指定大小 :returns: 生成好的图片 */ fileprivate func createNonInterpolatedUIImageFormCIImage(_ image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = image.extent.integral let scale: CGFloat = min(size/extent.width, size/extent.height) // 1.创建bitmap; let width = extent.width * scale let height = extent.height * scale let cs: CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)! let context = CIContext(options: nil) let bitmapImage: CGImage = context.createCGImage(image, from: extent)! bitmapRef.interpolationQuality = CGInterpolationQuality.none bitmapRef.scaleBy(x: scale, y: scale); bitmapRef.draw(bitmapImage, in: extent); // 2.保存bitmap到图片 let scaledImage: CGImage = bitmapRef.makeImage()! return UIImage(cgImage: scaledImage) } }
apache-2.0
f8f681b3acf5611e9e3de03a531769a8
27.893443
148
0.583546
4.277913
false
false
false
false
Yalantis/PixPic
PixPic/Classes/Services/PostService.swift
1
4740
// // PostService.swift // PixPic // // Created by Jack Lapin on 16.02.16. // Copyright © 2016 Yalantis. All rights reserved. // import Foundation private let messageUploadSuccessful = NSLocalizedString("upload_successful", comment: "") typealias LoadingPostsCompletion = (posts: [Post]?, error: NSError?) -> Void class PostService { // MARK: - Public methods func loadPosts(user: User? = nil, completion: LoadingPostsCompletion) { let query = Post.sortedQuery query.cachePolicy = .NetworkElseCache query.limit = Constants.DataSource.queryLimit loadPosts(user, query: query, completion: completion) } func loadPagedPosts(user: User? = nil, offset: Int = 0, completion: LoadingPostsCompletion) { let query = Post.sortedQuery query.cachePolicy = .NetworkElseCache query.limit = Constants.DataSource.queryLimit query.skip = offset loadPosts(user, query: query, completion: completion) } func savePost(image: PFFile, comment: String? = nil) { image.saveInBackgroundWithBlock({ succeeded, error in if succeeded { log.debug("Saved!") self.uploadPost(image, comment: comment) } else if let error = error { log.debug(error.localizedDescription) } }, progressBlock: { progress in log.debug("Uploaded: \(progress)%") }) } func removePost(post: Post, completion: (Bool, NSError?) -> Void) { post.deleteInBackgroundWithBlock(completion) } // MARK: - Private methods private func uploadPost(image: PFFile, comment: String?) { guard let user = User.currentUser() else { // Authentication service return } let post = Post(image: image, user: user, comment: comment) post.saveInBackgroundWithBlock { succeeded, error in if succeeded { AlertManager.sharedInstance.showSimpleAlert(messageUploadSuccessful) NSNotificationCenter.defaultCenter().postNotificationName( Constants.NotificationName.newPostIsUploaded, object: nil ) } else { if let error = error?.localizedDescription { log.debug(error) } } } } private func loadPosts(user: User?, query: PFQuery, completion: LoadingPostsCompletion) { if User.isAbsent { log.debug("No user signUP") fetchPosts(query, completion: completion) return } query.cachePolicy = .NetworkElseCache if let user = user { query.whereKey("user", equalTo: user) fetchPosts(query, completion: completion) } else if SettingsHelper.isShownOnlyFollowingUsersPosts && !User.notAuthorized { let followersQuery = PFQuery(className: Activity.parseClassName()) followersQuery.cachePolicy = .CacheThenNetwork followersQuery.whereKey(Constants.ActivityKey.fromUser, equalTo: User.currentUser()!) followersQuery.whereKey(Constants.ActivityKey.type, equalTo: ActivityType.Follow.rawValue) followersQuery.includeKey(Constants.ActivityKey.toUser) var arrayOfFollowers: [User] = [User.currentUser()!] followersQuery.findObjectsInBackgroundWithBlock { [weak self] activities, error in if let error = error { log.debug(error.localizedDescription) } else if let activities = activities as? [Activity] { let friends = activities.flatMap { $0[Constants.ActivityKey.toUser] as? User } arrayOfFollowers.appendContentsOf(friends) } query.whereKey("user", containedIn: arrayOfFollowers) self?.fetchPosts(query, completion: completion) } } else { fetchPosts(query, completion: completion) } } private func fetchPosts(query: PFQuery, completion: LoadingPostsCompletion) { var posts = [Post]() query.findObjectsInBackgroundWithBlock { objects, error in if let objects = objects { for object in objects { posts.append(object as! Post) object.saveEventually() } completion(posts: posts, error: nil) } else if let error = error { log.debug(error.localizedDescription) completion(posts: nil, error: error) } else { completion(posts: nil, error: nil) } } } }
mit
20fd2032247668b89a35b66ddd579eea
36.611111
102
0.597383
5.063034
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainSuggestions/DomainSuggestionsTableViewController.swift
1
20471
import UIKit import SVProgressHUD import WordPressAuthenticator protocol DomainSuggestionsTableViewControllerDelegate { func domainSelected(_ domain: FullyQuotedDomainSuggestion) func newSearchStarted() } /// This class provides domain suggestions based on keyword searches /// performed by the user. /// class DomainSuggestionsTableViewController: UITableViewController { // MARK: - Fonts private let domainBaseFont = WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular) private let domainTLDFont = WPStyleGuide.fontForTextStyle(.body, fontWeight: .semibold) private let saleCostFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular) private let suggestionCostFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular) private let perYearPostfixFont = WPStyleGuide.fontForTextStyle(.footnote, fontWeight: .regular) private let freeForFirstYearFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular) // MARK: - Cell Identifiers private static let suggestionCellIdentifier = "org.wordpress.domainsuggestionstable.suggestioncell" // MARK: - Properties var blog: Blog? var siteName: String? var delegate: DomainSuggestionsTableViewControllerDelegate? var domainSuggestionType: DomainsServiceRemote.DomainSuggestionType = .noWordpressDotCom var domainType: DomainType? var freeSiteAddress: String = "" var useFadedColorForParentDomains: Bool { return false } var searchFieldPlaceholder: String { return NSLocalizedString( "Type to get more suggestions", comment: "Register domain - Search field placeholder for the Suggested Domain screen" ) } private var noResultsViewController: NoResultsViewController? private var siteTitleSuggestions: [FullyQuotedDomainSuggestion] = [] private var searchSuggestions: [FullyQuotedDomainSuggestion] = [] { didSet { tableView.reloadSections(IndexSet(integer: Sections.suggestions.rawValue), with: .automatic) } } private var isSearching: Bool = false private var selectedCell: UITableViewCell? // API returned no domain suggestions. private var noSuggestions: Bool = false fileprivate enum ViewPadding: CGFloat { case noResultsView = 60 } private var parentDomainColor: UIColor { return useFadedColorForParentDomains ? .neutral(.shade30) : .neutral(.shade70) } private let searchDebouncer = Debouncer(delay: 0.5) // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() let bundle = WordPressAuthenticator.bundle tableView.register(UINib(nibName: "SearchTableViewCell", bundle: bundle), forCellReuseIdentifier: SearchTableViewCell.reuseIdentifier) setupBackgroundTapGestureRecognizer() } // MARK: - View override func viewDidLoad() { super.viewDidLoad() WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.layoutMargins = WPStyleGuide.edgeInsetForLoginTextFields() navigationItem.title = NSLocalizedString("Create New Site", comment: "Title for the site creation flow.") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // only procede with initial search if we don't have site title suggestions yet // (hopefully only the first time) guard siteTitleSuggestions.count < 1, let nameToSearch = siteName else { return } suggestDomains(for: nameToSearch) { [weak self] (suggestions) in self?.siteTitleSuggestions = suggestions self?.tableView.reloadSections(IndexSet(integer: Sections.suggestions.rawValue), with: .automatic) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13, *) { if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle { tableView.reloadData() } } } /// Fetches new domain suggestions based on the provided string /// /// - Parameters: /// - searchTerm: string to base suggestions on /// - addSuggestions: function to call when results arrive private func suggestDomains(for searchTerm: String, addSuggestions: @escaping (_: [FullyQuotedDomainSuggestion]) ->()) { guard !isSearching else { return } isSearching = true let account = try? WPAccount.lookupDefaultWordPressComAccount(in: ContextManager.shared.mainContext) let api = account?.wordPressComRestApi ?? WordPressComRestApi.defaultApi(oAuthToken: "") let service = DomainsService(managedObjectContext: ContextManager.sharedInstance().mainContext, remote: DomainsServiceRemote(wordPressComRestApi: api)) SVProgressHUD.setContainerView(tableView) SVProgressHUD.show(withStatus: NSLocalizedString("Loading domains", comment: "Shown while the app waits for the domain suggestions web service to return during the site creation process.")) service.getFullyQuotedDomainSuggestions(query: searchTerm, domainSuggestionType: domainSuggestionType, success: handleGetDomainSuggestionsSuccess, failure: handleGetDomainSuggestionsFailure) } private func handleGetDomainSuggestionsSuccess(_ suggestions: [FullyQuotedDomainSuggestion]) { isSearching = false noSuggestions = false SVProgressHUD.dismiss() tableView.separatorStyle = .singleLine searchSuggestions = suggestions } private func handleGetDomainSuggestionsFailure(_ error: Error) { DDLogError("Error getting Domain Suggestions: \(error.localizedDescription)") isSearching = false noSuggestions = true SVProgressHUD.dismiss() tableView.separatorStyle = .none // Dismiss the keyboard so the full no results view can be seen. view.endEditing(true) // Add no suggestions to display the no results view. searchSuggestions = [] } // MARK: background gesture recognizer /// Sets up a gesture recognizer to detect taps on the view, but not its content. /// func setupBackgroundTapGestureRecognizer() { let gestureRecognizer = UITapGestureRecognizer() gestureRecognizer.on { [weak self](gesture) in self?.view.endEditing(true) } gestureRecognizer.cancelsTouchesInView = false view.addGestureRecognizer(gestureRecognizer) } } // MARK: - UITableViewDataSource extension DomainSuggestionsTableViewController { fileprivate enum Sections: Int, CaseIterable { case topBanner case searchField case suggestions static var count: Int { return allCases.count } } override func numberOfSections(in tableView: UITableView) -> Int { return Sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Sections.topBanner.rawValue: return shouldShowTopBanner ? 1 : 0 case Sections.searchField.rawValue: return 1 case Sections.suggestions.rawValue: if noSuggestions == true { return 1 } return searchSuggestions.count > 0 ? searchSuggestions.count : siteTitleSuggestions.count default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell switch indexPath.section { case Sections.topBanner.rawValue: cell = topBannerCell() case Sections.searchField.rawValue: cell = searchFieldCell() case Sections.suggestions.rawValue: fallthrough default: if noSuggestions == true { cell = noResultsCell() } else { let suggestion: FullyQuotedDomainSuggestion if searchSuggestions.count > 0 { suggestion = searchSuggestions[indexPath.row] } else { suggestion = siteTitleSuggestions[indexPath.row] } cell = suggestionCell(suggestion) } } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == Sections.suggestions.rawValue && noSuggestions == true { // Calculate the height of the no results cell from the bottom of // the search field to the screen bottom, minus some padding. let searchFieldRect = tableView.rect(forSection: Sections.searchField.rawValue) let searchFieldBottom = searchFieldRect.origin.y + searchFieldRect.height let screenBottom = UIScreen.main.bounds.height return screenBottom - searchFieldBottom - ViewPadding.noResultsView.rawValue } return super.tableView(tableView, heightForRowAt: indexPath) } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == Sections.suggestions.rawValue { let footer = UIView() footer.backgroundColor = .neutral(.shade10) return footer } return nil } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == Sections.suggestions.rawValue { return 0.5 } return 0 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == Sections.searchField.rawValue { let header = UIView() header.backgroundColor = tableView.backgroundColor return header } return nil } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == Sections.searchField.rawValue { return 10 } return 0 } // MARK: table view cells private func topBannerCell() -> UITableViewCell { let cell = UITableViewCell() guard let textLabel = cell.textLabel else { return cell } textLabel.font = UIFont.preferredFont(forTextStyle: .body) textLabel.numberOfLines = 3 textLabel.lineBreakMode = .byTruncatingTail textLabel.adjustsFontForContentSizeCategory = true textLabel.adjustsFontSizeToFitWidth = true textLabel.minimumScaleFactor = 0.5 let template = NSLocalizedString("Domains purchased on this site will redirect to %@", comment: "Description for the first domain purchased with a free plan.") let formatted = String(format: template, freeSiteAddress) let attributed = NSMutableAttributedString(string: formatted, attributes: [:]) if let range = formatted.range(of: freeSiteAddress) { attributed.addAttributes([.font: textLabel.font.bold()], range: NSRange(range, in: formatted)) } textLabel.attributedText = attributed return cell } private var shouldShowTopBanner: Bool { if let domainType = domainType, domainType == .siteRedirect { return true } return false } private func searchFieldCell() -> SearchTableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: SearchTableViewCell.reuseIdentifier) as? SearchTableViewCell else { fatalError() } cell.allowSpaces = false cell.liveSearch = true cell.placeholder = searchFieldPlaceholder cell.reloadTextfieldStyle() cell.delegate = self cell.selectionStyle = .none cell.backgroundColor = .clear return cell } private func noResultsCell() -> UITableViewCell { let cell = UITableViewCell() addNoResultsTo(cell: cell) cell.isUserInteractionEnabled = false return cell } // MARK: - Suggestion Cell private func suggestionCell(_ suggestion: FullyQuotedDomainSuggestion) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: Self.suggestionCellIdentifier) cell.textLabel?.attributedText = attributedDomain(suggestion.domainName) cell.textLabel?.textColor = parentDomainColor cell.indentationWidth = 20.0 cell.indentationLevel = 1 if Feature.enabled(.domains) { cell.detailTextLabel?.attributedText = attributedCostInformation(for: suggestion) } return cell } private func attributedDomain(_ domain: String) -> NSAttributedString { let attributedDomain = NSMutableAttributedString(string: domain, attributes: [.font: domainBaseFont]) guard let dotPosition = domain.firstIndex(of: ".") else { return attributedDomain } let tldRange = dotPosition ..< domain.endIndex let nsRange = NSRange(tldRange, in: domain) attributedDomain.addAttribute(.font, value: domainTLDFont, range: nsRange) return attributedDomain } private func attributedCostInformation(for suggestion: FullyQuotedDomainSuggestion) -> NSAttributedString { let attributedString = NSMutableAttributedString() let hasDomainCredit = blog?.hasDomainCredit ?? false if hasDomainCredit { attributedString.append(attributedFreeForTheFirstYear()) } else if let saleCost = attributedSaleCost(for: suggestion) { attributedString.append(saleCost) } attributedString.append(attributedSuggestionCost(for: suggestion, hasDomainCredit: hasDomainCredit)) attributedString.append(attributedPerYearPostfix(for: suggestion, hasDomainCredit: hasDomainCredit)) return attributedString } // MARK: - Attributed partial strings private func attributedFreeForTheFirstYear() -> NSAttributedString { NSAttributedString( string: NSLocalizedString("Free for the first year ", comment: "Label shown for domains that will be free for the first year due to the user having a premium plan with available domain credit."), attributes: [.font: freeForFirstYearFont, .foregroundColor: UIColor.muriel(name: .green, .shade50)]) } private func attributedSaleCost(for suggestion: FullyQuotedDomainSuggestion) -> NSAttributedString? { guard let saleCostString = suggestion.saleCostString else { return nil } return NSAttributedString( string: saleCostString + " ", attributes: suggestionSaleCostAttributes()) } private func attributedSuggestionCost(for suggestion: FullyQuotedDomainSuggestion, hasDomainCredit: Bool) -> NSAttributedString { NSAttributedString( string: suggestion.costString, attributes: suggestionCostAttributes(striked: mustStrikeRegularPrice(suggestion, hasDomainCredit: hasDomainCredit))) } private func attributedPerYearPostfix(for suggestion: FullyQuotedDomainSuggestion, hasDomainCredit: Bool) -> NSAttributedString { NSAttributedString( string: NSLocalizedString(" / year", comment: "Per-year postfix shown after a domain's cost."), attributes: perYearPostfixAttributes(striked: mustStrikeRegularPrice(suggestion, hasDomainCredit: hasDomainCredit))) } // MARK: - Attributed partial string attributes private func mustStrikeRegularPrice(_ suggestion: FullyQuotedDomainSuggestion, hasDomainCredit: Bool) -> Bool { suggestion.saleCostString != nil || hasDomainCredit } private func suggestionSaleCostAttributes() -> [NSAttributedString.Key: Any] { [.font: suggestionCostFont, .foregroundColor: UIColor.muriel(name: .orange, .shade50)] } private func suggestionCostAttributes(striked: Bool) -> [NSAttributedString.Key: Any] { [.font: suggestionCostFont, .foregroundColor: striked ? UIColor.secondaryLabel : UIColor.label, .strikethroughStyle: striked ? 1 : 0] } private func perYearPostfixAttributes(striked: Bool) -> [NSAttributedString.Key: Any] { [.font: perYearPostfixFont, .foregroundColor: UIColor.secondaryLabel, .strikethroughStyle: striked ? 1 : 0] } } // MARK: - NoResultsViewController Extension private extension DomainSuggestionsTableViewController { func addNoResultsTo(cell: UITableViewCell) { if noResultsViewController == nil { instantiateNoResultsViewController() } guard let noResultsViewController = noResultsViewController else { return } noResultsViewController.view.frame = cell.frame cell.contentView.addSubview(noResultsViewController.view) addChild(noResultsViewController) noResultsViewController.didMove(toParent: self) } func removeNoResultsFromView() { noSuggestions = false tableView.reloadSections(IndexSet(integer: Sections.suggestions.rawValue), with: .automatic) noResultsViewController?.removeFromView() } func instantiateNoResultsViewController() { let title = NSLocalizedString("We couldn't find any available address with the words you entered - let's try again.", comment: "Primary message shown when there are no domains that match the user entered text.") let subtitle = NSLocalizedString("Enter different words above and we'll look for an address that matches it.", comment: "Secondary message shown when there are no domains that match the user entered text.") noResultsViewController = NoResultsViewController.controllerWith(title: title, buttonTitle: nil, subtitle: subtitle) } } // MARK: - UITableViewDelegate extension DomainSuggestionsTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedDomain: FullyQuotedDomainSuggestion switch indexPath.section { case Sections.suggestions.rawValue: if searchSuggestions.count > 0 { selectedDomain = searchSuggestions[indexPath.row] } else { selectedDomain = siteTitleSuggestions[indexPath.row] } default: return } delegate?.domainSelected(selectedDomain) tableView.deselectSelectedRowWithAnimation(true) // Uncheck the previously selected cell. if let selectedCell = selectedCell { selectedCell.accessoryType = .none } // Check the currently selected cell. if let cell = self.tableView.cellForRow(at: indexPath) { cell.accessoryType = .checkmark selectedCell = cell } } } // MARK: - SearchTableViewCellDelegate extension DomainSuggestionsTableViewController: SearchTableViewCellDelegate { func startSearch(for searchTerm: String) { searchDebouncer.call { [weak self] in self?.search(for: searchTerm) } } private func search(for searchTerm: String) { removeNoResultsFromView() delegate?.newSearchStarted() guard searchTerm.count > 0 else { searchSuggestions = [] return } suggestDomains(for: searchTerm) { [weak self] (suggestions) in self?.searchSuggestions = suggestions } } } extension SearchTableViewCell { fileprivate func reloadTextfieldStyle() { textField.textColor = .text textField.leftViewImage = UIImage(named: "icon-post-search") } }
gpl-2.0
1f5af6599046152f0f0d2ca3da55c16f
35.752244
219
0.672805
5.571856
false
false
false
false
acalvomartinez/RandomUser
RandomUserTests/UserDetailViewControllerTest.swift
1
2385
// // UserDetailViewControllerTest.swift // RandomUser // // Created by Toni on 03/07/2017. // Copyright © 2017 Random User Inc. All rights reserved. // import Foundation import KIF import Nimble import UIKit @testable import RandomUser class UserDetailViewControllerTest: AcceptanceTestCase { var usersRichModel = MockUsersRichModel() func testShowsUsernameAsTitle() { let user = givenAUser() openUserDetailViewController(user.username) tester().waitForView(withAccessibilityLabel: user.username) } func testShowsUserInfo() { let user = givenAUser() openUserDetailViewController(user.username) assertUserExpectedValues(user) } fileprivate func assertUserExpectedValues(_ user: User) { tester().waitForView(withAccessibilityLabel: "Name: \(user.displayName)") tester().waitForView(withAccessibilityLabel: "Gender: \(user.gender.rawValue)") tester().waitForView(withAccessibilityLabel: "Street: \(user.location.street)") tester().waitForView(withAccessibilityLabel: "City: \(user.location.city)") tester().waitForView(withAccessibilityLabel: "State: \(user.location.state)") tester().waitForView(withAccessibilityLabel: "Email: \(user.email)") tester().waitForView(withAccessibilityLabel: "Phone: \(user.phone)") tester().waitForView(withAccessibilityLabel: "Registered: \(user.registeredAt.toString())") } fileprivate func givenAUser() -> User { let fakeUser = FakeUserMother.aUserWithIndex(1) usersRichModel.users = [fakeUser] return fakeUser } fileprivate func openUserDetailViewController(_ username: String) { let serviceLocator = ServiceLocator() serviceLocator.usersRichModel = usersRichModel let userDetailViewController = serviceLocator.provideUserDetailViewController(username) as! UserDetailViewController userDetailViewController.presenter = UserDetailPresenter(username: username, ui: userDetailViewController, getUserDetail: GetUserDetail(richModel: usersRichModel)) let rootViewController = UINavigationController() rootViewController.viewControllers = [userDetailViewController] present(viewController: rootViewController) tester().waitForAnimationsToFinish() } }
apache-2.0
71220d92f1b8491edd02bb786c0ab23e
34.58209
120
0.712248
5.286031
false
true
false
false
shaymanjohn/speccyMac
speccyMac/Machine.swift
1
1470
// // Machine.swift // speccyMac // // Created by John Ward on 20/08/2017. // Copyright © 2017 John Ward. All rights reserved. // import Foundation import Cocoa protocol Machine : AnyObject { func start() func tick() func loadGame(_ game: String) func input(_ high: UInt8, low: UInt8) -> UInt8 func output(_ port: UInt8, byte: UInt8) func reportProblem(_ error: Error) var processor: Processor { get } var memory: Memory { get } var ula: UInt32 { get set } var videoRow: UInt16 { get set } var ticksPerFrame: Int { get } var games: [Game] { get } var clicks: UInt8 { get } var emulatorScreen: NSImageView? { get set } var emulatorView: EmulatorInputView? { get set } var lateLabel: NSTextField? { get set } } extension Machine { func start() { processor.machine = self DispatchQueue.global().async { self.processor.start() } } func reportProblem(_ error: Error) { let err = error as NSError if let instruction = err.userInfo["instruction"] as? String, let opcode = err.userInfo["opcode"] as? String { let alert = NSAlert() alert.messageText = "Unemulated Instruction:\n\n\(instruction)\nInstruction number: \(opcode)\nSection: \(err.domain)" alert.runModal() } } }
gpl-3.0
0269554ad97d07657e9742df4cb94656
23.081967
130
0.567052
4.161473
false
false
false
false
apple/swift-experimental-string-processing
Sources/VariadicsGenerator/VariadicsGenerator.swift
1
24154
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// // swift run VariadicsGenerator --max-arity 10 > Sources/RegexBuilder/Variadics.swift import ArgumentParser #if os(macOS) import Darwin #elseif os(Linux) import Glibc #elseif os(Windows) import CRT #endif // (T), (T) // (T), (T, T) // … // (T), (T, T, T, T, T, T, T) // (T, T), (T) // (T, T), (T, T) // … // (T, T), (T, T, T, T, T, T) // … struct Permutations: Sequence { let totalArity: Int struct Iterator: IteratorProtocol { let totalArity: Int var leftArity: Int = 0 var rightArity: Int = 0 mutating func next() -> (combinedArity: Int, nextArity: Int)? { guard leftArity < totalArity else { return nil } defer { if leftArity + rightArity >= totalArity { leftArity += 1 rightArity = 0 } else { rightArity += 1 } } return (leftArity, rightArity) } } public func makeIterator() -> Iterator { Iterator(totalArity: totalArity) } } func captureTypeList( _ arity: Int, lowerBound: Int = 0, optional: Bool = false ) -> String { let opt = optional ? "?" : "" return (lowerBound..<arity).map { "C\($0+1)\(opt)" }.joined(separator: ", ") } func output(_ content: String) { print(content, terminator: "") } func outputForEach<C: Collection>( _ elements: C, separator: String? = nil, lineTerminator: String? = nil, _ content: (C.Element) -> String ) { for i in elements.indices { output(content(elements[i])) let needsSep = elements.index(after: i) != elements.endIndex if needsSep, let sep = separator { output(sep) } if let lt = lineTerminator { let indent = needsSep ? " " : " " output("\(lt)\n\(indent)") } } } struct StandardErrorStream: TextOutputStream { func write(_ string: String) { fputs(string, stderr) } } var standardError = StandardErrorStream() typealias Counter = Int64 let regexComponentProtocolName = "RegexComponent" let outputAssociatedTypeName = "RegexOutput" let patternProtocolRequirementName = "regex" let regexTypeName = "Regex" let baseMatchTypeName = "Substring" let concatBuilderName = "RegexComponentBuilder" let altBuilderName = "AlternationBuilder" let defaultAvailableAttr = "@available(SwiftStdlib 5.7, *)" @main struct VariadicsGenerator: ParsableCommand { @Option(help: "The maximum arity of declarations to generate.") var maxArity: Int = 10 @Flag(help: "Suppress status messages while generating.") var silent: Bool = false func log(_ message: String, terminator: String = "\n") { if !silent { print(message, terminator: terminator, to: &standardError) } } func run() throws { precondition(maxArity > 1) precondition(maxArity < Counter.bitWidth) output(""" //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// // BEGIN AUTO-GENERATED CONTENT @_spi(RegexBuilder) import _StringProcessing """) log("Generating concatenation overloads...") for (leftArity, rightArity) in Permutations(totalArity: maxArity) { guard rightArity != 0 else { continue } log(" Left arity: \(leftArity) Right arity: \(rightArity)") emitConcatenation(leftArity: leftArity, rightArity: rightArity) } for arity in 0...maxArity { emitConcatenationWithEmpty(leftArity: arity) } output("\n\n") log("Generating quantifiers...") for arity in 0...maxArity { log(" Arity \(arity): ", terminator: "") for kind in QuantifierKind.allCases { log("\(kind.rawValue) ", terminator: "") emitQuantifier(kind: kind, arity: arity) } log("repeating ", terminator: "") emitRepeating(arity: arity) log("") } log("Generating atomic groups...") for arity in 0...maxArity { log(" Arity \(arity): ", terminator: "") emitAtomicGroup(arity: arity) log("") } log("Generating alternation overloads...") for (leftArity, rightArity) in Permutations(totalArity: maxArity) { log(" Left arity: \(leftArity) Right arity: \(rightArity)") emitAlternation(leftArity: leftArity, rightArity: rightArity) } log("Generating 'AlternationBuilder.buildBlock(_:)' overloads...") for arity in 1...maxArity { log(" Capture arity: \(arity)") emitUnaryAlternationBuildBlock(arity: arity) } log("Generating 'capture' and 'tryCapture' overloads...") for arity in 0...maxArity { log(" Capture arity: \(arity)") emitCapture(arity: arity) } output("\n\n") output("// END AUTO-GENERATED CONTENT\n") log("Done!") } func tupleType(arity: Int, genericParameters: () -> String) -> String { assert(arity >= 0) if arity == 0 { return genericParameters() } return "(\(genericParameters()))" } func emitConcatenation(leftArity: Int, rightArity: Int) { let genericParams: String = { var result = "W0, W1, " result += captureTypeList(leftArity+rightArity) result += ", R0: \(regexComponentProtocolName), R1: \(regexComponentProtocolName)" return result }() // Emit concatenation type declaration. let whereClause: String = { var result = " where R0.\(outputAssociatedTypeName) == " if leftArity == 0 { result += "W0" } else { result += "(W0, " result += captureTypeList(leftArity) result += ")" } result += ", R1.\(outputAssociatedTypeName) == " if rightArity == 0 { result += "W1" } else { result += "(W1, " result += captureTypeList(leftArity+rightArity, lowerBound: leftArity) result += ")" } return result }() let matchType: String = { if leftArity+rightArity == 0 { return baseMatchTypeName } else { return "(\(baseMatchTypeName), " + captureTypeList(leftArity+rightArity) + ")" } }() // Emit concatenation builder. output(""" \(defaultAvailableAttr) extension \(concatBuilderName) { @_alwaysEmitIntoClient public static func buildPartialBlock<\(genericParams)>( accumulated: R0, next: R1 ) -> \(regexTypeName)<\(matchType)> \(whereClause) { let factory = makeFactory() return factory.accumulate(accumulated, next) } } """) } func emitConcatenationWithEmpty(leftArity: Int) { // T + () = T output(""" \(defaultAvailableAttr) extension \(concatBuilderName) { \(defaultAvailableAttr) @_alwaysEmitIntoClient public static func buildPartialBlock<W0 """) outputForEach(0..<leftArity) { ", C\($0)" } output(""" , R0: \(regexComponentProtocolName), R1: \(regexComponentProtocolName)>( accumulated: R0, next: R1 ) -> \(regexTypeName)< """) if leftArity == 0 { output(baseMatchTypeName) } else { output("(\(baseMatchTypeName)") outputForEach(0..<leftArity) { ", C\($0)" } output(")") } output("> where R0.\(outputAssociatedTypeName) == ") if leftArity == 0 { output("W0") } else { output("(W0") outputForEach(0..<leftArity) { ", C\($0)" } output(")") } output(""" { let factory = makeFactory() return factory.accumulate(accumulated, next) } } """) } enum QuantifierKind: String, CaseIterable { case zeroOrOne = "Optionally" case zeroOrMore = "ZeroOrMore" case oneOrMore = "OneOrMore" var operatorName: String { switch self { case .zeroOrOne: return ".?" case .zeroOrMore: return ".*" case .oneOrMore: return ".+" } } var astQuantifierAmount: String { switch self { case .zeroOrOne: return "zeroOrOne" case .zeroOrMore: return "zeroOrMore" case .oneOrMore: return "oneOrMore" } } } struct QuantifierParameters { var disfavored: String var genericParams: String var whereClauseForInit: String var whereClause: String var quantifiedCaptures: String var matchType: String var repeatingWhereClause: String { whereClauseForInit.isEmpty ? "where R.Bound == Int" : whereClauseForInit + ", R.Bound == Int" } init(kind: QuantifierKind, arity: Int) { self.disfavored = arity == 0 ? " @_disfavoredOverload\n" : "" self.genericParams = { var result = "" if arity > 0 { result += "W, " result += captureTypeList(arity) result += ", " } result += "Component: \(regexComponentProtocolName)" return result }() let capturesJoined = captureTypeList(arity) self.quantifiedCaptures = { switch kind { case .zeroOrOne, .zeroOrMore: return captureTypeList(arity, optional: true) case .oneOrMore: return capturesJoined } }() self.matchType = arity == 0 ? baseMatchTypeName : "(\(baseMatchTypeName), \(quantifiedCaptures))" self.whereClauseForInit = "where \(outputAssociatedTypeName) == \(matchType)" + (arity == 0 ? "" : ", Component.\(outputAssociatedTypeName) == (W, \(capturesJoined))") self.whereClause = arity == 0 ? "" : "where Component.\(outputAssociatedTypeName) == (W, \(capturesJoined))" } } func emitQuantifier(kind: QuantifierKind, arity: Int) { assert(arity >= 0) let params = QuantifierParameters(kind: kind, arity: arity) output(""" \(defaultAvailableAttr) extension \(kind.rawValue) { \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams)>( _ component: Component, _ behavior: RegexRepetitionBehavior? = nil ) \(params.whereClauseForInit) { let factory = makeFactory() self.init(factory.\(kind.astQuantifierAmount)(component, behavior)) } } \(defaultAvailableAttr) extension \(kind.rawValue) { \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams)>( _ behavior: RegexRepetitionBehavior? = nil, @\(concatBuilderName) _ componentBuilder: () -> Component ) \(params.whereClauseForInit) { let factory = makeFactory() self.init(factory.\(kind.astQuantifierAmount)(componentBuilder(), behavior)) } } \(kind == .zeroOrOne ? """ \(defaultAvailableAttr) extension \(concatBuilderName) { @_alwaysEmitIntoClient public static func buildLimitedAvailability<\(params.genericParams)>( _ component: Component ) -> \(regexTypeName)<\(params.matchType)> \(params.whereClause) { let factory = makeFactory() return factory.\(kind.astQuantifierAmount)(component, nil) } } """ : "") """) } func emitAtomicGroup(arity: Int) { assert(arity >= 0) let groupName = "Local" func node(builder: Bool) -> String { """ component\(builder ? "Builder()" : "") """ } let disfavored = arity == 0 ? " @_disfavoredOverload\n" : "" let genericParams: String = { var result = "" if arity > 0 { result += "W, " result += captureTypeList(arity) result += ", " } result += "Component: \(regexComponentProtocolName)" return result }() let capturesJoined = captureTypeList(arity) let matchType = arity == 0 ? baseMatchTypeName : "(\(baseMatchTypeName), \(capturesJoined))" let whereClauseForInit = "where \(outputAssociatedTypeName) == \(matchType)" + (arity == 0 ? "" : ", Component.\(outputAssociatedTypeName) == (W, \(capturesJoined))") output(""" \(defaultAvailableAttr) extension \(groupName) { \(defaultAvailableAttr) \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( _ component: Component ) \(whereClauseForInit) { let factory = makeFactory() self.init(factory.atomicNonCapturing(\(node(builder: false)))) } } \(defaultAvailableAttr) extension \(groupName) { \(defaultAvailableAttr) \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( @\(concatBuilderName) _ componentBuilder: () -> Component ) \(whereClauseForInit) { let factory = makeFactory() self.init(factory.atomicNonCapturing(\(node(builder: true)))) } } """) } func emitRepeating(arity: Int) { assert(arity >= 0) // `repeat(..<5)` has the same generic semantics as zeroOrMore let params = QuantifierParameters(kind: .zeroOrMore, arity: arity) // TODO: Could `repeat(count:)` have the same generic semantics as oneOrMore? // We would need to prohibit `repeat(count: 0)`; can only happen at runtime output(""" \(defaultAvailableAttr) extension Repeat { \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams)>( _ component: Component, count: Int ) \(params.whereClauseForInit) { precondition(count >= 0, "Must specify a positive count") let factory = makeFactory() self.init(factory.exactly(count, component)) } \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams)>( count: Int, @\(concatBuilderName) _ componentBuilder: () -> Component ) \(params.whereClauseForInit) { precondition(count >= 0, "Must specify a positive count") let factory = makeFactory() self.init(factory.exactly(count, componentBuilder())) } \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams), R: RangeExpression>( _ component: Component, _ expression: R, _ behavior: RegexRepetitionBehavior? = nil ) \(params.repeatingWhereClause) { let factory = makeFactory() self.init(factory.repeating(expression.relative(to: 0..<Int.max), behavior, component)) } \(params.disfavored)\ @_alwaysEmitIntoClient public init<\(params.genericParams), R: RangeExpression>( _ expression: R, _ behavior: RegexRepetitionBehavior? = nil, @\(concatBuilderName) _ componentBuilder: () -> Component ) \(params.repeatingWhereClause) { let factory = makeFactory() self.init(factory.repeating(expression.relative(to: 0..<Int.max), behavior, componentBuilder())) } } """) } func emitAlternation(leftArity: Int, rightArity: Int) { let leftGenParams: String = { if leftArity == 0 { return "R0" } return "R0, W0, " + (0..<leftArity).map { "C\($0)" }.joined(separator: ", ") }() let rightGenParams: String = { if rightArity == 0 { return "R1" } return "R1, W1, " + (leftArity..<leftArity+rightArity).map { "C\($0)" }.joined(separator: ", ") }() let genericParams = leftGenParams + ", " + rightGenParams let whereClause: String = { var result = "where R0: \(regexComponentProtocolName), R1: \(regexComponentProtocolName)" if leftArity > 0 { result += ", R0.\(outputAssociatedTypeName) == (W0, \((0..<leftArity).map { "C\($0)" }.joined(separator: ", ")))" } if rightArity > 0 { result += ", R1.\(outputAssociatedTypeName) == (W1, \((leftArity..<leftArity+rightArity).map { "C\($0)" }.joined(separator: ", ")))" } return result }() let resultCaptures: String = { var result = (0..<leftArity).map { "C\($0)" }.joined(separator: ", ") if leftArity > 0, rightArity > 0 { result += ", " } result += (leftArity..<leftArity+rightArity).map { "C\($0)?" }.joined(separator: ", ") return result }() let matchType: String = { if leftArity == 0, rightArity == 0 { return baseMatchTypeName } return "(\(baseMatchTypeName), \(resultCaptures))" }() output(""" \(defaultAvailableAttr) extension \(altBuilderName) { @_alwaysEmitIntoClient public static func buildPartialBlock<\(genericParams)>( accumulated: R0, next: R1 ) -> ChoiceOf<\(matchType)> \(whereClause) { let factory = makeFactory() return .init(factory.accumulateAlternation(accumulated, next)) } } """) } func emitUnaryAlternationBuildBlock(arity: Int) { assert(arity > 0) let captures = captureTypeList(arity) let genericParams: String = { if arity == 0 { return "R" } return "R, W, " + captures }() let whereClause: String = """ where R: \(regexComponentProtocolName), \ R.\(outputAssociatedTypeName) == (W, \(captures)) """ let resultCaptures = captureTypeList(arity, optional: true) output(""" \(defaultAvailableAttr) extension \(altBuilderName) { @_alwaysEmitIntoClient public static func buildPartialBlock<\(genericParams)>(first regex: R) -> ChoiceOf<(W, \(resultCaptures))> \(whereClause) { let factory = makeFactory() return .init(factory.orderedChoice(regex)) } } """) } func emitCapture(arity: Int) { let disfavored = arity == 0 ? " @_disfavoredOverload\n" : "" let genericParams = arity == 0 ? "R: \(regexComponentProtocolName), W" : "R: \(regexComponentProtocolName), W, " + captureTypeList(arity) let matchType = arity == 0 ? "W" : "(W, " + captureTypeList(arity) + ")" func newMatchType(newCaptureType: String) -> String { return arity == 0 ? "(\(baseMatchTypeName), \(newCaptureType))" : "(\(baseMatchTypeName), \(newCaptureType), " + captureTypeList(arity) + ")" } let rawNewMatchType = newMatchType(newCaptureType: "W") let transformedNewMatchType = newMatchType(newCaptureType: "NewCapture") let whereClauseRaw = "where \(outputAssociatedTypeName) == \(rawNewMatchType), R.\(outputAssociatedTypeName) == \(matchType)" let whereClauseTransformed = "where \(outputAssociatedTypeName) == \(transformedNewMatchType), R.\(outputAssociatedTypeName) == \(matchType)" output(""" // MARK: - Non-builder capture arity \(arity) \(defaultAvailableAttr) extension Capture { \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( _ component: R ) \(whereClauseRaw) { let factory = makeFactory() self.init(factory.capture(component)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( _ component: R, as reference: Reference<W> ) \(whereClauseRaw) { let factory = makeFactory() self.init(factory.capture(component, reference._raw)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( _ component: R, transform: @escaping (W) throws -> NewCapture ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.capture(component, nil, transform)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( _ component: R, as reference: Reference<NewCapture>, transform: @escaping (W) throws -> NewCapture ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.capture(component, reference._raw, transform)) } } \(defaultAvailableAttr) extension TryCapture { \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( _ component: R, transform: @escaping (W) throws -> NewCapture? ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.captureOptional(component, nil, transform)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( _ component: R, as reference: Reference<NewCapture>, transform: @escaping (W) throws -> NewCapture? ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.captureOptional(component, reference._raw, transform)) } } // MARK: - Builder capture arity \(arity) \(defaultAvailableAttr) extension Capture { \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( @\(concatBuilderName) _ componentBuilder: () -> R ) \(whereClauseRaw) { let factory = makeFactory() self.init(factory.capture(componentBuilder())) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams)>( as reference: Reference<W>, @\(concatBuilderName) _ componentBuilder: () -> R ) \(whereClauseRaw) { let factory = makeFactory() self.init(factory.capture(componentBuilder(), reference._raw)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( @\(concatBuilderName) _ componentBuilder: () -> R, transform: @escaping (W) throws -> NewCapture ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.capture(componentBuilder(), nil, transform)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( as reference: Reference<NewCapture>, @\(concatBuilderName) _ componentBuilder: () -> R, transform: @escaping (W) throws -> NewCapture ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.capture(componentBuilder(), reference._raw, transform)) } } \(defaultAvailableAttr) extension TryCapture { \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( @\(concatBuilderName) _ componentBuilder: () -> R, transform: @escaping (W) throws -> NewCapture? ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.captureOptional(componentBuilder(), nil, transform)) } \(disfavored)\ @_alwaysEmitIntoClient public init<\(genericParams), NewCapture>( as reference: Reference<NewCapture>, @\(concatBuilderName) _ componentBuilder: () -> R, transform: @escaping (W) throws -> NewCapture? ) \(whereClauseTransformed) { let factory = makeFactory() self.init(factory.captureOptional(componentBuilder(), reference._raw, transform)) } } """) } }
apache-2.0
b14e8ab5456914e7775a72046868187f
29.64467
145
0.581912
4.37781
false
false
false
false
stephentyrone/swift
test/Driver/PrivateDependencies/private-fine.swift
5
4975
// a ==> b --> c ==> d | e ==> c // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/private-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // CHECK-INITIAL-NOT: warning // CHECK-INITIAL: Handled a.swift // CHECK-INITIAL: Handled b.swift // CHECK-INITIAL: Handled c.swift // CHECK-INITIAL: Handled d.swift // CHECK-INITIAL: Handled e.swift // RUN: touch -t 201401240006 %t/a.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/a.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=CHECK-A-NEG %s < %t/a.txt // CHECK-A: Handled a.swift // CHECK-A-DAG: Handled b.swift // CHECK-A-DAG: Handled c.swift // CHECK-A-NEG-NOT: Handled d.swift // CHECK-A-NEG-NOT: Handled e.swift // RUN: touch -t 201401240006 %t/b.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/b.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-B %s < %t/b.txt // RUN: %FileCheck -check-prefix=CHECK-B-NEG %s < %t/b.txt // CHECK-B-NEG-NOT: Handled a.swift // CHECK-B: Handled b.swift // CHECK-B: Handled c.swift // CHECK-B-NEG-NOT: Handled d.swift // CHECK-B-NEG-NOT: Handled e.swift // RUN: touch -t 201401240006 %t/c.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/c.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-C %s < %t/c.txt // RUN: %FileCheck -check-prefix=CHECK-C-NEG %s < %t/c.txt // CHECK-C-NEG-NOT: Handled a.swift // CHECK-C-NEG-NOT: Handled b.swift // CHECK-C: Handled c.swift // CHECK-C: Handled d.swift // CHECK-C-NEG-NOT: Handled e.swift // RUN: touch -t 201401240006 %t/d.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/d.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-D %s < %t/d.txt // RUN: %FileCheck -check-prefix=CHECK-D-NEG %s < %t/d.txt // CHECK-D-NEG-NOT: Handled a.swift // CHECK-D-NEG-NOT: Handled b.swift // CHECK-D-NEG-NOT: Handled c.swift // CHECK-D: Handled d.swift // CHECK-D-NEG-NOT: Handled e.swift // RUN: touch -t 201401240006 %t/e.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/e.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-E %s < %t/e.txt // RUN: %FileCheck -check-prefix=CHECK-E-NEG %s < %t/e.txt // CHECK-E-NEG-NOT: Handled a.swift // CHECK-E-NEG-NOT: Handled b.swift // CHECK-E: Handled c.swift // CHECK-E-NEG-NOT: Handled a.swift // CHECK-E-NEG-NOT: Handled b.swift // CHECK-E: Handled d.swift // CHECK-E-NEG-NOT: Handled a.swift // CHECK-E-NEG-NOT: Handled b.swift // CHECK-E: Handled e.swift // CHECK-E-NEG-NOT: Handled a.swift // CHECK-E-NEG-NOT: Handled b.swift // RUN: touch -t 201401240007 %t/a.swift %t/e.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/ae.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-AE %s < %t/ae.txt // RUN: %FileCheck -check-prefix=CHECK-AE-NEG %s < %t/ae.txt // CHECK-AE: Handled a.swift // CHECK-AE: Handled b.swift // CHECK-AE: Handled c.swift // CHECK-AE: Handled d.swift // CHECK-AE: Handled e.swift // CHECK-AE-NEG: Handled
apache-2.0
3b6ba562340909668844d5484e7b05f7
56.183908
380
0.696884
2.834758
false
false
true
false
joalbright/Gameboard
Games/BoardController/BoardViews/GoBoardView.swift
1
1898
// // GoBoardView.swift // Games // // Created by Jo Albright on 4/25/18. // Copyright © 2018 Jo Albright. All rights reserved. // import UIKit @IBDesignable class GoBoardView : BoardView { var passes: Int = 0 override func prepareForInterfaceBuilder() { board = Gameboard(.go) super.prepareForInterfaceBuilder() } override func awakeFromNib() { board = Gameboard(.go) super.awakeFromNib() } @IBAction func pass() { passes += 1 board.changePlayer() checkDone() } override func selectSquare(_ square: Square) { do { try board.move(toSquare: square) } catch { print(error) } updateBoard() checkDone() } override func coordinate(_ touch: UITouch) -> Square { let p = 30 let w = (frame.width - p * 2) / (board.gridSize - 1) let h = (frame.height - p * 2) / (board.gridSize - 1) let loc = touch.location(in: self) let c = Int((loc.x - (w / 2)) / w) let r = Int((loc.y - (w / 2)) / h) return (r,c) } override func checkDone() { guard board.grid.piecesOnBoard().count == board.totalSpaces || passes == 2 else { return } let pieces1 = board.grid.piecesOnBoard().filter { board.playerPieces[0].contains($0) } let pieces2 = board.grid.piecesOnBoard().filter { board.playerPieces[1].contains($0) } if pieces1.count == pieces2.count { board?.showAlert?("Game Over", "Stalemate") } else { board?.showAlert?("Game Over", "Player \(pieces1.count > pieces2.count ? 1 : 2) Wins") } passes = 0 } }
apache-2.0
a5e6b2ac0fdca3a679869e4178395351
20.077778
98
0.499736
4.272523
false
false
false
false
alfonsomiranda/Popular500px-demo
Popular500px/Common/Entity/User.swift
1
727
// // User.swift // Popular500px // // Created by Alfonso Miranda Castro on 14/11/15. // Copyright © 2015 Alfonso Miranda Castro. All rights reserved. // import Foundation import CoreData @objc(User) class User: NSManagedObject { func parseUserModel(userModel:UserModel, picture:Picture) { self.user_id = userModel.user_id self.city = userModel.city self.country = userModel.country self.cover_url = userModel.cover_url self.firstname = userModel.firstname self.fullname = userModel.fullname self.lastname = userModel.lastname self.username = userModel.username self.userpic_url = userModel.userpic_url self.picture = picture } }
mit
ec6d1dd1e1eb8c60559d8f2bdd783caf
24.928571
65
0.676309
3.989011
false
false
false
false
banxi1988/BXProgressHUD
Pod/Classes/BXProgressHUD+Builder.swift
2
3136
// // BXProgressHUD+Builder.swift // Pods // // Created by Haizhen Lee on 15/11/7. // // import Foundation public extension BXProgressHUD{ public class Builder { let hud:BXProgressHUD let targetView:UIView public init(forView:UIView){ hud = BXProgressHUD() targetView = forView } public convenience init(){ let window = UIApplication.shared.keyWindow! self.init(forView:window) } open func mode(_ mode:BXProgressHUDMode) -> Self{ hud.mode = mode return self } open func usingTextMode() -> Self{ return mode(.text) } open func animationType(_ type:BXProgressHUDAnimation) -> Self{ hud.animationType = type return self } open func dimBackground(_ dimBackground:Bool) -> Self{ hud.dimBackground = dimBackground return self } open func text(_ text:String) -> Self{ hud.label.text = text return self } open func textColor(_ color:UIColor) -> Self{ hud.label.textColor = color return self } open func detailText(_ text:String) -> Self{ hud.detailsLabel.text = text return self } open func detailColor(_ color:UIColor) -> Self{ hud.detailsLabel.textColor = color return self } open func customView(_ view:UIView) -> Self{ hud.customView = view return self } open func removeFromSuperViewOnHide(_ remove:Bool) -> Self{ hud.removeFromSuperViewOnHide = remove return self } open func margin(_ margin:CGFloat) -> Self{ hud.margin = margin return self } open func cornerRadius(_ radius:CGFloat) -> Self{ hud.cornerRadius = radius return self } open func xOffset(_ offset:CGFloat) -> Self{ hud.xOffset = offset return self } open func yOffset(_ offset:CGFloat) -> Self{ hud.yOffset = offset return self } open func graceTime(_ time:TimeInterval) -> Self{ hud.graceTime = time return self } open func minShowTime(_ time:TimeInterval) -> Self{ hud.minShowTime = time return self } open func show(_ animated:Bool = true) -> BXProgressHUD{ create().show(animated) return hud } open func create() -> BXProgressHUD{ hud.attachTo(targetView) return hud } open func delegate(_ delegate:BXProgressHUDDelegate?) -> Self{ hud.delegate = delegate return self } } }
mit
3d5318fabaf6414a393cee03ad4cfb9c
23.692913
71
0.487245
5.472949
false
false
false
false
andreamazz/AMScrollingNavbar
Source/ScrollingNavbar+Sizes.swift
1
2426
import UIKit import WebKit /** Implements the main functions providing constants values and computed ones */ extension ScrollingNavigationController { // MARK: - View sizing var fullNavbarHeight: CGFloat { return navbarHeight + statusBarHeight } var navbarHeight: CGFloat { return navigationBar.frame.size.height } var statusBarHeight: CGFloat { var statusBarHeight = UIApplication.shared.statusBarFrame.size.height if #available(iOS 11.0, *) { // Account for the notch when the status bar is hidden statusBarHeight = max(UIApplication.shared.statusBarFrame.size.height, UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0) } return max(statusBarHeight - extendedStatusBarDifference, 0) } // Extended status call changes the bounds of the presented view var extendedStatusBarDifference: CGFloat { var appHeight = view.bounds.height var nextView = view while let superView = nextView?.superview { appHeight = superView.bounds.height nextView = superView.superview } return abs(appHeight - (UIApplication.shared.delegate?.window??.frame.size.height ?? UIScreen.main.bounds.height)) } var tabBarOffset: CGFloat { // Only account for the tab bar if a tab bar controller is present and the bar is not translucent if let tabBarController = tabBarController, !(topViewController?.hidesBottomBarWhenPushed ?? false) { return tabBarController.tabBar.isTranslucent ? 0 : tabBarController.tabBar.frame.height } return 0 } func scrollView() -> UIScrollView? { if let wkWebView = self.scrollableView as? WKWebView { return wkWebView.scrollView } else { return scrollableView as? UIScrollView } } var contentOffset: CGPoint { return scrollView()?.contentOffset ?? CGPoint.zero } var contentSize: CGSize { guard let scrollView = scrollView() else { return CGSize.zero } let verticalInset = scrollView.contentInset.top + scrollView.contentInset.bottom return CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + verticalInset) } var navbarFullHeight: CGFloat { return navbarHeight - statusBarHeight + additionalOffset } var followersHeight: CGFloat { return self.followers.filter { $0.direction == .scrollUp }.compactMap { $0.view?.frame.height }.reduce(0, +) } }
mit
b5c75e7ec647d6cdb787d1725c8bfd92
31.346667
141
0.715581
4.90101
false
false
false
false
renxlWin/gege
swiftChuge/swiftChuge/Base/Controller/RxTabBarVC.swift
1
2205
// // RxTabBarVC.swift // swiftChuge // // Created by RXL on 17/3/21. // Copyright © 2017年 RXL. All rights reserved. // import UIKit class RxTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupChildVC(); setTabBar(); } private func setupChildVC(){ let homeVC = RxNearVC(); navController(vc: homeVC, title: "附近", image: "near", selectImg: "near_sel"); let nearVC = RxWishVC(); navController(vc: nearVC, title: "心愿", image: "wish", selectImg: "wish_sel"); let messageVC = RxMessageVC(); navController(vc: messageVC, title: "消息", image: "message", selectImg: "message_sel"); let accountVC = RxAccountVC(); navController(vc: accountVC, title: "我的", image: "account", selectImg: "account_sel"); } private func navController(vc :UIViewController , title : String , image : String, selectImg : String){ vc.title = title; vc.tabBarItem.image = UIImage(named : image)?.withRenderingMode(.alwaysOriginal); vc.tabBarItem.selectedImage = UIImage(named: selectImg)?.withRenderingMode(.alwaysOriginal); let nav = UINavigationController(rootViewController: vc); self.addChildViewController(nav); } private func setTabBar(){ //自定义TabBar let tabBar = RxTabBar(); tabBar.tabBarDelegate = self; self.setValue(tabBar, forKeyPath: "tabBar"); UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal); UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .selected); for vc in viewControllers! { vc.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0); } } } extension RxTabBarVC : RxTabBarDelegate{ func tabBarPlusBtnClick(){ print("点击了加号"); } }
mit
2e0281eef15bc53a07ff2c165ed7e55d
25.790123
122
0.577419
4.988506
false
false
false
false
myhgew/CodePractice
iOS/SwiftAssignment/Assignment4/Twitter/MediaItem.swift
8
1366
// // MediaItem.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // holds the network url and aspectRatio of an image attached to a Tweet // created automatically when a Tweet object is created public struct MediaItem { public let url: NSURL! public let aspectRatio: Double = 0 public var description: String { return (url.absoluteString ?? "no url") + " (aspect ratio = \(aspectRatio))" } // MARK: - Private Implementation init?(data: NSDictionary?) { var valid = false if let urlString = data?.valueForKeyPath(TwitterKey.MediaURL) as? NSString { if let url = NSURL(string: urlString) { self.url = url let h = data?.valueForKeyPath(TwitterKey.Height) as? NSNumber let w = data?.valueForKeyPath(TwitterKey.Width) as? NSNumber if h != nil && w != nil && h?.doubleValue != 0 { aspectRatio = w!.doubleValue / h!.doubleValue valid = true } } } if !valid { return nil } } struct TwitterKey { static let MediaURL = "media_url_https" static let Width = "sizes.small.w" static let Height = "sizes.small.h" } }
mit
7e2e5b8a8b5d0eb6c7ace36ed2ceb71a
28.695652
115
0.576867
4.568562
false
false
false
false
Johennes/firefox-ios
Storage/MockLogins.swift
1
5838
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Deferred public class MockLogins: BrowserLogins, SyncableLogins { private var cache = [Login]() public init(files: FileAccessor) { } public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> { let cursor = ArrayCursor(data: cache.filter({ login in return login.protectionSpace.host == protectionSpace.host }).sort({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed }).map({ login in return login as LoginData })) return Deferred(value: Maybe(success: cursor)) } public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> { let cursor = ArrayCursor(data: cache.filter({ login in return login.protectionSpace.host == protectionSpace.host && login.username == username }).sort({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed }).map({ login in return login as LoginData })) return Deferred(value: Maybe(success: cursor)) } public func getLoginDataForGUID(guid: GUID) -> Deferred<Maybe<Login>> { if let login = (cache.filter { $0.guid == guid }).first { return deferMaybe(login) } else { return deferMaybe(LoginDataError(description: "Login for GUID \(guid) not found")) } } public func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> { let cursor = ArrayCursor(data: cache.sort({ (loginA, loginB) -> Bool in return loginA.hostname > loginB.hostname })) return Deferred(value: Maybe(success: cursor)) } public func searchLoginsWithQuery(query: String?) -> Deferred<Maybe<Cursor<Login>>> { let cursor = ArrayCursor(data: cache.filter({ login in var checks = [Bool]() if let query = query { checks.append(login.username?.contains(query) ?? false) checks.append(login.password.contains(query)) checks.append(login.hostname.contains(query)) } return checks.contains(true) }).sort({ (loginA, loginB) -> Bool in return loginA.hostname > loginB.hostname })) return Deferred(value: Maybe(success: cursor)) } // This method is only here for testing public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> { let res = cache.filter({ login in return login.guid == guid }).sort({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed })[0] as LoginUsageData return Deferred(value: Maybe(success: res)) } public func addLogin(login: LoginData) -> Success { if let _ = cache.indexOf(login as! Login) { return deferMaybe(LoginDataError(description: "Already in the cache")) } cache.append(login as! Login) return succeed() } public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success { // TODO return succeed() } public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> { // TODO return deferMaybe([]) } public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> { // TODO return deferMaybe([]) } public func updateLogin(login: LoginData) -> Success { if let index = cache.indexOf(login as! Login) { cache[index].timePasswordChanged = NSDate.nowMicroseconds() return succeed() } return deferMaybe(LoginDataError(description: "Password wasn't cached yet. Can't update")) } public func addUseOfLoginByGUID(guid: GUID) -> Success { if let login = cache.filter({ $0.guid == guid }).first { login.timeLastUsed = NSDate.nowMicroseconds() return succeed() } return deferMaybe(LoginDataError(description: "Password wasn't cached yet. Can't update")) } public func removeLoginByGUID(guid: GUID) -> Success { let filtered = cache.filter { $0.guid != guid } if filtered.count == cache.count { return deferMaybe(LoginDataError(description: "Can not remove a password that wasn't stored")) } cache = filtered return succeed() } public func removeLoginsWithGUIDs(guids: [GUID]) -> Success { return walk(guids) { guid in self.removeLoginByGUID(guid) } } public func removeAll() -> Success { cache.removeAll(keepCapacity: false) return succeed() } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return deferMaybe(true) } // TODO public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { return succeed() } public func applyChangedLogin(upstream: ServerLogin) -> Success { return succeed() } public func markAsSynchronized<T: CollectionType where T.Generator.Element == GUID>(_: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> { return deferMaybe(0) } public func markAsDeleted<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { return succeed() } public func onRemovedAccount() -> Success { return succeed() } } extension MockLogins: ResettableSyncStorage { public func resetClient() -> Success { return succeed() } }
mpl-2.0
f4d6f0f7e0095dc7102e5db6daa9c606
36.915584
169
0.62864
4.808896
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/TextKit/CommentAttachment.swift
2
1984
import Foundation import UIKit /// Comment Attachments: Represents an HTML Comment /// open class CommentAttachment: NSTextAttachment, RenderableAttachment { /// Internal Cached Image /// fileprivate var glyphImage: UIImage? /// Delegate /// public weak var delegate: RenderableAttachmentDelegate? /// A message to display overlaid on top of the image /// open var text: String = "" { didSet { glyphImage = nil } } // MARK: - Initializers init() { super.init(data: nil, ofType: nil) } public required init?(coder aDecoder: NSCoder) { super.init(data: nil, ofType: nil) guard let text = aDecoder.decodeObject(forKey: Keys.text) as? String else { return } self.text = text } // MARK: - NSCoder Methods open override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(text, forKey: Keys.text) } // MARK: - NSTextAttachmentContainer override open func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? { if let cachedImage = glyphImage, imageBounds.size.equalTo(cachedImage.size) { return cachedImage } glyphImage = delegate?.attachment(self, imageForSize: imageBounds.size) return glyphImage } override open func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect { guard let bounds = delegate?.attachment(self, boundsForLineFragment: lineFrag) else { assertionFailure("Could not determine Comment Attachment Size") return .zero } return bounds } } // MARK: - Private Helpers // private extension CommentAttachment { struct Keys { static let text = "text" } }
mpl-2.0
79927c1a873f56559b7e27e62b8c478b
22.903614
191
0.643649
4.898765
false
false
false
false
practicalswift/swift
benchmark/single-source/ArrayOfGenericRef.swift
10
2420
//===--- ArrayOfGenericRef.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This benchmark tests creation and destruction of an array of enum // and generic type bound to nontrivial types. // // For comparison, we always create three arrays of 1,000 words. import TestsUtils public let ArrayOfGenericRef = BenchmarkInfo( name: "ArrayOfGenericRef", runFunction: run_ArrayOfGenericRef, tags: [.validation, .api, .Array], legacyFactor: 10) protocol Constructible { associatedtype Element init(e:Element) } class ConstructibleArray<T:Constructible> { var array: [T] init(_ e:T.Element) { array = [T]() array.reserveCapacity(1_000) for _ in 0...1_000 { array.append(T(e:e) as T) } } } class GenericRef<T> : Constructible { typealias Element=T var x: T required init(e:T) { self.x = e } } // Reference to a POD class. @inline(never) func genPODRefArray() { blackHole(ConstructibleArray<GenericRef<Int>>(3)) // should be a nop } class Dummy {} // Reference to a reference. The nested reference is shared across elements. @inline(never) func genCommonRefArray() { let d = Dummy() blackHole(ConstructibleArray<GenericRef<Dummy>>(d)) // should be a nop } // Reuse the same enum value for each element. class RefArray<T> { var array: [T] init(_ i:T, count:Int = 1_000) { array = [T](repeating: i, count: count) } } // enum holding a reference. @inline(never) func genRefEnumArray() { let d = Dummy() blackHole(RefArray<Dummy?>(d)) // should be a nop } struct GenericVal<T> : Constructible { typealias Element=T var x: T init(e:T) { self.x = e } } // Struct holding a reference. @inline(never) func genRefStructArray() { let d = Dummy() blackHole(ConstructibleArray<GenericVal<Dummy>>(d)) // should be a nop } @inline(never) public func run_ArrayOfGenericRef(_ N: Int) { for _ in 0..<N { genPODRefArray() genCommonRefArray() genRefEnumArray() genRefStructArray() } }
apache-2.0
21b290071bbcee19e030ba10d9072275
22.269231
80
0.65124
3.617339
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyDomain/Models/DelegatedCustodyTransactionInput.swift
1
1260
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct DelegatedCustodyTransactionInput: Hashable { public let account: Int public let amount: DelegatedCustodyAmount public let currency: String public let destination: String public let fee: DelegatedCustodyFee public let feeCurrency: String public let maxVerificationVersion: Int? public let memo: String public let type: String public init( account: Int, amount: DelegatedCustodyAmount, currency: String, destination: String, fee: DelegatedCustodyFee, feeCurrency: String, maxVerificationVersion: Int?, memo: String, type: String ) { self.account = account self.amount = amount self.currency = currency self.destination = destination self.fee = fee self.feeCurrency = feeCurrency self.maxVerificationVersion = maxVerificationVersion self.memo = memo self.type = type } } public enum DelegatedCustodyFee: Hashable { case low case normal case high case custom(String) } public enum DelegatedCustodyAmount: Hashable { case max case custom(String) }
lgpl-3.0
ff12361227c5455574ff17b25a60c8a4
24.693878
62
0.668785
4.697761
false
false
false
false
travismmorgan/TMPasscodeLock
TMPasscodeLockDemo/PasscodeViewController.swift
1
1844
// // PasscodeViewController.swift // TMPasscodeLock // // Created by Travis Morgan on 1/16/17. // Copyright © 2017 Travis Morgan. All rights reserved. // import UIKit import TMPasscodeLock class PasscodeViewController: UITableViewController, TMPasscodeLockControllerDelegate { @IBOutlet var changePasscodeCell: UITableViewCell! @IBOutlet var removePasscodeCell: UITableViewCell! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.cellForRow(at: indexPath) == changePasscodeCell { let passcodeLockController = TMPasscodeLockController(style: .basic, state: .change) passcodeLockController.delegate = self passcodeLockController.presentIn(viewController: self, animated: true) } else if tableView.cellForRow(at: indexPath) == removePasscodeCell { let passcodeLockController = TMPasscodeLockController(style: .basic, state: .remove) passcodeLockController.delegate = self passcodeLockController.presentIn(viewController: self, animated: true) } tableView.deselectRow(at: indexPath, animated: true) } func passcodeLockControllerDidCancel(passcodeLockController: TMPasscodeLockController) { } func passcodeLockController(passcodeLockController: TMPasscodeLockController, didFinishFor state: TMPasscodeLockState) { if state == .remove { DispatchQueue.main.asyncAfter(deadline: .now()+0.3, execute: { _ = self.navigationController?.popViewController(animated: true) }) } } }
mit
2f022bee946275eb36d5c225df971e8a
33.12963
124
0.672816
5.191549
false
false
false
false
argent-os/argent-ios
app-ios/LoginBoxTableViewController.swift
1
10815
// // LoginBoxTableViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 3/21/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import WatchConnectivity import Crashlytics import OnePasswordExtension class LoginBoxTableViewController: UITableViewController, UITextFieldDelegate, WCSessionDelegate { var window:UIWindow = UIWindow() @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet var loginTableView: UITableView! @IBOutlet weak var usernameCell: UITableViewCell! @IBOutlet weak var passwordCell: UITableViewCell! private let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) let toolBar = UIToolbar() override func viewDidLoad() { super.viewDidLoad() configure() } func configure() { let screen = UIScreen.mainScreen().bounds let _ = screen.size.width loginTableView.tableFooterView = UIView() self.usernameTextField.delegate = self self.passwordTextField.delegate = self usernameTextField.tag = 63631 let str = NSAttributedString(string: "Username or Email", attributes: [NSForegroundColorAttributeName:UIColor.lightBlue()]) usernameTextField.attributedPlaceholder = str usernameTextField.textRectForBounds(CGRectMake(0, 0, 0, 0)) usernameTextField.font = UIFont.systemFontOfSize(13) usernameTextField.tintColor = UIColor.pastelBlue() usernameTextField.addTarget(LoginViewController(), action: #selector(LoginViewController().textFieldDidChange(_:)), forControlEvents: .EditingChanged) passwordTextField.tag = 63632 let str2 = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName:UIColor.lightBlue()]) passwordTextField.attributedPlaceholder = str2 passwordTextField.textRectForBounds(CGRectMake(0, 0, 0, 0)) passwordTextField.clearsOnBeginEditing = false passwordTextField.font = UIFont.systemFontOfSize(13) passwordTextField.tintColor = UIColor.pastelBlue() passwordTextField.addTarget(LoginViewController(), action: #selector(LoginViewController().textFieldDidChange(_:)), forControlEvents: .EditingChanged) loginTableView.separatorColor = UIColor.paleBlue().colorWithAlphaComponent(0.5) loginTableView.backgroundColor = UIColor.whiteColor() usernameCell.backgroundColor = UIColor.clearColor() usernameCell.textLabel?.textColor = UIColor.lightBlue() passwordCell.backgroundColor = UIColor.clearColor() passwordCell.textLabel?.textColor = UIColor.lightBlue() // Blurview // let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) // visualEffectView.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height) // self.view.addSubview(visualEffectView) // self.view.sendSubviewToBack(visualEffectView) } // Add send toolbar func addToolbarButton() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height toolBar.frame = CGRect(x: 0, y: screenHeight-250, width: screenWidth, height: 50) toolBar.barStyle = UIBarStyle.Default toolBar.translucent = false toolBar.sizeToFit() let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let next: UIBarButtonItem = UIBarButtonItem(title: "Login", style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.login(_:))) UIToolbar.appearance().barTintColor = UIColor.brandGreen() UIToolbar.appearance().backgroundColor = UIColor.brandGreen() next.setTitleTextAttributes([ NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 15)!, NSForegroundColorAttributeName : UIColor.whiteColor() ], forState: .Normal) toolBar.setItems([flexSpace, next, flexSpace], animated: false) toolBar.userInteractionEnabled = true usernameTextField.inputAccessoryView=toolBar passwordTextField.inputAccessoryView=toolBar } func login(sender: AnyObject) { activityIndicator.center = tableView.center activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) if(usernameTextField.text == "" || passwordTextField.text == "") { displayAlertMessage("Fields cannot be empty") activityIndicator.stopAnimating() activityIndicator.hidden = true } Auth.login(usernameTextField.text!, username: usernameTextField.text!, password: passwordTextField.text!) { (token, grant, username, err) in if(grant == true && token != "") { self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true // Performs segue to home, repeats in LoginViewController, @todo: DRY self.performSegueWithIdentifier("homeView", sender: self) // Sets access token on login, otherwise will log out userAccessToken = token Answers.logLoginWithMethod("Default", success: true, customAttributes: [ "user": username ]) // Send access token and Stripe key to Apple Watch if WCSession.isSupported() { //makes sure it's not an iPad or iPod let watchSession = WCSession.defaultSession() watchSession.delegate = self watchSession.activateSession() if watchSession.paired && watchSession.watchAppInstalled { do { try watchSession.updateApplicationContext( [ "token": token ] ) print("setting watch data") } catch let error as NSError { print(error.description) } } } } else { self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true Answers.logLoginWithMethod("Default", success: false, customAttributes: [ "error": "Error using default login method" ]) self.displayAlertMessage("Error logging in") } } } func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, 0, 10) } func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, 0, 10) } override func viewWillDisappear(animated: Bool) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // IMPORTANT: This allows the rootViewController to be prepared upon login when preparing for segue (transition) to the HomeViewController // Without this the nav menu will not work! segue.destinationViewController.hidesBottomBarWhenPushed = false switch sender?.tag { case 1?: // Login button pressed print("logging in") case 2?: // Signup button pressed print("signup pressed") case 3?: // New signup button pressed print("new signup pressed") default: // Sent root view controller (default is login) otherwise send to register page let sb = UIStoryboard(name: "Main", bundle: nil) let rootViewController = (sb.instantiateViewControllerWithIdentifier("RootViewController")) as UIViewController self.presentViewController(rootViewController, animated: true, completion: nil) self.window.rootViewController = rootViewController UIApplication.sharedApplication().keyWindow?.rootViewController = rootViewController // critical: ensures rootViewController is set on login } } // Allow use of next and join on keyboard func textFieldShouldReturn(textField: UITextField) -> Bool { let nextTag: Int = textField.tag + 1 let nextResponder: UIResponder? = textField.superview?.superview?.viewWithTag(nextTag) if let nextR = nextResponder { // Found next responder, so set it. nextR.becomeFirstResponder() } else { // Not found, so remove keyboard. self.login(self) textField.resignFirstResponder() return true } return false } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } func displayDefaultErrorAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } func displayAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } func displayErrorAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } }
mit
f03000051f7ebbaf451ce86236efb606
41.916667
158
0.625393
6.041341
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/Pods/SwiftMessages/SwiftMessages/WindowViewController.swift
1
1469
// // WindowViewController.swift // SwiftMessages // // Created by Timothy Moose on 8/1/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit class WindowViewController: UIViewController { fileprivate var window: UIWindow? let windowLevel: UIWindowLevel let config: SwiftMessages.Config override var shouldAutorotate: Bool { return config.shouldAutorotate } init(windowLevel: UIWindowLevel = UIWindowLevelNormal, config: SwiftMessages.Config) { self.windowLevel = windowLevel self.config = config let window = PassthroughWindow(frame: UIScreen.main.bounds) self.window = window super.init(nibName: nil, bundle: nil) self.view = PassthroughView() window.rootViewController = self window.windowLevel = windowLevel } func install() { guard let window = window else { return } window.makeKeyAndVisible() } func uninstall() { window?.isHidden = true window = nil } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public var preferredStatusBarStyle: UIStatusBarStyle { return config.preferredStatusBarStyle ?? UIApplication.shared.statusBarStyle } override var prefersStatusBarHidden: Bool { return UIApplication.shared.isStatusBarHidden } }
apache-2.0
5146572c06115cc5c4f651e4ca28d022
25.690909
88
0.662125
5.280576
false
true
false
false