repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Burning-Man-Earth/iBurn-iOS
iBurn/BRCEventObject.swift
1
572
// // BRCEventObject.swift // iBurn // // Created by Chris Ballinger on 8/11/19. // Copyright © 2019 Burning Man Earth. All rights reserved. // import Foundation extension BRCEventObject { /// e.g. "10:00AM - 4:00PM" @objc public var startAndEndString: String { let timeOnly = DateFormatter.timeOnly return "\(timeOnly.string(from: startDate)) - \(timeOnly.string(from: endDate))" } public var startWeekdayString: String { let dayOfWeek = DateFormatter.dayOfWeek return dayOfWeek.string(from: startDate) } }
mpl-2.0
Mohammad103/MSTestPods
Example/Tests/Tests.swift
1
760
import UIKit import XCTest import MSTestPods class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
tkremenek/swift
test/DebugInfo/async-boxed-arg.swift
1
777
// RUN: %target-swift-frontend %s -emit-ir -g -o - -parse-as-library \ // RUN: -module-name M -enable-experimental-concurrency -disable-availability-checking | %FileCheck %s --dump-input always // REQUIRES: concurrency @available(SwiftStdlib 5.5, *) extension Collection where Element: Sendable { public func f() async throws { return try await withThrowingTaskGroup(of: Element.self) { group in var i = self.startIndex func doit() async throws { group.spawn { [i] in return self[i] } } try await doit() } } } // CHECK: ![[BOXTY:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$s5IndexSlQzz_x_SlRzs8Sendable7ElementSTRpzlXXD" // CHECK: !DILocalVariable(name: "i", arg: 3, {{.*}}type: ![[BOXTY]]
apache-2.0
testpress/ios-app
ios-app/UI/TargetThreatViewController.swift
1
4111
// // TargetThreatViewController.swift // ios-app // // Copyright © 2017 Testpress. 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 ObjectMapper import UIKit import XLPagerTabStrip class TargetThreatViewController: BaseTableViewController<Reputation>, BaseTableViewDelegate, IndicatorInfoProvider { var userReputation: Reputation? var startingRank: Int = 1 override func viewDidLoad() { super.viewDidLoad() tableViewDelegate = self tableView.register( UINib(nibName: Constants.LEADERBOARD_TABLE_VIEW_CELL, bundle: Bundle.main), forCellReuseIdentifier: Constants.LEADERBOARD_TABLE_VIEW_CELL ) tableView.rowHeight = 80 tableView.allowsSelection = false tableView.separatorStyle = .none } func loadItems() { // Load targets TPApiClient.getListItems( endpointProvider: TPEndpointProvider(.getTargets), completion: { response, error in if let error = error { debugPrint(error.message ?? "No error") debugPrint(error.kind) self.handleError(error) return } let items = response!.results.reversed() self.items.append(contentsOf: items) if self.userReputation != nil { self.items.append(self.userReputation!) self.startingRank = self.userReputation!.rank - items.count } self.loadThreats() }, type: Reputation.self ) } func loadThreats() { TPApiClient.getListItems( endpointProvider: TPEndpointProvider(.getThreats), completion: { response, error in if let error = error { debugPrint(error.message ?? "No error") debugPrint(error.kind) self.handleError(error) return } let items = response!.results.reversed() self.items.append(contentsOf: items) self.onLoadFinished(items: self.items) }, type: Reputation.self ) } // MARK: - Table view data source override func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: Constants.LEADERBOARD_TABLE_VIEW_CELL, for: indexPath ) as! LeaderboardTableViewCell cell.initCell(reputation: items[indexPath.row], rank: startingRank + indexPath.row, userId: userReputation?.user.id) return cell } func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: Strings.TARGETS_AND_THREATS) } }
mit
ahmetkgunay/DrawPathView
DrawPathViewSwiftDemo/DrawPathViewSwiftDemoTests/DrawPathViewSwiftDemoTests.swift
1
1040
// // DrawPathViewSwiftDemoTests.swift // DrawPathViewSwiftDemoTests // // Created by Ahmet Kazim Günay on 15/12/15. // Copyright © 2015 Ahmet Kazim Günay. All rights reserved. // import XCTest @testable import DrawPathViewSwiftDemo class DrawPathViewSwiftDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
mohojojo/iOS-swiftbond-viper
Pods/Bond/Sources/Bond/UIKit/UIBarItem.swift
4
1675
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) || os(tvOS) import UIKit import ReactiveKit extension UIBarItem: BindingExecutionContextProvider { public var bindingExecutionContext: ExecutionContext { return .immediateOnMain } } public extension ReactiveExtensions where Base: UIBarItem { public var title: Bond<String?> { return bond { $0.title = $1 } } public var image: Bond<UIImage?> { return bond { $0.image = $1 } } public var isEnabled: Bond<Bool> { return bond { $0.isEnabled = $1 } } } #endif
mit
TalkingBibles/Talking-Bible-iOS
TalkingBible/Notification.swift
1
2005
// // Copyright 2015 Talking Bibles International // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class Box<T> { let unbox: T init(_ value: T) { self.unbox = value } } class Notification<A> { let name: String var observers: [String: NSObjectProtocol] = [:] init(name: String) { self.name = name } } func postNotification<A>(note: Notification<A>, value: A) { let userInfo = ["value": Box(value)] NSNotificationCenter.defaultCenter().postNotificationName(note.name, object: nil, userInfo: userInfo) } class NotificationObserver { let observer: NSObjectProtocol init<A>(notification: Notification<A>, withName observerName: String, block aBlock: A -> ()) { if let observer = notification.observers[observerName] { NSNotificationCenter.defaultCenter().removeObserver(observer) } observer = NSNotificationCenter.defaultCenter().addObserverForName(notification.name, object: nil, queue: nil) { note in if let value = (note.userInfo?["value"] as? Box<A>)?.unbox { aBlock(value) } else if let object = note.object as? A { aBlock(object) } else { assert(false, "Couldn't understand user info") } } notification.observers[observerName] = observer } deinit { NSNotificationCenter.defaultCenter().removeObserver(observer) } }
apache-2.0
zerovagner/iOS-Studies
SwappingScreens/SwappingScreens/MusicListViewController.swift
1
1202
// // MusicListViewController.swift // SwappingScreens // // Created by Vagner Oliveira on 5/5/17. // Copyright © 2017 Vagner Oliveira. All rights reserved. // import UIKit class MusicListViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func load3rdScreenButtonPressed(_ sender: Any) { let songTitle = "Smells Like Teen Spirit" performSegue(withIdentifier: "musicListPlaySongSegue", sender: songTitle) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? PlaySongViewController { if let song = sender as? String { destination.selectedSong = song } } } }
gpl-3.0
jkolb/Shkadov
Shkadov/engine/DisplaySystem.swift
1
1340
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Swiftish public protocol Screen { var region: Region2<Int> { get } var size: Vector2<Int> { get } var scale: Float { get } } public protocol DisplaySystem : class { func queryAvailableScreens() -> [Screen] }
mit
Hodglim/hacking-with-swift
Project-09/Petitions/MasterViewController.swift
1
3926
// // MasterViewController.swift // Petitions // // Created by Darren Hodges on 13/10/2015. // Copyright © 2015 Darren Hodges. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [[String: String]]() override func viewDidLoad() { super.viewDidLoad() let urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in if let url = NSURL(string: urlString) { if let data = try? NSData(contentsOfURL: url, options: []) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { self.parseJSON(json) } else { self.showError() } } else { self.showError() } } else { self.showError() } } } func parseJSON(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let obj = ["title": title, "body": body, "sigs": sigs] objects.append(obj) } dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.tableView.reloadData() } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } func showError() { dispatch_async(dispatch_get_main_queue()) { [unowned self] in let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object["title"] cell.detailTextLabel!.text = object["body"] return cell } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } }
mit
nikita-leonov/boss-client
BoSS/Models/Transformers/LocationTransform.swift
1
1119
// // LocationTransform.swift // BoSS // // Created by Emanuele Rudel on 28/02/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import Foundation import CoreLocation import ObjectMapper class LocationTransform: TransformType { typealias Object = CLLocation typealias JSON = [String: Double] private let latitudeKey = "lat" private let longitudeKey = "lng" required init() { } func transformFromJSON(value: AnyObject?) -> Object? { var result: Object? if let geopoint = value as? [String: Double] { if let latitude = geopoint[latitudeKey], longitude = geopoint[longitudeKey] { result = CLLocation(latitude: latitude, longitude: longitude) } } return result } func transformToJSON(value: Object?) -> JSON? { var result: JSON? if let coordinate = value?.coordinate { result = [latitudeKey: coordinate.latitude, longitudeKey: coordinate.longitude] } return result } }
mit
taqun/HBR
HBR/Classes/Extension/UIColorExtension.swift
1
464
// // UIColorExtension.swift // HBR // // Created by taqun on 2014/09/19. // Copyright (c) 2014年 envoixapp. All rights reserved. // import UIKit extension UIColor { convenience init(hex: Int, alpha: CGFloat = 1.0) { let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 let blue = CGFloat((hex & 0xFF)) / 255.0 self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
sugar2010/arcgis-runtime-samples-ios
LocalTiledLayerSample/swift/LocalTiledLayer/AppDelegate.swift
8
2551
/* Copyright 2015 Esri 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 UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
lhc70000/iina
iina/FilterPresets.swift
2
7539
// // FilterPresets.swift // iina // // Created by lhc on 25/8/2017. // Copyright © 2017 lhc. All rights reserved. // import Foundation fileprivate typealias PM = FilterParameter /** A fliter preset or tamplate, which contains the filter name and definitions of all parameters. */ class FilterPreset { typealias Transformer = (FilterPresetInstance) -> MPVFilter private static let defaultTransformer: Transformer = { instance in return MPVFilter(lavfiFilterFromPresetInstance: instance) } var name: String var params: [String: FilterParameter] var paramOrder: [String]? /** Given an instance, create the corresponding `MPVFilter`. */ var transformer: Transformer var localizedName: String { return FilterPreset.l10nDic[name] ?? name } init(_ name: String, params: [String: FilterParameter], paramOrder: String? = nil, transformer: @escaping Transformer = FilterPreset.defaultTransformer) { self.name = name self.params = params self.paramOrder = paramOrder?.components(separatedBy: ":") self.transformer = transformer } func localizedParamName(_ param: String) -> String { return FilterPreset.l10nDic["\(name).\(param)"] ?? param } } /** An instance of a filter preset, with concrete values for each parameter. */ class FilterPresetInstance { var preset: FilterPreset var params: [String: FilterParameterValue] = [:] init(from preset: FilterPreset) { self.preset = preset } func value(for name: String) -> FilterParameterValue { return params[name] ?? preset.params[name]!.defaultValue } } /** Definition of a filter parameter. It can be one of several types: - `text`: A generic string value. - `int`: An int value with range. It will be rendered as a slider. - `float`: A float value with range. It will be rendered as a slider. */ class FilterParameter { enum ParamType { case text, int, float, choose } var type: ParamType var defaultValue: FilterParameterValue // for float var min: Float? var max: Float? // for int var minInt: Int? var maxInt: Int? var step: Int? // for choose var choices: [String] = [] static func text(defaultValue: String = "") -> FilterParameter { return FilterParameter(.text, defaultValue: FilterParameterValue(string: defaultValue)) } static func int(min: Int, max: Int, step: Int = 1, defaultValue: Int = 0) -> FilterParameter { let pm = FilterParameter(.int, defaultValue: FilterParameterValue(int: defaultValue)) pm.minInt = min pm.maxInt = max pm.step = step return pm } static func float(min: Float, max: Float, defaultValue: Float = 0) -> FilterParameter { let pm = FilterParameter(.float, defaultValue: FilterParameterValue(float: defaultValue)) pm.min = min pm.max = max return pm } static func choose(from choices: [String], defaultChoiceIndex: Int = 0) -> FilterParameter { guard !choices.isEmpty else { fatalError("FilterParameter: Choices cannot be empty") } let pm = FilterParameter(.choose, defaultValue: FilterParameterValue(string: choices[defaultChoiceIndex])) pm.choices = choices return pm } private init(_ type: ParamType, defaultValue: FilterParameterValue) { self.type = type self.defaultValue = defaultValue } } /** The structure to store values of different param types. */ struct FilterParameterValue { private var _stringValue: String? private var _intValue: Int? private var _floatValue: Float? var stringValue: String { return _stringValue ?? _intValue?.description ?? _floatValue?.description ?? "" } var intValue: Int { return _intValue ?? 0 } var floatValue: Float { return _floatValue ?? 0 } init(string: String) { self._stringValue = string } init(int: Int) { self._intValue = int } init(float: Float) { self._floatValue = float } } /** Related data. */ extension FilterPreset { /** Preloaded localization. */ static let l10nDic: [String: String] = { guard let filePath = Bundle.main.path(forResource: "FilterPresets", ofType: "strings"), let dic = NSDictionary(contentsOfFile: filePath) as? [String : String] else { return [:] } return dic }() static private let customMPVFilterPreset = FilterPreset("custom_mpv", params: ["name": PM.text(defaultValue: ""), "string": PM.text(defaultValue: "")]) { instance in return MPVFilter(rawString: instance.value(for: "name").stringValue + "=" + instance.value(for: "string").stringValue)! } // custom ffmpeg static private let customFFmpegFilterPreset = FilterPreset("custom_ffmpeg", params: [ "name": PM.text(defaultValue: ""), "string": PM.text(defaultValue: "") ]) { instance in return MPVFilter(name: "lavfi", label: nil, paramString: "[\(instance.value(for: "name").stringValue)=\(instance.value(for: "string").stringValue)]") } /** All filter presets. */ static let vfPresets: [FilterPreset] = [ // crop FilterPreset("crop", params: [ "x": PM.text(), "y": PM.text(), "w": PM.text(), "h": PM.text() ], paramOrder: "w:h:x:y") { instance in return MPVFilter(mpvFilterFromPresetInstance: instance) }, // expand FilterPreset("expand", params: [ "x": PM.text(), "y": PM.text(), "w": PM.text(), "h": PM.text(), "aspect": PM.text(defaultValue: "0"), "round": PM.text(defaultValue: "1") ], paramOrder: "w:h:x:y:aspect:round") { instance in return MPVFilter(mpvFilterFromPresetInstance: instance) }, // sharpen FilterPreset("sharpen", params: [ "amount": PM.float(min: 0, max: 1.5), "msize": PM.int(min: 3, max: 23, step: 2, defaultValue: 5) ]) { instance in return MPVFilter.unsharp(amount: instance.value(for: "amount").floatValue, msize: instance.value(for: "msize").intValue) }, // blur FilterPreset("blur", params: [ "amount": PM.float(min: 0, max: 1.5), "msize": PM.int(min: 3, max: 23, step: 2, defaultValue: 5) ]) { instance in return MPVFilter.unsharp(amount: -instance.value(for: "amount").floatValue, msize: instance.value(for: "msize").intValue) }, // delogo FilterPreset("delogo", params: [ "x": PM.text(defaultValue: "1"), "y": PM.text(defaultValue: "1"), "w": PM.text(defaultValue: "1"), "h": PM.text(defaultValue: "1") ], paramOrder: "x:y:w:h"), // invert color FilterPreset("negative", params: [:]) { instance in return MPVFilter(lavfiName: "lutrgb", label: nil, paramDict: [ "r": "negval", "g": "negval", "b": "negval" ]) }, // flip FilterPreset("vflip", params: [:]) { instance in return MPVFilter(mpvFilterFromPresetInstance: instance) }, // mirror FilterPreset("hflip", params: [:]) { instance in return MPVFilter(mpvFilterFromPresetInstance: instance) }, // 3d lut FilterPreset("lut3d", params: [ "file": PM.text(), "interp": PM.choose(from: ["nearest", "trilinear", "tetrahedral"], defaultChoiceIndex: 0) ]) { instance in return MPVFilter(lavfiName: "lut3d", label: nil, paramDict: [ "file": instance.value(for: "file").stringValue, "interp": instance.value(for: "interp").stringValue, ]) }, // custom customMPVFilterPreset, customFFmpegFilterPreset ] static let afPresets: [FilterPreset] = [ customMPVFilterPreset, customFFmpegFilterPreset ] }
gpl-3.0
Gaantz/SocketsIO---iOS
socket.io-client-swift-master/SocketIO-iOSTests/SocketParserTest.swift
10
3851
// // SocketParserTest.swift // Socket.IO-Client-Swift // // Created by Lukas Schmidt on 05.09.15. // // import XCTest class SocketParserTest: XCTestCase { //Format key: message; namespace-data-binary-id static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [ "0": ("/", [], [], -1), "1": ("/", [], [], -1), "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1), "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1), "3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0), "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19), "4/swift,": ("/swift", [], [], -1), "0/swift": ("/swift", [], [], -1), "1/swift": ("/swift", [], [], -1)] func testDisconnect() { let message = "1" validateParseResult(message) } func testConnect() { let message = "0" validateParseResult(message) } func testDisconnectNameSpace() { let message = "1/swift" validateParseResult(message) } func testConnecttNameSpace() { let message = "0/swift" validateParseResult(message) } func testNameSpaceArrayParse() { let message = "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]" validateParseResult(message) } func testNameSpaceArrayAckParse() { let message = "3/swift,0[[\"test3\",\"test4\"]]" validateParseResult(message) } func testNameSpaceBinaryEventParse() { let message = "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]" validateParseResult(message) } func testNameSpaceBinaryAckParse() { let message = "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]" validateParseResult(message) } func testNamespaceErrorParse() { let message = "4/swift," validateParseResult(message) } func testInvalidInput() { let message = "8" XCTAssertNil(SocketParser.parseString(message)) } func testGenericParser() { var parser = SocketStringReader(message: "61-/swift,") XCTAssertEqual(parser.read(1), "6") XCTAssertEqual(parser.currentCharacter, "1") XCTAssertEqual(parser.readUntilStringOccurence("-"), "1") XCTAssertEqual(parser.currentCharacter, "/") } func validateParseResult(message: String) { let validValues = SocketParserTest.packetTypes[message]! let packet = SocketParser.parseString(message) let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1))) if let packet = packet { XCTAssertEqual(packet.type, SocketPacket.PacketType(str:type)!) XCTAssertEqual(packet.nsp, validValues.0) XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1)) XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2)) XCTAssertEqual(packet.id, validValues.3) } else { XCTFail() } } func testParsePerformance() { let keys = Array(SocketParserTest.packetTypes.keys) measureBlock({ for item in keys.enumerate() { SocketParser.parseString(item.element) } }) } }
mit
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/SiteManagementServiceTests.swift
1
9303
import Foundation import XCTest @testable import WordPress class SiteManagementServiceTests: CoreDataTestCase { var mockRemoteService: MockSiteManagementServiceRemote! var siteManagementService: SiteManagementServiceTester! class MockSiteManagementServiceRemote: SiteManagementServiceRemote { var deleteSiteCalled = false var exportContentCalled = false var getActivePurchasesCalled = false var successBlockPassedIn: (() -> Void)? var successResultBlockPassedIn: (([SitePurchase]) -> Void)? var failureBlockPassedIn: ((NSError) -> Void)? override func deleteSite(_ siteID: NSNumber, success: (() -> Void)?, failure: ((NSError) -> Void)?) { deleteSiteCalled = true successBlockPassedIn = success failureBlockPassedIn = failure } override func exportContent(_ siteID: NSNumber, success: (() -> Void)?, failure: ((NSError) -> Void)?) { exportContentCalled = true successBlockPassedIn = success failureBlockPassedIn = failure } override func getActivePurchases(_ siteID: NSNumber, success: (([SitePurchase]) -> Void)?, failure: ((NSError) -> Void)?) { getActivePurchasesCalled = true failureBlockPassedIn = failure successResultBlockPassedIn = success } func reset() { deleteSiteCalled = false exportContentCalled = false getActivePurchasesCalled = false successBlockPassedIn = nil successResultBlockPassedIn = nil failureBlockPassedIn = nil } } class SiteManagementServiceTester: SiteManagementService { let mockRemoteApi = MockWordPressComRestApi() lazy var mockRemoteService: MockSiteManagementServiceRemote = { return MockSiteManagementServiceRemote(wordPressComRestApi: self.mockRemoteApi) }() override func siteManagementServiceRemoteForBlog(_ blog: Blog) -> SiteManagementServiceRemote { return mockRemoteService } } override func setUp() { super.setUp() siteManagementService = SiteManagementServiceTester(managedObjectContext: contextManager.mainContext) mockRemoteService = siteManagementService.mockRemoteService } func insertBlog(_ context: NSManagedObjectContext) -> Blog { let blog = NSEntityDescription.insertNewObject(forEntityName: "Blog", into: context) as! Blog blog.xmlrpc = "http://mock.blog/xmlrpc.php" blog.url = "http://mock.blog/" blog.dotComID = 999999 try! context.obtainPermanentIDs(for: [blog]) try! context.save() return blog } func testDeleteSiteCallsServiceRemoteDeleteSite() { let context = contextManager.mainContext let blog = insertBlog(context) mockRemoteService.reset() siteManagementService.deleteSiteForBlog(blog, success: nil, failure: nil) XCTAssertTrue(mockRemoteService.deleteSiteCalled, "Remote DeleteSite should have been called") } func testDeleteSiteCallsSuccessBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let expect = expectation(description: "Delete Site success expectation") mockRemoteService.reset() siteManagementService.deleteSiteForBlog(blog, success: { expect.fulfill() }, failure: nil) mockRemoteService.successBlockPassedIn?() waitForExpectations(timeout: 2, handler: nil) } func testDeleteSiteRemovesExistingBlogOnSuccess() { let context = contextManager.mainContext let blog = insertBlog(context) let blogObjectID = blog.objectID XCTAssertFalse(blogObjectID.isTemporaryID, "Should be a permanent object") let expect = expectation( description: "Remove Blog success expectation") mockRemoteService.reset() siteManagementService.deleteSiteForBlog(blog, success: { expect.fulfill() }, failure: nil) mockRemoteService.successBlockPassedIn?() waitForExpectations(timeout: 2, handler: nil) let shouldBeRemoved = try? context.existingObject(with: blogObjectID) XCTAssertFalse(shouldBeRemoved != nil, "Blog was not removed") } func testDeleteSiteCallsFailureBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let testError = NSError(domain: "UnitTest", code: 0, userInfo: nil) let expect = expectation(description: "Delete Site failure expectation") mockRemoteService.reset() siteManagementService.deleteSiteForBlog(blog, success: nil, failure: { error in XCTAssertEqual(error, testError, "Error not propagated") expect.fulfill() }) mockRemoteService.failureBlockPassedIn?(testError) waitForExpectations(timeout: 2, handler: nil) } func testDeleteSiteDoesNotRemoveExistingBlogOnFailure() { let context = contextManager.mainContext let blog = insertBlog(context) let blogObjectID = blog.objectID XCTAssertFalse(blogObjectID.isTemporaryID, "Should be a permanent object") let testError = NSError(domain: "UnitTest", code: 0, userInfo: nil) let expect = expectation(description: "Remove Blog success expectation") mockRemoteService.reset() siteManagementService.deleteSiteForBlog(blog, success: nil, failure: { error in XCTAssertEqual(error, testError, "Error not propagated") expect.fulfill() }) mockRemoteService.failureBlockPassedIn?(testError) waitForExpectations(timeout: 2, handler: nil) let shouldNotBeRemoved = try? context.existingObject(with: blogObjectID) XCTAssertFalse(shouldNotBeRemoved == nil, "Blog was removed") } func testExportContentCallsServiceRemoteExportContent() { let context = contextManager.mainContext let blog = insertBlog(context) mockRemoteService.reset() siteManagementService.exportContentForBlog(blog, success: nil, failure: nil) XCTAssertTrue(mockRemoteService.exportContentCalled, "Remote ExportContent should have been called") } func testExportContentCallsSuccessBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let expect = expectation(description: "ExportContent success expectation") mockRemoteService.reset() siteManagementService.exportContentForBlog(blog, success: { expect.fulfill() }, failure: nil) mockRemoteService.successBlockPassedIn?() waitForExpectations(timeout: 2, handler: nil) } func testExportContentCallsFailureBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let testError = NSError(domain: "UnitTest", code: 0, userInfo: nil) let expect = expectation(description: "ExportContent failure expectation") mockRemoteService.reset() siteManagementService.exportContentForBlog(blog, success: nil, failure: { error in XCTAssertEqual(error, testError, "Error not propagated") expect.fulfill() }) mockRemoteService.failureBlockPassedIn?(testError) waitForExpectations(timeout: 2, handler: nil) } func testGetActivePurchasesCallsServiceRemoteGetActivePurchases() { let context = contextManager.mainContext let blog = insertBlog(context) mockRemoteService.reset() siteManagementService.getActivePurchasesForBlog(blog, success: nil, failure: nil) XCTAssertTrue(mockRemoteService.getActivePurchasesCalled, "Remote GetActivePurchases should have been called") } func testGetActivePurchasesCallsSuccessBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let expect = expectation(description: "GetActivePurchases success expectation") mockRemoteService.reset() siteManagementService.getActivePurchasesForBlog(blog, success: { purchases in expect.fulfill() }, failure: nil) mockRemoteService.successResultBlockPassedIn?([]) waitForExpectations(timeout: 2, handler: nil) } func testGetActivePurchasesCallsFailureBlock() { let context = contextManager.mainContext let blog = insertBlog(context) let testError = NSError(domain: "UnitTest", code: 0, userInfo: nil) let expect = expectation(description: "GetActivePurchases failure expectation") mockRemoteService.reset() siteManagementService.getActivePurchasesForBlog(blog, success: nil, failure: { error in XCTAssertEqual(error, testError, "Error not propagated") expect.fulfill() }) mockRemoteService.failureBlockPassedIn?(testError) waitForExpectations(timeout: 2, handler: nil) } }
gpl-2.0
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/User Profile Sheet/UserProfileUserInfoCell.swift
2
1757
class UserProfileUserInfoCell: UITableViewCell, NibReusable { // MARK: - Properties @IBOutlet weak var gravatarImageView: CircularImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var userBioLabel: UILabel! static let estimatedRowHeight: CGFloat = 200 // MARK: - View override func awakeFromNib() { super.awakeFromNib() configureCell() } // MARK: - Public Methods func configure(withUser user: LikeUser) { nameLabel.text = user.displayName usernameLabel.text = String(format: Constants.usernameFormat, user.username) userBioLabel.text = user.bio userBioLabel.isHidden = user.bio.isEmpty downloadGravatarWithURL(user.avatarUrl) } } // MARK: - Private Extension private extension UserProfileUserInfoCell { func configureCell() { nameLabel.textColor = .text nameLabel.font = WPStyleGuide.serifFontForTextStyle(.title3, fontWeight: .semibold) usernameLabel.textColor = .textSubtle userBioLabel.textColor = .text } func downloadGravatarWithURL(_ url: String?) { // Always reset gravatar gravatarImageView.cancelImageDownload() gravatarImageView.image = .gravatarPlaceholderImage guard let url = url, let gravatarURL = URL(string: url) else { return } gravatarImageView.downloadImage(from: gravatarURL, placeholderImage: .gravatarPlaceholderImage) } struct Constants { static let usernameFormat = NSLocalizedString("@%1$@", comment: "Label displaying the user's username preceeded by an '@' symbol. %1$@ is a placeholder for the username.") } }
gpl-2.0
winkelsdorf/SwiftWebViewProgress
SwiftWebViewProgress/SwiftWebViewProgress/SwiftWebViewProgress.swift
1
6726
// // SwiftWebViewProgress.swift // SwiftWebViewProgress // // Created by Daichi Ichihara on 2014/12/03. // Copyright (c) 2014 MokuMokuCloud. All rights reserved. // import UIKit protocol WebViewProgressDelegate { func webViewProgress(webViewProgress: WebViewProgress, updateProgress progress: Float) } class WebViewProgress: NSObject, UIWebViewDelegate { var progressDelegate: WebViewProgressDelegate? var webViewProxyDelegate: UIWebViewDelegate? var progress: Float = 0.0 private var loadingCount: Int! private var maxLoadCount: Int! private var currentUrl: NSURL? private var interactive: Bool! private let InitialProgressValue: Float = 0.1 private let InteractiveProgressValue: Float = 0.5 private let FinalProgressValue: Float = 0.9 private let completePRCURLPath = "/webviewprogressproxy/complete" // MARK: Initializer override init() { super.init() maxLoadCount = 0 loadingCount = 0 interactive = false } // MARK: Private Method private func startProgress() { if progress < InitialProgressValue { setProgress(InitialProgressValue) } } private func incrementProgress() { var progress = self.progress var maxProgress = interactive == true ? FinalProgressValue : InteractiveProgressValue let remainPercent = Float(loadingCount / maxLoadCount) let increment = (maxProgress - progress) / remainPercent progress += increment progress = fmin(progress, maxProgress) setProgress(progress) } private func completeProgress() { setProgress(1.0) } private func setProgress(progress: Float) { if progress > self.progress || progress == 0 { self.progress = progress progressDelegate?.webViewProgress(self, updateProgress: progress) } } // MARK: Public Method func reset() { maxLoadCount = 0 loadingCount = 0 interactive = false setProgress(0.0) } // MARK: - UIWebViewDelegate func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL!.path == completePRCURLPath { completeProgress() return false } var ret = true if webViewProxyDelegate!.respondsToSelector("webView:shouldStartLoadWithRequest:navigationType:") { ret = webViewProxyDelegate!.webView!(webView, shouldStartLoadWithRequest: request, navigationType: navigationType) } var isFragmentJump = false if let fragmentURL = request.URL?.fragment { let nonFragmentURL = request.URL?.absoluteString?.stringByReplacingOccurrencesOfString("#"+fragmentURL, withString: "") isFragmentJump = nonFragmentURL == webView.request!.URL?.absoluteString } var isTopLevelNavigation = request.mainDocumentURL! == request.URL var isHTTP = request.URL?.scheme == "http" || request.URL?.scheme == "https" if ret && !isFragmentJump && isHTTP && isTopLevelNavigation { currentUrl = request.URL reset() } return ret } func webViewDidStartLoad(webView: UIWebView) { if webViewProxyDelegate!.respondsToSelector("webViewDidStartLoad:") { webViewProxyDelegate!.webViewDidStartLoad!(webView) } loadingCount = loadingCount + 1 maxLoadCount = Int(fmax(Double(maxLoadCount), Double(loadingCount))) startProgress() } func webViewDidFinishLoad(webView: UIWebView) { if webViewProxyDelegate!.respondsToSelector("webViewDidFinishLoad:") { webViewProxyDelegate!.webViewDidFinishLoad!(webView) } loadingCount = loadingCount - 1 // incrementProgress() let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState") var interactive = readyState == "interactive" if interactive { self.interactive = true let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);" webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS) } var isNotRedirect: Bool if let _currentUrl = currentUrl { if _currentUrl == webView.request?.mainDocumentURL { isNotRedirect = true } else { isNotRedirect = false } } else { isNotRedirect = false } var complete = readyState == "complete" if complete && isNotRedirect { completeProgress() } } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { if webViewProxyDelegate!.respondsToSelector("webView:didFailLoadWithError:") { webViewProxyDelegate!.webView!(webView, didFailLoadWithError: error) } loadingCount = loadingCount - 1 // incrementProgress() let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState") var interactive = readyState == "interactive" if interactive { self.interactive = true let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);" webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS) } var isNotRedirect: Bool if let _currentUrl = currentUrl { if _currentUrl == webView.request?.mainDocumentURL { isNotRedirect = true } else { isNotRedirect = false } } else { isNotRedirect = false } var complete = readyState == "complete" if complete && isNotRedirect { completeProgress() } } }
mit
apple/swift-nio
Tests/NIOPosixTests/SelectorTest.swift
1
23469
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore @testable import NIOPosix import Atomics class SelectorTest: XCTestCase { func testDeregisterWhileProcessingEvents() throws { try assertDeregisterWhileProcessingEvents(closeAfterDeregister: false) } func testDeregisterAndCloseWhileProcessingEvents() throws { try assertDeregisterWhileProcessingEvents(closeAfterDeregister: true) } private func assertDeregisterWhileProcessingEvents(closeAfterDeregister: Bool) throws { struct TestRegistration: Registration { let socket: Socket var interested: SelectorEventSet var registrationID: SelectorRegistrationID } let selector = try NIOPosix.Selector<TestRegistration>() defer { XCTAssertNoThrow(try selector.close()) } let socket1 = try Socket(protocolFamily: .inet, type: .stream, protocolSubtype: .default) defer { if socket1.isOpen { XCTAssertNoThrow(try socket1.close()) } } try socket1.setNonBlocking() let socket2 = try Socket(protocolFamily: .inet, type: .stream, protocolSubtype: .default) defer { if socket2.isOpen { XCTAssertNoThrow(try socket2.close()) } } try socket2.setNonBlocking() let serverSocket = try assertNoThrowWithValue(ServerSocket.bootstrap(protocolFamily: .inet, host: "127.0.0.1", port: 0)) defer { XCTAssertNoThrow(try serverSocket.close()) } _ = try socket1.connect(to: serverSocket.localAddress()) _ = try socket2.connect(to: serverSocket.localAddress()) let accepted1 = try serverSocket.accept()! defer { XCTAssertNoThrow(try accepted1.close()) } let accepted2 = try serverSocket.accept()! defer { XCTAssertNoThrow(try accepted2.close()) } // Register both sockets with .write. This will ensure both are ready when calling selector.whenReady. try selector.register(selectable: socket1 , interested: [.reset, .write], makeRegistration: { ev, regID in return TestRegistration(socket: socket1, interested: ev, registrationID: regID) }) try selector.register(selectable: socket2 , interested: [.reset, .write], makeRegistration: { ev, regID in return TestRegistration(socket: socket2, interested: ev, registrationID: regID) }) var readyCount = 0 try selector.whenReady(strategy: .block, onLoopBegin: { }) { ev in readyCount += 1 if socket1 === ev.registration.socket { try selector.deregister(selectable: socket2) if closeAfterDeregister { try socket2.close() } } else if socket2 === ev.registration.socket { try selector.deregister(selectable: socket1) if closeAfterDeregister { try socket1.close() } } else { XCTFail("ev.registration.socket was neither \(socket1) or \(socket2) but \(ev.registration.socket)") } } XCTAssertEqual(1, readyCount) } private static let testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse = 10 func testWeDoNotDeliverEventsForPreviouslyClosedChannels() { /// We use this class to box mutable values, generally in this test anything boxed should only be read/written /// on the event loop `el`. class Box<T> { init(_ value: T) { self._value = value } private var _value: T var value: T { get { XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop) return self._value } set { XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop) self._value = newValue } } } enum DidNotReadError: Error { case didNotReadGotInactive case didNotReadGotReadComplete } /// This handler is inserted in the `ChannelPipeline` that are re-connected. So we're closing a bunch of /// channels and (in the same event loop tick) we then connect the same number for which I'm using the /// terminology 're-connect' here. /// These re-connected channels will re-use the fd numbers of the just closed channels. The interesting thing /// is that the `Selector` will still have events buffered for the _closed fds_. Note: the re-connected ones /// will end up using the _same_ fds and this test ensures that we're not getting the outdated events. In this /// case the outdated events are all `.readEOF`s which manifest as `channelReadComplete`s. If we're delivering /// outdated events, they will also happen in the _same event loop tick_ and therefore we do quite a few /// assertions that we're either in or not in that interesting event loop tick. class HappyWhenReadHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer private let didReadPromise: EventLoopPromise<Void> private let hasReConnectEventLoopTickFinished: Box<Bool> private var didRead: Bool = false init(hasReConnectEventLoopTickFinished: Box<Bool>, didReadPromise: EventLoopPromise<Void>) { self.didReadPromise = didReadPromise self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished } func channelActive(context: ChannelHandlerContext) { // we expect these channels to be connected within the re-connect event loop tick XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value) } func channelInactive(context: ChannelHandlerContext) { // we expect these channels to be close a while after the re-connect event loop tick XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertTrue(self.didRead) if !self.didRead { self.didReadPromise.fail(DidNotReadError.didNotReadGotInactive) context.close(promise: nil) } } func channelRead(context: ChannelHandlerContext, data: NIOAny) { // we expect these channels to get data only a while after the re-connect event loop tick as it's // impossible to get a read notification in the very same event loop tick that you got registered XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertFalse(self.didRead) var buf = self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) XCTAssertEqual("H", buf.readString(length: 1)!) self.didRead = true self.didReadPromise.succeed(()) } func channelReadComplete(context: ChannelHandlerContext) { // we expect these channels to get data only a while after the re-connect event loop tick as it's // impossible to get a read notification in the very same event loop tick that you got registered XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertTrue(self.didRead) if !self.didRead { self.didReadPromise.fail(DidNotReadError.didNotReadGotReadComplete) context.close(promise: nil) } } } /// This handler will wait for all client channels to have come up and for one of them to have received EOF. /// (We will see the EOF as they're set to support half-closure). Then, it'll close half of those file /// descriptors and open the same number of new ones. The new ones (called re-connected) will share the same /// fd numbers as the recently closed ones. That brings us in an interesting situation: There will (very likely) /// be `.readEOF` events enqueued for the just closed ones and because the re-connected channels share the same /// fd numbers danger looms. The `HappyWhenReadHandler` above makes sure nothing bad happens. class CloseEveryOtherAndOpenNewOnesHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer private let allChannels: Box<[Channel]> private let serverAddress: SocketAddress private let everythingWasReadPromise: EventLoopPromise<Void> private let hasReConnectEventLoopTickFinished: Box<Bool> init(allChannels: Box<[Channel]>, hasReConnectEventLoopTickFinished: Box<Bool>, serverAddress: SocketAddress, everythingWasReadPromise: EventLoopPromise<Void>) { self.allChannels = allChannels self.serverAddress = serverAddress self.everythingWasReadPromise = everythingWasReadPromise self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished } func channelActive(context: ChannelHandlerContext) { // collect all the channels context.channel.getOption(ChannelOptions.allowRemoteHalfClosure).whenSuccess { halfClosureAllowed in precondition(halfClosureAllowed, "the test configuration is bogus: half-closure is dis-allowed which breaks the setup of this test") } self.allChannels.value.append(context.channel) } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { // this is the `.readEOF` that is triggered by the `ServerHandler`'s `close` calls because our channel // supports half-closure guard self.allChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse else { return } // all channels are up, so let's construct the situation we want to be in: // 1. let's close half the channels // 2. then re-connect (must be synchronous) the same number of channels and we'll get fd number re-use context.channel.eventLoop.execute { // this will be run immediately after we processed all `Selector` events so when // `self.hasReConnectEventLoopTickFinished.value` becomes true, we're out of the event loop // tick that is interesting. XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value) self.hasReConnectEventLoopTickFinished.value = true } XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value) let everyOtherIndex = stride(from: 0, to: SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, by: 2) for f in everyOtherIndex { XCTAssertTrue(self.allChannels.value[f].isActive) // close will succeed synchronously as we're on the right event loop. self.allChannels.value[f].close(promise: nil) XCTAssertFalse(self.allChannels.value[f].isActive) } // now we have completed stage 1: we freed up a bunch of file descriptor numbers, so let's open // some new ones var reconnectedChannelsHaveRead: [EventLoopFuture<Void>] = [] for _ in everyOtherIndex { var hasBeenAdded: Bool = false let p = context.channel.eventLoop.makePromise(of: Void.self) reconnectedChannelsHaveRead.append(p.futureResult) let newChannel = ClientBootstrap(group: context.eventLoop) .channelInitializer { channel in channel.pipeline.addHandler(HappyWhenReadHandler(hasReConnectEventLoopTickFinished: self.hasReConnectEventLoopTickFinished, didReadPromise: p)).map { hasBeenAdded = true } } .connect(to: self.serverAddress) .map { (channel: Channel) -> Void in XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value, """ This is bad: the connect of the channels to be re-connected has not completed synchronously. We assumed that on all platform a UNIX Domain Socket connect is synchronous but we must be wrong :(. The good news is: Not everything is lost, this test should also work if you instead open a regular file (in O_RDWR) and just use this file's fd with `ClientBootstrap(group: group).withConnectedSocket(fileFD)`. Sure, a file is not a socket but it's always readable and writable and that fulfills the requirements we have here. I still hope this change will never have to be done. Note: if you changed anything about the pipeline's handler adding/removal you might also have a bug there. """) } // just to make sure we got `newChannel` synchronously and we could add our handler to the // pipeline synchronously too. XCTAssertTrue(newChannel.isFulfilled) XCTAssertTrue(hasBeenAdded) } // if all the new re-connected channels have read, then we're happy here. EventLoopFuture.andAllSucceed(reconnectedChannelsHaveRead, on: context.eventLoop) .cascade(to: self.everythingWasReadPromise) // let's also remove all the channels so this code will not be triggered again. self.allChannels.value.removeAll() } } // all of the following are boxed as we need mutable references to them, they can only be read/written on the // event loop `el`. let allServerChannels: Box<[Channel]> = Box([]) let allChannels: Box<[Channel]> = Box([]) let hasReConnectEventLoopTickFinished: Box<Bool> = Box(false) let numberOfConnectedChannels: Box<Int> = Box(0) /// This spawns a server, always send a character immediately and after the first /// `SelectorTest.numberOfChannelsToUse` have been established, we'll close them all. That will trigger /// an `.readEOF` in the connected client channels which will then trigger other interesting things (see above). class ServerHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer private var number: Int = 0 private let allServerChannels: Box<[Channel]> private let numberOfConnectedChannels: Box<Int> init(allServerChannels: Box<[Channel]>, numberOfConnectedChannels: Box<Int>) { self.allServerChannels = allServerChannels self.numberOfConnectedChannels = numberOfConnectedChannels } func channelActive(context: ChannelHandlerContext) { var buf = context.channel.allocator.buffer(capacity: 1) buf.writeString("H") context.channel.writeAndFlush(buf, promise: nil) self.number += 1 self.allServerChannels.value.append(context.channel) if self.allServerChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse { // just to be sure all of the client channels have connected XCTAssertEqual(SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, numberOfConnectedChannels.value) self.allServerChannels.value.forEach { c in c.close(promise: nil) } } } } let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1) let el = elg.next() defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } XCTAssertNoThrow(try withTemporaryUnixDomainSocketPathName { udsPath in let secondServerChannel = try! ServerBootstrap(group: el) .childChannelInitializer { channel in channel.pipeline.addHandler(ServerHandler(allServerChannels: allServerChannels, numberOfConnectedChannels: numberOfConnectedChannels)) } .bind(to: SocketAddress(unixDomainSocketPath: udsPath)) .wait() let everythingWasReadPromise = el.makePromise(of: Void.self) XCTAssertNoThrow(try el.submit { () -> [EventLoopFuture<Channel>] in (0..<SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse).map { (_: Int) in ClientBootstrap(group: el) .channelOption(ChannelOptions.allowRemoteHalfClosure, value: true) .channelInitializer { channel in channel.pipeline.addHandler(CloseEveryOtherAndOpenNewOnesHandler(allChannels: allChannels, hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished, serverAddress: secondServerChannel.localAddress!, everythingWasReadPromise: everythingWasReadPromise)) } .connect(to: secondServerChannel.localAddress!) .map { channel in numberOfConnectedChannels.value += 1 return channel } } }.wait().forEach { XCTAssertNoThrow(try $0.wait()) } as Void) XCTAssertNoThrow(try everythingWasReadPromise.futureResult.wait()) }) } func testTimerFDIsLevelTriggered() throws { // this is a regression test for https://github.com/apple/swift-nio/issues/872 let delayToUseInMicroSeconds: Int64 = 100_000 // needs to be much greater than time it takes to EL.execute let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } class FakeSocket: Socket { private let hasBeenClosedPromise: EventLoopPromise<Void> init(hasBeenClosedPromise: EventLoopPromise<Void>, socket: NIOBSDSocket.Handle) throws { self.hasBeenClosedPromise = hasBeenClosedPromise try super.init(socket: socket) } override func close() throws { self.hasBeenClosedPromise.succeed(()) try super.close() } } var socketFDs: [CInt] = [-1, -1] XCTAssertNoThrow(try Posix.socketpair(domain: .local, type: .stream, protocolSubtype: .default, socketVector: &socketFDs)) let numberFires = ManagedAtomic(0) let el = group.next() as! SelectableEventLoop let channelHasBeenClosedPromise = el.makePromise(of: Void.self) let channel = try SocketChannel(socket: FakeSocket(hasBeenClosedPromise: channelHasBeenClosedPromise, socket: socketFDs[0]), eventLoop: el) let sched = el.scheduleRepeatedTask(initialDelay: .microseconds(delayToUseInMicroSeconds), delay: .microseconds(delayToUseInMicroSeconds)) { (_: RepeatedTask) in numberFires.wrappingIncrement(ordering: .relaxed) } XCTAssertNoThrow(try el.submit { // EL tick 1: this is used to // - actually arm the timer (timerfd_settime) // - set the channel registration up if numberFires.load(ordering: .relaxed) > 0 { print("WARNING: This test hit a race and this result doesn't mean it actually worked." + " This should really only ever happen in very bizarre conditions.") } channel.interestedEvent = [.readEOF, .reset] func workaroundSR9815() { channel.registerAlreadyConfigured0(promise: nil) } workaroundSR9815() }.wait()) usleep(10_000) // this makes this repro very stable el.execute { // EL tick 2: this is used to // - close one end of the socketpair so that in EL tick 3, we'll see a EPOLLHUP // - sleep `delayToUseInMicroSeconds + 10` so in EL tick 3, we'll also see timerfd fire close(socketFDs[1]) usleep(.init(delayToUseInMicroSeconds)) } // EL tick 3: happens in the background here. We will likely lose the timer signal because of the // `deregistrationsHappened` workaround in `Selector.swift` and we expect to pick it up again when we enter // `epoll_wait`/`kevent` next. This however only works if the timer event is level triggered. assert(numberFires.load(ordering: .relaxed) > 5, within: .seconds(1), "timer only fired \(numberFires.load(ordering: .relaxed)) times") sched.cancel() XCTAssertNoThrow(try channelHasBeenClosedPromise.futureResult.wait()) } }
apache-2.0
dautermann/IHRAtlassanJSONSwiftParser
SimpleTicketSwift/IHRTicketCollectionTableViewCell.swift
1
1159
// // IHRTicketCollectionTableViewCell.swift // SimpleTicketSwift // // Created by Michael Dautermann on 9/16/14. // Copyright (c) 2014 Michael Dautermann. All rights reserved. // import UIKit class IHRTicketCollectionTableViewCell: UITableViewCell { var ticketURL : NSURL? var parentVC : TicketListViewController? func setTicketURL(urlToSet : NSURL) { ticketURL = urlToSet } func setParentVC(parentVCToSet : TicketListViewController) { parentVC = parentVCToSet } override func setSelected(selected: Bool, animated: Bool) { if(self.selected != selected) { // Configure the view for the selected state super.setSelected(selected, animated: animated) // and if we're selected for the first time, let's do a segue to the detail view if(selected) { parentVC?.performSegueWithIdentifier("seeTicketDetail", sender: self) // and de-select the cell, too super.setSelected(false, animated: false) } } } }
mit
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Analysis.playground/Pages/FFT Analysis.xcplaygroundpage/Contents.swift
1
480
//: ## FFT Analysis //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: "leadloop.wav") var player = try AKAudioPlayer(file: file) player.looping = true AudioKit.output = player AudioKit.start() player.play() let fft = AKFFTTap(player) AKPlaygroundLoop(every: 0.1) { if let max = fft.fftData.max() { let index = fft.fftData.index(of: max) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true
mit
zizi4n5/mecab-swift
Tests/MeCabTests/MeCabTests.swift
1
3209
// // MeCabTests.swift // MeCabTests // // Created by Yusuke Ito on 12/25/15. // Copyright © 2015 Yusuke Ito. All rights reserved. // import XCTest @testable import MeCab extension MeCabTests { static var allTests : [(String, (MeCabTests) -> () throws -> Void)] { return [ ("testTokenizeWithDefaults", testTokenizeWithDefaults), ("testDemo", testDemo) ] } } class MeCabTests: XCTestCase { func testTokenizeWithDefaults() throws { let mecab = try Mecab() let text = "あのイーハトーヴォのすきとおった風、" let nodes = try mecab.tokenize(string: text) for n in nodes { print(n.description) } XCTAssertEqual(nodes.count, 9) XCTAssertTrue(nodes[0].isBosEos) XCTAssertEqual(nodes[1].surface, "あの") XCTAssertEqual(nodes[1].posId, 68) // this value for ipadic XCTAssertEqual(nodes[2].surface, "イーハトーヴォ") XCTAssertEqual(nodes[2].posId, 38) XCTAssertEqual(nodes[3].surface, "の") XCTAssertEqual(nodes[3].posId, 13) XCTAssertEqual(nodes[4].surface, "すきとおっ") XCTAssertEqual(nodes[4].posId, 31) XCTAssertEqual(nodes[5].surface, "た") XCTAssertEqual(nodes[5].posId, 25) XCTAssertEqual(nodes[6].surface, "風") XCTAssertEqual(nodes[6].posId, 38) XCTAssertEqual(nodes[7].surface, "、") XCTAssertEqual(nodes[7].posId, 9) XCTAssertTrue(nodes[8].isBosEos) } func testDemo() throws { let m = try Mecab() let nodes = try m.tokenize(string: "太郎は次郎が持っている本を花子に渡した。") // MARK: Demo for n in nodes.filter({ !$0.isBosEos }) { print(n.surface, n.features, n.posId) } // MARK: Test let expected = "太郎 は 次郎 が 持っ て いる 本 を 花 子 に 渡し た 。".characters.split(separator: " ").map(String.init) let bodyNodes = nodes.filter({ !$0.isBosEos }) XCTAssertEqual(expected, bodyNodes.map{ $0.surface }) XCTAssertEqual(expected.count, bodyNodes.count) } func testNaistDictionary() throws { let m = try Mecab(dictionaryPath: "/usr/local/lib/mecab/dic/naist-jdic") let nodes = try m.tokenize(string: "太郎は次郎が持っている本を花子に渡した。") // MARK: Demo for n in nodes.filter({ !$0.isBosEos }) { print(n.surface, n.features, n.posId) } // MARK: Test let expected = "太郎 は 次郎 が 持っ て いる 本 を 花 子 に 渡し た 。".characters.split(separator: " ").map(String.init) let bodyNodes = nodes.filter({ !$0.isBosEos }) XCTAssertEqual(expected, bodyNodes.map{ $0.surface }) XCTAssertEqual(expected.count, bodyNodes.count) } }
mit
gkaimakas/ReactiveBluetooth
ReactiveBluetooth/Classes/CBDescriptor/CBDescriptor+Reactive.swift
1
994
// // CBDescriptor+Reactive.swift // ReactiveBluetooth // // Created by George Kaimakas on 04/03/2018. // import CoreBluetooth import Foundation import ReactiveCocoa import ReactiveSwift import Result extension Reactive where Base: CBDescriptor { /// The value of the descriptor. public var value: Property<Any?> { get { guard let value = objc_getAssociatedObject(base, &CBDescriptor.Associations.value) as? Property<Any?> else { let value = Property<Any?>(initial: base.value, then: producer(forKeyPath: #keyPath(CBCharacteristic.value))) objc_setAssociatedObject(base, &CBDescriptor.Associations.value, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return value } return value } } }
mit
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Services/TeamService.swift
1
5678
// // TeamService.swift // ScoreReporter // // Created by Bradley Smith on 11/6/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation public struct TeamService { fileprivate let client: APIClient public init(client: APIClient) { self.client = client } } // MARK: - Public public extension TeamService { func downloadTeamList(completion: DownloadCompletion?) { let parameters: [String: Any] = [ APIConstants.Path.Keys.function: APIConstants.Path.Values.teams ] client.request(.get, path: "", parameters: parameters) { result in switch result { case .success(let value): self.parseTeamList(response: value, completion: completion) case .failure(let error): completion?(DownloadResult(error: error)) } } } func downloadDetails(for team: Team, completion: DownloadCompletion?) { let parameters: [String: Any] = [ APIConstants.Path.Keys.function: APIConstants.Path.Values.teamDetails, APIConstants.Request.Keys.teamID: team.teamID.intValue ] client.request(.get, path: "", parameters: parameters) { result in switch result { case .success(let value): self.parseTeam(response: value, team: team, completion: completion) case .failure(let error): completion?(DownloadResult(error: error)) } } } } // MARK: - Private private extension TeamService { func parseTeamList(response: [String: Any], completion: DownloadCompletion?) { guard let teamArray = response[APIConstants.Response.Keys.teams] as? [[String: AnyObject]] else { let error = NSError(type: .invalidResponse) completion?(DownloadResult(error: error)) return } Team.teams(from: teamArray) { error in completion?(DownloadResult(error: error)) } } func parseTeam(response: [String: Any], team: Team, completion: DownloadCompletion?) { guard let responseArray = response[APIConstants.Response.Keys.groups] as? [[String: AnyObject]] else { let error = NSError(type: .invalidResponse) completion?(DownloadResult(error: error)) return } let partialEventDictionaries = responseArray.flatMap { dictionary -> [String: AnyObject]? in guard let eventID = dictionary[APIConstants.Response.Keys.eventID] as? NSNumber else { return nil } var partial = [String: AnyObject]() partial[APIConstants.Response.Keys.eventID] = eventID partial[APIConstants.Response.Keys.eventName] = dictionary[APIConstants.Response.Keys.eventName] return partial } let eventImportOperations = partialEventDictionaries.map { EventImportOperation(eventDictionary: $0) } let groupEventTuples = responseArray.flatMap { dictionary -> (NSNumber, NSNumber)? in guard let eventID = dictionary[APIConstants.Response.Keys.eventID] as? NSNumber, let groupID = dictionary[APIConstants.Response.Keys.groupID] as? NSNumber else { return nil } return (groupID, eventID) } let eventIDs = responseArray.flatMap { $0[APIConstants.Response.Keys.eventID] as? NSNumber } let eventDetailsOperations = eventIDs.map { EventDetailsOperation(eventID: $0) } let terminalOperation = BlockOperation { Group.coreDataStack.performBlockUsingBackgroundContext({ context in if let contextualTeam = context.object(with: team.objectID) as? Team { groupEventTuples.forEach { (groupID, eventID) in let group = Group.object(primaryKey: groupID, context: context) let event = Event.object(primaryKey: eventID, context: context) group?.add(team: contextualTeam) group?.event = event } } }, completion: { error in completion?(DownloadResult(error: error)) }) } eventImportOperations.forEach { operation in eventDetailsOperations.forEach { $0.addDependency(operation) } } eventDetailsOperations.forEach { terminalOperation.addDependency($0) } let queue = OperationQueue() queue.addOperations(eventImportOperations, waitUntilFinished: false) queue.addOperations(eventDetailsOperations, waitUntilFinished: false) queue.addOperation(terminalOperation) } } class EventImportOperation: AsyncOperation { convenience init(eventDictionary: [String: AnyObject]) { let block = { (completionHandler: @escaping AsyncOperationCompletionHandler) in Event.events(from: [eventDictionary], completion: { _ in print("Finished importing event") completionHandler() }) } self.init(block: block) } } class EventDetailsOperation: AsyncOperation { convenience init(eventID: NSNumber) { let block = { (completionHandler: @escaping AsyncOperationCompletionHandler) in let eventService = EventService(client: APIClient.sharedInstance) eventService.downloadDetails(for: eventID, completion: { error in print("Finished downloading \(eventID) with error: \(error)") completionHandler() }) } self.init(block: block) } }
mit
wireapp/wire-ios-data-model
Tests/Source/Model/Observer/SearchUserObserverTests.swift
1
4977
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @testable import WireDataModel class SearchUserObserverTests: NotificationDispatcherTestBase { class TestSearchUserObserver: NSObject, ZMUserObserver { var receivedChangeInfo: [UserChangeInfo] = [] func userDidChange(_ changeInfo: UserChangeInfo) { receivedChangeInfo.append(changeInfo) } } var testObserver: TestSearchUserObserver! override func setUp() { super.setUp() testObserver = TestSearchUserObserver() } override func tearDown() { testObserver = nil uiMOC.searchUserObserverCenter.reset() super.tearDown() } func testThatItNotifiesTheObserverOfASmallProfilePictureChange() { // given let remoteID = UUID.create() let searchUser = ZMSearchUser(contextProvider: coreDataStack, name: "Hans", handle: "hans", accentColor: .brightOrange, remoteIdentifier: remoteID) uiMOC.searchUserObserverCenter.addSearchUser(searchUser) self.token = UserChangeInfo.add(observer: testObserver, for: searchUser, in: self.uiMOC) // when searchUser.updateImageData(for: .preview, imageData: verySmallJPEGData()) // then XCTAssertEqual(testObserver.receivedChangeInfo.count, 1) if let note = testObserver.receivedChangeInfo.first { XCTAssertTrue(note.imageSmallProfileDataChanged) } } func testThatItNotifiesTheObserverOfASmallProfilePictureChangeIfTheInternalUserUpdates() { // given let user = ZMUser.insertNewObject(in: self.uiMOC) user.remoteIdentifier = UUID.create() self.uiMOC.saveOrRollback() let searchUser = ZMSearchUser(contextProvider: coreDataStack, name: "", handle: nil, accentColor: .brightYellow, remoteIdentifier: nil, user: user) uiMOC.searchUserObserverCenter.addSearchUser(searchUser) self.token = UserChangeInfo.add(observer: testObserver, for: searchUser, in: self.uiMOC) // when user.previewProfileAssetIdentifier = UUID.create().transportString() user.setImage(data: verySmallJPEGData(), size: .preview) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertEqual(testObserver.receivedChangeInfo.count, 1) if let note = testObserver.receivedChangeInfo.first { XCTAssertTrue(note.imageSmallProfileDataChanged) } } func testThatItStopsNotifyingAfterUnregisteringTheToken() { // given let remoteID = UUID.create() let searchUser = ZMSearchUser(contextProvider: coreDataStack, name: "Hans", handle: "hans", accentColor: .brightOrange, remoteIdentifier: remoteID) uiMOC.searchUserObserverCenter.addSearchUser(searchUser) self.token = UserChangeInfo.add(observer: testObserver, for: searchUser, in: self.uiMOC) // when self.token = nil searchUser.updateImageData(for: .preview, imageData: verySmallJPEGData()) // then XCTAssertEqual(testObserver.receivedChangeInfo.count, 0) } func testThatItNotifiesObserversWhenConnectingToASearchUserThatHasNoLocalUser() { // given let remoteID = UUID.create() let searchUser = ZMSearchUser(contextProvider: coreDataStack, name: "Hans", handle: "hans", accentColor: .brightOrange, remoteIdentifier: remoteID) let actionHandler = MockActionHandler<ConnectToUserAction>(result: .success(()), context: uiMOC.notificationContext) XCTAssertFalse(searchUser.isPendingApprovalByOtherUser) uiMOC.searchUserObserverCenter.addSearchUser(searchUser) self.token = UserChangeInfo.add(observer: testObserver, for: searchUser, in: self.uiMOC) // when searchUser.connect(completion: {_ in }) XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // then XCTAssertTrue(actionHandler.didPerformAction) XCTAssertEqual(testObserver.receivedChangeInfo.count, 1) guard let note = testObserver.receivedChangeInfo.first else { return XCTFail()} XCTAssertEqual(note.user as? ZMSearchUser, searchUser) XCTAssertTrue(note.connectionStateChanged) } }
gpl-3.0
fuzongjian/SwiftStudy
SwiftStudy/Advance/DetailController.swift
1
11559
// // DetailController.swift // SwiftStudy // // Created by 付宗建 on 16/8/15. // Copyright © 2016年 youran. All rights reserved. // import UIKit class DetailController: SuperViewController,UICollectionViewDelegate,UICollectionViewDataSource { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() chooseInit() // Do any additional setup after loading the view. } func chooseInit(){ if self.title == "UILabel"{// Lable let lable = UILabel(frame: self.view.bounds) lable.text = "Hello,World" lable.backgroundColor = UIColor.blueColor() lable.textAlignment = NSTextAlignment.Center lable.font = UIFont.boldSystemFontOfSize(25) self.view.addSubview(lable) }else if self.title == "UIButton"{// UIButton let button = UIButton(type: .System) button.frame = self.view.bounds button.center = self.view.center button.setTitle("点我", forState: .Normal) button.setTitle("点我", forState: .Highlighted) button.setTitleColor(UIColor.redColor(), forState: .Normal) button.setTitleColor(UIColor.blueColor(), forState: .Highlighted) button.addTarget(self, action: #selector(backButtonClicked(_:)), forControlEvents: .TouchUpInside) self.view.addSubview(button) }else if self.title == "UIImageView"{// UIImageView let image = UIImage(named: "press-to-h") let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100)) imageView.center = self.view.center imageView.image = image self.view.addSubview(imageView) }else if self.title == "UISlider"{// UISlider let slider = UISlider(frame: CGRectMake(0,0,300,30)) slider.center = self.view.center slider.value = 0.5 self.view.addSubview(slider) }else if self.title == "UIWebView"{ let webView = UIWebView(frame: self.view.bounds) let url = NSURL(fileURLWithPath:"http://caipiao.m.taobao.com") let request = NSURLRequest(URL: url) webView.loadRequest(request) self.view.addSubview(webView) }else if self.title == "UISegmentedControl"{ let segment = UISegmentedControl(items: ["fu","zong","jian"]) segment.frame = CGRectMake(0, 0, 200, 30) segment.center = self.view.center self.view.addSubview(segment) }else if self.title == "UISwitch"{ let swtch = UISwitch(frame: CGRectMake(0,0,100,30)) swtch.on = true swtch.center = self.view.center self.view.addSubview(swtch) }else if self.title == "UITextField"{ let textField = UITextField(frame: CGRectMake(0,0,200,30)) textField.center = self.view.center textField.borderStyle = .RoundedRect textField.placeholder = "hello world" self.view.addSubview(textField) }else if self.title == "UIScrollView"{ let scroll = UIScrollView(frame: CGRectMake(0,0,200,200)) scroll.center = self.view.center scroll.pagingEnabled = true scroll.showsVerticalScrollIndicator = false self.view.addSubview(scroll) var fx: CGFloat = 0.0 for i in 1...3{ let view = UIView(frame:CGRectMake(fx,0.0,200,200)) if i == 1{ view.backgroundColor = UIColor.redColor() }else{ view.backgroundColor = UIColor.blueColor() } fx += 200 scroll.addSubview(view) } scroll.contentSize = CGSizeMake(3 * 200, 200) }else if self.title == "UISearchBar"{ let searchbar = UISearchBar(frame: CGRectMake(0,0,300,40)) searchbar.center = self.view.center searchbar.showsCancelButton = true searchbar.searchBarStyle = .Minimal self.view.addSubview(searchbar) }else if self.title == "UIPageControl"{ let pageControl = UIPageControl(frame: CGRectMake(0,0,200,200)) pageControl.center = self.view.center pageControl.numberOfPages = 5; pageControl.currentPage = 2 pageControl.currentPageIndicatorTintColor = UIColor.redColor() pageControl.pageIndicatorTintColor = UIColor.blueColor() self.view.addSubview(pageControl) }else if self.title == "UIDatePicker"{ let datePicker = UIDatePicker(frame: CGRectMake(0,0,300,200)) datePicker.center = self.view.center self.view.addSubview(datePicker) }else if self.title == "UIPickerView"{ let pickerView = UIPickerView(frame: CGRectMake(0,0,300,200)) pickerView.center = self.view.center self.view.addSubview(pickerView) }else if self.title == "UIProgressView"{ let progress = UIProgressView(progressViewStyle: .Default) progress.frame = CGRectMake(0, 0, 300, 30) progress.center = self.view.center progress.setProgress(0.5, animated: false) self.view.addSubview(progress) }else if self.title == "UITextView"{ let textView = UITextView(frame: CGRectMake(0, 0, 300, 200)) textView.center = self.view.center textView.backgroundColor = UIColor.lightGrayColor() textView.editable = false textView.font = UIFont.boldSystemFontOfSize(20) textView.text = "2012年,魏则西考入西安电子科技大学计算机专业。他成绩优异,排名在班级前5%。2014年4月,魏则西被查出得了滑膜肉瘤。这是一种恶性软组织肿瘤,目前没有有效的治疗手段,生存率极低。休学。2014年5月20日至2014年8月15日,魏则西接连做了4次化疗,25次放疗。2014年9月至2015年底,魏则西先后在武警二院进行了4次生物免疫疗法的治疗,花了二十多万元.治病的巨额花费将家里积蓄掏空,魏则西接受了4次化疗、25次放疗,吃了几百服中药,经历了3次手术。检查出滑膜肉瘤之后,学校曾经组织了募捐活动,在学校食堂放置了几处募捐箱,筹集了8万元钱,也有人进行义卖筹钱。所做的这一切都是希望能够帮助挽回年轻的生命,结果却是未能如愿。" self.view.addSubview(textView) }else if self.title == "UIToolbar"{ let toolBar = UIToolbar(frame: CGRectMake(0,0,200,30)) toolBar.center = self.view.center let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let ItemA = UIBarButtonItem(title: "A", style: .Plain, target: nil, action: nil) let ItemB = UIBarButtonItem(title: "B", style: .Plain, target: nil, action: nil) let ItemC = UIBarButtonItem(title: "C", style: .Plain, target: nil, action: nil) let ItemD = UIBarButtonItem(title: "D", style: .Plain, target: nil, action: nil) toolBar.items = [flexibleSpace,ItemA,flexibleSpace,ItemB,flexibleSpace,ItemC,flexibleSpace,ItemD,flexibleSpace] self.view.addSubview(toolBar) }else if self.title == "UIActionSheet"{ let button = UIButton(type: .System) button.frame = CGRectMake(0, 0, 100, 40) button.center = self.view.center button.setTitle("show", forState: .Normal) button.setTitle("show", forState: .Highlighted) button.setTitleColor(UIColor.redColor(), forState: .Normal) button.setTitleColor(UIColor.blueColor(), forState: .Highlighted) button.addTarget(self, action: #selector(shouActionSheet(_:)), forControlEvents: .TouchUpInside) self.view .addSubview(button) }else if self.title == "UIActivityIndicatorView"{ let activity = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activity.frame = CGRectMake(0, 0, 40, 40) activity.center = self.view.center activity.startAnimating() self.view.addSubview(activity) }else if self.title == "UICollectionView"{ let flowlayout = UICollectionViewFlowLayout(); flowlayout.scrollDirection = UICollectionViewScrollDirection.Vertical let collectionView = UICollectionView(frame: self.view.bounds,collectionViewLayout: flowlayout) collectionView.backgroundColor = UIColor.whiteColor() collectionView.delegate = self collectionView.dataSource = self self.view.addSubview(collectionView) collectionView.registerClass(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "ReuseIdentifier") } } func ButtonClicked(sender: UIButton!) { print("按钮点击事件处理") } func shouActionSheet(sender: UIButton){ /* let alert = UIAlertController(title: "I'm title", message: "choose", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "YES", style: .Default, handler: nil)) alert.addAction(UIAlertAction(title: "NO", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) */ let alertView = UIAlertView() alertView.title = "I'm title" alertView.message = "I'm message" alertView.addButtonWithTitle("OK") alertView.addButtonWithTitle("NO") alertView.show() } // UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 30 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ReuseIdentifier", forIndexPath: indexPath) as! CustomCollectionViewCell cell.imageView?.image = UIImage.init(named: "0.jpg") // cell.imageView?.image = UIImage(named: String(format: "%ld.jpg", indexPath.row)) cell.imageView?.userInteractionEnabled = true return cell } // UICollectionViewDelegateFlowLayout methods func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(90, 90); } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0); } // UICollectionViewDelegate method func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print("点击了第\(indexPath.row + 1)张") } }
apache-2.0
silan-liu/SwiftDanmuView
SwiftDanmuView/AppDelegate.swift
1
2174
// // AppDelegate.swift // SwiftDanmuView // // Created by liusilan on 2017/4/12. // Copyright © 2017年 silan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
dalu93/SwiftHelpSet
SwiftHelpSetTests/CompletionTestCases.swift
1
938
// // CompletionTestCases.swift // SwiftHelpSet // // Created by Luca D'Alberti on 8/29/16. // Copyright © 2016 dalu93. All rights reserved. // import XCTest @testable import SwiftHelpSet class CompletionTestCases: XCTestCase { var status: Completion<Int> = .success(0) override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testSuccess() { let value = 1 status = .success(value) XCTAssert(status.isSuccess == true && status.isFailed == false && status.value == value, "Current success status is invalid") } func testFailed() { let error = NSError(domain: "TestCompletion", code: -1, userInfo: nil) status = .failed(error) XCTAssert(status.isFailed == true && status.isSuccess == false && status.error == error, "Current failed status is invalid") } }
mit
sxend/FrameworkBenchmarks
frameworks/Swift/kitura/Sources/TechEmpowerCommon/Error.swift
23
1273
/* * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// Represents various errors that can occur with the Kitura TechEmpower benchmark. public enum AppError: Error { /// An error occurring when executing a raw SQL query against a database. case DBError(String, query: String) /// An error occurring when executing a Kuery operation against a database. case DBKueryError(String) /// An error occurring when the format of the data retrieved by a database /// operation was not as expected. case DataFormatError(String) /// An error occurring when a connection to the database cannot be established. case ConnectionError(String) /// Any other type of error case OtherError(String) }
bsd-3-clause
dsmelov/simsim
SimSim/Tools.swift
1
8261
// // Tools.swift // SimSim // // Created by Daniil Smelov on 16/04/2018. // Copyright © 2018 Daniil Smelov. All rights reserved. // import Foundation import Cocoa //============================================================================ class Tools: NSObject { //---------------------------------------------------------------------------- struct Keys { static let fileName = "fileName" static let fileDate = "modificationDate" static let fileType = "fileType" } //---------------------------------------------------------------------------- class func homeDirectoryPath() -> String { return NSHomeDirectory() } //---------------------------------------------------------------------------- class func simulatorRootPath(byUUID uuid: String) -> String { return Tools.homeDirectoryPath() + "/" + Constants.Simulator.rootPath + "/" + uuid + "/" } //---------------------------------------------------------------------------- class func getSimulatorProperties() -> NSDictionary? { let path = Tools.homeDirectoryPath() + "/Library/Preferences/com.apple.iphonesimulator.plist" return NSDictionary(contentsOfFile: path) } //---------------------------------------------------------------------------- class func simulatorPaths() -> Set<String> { let properties = getSimulatorProperties() var simulatorPaths = Set<String>() if let currentSimulatorUuid = properties?["CurrentDeviceUDID"] as? String { _ = simulatorPaths.insert(simulatorRootPath(byUUID: currentSimulatorUuid)) } if let devicePreferences = properties?["DevicePreferences"] as? NSDictionary { // we're running on xcode 9 for uuid: NSString in devicePreferences.allKeys as! [NSString] { _ = simulatorPaths.insert(self.simulatorRootPath(byUUID: uuid as String)) } } return simulatorPaths } //---------------------------------------------------------------------------- class func activeSimulators() -> [Simulator] { let paths = self.simulatorPaths() var simulators = [Simulator]() for path in paths { let propertiesPath = path + Constants.Simulator.deviceProperties guard let properties = NSDictionary(contentsOfFile: propertiesPath) as? [AnyHashable : Any] else { continue } let simulator = Simulator(dictionary: properties, path: path) simulators.append(simulator) } return simulators } //---------------------------------------------------------------------------- class func validApplication(_ application: Application) -> Bool { guard application.bundleName != nil else { return false } guard application.version != nil else { return false } guard !application.isAppleApplication else { return false } return true } //---------------------------------------------------------------------------- class func installedApps(on simulator: Simulator) -> [Application] { let installedApplicationsDataPath = simulator.path + ("data/Containers/Data/Application/") let installedApplications = Tools.getSortedFiles(fromFolder: installedApplicationsDataPath) let userApplications = installedApplications .compactMap { Application(dictionary: $0, simulator: simulator) } .filter { !$0.isAppleApplication } return userApplications } //---------------------------------------------------------------------------- class func sharedAppGroups(on simulator: Simulator) -> [AppGroup] { let appGroupsDataPath = simulator.path + ("data/Containers/Shared/AppGroup/") let appGroups = Tools.getSortedFiles(fromFolder: appGroupsDataPath) return appGroups .compactMap { AppGroup(dictionary: $0 as! [AnyHashable: Any], simulator: simulator) } .filter { !$0.isAppleAppGroup } } //---------------------------------------------------------------------------- class func appExtensions(on simulator: Simulator) -> [AppExtension] { let appExtensionsDataPath = simulator.path + ("data/Containers/Data/PluginKitPlugin/") let appExtensions = Tools.getSortedFiles(fromFolder: appExtensionsDataPath) return appExtensions .compactMap { AppExtension(dictionary: $0 as! [AnyHashable: Any], simulator: simulator) } .filter { !$0.isAppleExtension } } //---------------------------------------------------------------------------- class func commanderOneAvailable() -> Bool { let fileManager = FileManager.default // Check for App Store version let isApplicationExist: Bool = fileManager.fileExists(atPath: Constants.Paths.commanderOneApp) let isApplicationProExist: Bool = fileManager.fileExists(atPath: Constants.Paths.commanderOneProApp) if isApplicationExist || isApplicationProExist { return true } // Check for version from Web let plistPath = NSHomeDirectory() + "/" + Constants.Other.commanderOnePlist let isPlistExist: Bool = fileManager.fileExists(atPath: plistPath) return isPlistExist } //---------------------------------------------------------------------------- class func allFilesAt(path: String) -> [String] { let files = try? FileManager.default.contentsOfDirectory(atPath: path) return files ?? [] } //---------------------------------------------------------------------------- class func getFiles(fromFolder folderPath: String) -> [NSDictionary] { let files = allFilesAt(path: folderPath) var filesAndProperties: [NSDictionary] = [] for file in files { if !(file == Constants.Other.dsStore) { let filePath = folderPath + "/" + file let properties = try? FileManager.default.attributesOfItem(atPath: filePath) let modificationDate = properties![.modificationDate] as! Date let fileType = properties![.type] as! String filesAndProperties.append([ Keys.fileName : file, Keys.fileDate : modificationDate, Keys.fileType : fileType ]) } } return filesAndProperties } //---------------------------------------------------------------------------- class func getName(from file: NSDictionary) -> NSString { return file.object(forKey: Keys.fileName) as! NSString } //---------------------------------------------------------------------------- class func getSortedFiles(fromFolder folderPath: String) -> [NSDictionary] { let filesAndProperties = getFiles(fromFolder: folderPath) let sortedFiles = filesAndProperties.sorted(by: { path1, path2 in guard let date1 = path1[Keys.fileDate] as? Date, let date2 = path2[Keys.fileDate] as? Date else { return false } return date1 < date2 }) return sortedFiles } //---------------------------------------------------------------------------- class func getApplicationFolder(fromPath folderPath: String) -> String { return allFilesAt(path: folderPath) .first(where: { URL(fileURLWithPath: $0).pathExtension == "app" })! } }
mit
shabib87/SHVideoPlayer
SHVideoPlayer/Classes/SHVideoPlayerOrientationHandler.swift
1
2154
// // SHVideoPlayerOrientationHandler.swift // Pods // // Created by shabib hossain on 2/11/17. // // import Foundation import UIKit final class SHVideoPlayerOrientationHandler { public var isLandscape: Bool { get { return UIApplication.shared.statusBarOrientation.isLandscape } } private var playerControl: SHVideoPlayerControl! init(playerControlView playerControl: SHVideoPlayerControl) { self.playerControl = playerControl self.addPlayerControlFullScreenButtonAction() self.addOrientationChangedNotification() } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) } private func addPlayerControlFullScreenButtonAction() { playerControl.fullScreenButton?.addTarget(self, action: #selector(self.fullScreenAction(_:)), for: .touchUpInside) playerControl.updateUI(!isLandscape) } private func addOrientationChangedNotification() { NotificationCenter.default.addObserver(self, selector: #selector(self.onOrientationChanged), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) } @objc private func onOrientationChanged() { playerControl.updateUI(!isLandscape) } @objc private func fullScreenAction(_ button: Any?) { playerControl.updateUI(!isLandscape) if isLandscape { rotatePortraitAction() } else { rotateLandscapeAction() } } private func rotatePortraitAction() { UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") UIApplication.shared.isStatusBarHidden = false UIApplication.shared.statusBarOrientation = .portrait } private func rotateLandscapeAction() { UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation") UIApplication.shared.isStatusBarHidden = false UIApplication.shared.statusBarOrientation = .landscapeRight } }
mit
rumana1411/Giphying
SwappingCollectionView/BackTableViewController.swift
1
6859
// // BackTableViewController.swift // swRevealSlidingMenu // // Created by Rumana Nazmul on 20/6/17. // Copyright © 2017 ALFA. All rights reserved. // import UIKit class BackTableViewController: UITableViewController { var menuArray = ["Home","Level","Album","Score","About", "Help"] var controllers = ["ViewController","LvlViewController","AlbumViewController","ScrViewController","AboutViewController","HelpViewController"] var menuIcon = ["iconsHome","iconsLevel","iconsAbout","iconsScore","iconsAbout","iconsHelp"] var frontNVC: UINavigationController? var frontVC: ViewController? override func viewDidLoad() { super.viewDidLoad() let logo = UIImage(named: "Logo.png") let logoImgView = UIImageView(image: logo) logoImgView.frame = CGRect(x: 100, y: 10, width: 10, height: 40 ) self.navigationItem.titleView = logoImgView } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell var imgName = menuIcon[indexPath.row] + ".png" cell.myImgView.image = UIImage(named: imgName) cell.myLbl.text = menuArray[indexPath.row] return cell } // override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // // let revealViewController: SWRevealViewController = self.revealViewController() // // let cell:CustomTableViewCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // // // // // if cell.myLbl.text == "Home"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "Level"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "LvlViewController") as! LvlViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // if cell.myLbl.text == "Album"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AlbumViewController") as! AlbumViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "Score"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ScrViewController") as! ScrViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "About"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // } // // } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //tableView.deselectRow(at: indexPath, animated: true) var controller: UIViewController? = nil switch indexPath.row { case 0: controller = frontVC default: // Instantiate the controller to present let storyboard = UIStoryboard(name: "Main", bundle: nil) controller = storyboard.instantiateViewController(withIdentifier: controllers[indexPath.row]) break } if controller != nil { // Prevent stacking the same controller multiple times _ = frontNVC?.popViewController(animated: false) // Prevent pushing twice FrontTableViewController if !(controller is ViewController) { // Show the controller with the front view controller's navigation controller frontNVC!.pushViewController(controller!, animated: false) } // Set front view controller's position to left revealViewController().setFrontViewPosition(.left, animated: true) } } // override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // // var headerTitle: String! // headerTitle = "Giphying" // return headerTitle // } // override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // // // let headerView = UIView() // // // headerView.backgroundColor = UIColor.white // let viewImg = UIImage(named: "Logo.png") // let headerImgView = UIImageView(image: viewImg) // headerImgView.frame = CGRect(x: 60, y: 10, width: 120, height: 100) // headerView.addSubview(headerImgView) // // return headerView // // // } // // override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // // // return 110 // } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 112 } }
mit
izotx/iTenWired-Swift
Conference App/ItenWiredBeacon.swift
1
3116
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // // ItenWiredBeacon.swift // Conference App // // Created by Felipe on 7/7/16. // // import Foundation import JMCiBeaconManager enum ItenWiredBeaconEnum : String { case id case udid case minor case major case name } class ItenWiredBeacon : iBeacon { /// Date the beacon was last ranged internal var lastRanged : NSDate! /** Initializes the Beacon with the data provided in the dictionary */ init(dictionary: NSDictionary) { var minor = 0 var major = 0 var id:String = "" var uuid = "" if let unwrapedMinor = dictionary.objectForKey(ItenWiredBeaconEnum.minor.rawValue) as? Int { minor = unwrapedMinor } if let unwrapedMajor = dictionary.objectForKey(ItenWiredBeaconEnum.major.rawValue) as? Int { major = unwrapedMajor } if let unwrapedID = dictionary.objectForKey(ItenWiredBeaconEnum.id.rawValue) as? String { id = unwrapedID } if let unwrapedUdid = dictionary.objectForKey(ItenWiredBeaconEnum.udid.rawValue) as? String { uuid = unwrapedUdid } super.init(minor: UInt16(minor), major: UInt16(major), proximityId:uuid, id:id) } init(with beacon: iBeacon){ super.init(minor: beacon.minor, major: beacon.major, proximityId: beacon.UUID, id: beacon.id) self.proximity = beacon.proximity } }
bsd-2-clause
satorun/designPattern
AbstractFactory/AbstractFactory/Factory.swift
1
508
// // Factory.swift // AbstractFactory // // Created by satorun on 2016/02/03. // Copyright © 2016年 satorun. All rights reserved. // import Foundation class Factory { func createLink(caption: String, url: String) -> Link { fatalError("override createLink") } func createTray(caption: String) -> Tray { fatalError("createTray") } func createPage(title: String, author: String) -> Page { fatalError("createPage") } required init() { } }
mit
to4iki/conference-app-2017-ios
conference-app-2017/data/repository/SessionRepository.swift
1
1499
import OctavKit import RxSwift struct SessionRepository: Repository { private let localDataStore: SessionLocalDataStore private let remoteDataStore: SessionRemoteDataStore private let disposeBag = DisposeBag() init( localDataStore: SessionLocalDataStore = SessionLocalDataStore.shared, remoteDataStore: SessionRemoteDataStore = SessionRemoteDataStore.shared) { self.localDataStore = localDataStore self.remoteDataStore = remoteDataStore } func findAll() -> Single<[Session]> { return localDataStore.findAll().catchError { _ in self.remoteDataStore.findAll().map { sessions in self.storeToLocalDataStore(sessions) return sessions } } } func update() { remoteDataStore.findAll().subscribe { observer in switch observer { case .success(let sessions): self.storeToLocalDataStore(sessions) case .error(let error): log.error("remoteDataStore error: \(error.localizedDescription)") } } .disposed(by: disposeBag) } private func storeToLocalDataStore(_ value: [Session]) { self.localDataStore.store(value).subscribe( onCompleted: { _ in log.debug("localDataStore store completed") }, onError: { error in log.error("localDataStore error: \(error.localizedDescription)") } ).disposed(by: self.disposeBag) } }
apache-2.0
erikmartens/NearbyWeather
NearbyWeather/Commons/Core User Interface Building Blocks/MapView/BaseMapViewSelectionDelegate.swift
1
334
// // BaseMapViewSelectionDelegate.swift // NearbyWeather // // Created by Erik Maximilian Martens on 10.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import MapKit protocol BaseMapViewSelectionDelegate: AnyObject { func didSelectView(for annotationViewModel: BaseAnnotationViewModelProtocol) }
mit
2345Team/Swifter-Tips
5.Tuple/5.Tuple/ViewController.swift
1
2272
// // ViewController.swift // 5.Tuple // // Created by luzhiyong on 16/6/15. // Copyright © 2016年 2345. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var a = 3 var b = 4 swapMe(&a, b: &b) print(a) print(b) swapMe2(&a, b: &b) print(a) print(b) // 利用元组同时返回多个值,从而解决了在Objective-C中返回值只能有一个而造成的一些问题 // var areaOne: CGRect = CGRectMake(0, 0, 0, 0) // var areaTwo: CGRect = CGRectMake(0, 0, 0, 0) // // CGRectDivide(self.view.bounds, &areaOne, &areaTwo, self.view.bounds.size.width * 0.3, .MinXEdge) // // let viewOne = UIView() // viewOne.frame = areaOne // viewOne.backgroundColor = UIColor.redColor() // self.view.addSubview(viewOne) // // let viewTwo = UIView() // viewTwo.frame = areaTwo // viewTwo.backgroundColor = UIColor.yellowColor() // self.view.addSubview(viewTwo) var (areaOne, areaTwo) = CGRectDivide(self.view.bounds, amount: self.view.bounds.size.width * 0.3, edge: .MinXEdge) let viewOne = UIView() viewOne.frame = areaOne viewOne.backgroundColor = UIColor.redColor() self.view.addSubview(viewOne) let viewTwo = UIView() viewTwo.frame = areaTwo viewTwo.backgroundColor = UIColor.yellowColor() self.view.addSubview(viewTwo) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /*! 普通实现方法 - parameter a: 参数a - parameter b: 参数b */ func swapMe<T>(inout a: T, inout b: T) { let tmp = a a = b b = tmp } /*! 高级实现方法 - parameter a: 参数a - parameter b: 参数b */ func swapMe2<T>(inout a: T, inout b: T) { (a,b) = (b,a) } }
mit
ahernandezlopez/Preacher
Preacher/Comparison/StringComparisonModifier.swift
1
1778
// // StringComparisonModifier.swift // Preacher // // Created by Albert Hernández López on 7/6/15. // Copyright (c) 2015 Albert Hernández López. All rights reserved. // /** Lists all string comparison modifier options. - None: No modifiers. - CaseInsensitivity: Case insensitive. - DiacriticInsensitivity: Diacritic insensitive. */ public struct StringComparisonModifier: RawOptionSetType, BooleanType, Printable { public static var None: StringComparisonModifier { return self(rawValue: 0b00) } public static var CaseInsensitivity: StringComparisonModifier { return self(rawValue: 0b01) } public static var DiacriticInsensitivity: StringComparisonModifier { return self(rawValue: 0b10) } // MARK: - RawRepresentable public var rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } // MARK: - NilLiteralConvertible public init(nilLiteral: ()) { self.rawValue = 0 } // MARK: - BitwiseOperationsType public static var allZeros: StringComparisonModifier { return StringComparisonModifier.None } // MARK: - BooleanType public var boolValue: Bool { return rawValue != 0 } // MARK: - Printable public var description: String { var modifiersStr = "" if self & StringComparisonModifier.CaseInsensitivity { modifiersStr += "c" } if self & StringComparisonModifier.DiacriticInsensitivity { modifiersStr += "d" } if modifiersStr.isEmpty { return "" } else { return "[\(modifiersStr)]" } } }
mit
nervousnet/nervousnet-iOS
nervous/Controllers/RegisterController.swift
1
296
// // RegisterController.swift // nervousnet // // Created by spadmin on 31/03/16. // Copyright © 2016 ethz. All rights reserved. // import Foundation // this is used to add virtual sensors that developers // want to add to the nervousne system class RegisterController : NSObject { }
gpl-3.0
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Views/LoaderView/EYELoaderView.swift
1
2257
// // EYELoaderView.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/17. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit class EYELoaderView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.addSubview(eyeBackgroundLoaderView) self.addSubview(eyeCenterLoaderView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startLoadingAnimation() { self.hidden = false let animation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = M_PI * 2 animation.duration = 2 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.repeatCount = HUGE animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false self.eyeCenterLoaderView.layer.addAnimation(animation, forKey: animation.keyPath) } func stopLoadingAnimation() { // self.hidden = true self.eyeCenterLoaderView.layer.removeAllAnimations() } /// 外面眼圈 private lazy var eyeBackgroundLoaderView : UIImageView = { let eyeBackgroundLoaderView = UIImageView(image: UIImage(named: "ic_eye_black_outer")) eyeBackgroundLoaderView.frame = CGRect(x: 0, y: 0, width: self.height,height: self.height) eyeBackgroundLoaderView.center = self.center eyeBackgroundLoaderView.contentMode = .ScaleAspectFit eyeBackgroundLoaderView.layer.allowsEdgeAntialiasing = true return eyeBackgroundLoaderView; }() /// 中间眼球 private lazy var eyeCenterLoaderView : UIImageView = { let eyeCenterLoaderView = UIImageView(image: UIImage(named: "ic_eye_black_inner")) eyeCenterLoaderView.frame = CGRect(x: 0, y: 0, width: self.height - UIConstant.UI_MARGIN_5, height: self.height - UIConstant.UI_MARGIN_5) eyeCenterLoaderView.center = self.center eyeCenterLoaderView.contentMode = .ScaleAspectFit eyeCenterLoaderView.layer.allowsEdgeAntialiasing = true return eyeCenterLoaderView; }() }
mit
ashfurrow/RxSwift
RxTests/RxSwiftTests/Tests/Observable+BlockingTest.swift
2
7599
// // Observable+BlockingTest.swift // RxTests // // Created by Krunoslav Zaher on 7/12/15. // // import Foundation import RxSwift import RxBlocking import XCTest class ObservableBlockingTest : RxTest { } // toArray extension ObservableBlockingTest { func testToArray_empty() { XCTAssert(try! (empty() as Observable<Int>).toBlocking().toArray() == []) } func testToArray_return() { XCTAssert(try! just(42).toBlocking().toArray() == [42]) } func testToArray_fail() { do { try (failWith(testError) as Observable<Int>).toBlocking().toArray() XCTFail("It should fail") } catch let e { XCTAssertTrue(e as NSError === testError) } } func testToArray_someData() { XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().toArray() == [42, 43, 44, 45]) } func testToArray_withRealScheduler() { let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default) let array = try! interval(0.001, scheduler) .take(10) .toBlocking() .toArray() XCTAssert(array == Array(0..<10)) } } // first extension ObservableBlockingTest { func testFirst_empty() { XCTAssert(try! (empty() as Observable<Int>).toBlocking().first() == nil) } func testFirst_return() { XCTAssert(try! just(42).toBlocking().first() == 42) } func testFirst_fail() { do { try (failWith(testError) as Observable<Int>).toBlocking().first() XCTFail() } catch let e { XCTAssertTrue(e as NSError === testError) } } func testFirst_someData() { XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().first() == 42) } func testFirst_withRealScheduler() { let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default) let array = try! interval(0.001, scheduler) .take(10) .toBlocking() .first() XCTAssert(array == 0) } } // last extension ObservableBlockingTest { func testLast_empty() { XCTAssert(try! (empty() as Observable<Int>).toBlocking().last() == nil) } func testLast_return() { XCTAssert(try! just(42).toBlocking().last() == 42) } func testLast_fail() { do { try (failWith(testError) as Observable<Int>).toBlocking().last() XCTFail() } catch let e { XCTAssertTrue(e as NSError === testError) } } func testLast_someData() { XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().last() == 45) } func testLast_withRealScheduler() { let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default) let array = try! interval(0.001, scheduler) .take(10) .toBlocking() .last() XCTAssert(array == 9) } } // single extension ObservableBlockingTest { func testSingle_empty() { do { try (empty() as Observable<Int>).toBlocking().single() XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code) } } func testSingle_return() { XCTAssert(try! just(42).toBlocking().single() == 42) } func testSingle_two() { do { try (sequenceOf(42, 43) as Observable<Int>).toBlocking().single() XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code) } } func testSingle_someData() { do { try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single() XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code) } } func testSingle_fail() { do { try (failWith(testError) as Observable<Int>).toBlocking().single() XCTFail() } catch let e { XCTAssertTrue(e as NSError === testError) } } func testSingle_withRealScheduler() { let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default) let array = try! interval(0.001, scheduler) .take(1) .toBlocking() .single() XCTAssert(array == 0) } func testSingle_predicate_empty() { do { try (empty() as Observable<Int>).toBlocking().single { _ in true } XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code) } } func testSingle_predicate_return() { XCTAssert(try! just(42).toBlocking().single( { _ in true } ) == 42) } func testSingle_predicate_someData_one_match() { var predicateVals = [Int]() do { try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in predicateVals.append(e) return e == 44 } ) } catch _ { XCTFail() } XCTAssertEqual(predicateVals, [42, 43, 44, 45]) } func testSingle_predicate_someData_two_match() { var predicateVals = [Int]() do { try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in predicateVals.append(e) return e >= 43 } ) XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code) } XCTAssertEqual(predicateVals, [42, 43, 44]) } func testSingle_predicate_none() { var predicateVals = [Int]() do { try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in predicateVals.append(e) return e > 50 } ) XCTFail() } catch let e { XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code) } XCTAssertEqual(predicateVals, [42, 43, 44, 45]) } func testSingle_predicate_throws() { var predicateVals = [Int]() do { try (sequenceOf(42, 43, 44, 45, scheduler: CurrentThreadScheduler.instance) as Observable<Int>).toBlocking().single( { e in predicateVals.append(e) if e < 43 { return false } throw testError } ) XCTFail() } catch let e { XCTAssertTrue(e as NSError === testError) } XCTAssertEqual(predicateVals, [42, 43]) } func testSingle_predicate_fail() { do { try (failWith(testError) as Observable<Int>).toBlocking().single( { _ in true } ) XCTFail() } catch let e { XCTAssertTrue(e as NSError === testError) } } func testSingle_predicate_withRealScheduler() { let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default) let array = try! interval(0.001, scheduler) .take(4) .toBlocking() .single( { $0 == 3 } ) XCTAssert(array == 3) } }
mit
arrrnas/vinted-ab-ios
Carthage/Checkouts/BigInt/sources/BigUInt.swift
1
11407
// // BigUInt.swift // BigInt // // Created by Károly Lőrentey on 2015-12-26. // Copyright © 2016 Károly Lőrentey. // /// An arbitary precision unsigned integer type, also known as a "big integer". /// /// Operations on big integers never overflow, but they might take a long time to execute. /// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers. /// /// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper /// around `Array<UInt64>`. In fact, `BigUInt` implements a mutable collection of its `UInt64` digits, with the /// digit at index 0 being the least significant. /// /// To make memory management simple, `BigUInt` allows you to subscript it with out-of-bounds indexes: /// the subscript getter zero-extends the digit sequence, while the subscript setter automatically extends the /// underlying storage when necessary: /// /// ```Swift /// var number = BigUInt(1) /// number[42] // Not an error, returns 0 /// number[23] = 1 // Not an error, number is now 2^1472 + 1. /// ``` /// /// Note that it is rarely a good idea to use big integers as collections; in the vast majority of cases it is much /// easier to work with the provided high-level methods and operators rather than with raw big digits. public struct BigUInt { /// The type representing a digit in `BigUInt`'s underlying number system. public typealias Digit = UIntMax internal var _digits: [Digit] internal var _start: Int internal var _end: Int internal init(digits: [Digit], start: Int, end: Int) { precondition(start >= 0 && start <= end) let start = Swift.min(start, digits.count) var end = Swift.min(end, digits.count) while end > start && digits[end - 1] == 0 { end -= 1 } self._digits = digits self._start = start self._end = end } /// Initializes a new BigUInt with value 0. public init() { self.init([]) } /// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant. public init(_ digits: [Digit]) { self.init(digits: digits, start: 0, end: digits.count) } /// Initializes a new BigUInt that has the supplied value. public init<I: UnsignedInteger>(_ integer: I) { self.init(Digit.digitsFromUIntMax(integer.toUIntMax())) } /// Initializes a new BigUInt that has the supplied value. /// /// - Requires: integer >= 0 public init<I: SignedInteger>(_ integer: I) { precondition(integer >= 0) self.init(UIntMax(integer.toIntMax())) } } extension BigUInt: ExpressibleByIntegerLiteral { //MARK: Init from Integer literals /// Initialize a new big integer from an integer literal. public init(integerLiteral value: UInt64) { self.init(value.toUIntMax()) } } extension BigUInt: ExpressibleByStringLiteral { //MARK: Init from String literals /// Initialize a new big integer from a Unicode scalar. /// The scalar must represent a decimal digit. public init(unicodeScalarLiteral value: UnicodeScalar) { self = BigUInt(String(value), radix: 10)! } /// Initialize a new big integer from an extended grapheme cluster. /// The cluster must consist of a decimal digit. public init(extendedGraphemeClusterLiteral value: String) { self = BigUInt(value, radix: 10)! } /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. /// The string must contain only decimal digits. public init(stringLiteral value: StringLiteralType) { self = BigUInt(value, radix: 10)! } } extension BigUInt: IntegerArithmetic { /// Explicitly convert to `IntMax`, trapping on overflow. public func toIntMax() -> IntMax { precondition(count <= 1) return IntMax(self[0]) } } extension BigUInt { //MARK: Lift and shrink /// True iff this integer is not a slice. internal var isTop: Bool { return _start == 0 && _end == _digits.count } /// Ensures that this integer is not a slice, allocating a new digit array if necessary. internal mutating func lift() { guard !isTop else { return } _digits = Array(self) _start = 0 _end = _digits.count } /// Gets rid of leading zero digits in the digit array. internal mutating func shrink() { assert(isTop) while _digits.last == 0 { _digits.removeLast() } _end = _digits.count } } extension BigUInt: RandomAccessCollection { //MARK: Collection /// Big integers implement `Collection` to provide access to their big digits, indexed by integers; a zero index refers to the least significant digit. public typealias Index = Int /// The type representing the number of steps between two indices. public typealias IndexDistance = Int /// The type representing valid indices for subscripting the collection. public typealias Indices = CountableRange<Int> /// The type representing the iteration interface for the digits in a big integer. public typealias Iterator = DigitIterator<Digit> /// Big integers can be contiguous digit subranges of another big integer. public typealias SubSequence = BigUInt public var indices: Indices { return startIndex ..< endIndex } /// The index of the first digit, starting from the least significant. (This is always zero.) public var startIndex: Int { return 0 } /// The index of the digit after the most significant digit in this integer. public var endIndex: Int { return count } /// The number of digits in this integer, excluding leading zero digits. public var count: Int { return _end - _start } /// Return a generator over the digits of this integer, starting at the least significant digit. public func makeIterator() -> DigitIterator<Digit> { return DigitIterator(digits: _digits, end: _end, index: _start) } /// Returns the position immediately after the given index. public func index(after i: Int) -> Int { return i + 1 } /// Returns the position immediately before the given index. public func index(before i: Int) -> Int { return i - 1 } /// Replaces the given index with its successor. public func formIndex(after i: inout Int) { i += 1 } /// Replaces the given index with its predecessor. public func formIndex(before i: inout Int) { i -= 1 } /// Returns an index that is the specified distance from the given index. public func index(_ i: Int, offsetBy n: Int) -> Int { return i + n } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. public func index(_ i: Int, offsetBy n: Int, limitedBy limit: Int) -> Int? { let r = i + n if n >= 0 { return r <= limit ? r : nil } return r >= limit ? r : nil } /// Returns the number of steps between two indices. public func distance(from start: Int, to end: Int) -> Int { return end - start } /// Get or set a digit at a given index. /// /// - Note: Unlike a normal collection, it is OK for the index to be greater than or equal to `endIndex`. /// The subscripting getter returns zero for indexes beyond the most significant digit. /// Setting these extended digits automatically appends new elements to the underlying digit array. /// - Requires: index >= 0 /// - Complexity: The getter is O(1). The setter is O(1) if the conditions below are true; otherwise it's O(count). /// - The integer's storage is not shared with another integer /// - The integer wasn't created as a slice of another integer /// - `index < count` public subscript(index: Int) -> Digit { get { precondition(index >= 0) let i = _start + index return (i < Swift.min(_end, _digits.count) ? _digits[i] : 0) } set(digit) { precondition(index >= 0) lift() let i = _start + index if i < _end { _digits[i] = digit if digit == 0 && i == _end - 1 { shrink() } } else { guard digit != 0 else { return } while _digits.count < i { _digits.append(0) } _digits.append(digit) _end = i + 1 } } } /// Returns an integer built from the digits of this integer in the given range. public subscript(bounds: Range<Int>) -> BigUInt { get { return BigUInt(digits: _digits, start: _start + bounds.lowerBound, end: _start + bounds.upperBound) } } } /// State for iterating through the digits of a big integer. public struct DigitIterator<Digit>: IteratorProtocol { internal let digits: [Digit] internal let end: Int internal var index: Int /// Return the next digit in the integer, or nil if there are no more digits. /// Returned digits range from least to most significant. public mutating func next() -> Digit? { guard index < end else { return nil } let v = digits[index] index += 1 return v } } extension BigUInt: Strideable { /// A type that can represent the distance between two values of `BigUInt`. public typealias Stride = BigInt /// Adds `n` to `self` and returns the result. Traps if the result would be less than zero. public func advanced(by n: BigInt) -> BigUInt { return n < 0 ? self - n.abs : self + n.abs } /// Returns the (potentially negative) difference between `self` and `other` as a `BigInt`. Never traps. public func distance(to other: BigUInt) -> BigInt { return BigInt(other) - BigInt(self) } } extension BigUInt { //MARK: Low and High /// Split this integer into a high-order and a low-order part. /// /// - Requires: count > 1 /// - Returns: `(low, high)` such that /// - `self == low.add(high, atPosition: middleIndex)` /// - `high.width <= floor(width / 2)` /// - `low.width <= ceil(width / 2)` /// - Complexity: Typically O(1), but O(count) in the worst case, because high-order zero digits need to be removed after the split. internal var split: (high: BigUInt, low: BigUInt) { precondition(count > 1) let mid = middleIndex return (self[mid ..< count], self[0 ..< mid]) } /// Index of the digit at the middle of this integer. /// /// - Returns: The index of the digit that is least significant in `self.high`. internal var middleIndex: Int { return (count + 1) / 2 } /// The low-order half of this BigUInt. /// /// - Returns: `self[0 ..< middleIndex]` /// - Requires: count > 1 internal var low: BigUInt { return self[0 ..< middleIndex] } /// The high-order half of this BigUInt. /// /// - Returns: `self[middleIndex ..< count]` /// - Requires: count > 1 internal var high: BigUInt { return self[middleIndex ..< count] } }
mit
JetBrains/kotlin-native
backend.native/tests/framework/kt43517/kt43517.swift
3
562
import Foundation import Kt43517 func testKt43517() throws { try assertEquals( actual: Kt43517Kt.compareEnums(e1: Kt43517Kt.produceEnum(), e2: Kt43517Kt.produceEnum()), expected: true ) try assertEquals( actual: Kt43517Kt.getFirstField(s: Kt43517Kt.getGlobalS()), expected: 3 ) } class Kt43517Tests : TestProvider { var tests: [TestCase] = [] init() { providers.append(self) tests = [ TestCase(name: "Kt43517", method: withAutorelease(testKt43517)), ] } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/Examples/2 - Primitives/TabBarExamples.swift
1
4840
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import SwiftUI struct TabBarExamplesView: View { @State var wallet: AnyHashable = WalletPreviewContainer.Tab.home @State var exchange: AnyHashable = ExchangePreviewContainer.Tab.home var body: some View { NavigationLinkProviderView( data: [ "Examples": [ NavigationLinkProvider( view: WalletPreviewContainer( activeTabIdentifier: wallet, fabIsActive: false ), title: "Wallet" ), NavigationLinkProvider( view: ExchangePreviewContainer( activeTabIdentifier: exchange ), title: "Exchange" ) ] ] ) } struct WalletPreviewContainer: View { enum Tab: Hashable { case home case prices case rewards case activity } @State var activeTabIdentifier: AnyHashable @State var fabIsActive: Bool var body: some View { TabBar( activeTabIdentifier: $activeTabIdentifier, highlightBarVisible: true ) { Text("Home") .tabBarItem( .tab( identifier: Tab.home, icon: .home, title: "Home" ) ) Text("Prices") .tabBarItem( .tab( identifier: Tab.prices, icon: .lineChartUp, title: "Prices" ) ) Text("Foo") .tabBarItem( .fab( identifier: "floatingActionButtonIdentifier", isActive: $fabIsActive, isPulsing: true ) ) Text("Rewards") .tabBarItem( .tab( identifier: Tab.rewards, icon: .interestCircle, title: "Rewards" ) ) Text("Activity") .tabBarItem( .tab( identifier: Tab.activity, icon: .pending, title: "Activity" ) ) } } } struct ExchangePreviewContainer: View { enum Tab: Hashable { case home case trade case portfolio case history case account } @State var activeTabIdentifier: AnyHashable var body: some View { TabBar(activeTabIdentifier: $activeTabIdentifier) { Text("Home") .tabBarItem( .tab( identifier: Tab.home, icon: .home, title: "Home" ) ) Text("Trade") .tabBarItem( .tab( identifier: Tab.trade, icon: .swap, title: "Trade" ) ) Text("Portfolio") .tabBarItem( .tab( identifier: Tab.portfolio, icon: .portfolio, title: "Portfolio" ) ) Text("History") .tabBarItem( .tab( identifier: Tab.history, icon: .pending, title: "History" ) ) Text("Account") .tabBarItem( .tab( identifier: Tab.account, icon: .user, title: "Account" ) ) } } } } struct TabBarExamplesView_Previews: PreviewProvider { static var previews: some View { TabBarExamplesView() } }
lgpl-3.0
toshiapp/toshi-ios-client
Toshi/Extensions/Codable+Parsing.swift
1
1966
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation extension Decodable { static func fromJSONData(_ data: Data, with decoder: JSONDecoder = JSONDecoder(), successCompletion: (Self) -> Void, errorCompletion: ((ToshiError) -> Void)?) { do { let decoded = try decoder.decode(Self.self, from: data) successCompletion(decoded) } catch let error { DLog("Parsing error: \(error)") errorCompletion?(.invalidResponseJSON) } } static func optionalFromJSONData(_ data: Data, with decoder: JSONDecoder = JSONDecoder()) -> Self? { return try? decoder.decode(Self.self, from: data) } } extension Encodable { func toJSONData(with encoder: JSONEncoder = JSONEncoder(), successCompletion: (Data) -> Void, errorCompletion: (Error) -> Void) { do { let encoded = try encoder.encode(self) successCompletion(encoded) } catch let error { errorCompletion(error) } } func toOptionalJSONData(with encoder: JSONEncoder = JSONEncoder()) -> Data? { return try? encoder.encode(self) } }
gpl-3.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureReferral/Sources/FeatureReferralUI/ReferralPopup.swift
1
2987
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import ComposableArchitecture import SwiftUI import UIComponentsKit public struct ReferralPopup: View { let store: Store<ReferFriendState, ReferFriendAction> @Environment(\.presentationMode) var presentationMode @ObservedObject var viewStore: ViewStore<ReferFriendState, ReferFriendAction> public init(store: Store<ReferFriendState, ReferFriendAction>) { self.store = store viewStore = ViewStore(store) } public var body: some View { ZStack { VStack { ZStack { imageSection closeButton } labelsSection buttonsSection .padding(.top, 65) .padding(.bottom, 20) } .frame(maxHeight: .infinity) } .background(Color.WalletSemantic.primary) .onAppear(perform: { viewStore.send(.onAppear) }) .sheet( isPresented: viewStore .binding(\.$isShowReferralViewPresented), content: { ReferFriendView(store: store) } ) } private var imageSection: some View { Image("image_referral_popup", bundle: .module) .resizable() .frame(width: 331, height: 331) } var labelsSection: some View { VStack(spacing: 30, content: { Text(viewStore.referralInfo.rewardTitle) .typography(.title1) .foregroundColor(.white) .multilineTextAlignment(.center) .lineLimit(4) .padding(.horizontal, Spacing.padding3) Text(viewStore.referralInfo.rewardSubtitle) .typography(.paragraph1) .foregroundColor(.white) }) } var closeButton: some View { VStack { HStack { Spacer() Button { presentationMode.wrappedValue.dismiss() } label: { Image("cancel_icon", bundle: Bundle.UIComponents) .renderingMode(.template) .foregroundColor(.white) } } .padding(.top, Spacing.padding3) .padding(.bottom, 400) .padding(.trailing, Spacing.padding3) } } private var buttonsSection: some View { VStack(spacing: 2, content: { PrimaryWhiteButton(title: "Share") { viewStore.send(.onShowRefferalTapped) } .frame(maxWidth: .infinity) .padding(.horizontal, Spacing.padding3) .padding(.bottom, Spacing.padding5) Button("Skip") { presentationMode.wrappedValue.dismiss() } .foregroundColor(.white) }) } }
lgpl-3.0
huonw/swift
validation-test/compiler_crashers_fixed/28728-d-isbeingvalidated-d-hasvalidsignature.swift
42
436
// 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 // RUN: not %target-swift-frontend %s -emit-ir typealias e:a struct A:a{}typealias a=A
apache-2.0
xxxAIRINxxx/ContainerInteractiveTransitionExample
ContainerInteractiveTransitionExample/FirstViewController.swift
1
562
// // FirstViewController.swift // ContainerInteractiveTransitionExample // // Created by xxxAIRINxxx on 2016/06/15. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import UIKit final class FirstViewController: UIViewController { deinit { print("deinit FirstViewController") } @IBAction func push() { if let p = self.parent as? ViewController { p.push() return } if let p = self.navigationController?.parent as? ViewController { p.push() } } }
mit
eofster/Telephone
UseCases/CallHistoryRecord.swift
1
2169
// // CallHistoryRecord.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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 Foundation public struct CallHistoryRecord { public let identifier: String public let uri: URI public let date: Date public let duration: Int public let isIncoming: Bool public let isMissed: Bool public init(uri: URI, date: Date, duration: Int, isIncoming: Bool, isMissed: Bool) { identifier = "\(uri.user)@\(uri.host)|\(date.timeIntervalSinceReferenceDate)|\(duration)|\(isIncoming ? 1 : 0)" self.uri = uri self.date = date self.duration = duration self.isIncoming = isIncoming self.isMissed = isMissed } public func removingHost() -> CallHistoryRecord { return CallHistoryRecord( uri: URI(user: uri.user, host: "", displayName: uri.displayName), date: date, duration: duration, isIncoming: isIncoming, isMissed: isMissed ) } } extension CallHistoryRecord: Equatable { public static func ==(lhs: CallHistoryRecord, rhs: CallHistoryRecord) -> Bool { return lhs.uri == rhs.uri && lhs.date == rhs.date && lhs.duration == rhs.duration && lhs.isIncoming == rhs.isIncoming && lhs.isMissed == rhs.isMissed } } extension CallHistoryRecord { public init(call: Call) { self.init( uri: call.remote, date: call.date, duration: call.duration, isIncoming: call.isIncoming, isMissed: call.isMissed ) } }
gpl-3.0
zmian/xcore.swift
Sources/Xcore/Cocoa/Extensions/UIToolbar+Extensions.swift
1
821
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // import UIKit extension UIToolbar { private enum AssociatedKey { static var isTransparent = "isTransparent" } open var isTransparent: Bool { get { associatedObject(&AssociatedKey.isTransparent, default: false) } set { guard newValue != isTransparent else { return } setAssociatedObject(&AssociatedKey.isTransparent, value: newValue) guard newValue else { setBackgroundImage(nil, forToolbarPosition: .any, barMetrics: .default) return } setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) isTranslucent = true backgroundColor = .clear } } }
mit
makingspace/NetworkingServiceKit
NetworkingServiceKit/Classes/Networking/APIConfigurations.swift
1
2756
// // APIConfiguration.swift // Makespace Inc. // // Created by Phillipe Casorla Sagot (@darkzlave) on 2/27/17. // // import Foundation import Alamofire let APIConfigurationKey = "Server" /// Protocol for describing the necessary authentication key/secret to use when authenticating a client public protocol APIConfigurationAuth { var secret: String { get } var key: String { get } init(bundleId: String?) } /// Protocol for describing a server connection public protocol APIConfigurationType { var URL: String { get } var webURL: String { get } static var defaultConfiguration: APIConfigurationType { get } init(stringKey: String) } /// Handles the current server connection and authentication for a valid APIConfigurationType and APIConfigurationAuth @objc public class APIConfiguration: NSObject { public static var apiConfigurationType: APIConfigurationType.Type? public static var authConfigurationType: APIConfigurationAuth.Type? @objc public let baseURL: String @objc public let webURL: String @objc public let APIKey: String @objc public let APISecret: String internal init(type: APIConfigurationType, auth: APIConfigurationAuth) { self.baseURL = type.URL self.webURL = type.webURL self.APIKey = auth.key self.APISecret = auth.secret } private override init() { self.baseURL = "" self.webURL = "" self.APIKey = "" self.APISecret = "" } /// Returns the current APIConfiguration, either staging or production @objc public static var current: APIConfiguration { return current() } public static func currentConfigurationType(with configuration: APIConfigurationType.Type) -> APIConfigurationType { let environmentDictionary = ProcessInfo.processInfo.environment if let environmentConfiguration = environmentDictionary[APIConfigurationKey] { return configuration.init(stringKey: environmentConfiguration) } return configuration.defaultConfiguration } @objc public static func current(bundleId: String = Bundle.main.appBundleIdentifier) -> APIConfiguration { guard let configurationType = APIConfiguration.apiConfigurationType, let authType = APIConfiguration.authConfigurationType else { fatalError("Error: ServiceLocator couldn't find the current APIConfiguration, make sure to define your own types for APIConfiguration.apiConfigurationType and APIConfiguration.authConfigurationType") } return APIConfiguration(type: self.currentConfigurationType(with: configurationType), auth: authType.init(bundleId: bundleId)) } }
mit
ldt25290/MyInstaMap
ThirdParty/AlamofireImage/Tests/AFError+AlamofireImageTests.swift
4
4133
// // AFError+AlamofireImageTests.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire extension AFError { // ResponseSerializationFailureReason var isInputDataNil: Bool { if case let .responseSerializationFailed(reason) = self, reason.isInputDataNil { return true } return false } var isInputDataNilOrZeroLength: Bool { if case let .responseSerializationFailed(reason) = self, reason.isInputDataNilOrZeroLength { return true } return false } var isInputFileNil: Bool { if case let .responseSerializationFailed(reason) = self, reason.isInputFileNil { return true } return false } var isInputFileReadFailed: Bool { if case let .responseSerializationFailed(reason) = self, reason.isInputFileReadFailed { return true } return false } // ResponseValidationFailureReason var isDataFileNil: Bool { if case let .responseValidationFailed(reason) = self, reason.isDataFileNil { return true } return false } var isDataFileReadFailed: Bool { if case let .responseValidationFailed(reason) = self, reason.isDataFileReadFailed { return true } return false } var isMissingContentType: Bool { if case let .responseValidationFailed(reason) = self, reason.isMissingContentType { return true } return false } var isUnacceptableContentType: Bool { if case let .responseValidationFailed(reason) = self, reason.isUnacceptableContentType { return true } return false } var isUnacceptableStatusCode: Bool { if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true } return false } } // MARK: - extension AFError.ResponseSerializationFailureReason { var isInputDataNil: Bool { if case .inputDataNil = self { return true } return false } var isInputDataNilOrZeroLength: Bool { if case .inputDataNilOrZeroLength = self { return true } return false } var isInputFileNil: Bool { if case .inputFileNil = self { return true } return false } var isInputFileReadFailed: Bool { if case .inputFileReadFailed = self { return true } return false } } // MARK: - extension AFError.ResponseValidationFailureReason { var isDataFileNil: Bool { if case .dataFileNil = self { return true } return false } var isDataFileReadFailed: Bool { if case .dataFileReadFailed = self { return true } return false } var isMissingContentType: Bool { if case .missingContentType = self { return true } return false } var isUnacceptableContentType: Bool { if case .unacceptableContentType = self { return true } return false } var isUnacceptableStatusCode: Bool { if case .unacceptableStatusCode = self { return true } return false } }
mit
coach-plus/ios
Pods/Eureka/Source/Validations/RuleLength.swift
3
3030
// RuleLength.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct RuleMinLength: RuleType { let min: UInt public var id: String? public var validationError: ValidationError public init(minLength: UInt, msg: String? = nil, id: String? = nil) { let ruleMsg = msg ?? "Field value must have at least \(minLength) characters" min = minLength validationError = ValidationError(msg: ruleMsg) self.id = id } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count < Int(min) ? validationError : nil } } public struct RuleMaxLength: RuleType { let max: UInt public var id: String? public var validationError: ValidationError public init(maxLength: UInt, msg: String? = nil, id: String? = nil) { let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters" max = maxLength validationError = ValidationError(msg: ruleMsg) self.id = id } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count > Int(max) ? validationError : nil } } public struct RuleExactLength: RuleType { let length: UInt public var id: String? public var validationError: ValidationError public init(exactLength: UInt, msg: String? = nil, id: String? = nil) { let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters" length = exactLength validationError = ValidationError(msg: ruleMsg) self.id = id } public func isValid(value: String?) -> ValidationError? { guard let value = value else { return nil } return value.count != Int(length) ? validationError : nil } }
mit
LearningSwift2/LearningApps
ReminderApp/ReminderApp/ThemeManager.swift
1
761
// // ThemeManager.swift // SimpleReminders // // Created by Phil Wright on 4/4/16. // Copyright © 2016 Touchopia, LLC. All rights reserved. // import UIKit struct ThemeFont { static let defaultFontName = "Merriweather" static let defaultBoldFontName = "Merriweather-Bold" static let defaultFontSize: CGFloat = 16.0 } class ThemeManager { // Setup ThemeManager as Singleton static let sharedInstance = ThemeManager() private init() {} func defaultFont() -> UIFont? { return UIFont(name: ThemeFont.defaultFontName, size: ThemeFont.defaultFontSize) } func defaultBoldFont() -> UIFont? { return UIFont(name: ThemeFont.defaultBoldFontName, size: ThemeFont.defaultFontSize) } }
apache-2.0
supp-f/SFTouchUI
SFTouchUIDemo/SFTouchUIDemo/ViewController.swift
1
855
// // ViewController.swift // SFTouchUIDemo // // Created by Marat Shilibaev on 13/03/16. // Copyright © 2016 supp-f. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var mainRateStarsView: SFRateStarsView! @IBOutlet weak var displayRateStarsView: SFRateStarsView! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() _setupDisplayStarsView() } // MARK: - Private class logic private func _setupDisplayStarsView() { displayRateStarsView.starsAlignment = .Left displayRateStarsView.style = .Display } // MARK: - Actions @IBAction func onMainRateStarsViewValueChanged(sender: AnyObject) { displayRateStarsView.rateValue = mainRateStarsView.rateValue } }
mit
DanielTomlinson/Persist
Persist/NSManagedObject+Helpers.swift
1
2330
// // NSManagedObject+Helpers.swift // Persist // // Created by Daniel Tomlinson on 13/09/2015. // Copyright © 2015 Daniel Tomlinson. All rights reserved. // import Foundation import CoreData /** ManagedObjectType is a protocol that exposes convenience methods for NSManagedObjects. Default implementations are provided, but they can be overriden by individual classes as needeed. To opt into these methods, add the ManagedObjectType protocol to your NSManagedObject subclass. */ public protocol ManagedObjectType : class { typealias T = Self /** The name of the class in the managed object model. */ static func entityName() -> String /** Create a new instance of the model object in the given context. - parameter context: The NSManagedObjectContext in which to create the object. - returns: A new instance of the model. */ static func create(inContext context: NSManagedObjectContext) -> T /** Create a new fetch request for the entity. */ static func fetchRequest() -> NSFetchRequest /** Create and execute a fetch request with the given predicate to return all matching records of the entity. */ static func findAllMatchingPredicate(predicate: NSPredicate, inContext: NSManagedObjectContext) throws -> [T] } extension ManagedObjectType where Self: NSManagedObject { public static func entityName() -> String { return NSStringFromClass(self) } public static func create(inContext context: NSManagedObjectContext) -> Self { guard let object = NSEntityDescription.insertNewObjectForEntityForName(entityName(), inManagedObjectContext: context) as? Self else { preconditionFailure("Could not find entity named \(entityName()) in context \(context)") } return object } public static func fetchRequest() -> NSFetchRequest { return NSFetchRequest(entityName: entityName()) } public static func findAllMatchingPredicate(predicate: NSPredicate, inContext context: NSManagedObjectContext) throws -> [Self] { let fetchRequest = self.fetchRequest() fetchRequest.predicate = predicate let result = try context.executeFetchRequest(fetchRequest) return result as? [Self] ?? [] } }
mit
mspvirajpatel/SwiftyBase
Example/SwiftyBase/Controller/SideMenu/SideMenuView.swift
1
12766
// // SideMenuView.swift // SwiftyBase // // Created by MacMini-2 on 06/09/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import SwiftyBase import UIKit class SideMenuView: BaseView { // MARK: - Attribute - internal var userProfileView : UIView! private var imgUser : BaseImageView! var lblUserRealName : BaseLabel! var lblUserName: BaseLabel! private var seperatorView : UIView! private var tblMenu : UITableView! private var btnlogin : BaseButton! internal var arrMenuData : NSMutableArray! = NSMutableArray() internal var selectedCell : IndexPath = IndexPath(item: 0, section: 0) internal var selectedMenu : Int = Menu.api.rawValue fileprivate var cellSelecteEvent : TableCellSelectEvent! // MARK: - Lifecycle - init(){ super.init(frame: .zero) self.loadViewControls() self.setViewlayout() self.loadMenuData() } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override func layoutSubviews() { super.layoutSubviews() if imgUser != nil{ imgUser.clipsToBounds = true imgUser.layer.cornerRadius = imgUser.frame.size.width / 2 } } deinit{ print("side menu deinit called") self.releaseObject() } override func releaseObject() { super.releaseObject() } // MARK: - Layout - override func loadViewControls() { super.loadViewControls() self.backgroundColor = AppColor.appPrimaryBG.value userProfileView = UIView() userProfileView.layer .setValue("userProfileView", forKey: ControlConstant.name) userProfileView.translatesAutoresizingMaskIntoConstraints = false userProfileView.backgroundColor = UIColor.clear self.addSubview(userProfileView) btnlogin = BaseButton(ibuttonType: .transparent, iSuperView: userProfileView) btnlogin.backgroundColor = UIColor.clear btnlogin.isHidden = false btnlogin.setButtonTouchUpInsideEvent { [weak self] (sendor, object) in if self == nil{ return } if self!.cellSelecteEvent != nil{ self!.cellSelecteEvent(nil,Menu.api.rawValue as AnyObject) } } imgUser = BaseImageView(type: .defaultImg, superView: userProfileView) imgUser.layer .setValue("imgUser", forKey: ControlConstant.name) imgUser.backgroundColor = UIColor.white imgUser.isHidden = true seperatorView = UIView() seperatorView.layer .setValue("seperatorView", forKey: ControlConstant.name) seperatorView.backgroundColor = AppColor.appSecondaryBG.value seperatorView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(seperatorView) lblUserName = BaseLabel(labelType: .small, superView: userProfileView) lblUserName.layer .setValue("lblUserName", forKey: ControlConstant.name) lblUserName.text = "" lblUserName.textColor = AppColor.appSecondaryBG.value lblUserName.isHidden = true lblUserName.textAlignment = .left lblUserRealName = BaseLabel(labelType: .large, superView: userProfileView) lblUserRealName.layer .setValue("lblUserRealName", forKey: ControlConstant.name) lblUserRealName.text = "" lblUserRealName.textColor = AppColor.appSecondaryBG.value lblUserRealName.isHidden = true tblMenu = UITableView(frame: .zero, style: .grouped) tblMenu.layer .setValue("tblMenu", forKey: ControlConstant.name) tblMenu.translatesAutoresizingMaskIntoConstraints = false tblMenu.backgroundColor = UIColor.clear tblMenu.separatorStyle = .none tblMenu.cellLayoutMarginsFollowReadableWidth = false tblMenu.alwaysBounceVertical = false tblMenu.delegate = self tblMenu.dataSource = self tblMenu.tableFooterView = UIView(frame: .zero) tblMenu.register(LeftMenuCell.self, forCellReuseIdentifier: CellIdentifire.leftMenu) self.addSubview(tblMenu) } override func setViewlayout() { super.setViewlayout() baseLayout.viewDictionary = self.getDictionaryOfVariableBindings(superView: self, viewDic: NSDictionary()) as? [String : AnyObject] baseLayout.metrics = ["hSpace" : ControlConstant.horizontalPadding, "vSpace" : ControlConstant.verticalPadding / 2] baseLayout.control_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|[userProfileView]|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary) baseLayout.control_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[userProfileView]-[seperatorView(==1)][tblMenu]|", options: [.alignAllLeading,.alignAllTrailing], metrics: baseLayout.metrics, views: baseLayout.viewDictionary) self.addConstraints(baseLayout.control_H) self.addConstraints(baseLayout.control_V) baseLayout.expandView(btnlogin, insideView: userProfileView) // UserProfile View Constraint baseLayout.control_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-vSpace-[imgUser]-vSpace-|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary) baseLayout.control_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|-hSpace-[imgUser]-hSpace-[lblUserName]-hSpace-|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary) userProfileView.addConstraints(baseLayout.control_H) userProfileView.addConstraints(baseLayout.control_V) lblUserRealName.bottomAnchor.constraint(equalTo: imgUser.centerYAnchor, constant: ControlConstant.verticalPadding / 2).isActive = true lblUserName.topAnchor.constraint(equalTo: imgUser.centerYAnchor, constant: ControlConstant.verticalPadding / 2).isActive = true lblUserRealName.leadingAnchor.constraint(equalTo: lblUserName.leadingAnchor).isActive = true lblUserRealName.trailingAnchor.constraint(equalTo: lblUserName.trailingAnchor).isActive = true imgUser.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.size.width * 0.20).isActive = true imgUser.heightAnchor.constraint(equalTo: imgUser.widthAnchor).isActive = true self.layoutIfNeeded() self.layoutSubviews() } // MARK: - Public Interface - open func updateUI(){ // imgUser.layer.cornerRadius = (UIScreen.main.bounds.size.width * 0.15) / 2 // imgUser.clipsToBounds = true } open func cellSelectedEvent( event : @escaping TableCellSelectEvent) -> Void{ cellSelecteEvent = event } open func setSelectedMenu(type : Int) -> Void{ selectedCell = IndexPath.init() for (section,item) in arrMenuData.enumerated(){ for (index,menu) in ((item as! NSDictionary)["item"] as! NSArray).enumerated(){ if (menu as! NSDictionary)["type"] as! Int == type{ selectedCell = IndexPath(row: index, section: section) } } } tblMenu.reloadData() } open func showLoginView(){ self.btnlogin.isHidden = false self.imgUser.isHidden = false self.lblUserName.isHidden = false self.lblUserRealName.isHidden = false self.imgUser.image = UIImage(named: "App_icon")! self.lblUserName.text = "Login with Instagram" self.lblUserRealName.text = "LargeDp" } open func showProfileView(){ self.btnlogin.isHidden = true self.imgUser.isHidden = false self.lblUserName.isHidden = false self.lblUserRealName.isHidden = false } open func loadMenuData(){ arrMenuData.removeAllObjects() for menuData in AppPlistManager().readFromPlist("Menu") as! NSMutableArray { let dicMenu : NSMutableDictionary = menuData as! NSMutableDictionary var arrItem : [NSDictionary] = [] for item in dicMenu["item"] as! NSArray { arrItem.append(item as! NSDictionary) } dicMenu .setObject(arrItem, forKey: "item" as NSCopying) arrMenuData.add(dicMenu) } tblMenu.reloadData() } // MARK: - User Interaction - // MARK: - Internal Helpers - fileprivate func getDataForCell(indexPath : IndexPath) -> NSDictionary{ var dicMenu : NSDictionary! = arrMenuData[indexPath.section] as? NSDictionary var arrItem : NSArray! = dicMenu["item"] as? NSArray defer { dicMenu = nil arrItem = nil } return arrItem[indexPath.row] as! NSDictionary } // MARK: - Delegate Method - // MARK: - Server Request - } // MARK : Extension // TODO : UITableView Delegate extension SideMenuView : UITableViewDelegate{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cellData : NSDictionary = self.getDataForCell(indexPath: indexPath) if self.cellSelecteEvent != nil{ self.cellSelecteEvent(nil,cellData["type"] as AnyObject) } } } // TODO : UITableView DataSource extension SideMenuView : UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return self.arrMenuData.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let dicMenu : NSDictionary = arrMenuData[section] as! NSDictionary let arrItem : NSArray = dicMenu["item"] as! NSArray return arrItem.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : LeftMenuCell! cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifire.leftMenu) as? LeftMenuCell if cell == nil { cell = LeftMenuCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: CellIdentifire.leftMenu) } let cellData : NSDictionary = self.getDataForCell(indexPath: indexPath) cell.selectionStyle = .none cell.backgroundColor = UIColor.clear cell.imageView?.image = UIImage(named:"ic_file")?.withRenderingMode(.alwaysTemplate) cell.imageView?.tintColor = UIColor.green cell.backgroundColor = UIColor.blue if indexPath == selectedCell { cell.lblMenuText.textColor = AppColor.navigationBottomBorder.value if let image = UIImage(named: cellData["icon"] as! String) { cell.imgIcon.image = image.maskWithColor(AppColor.navigationBottomBorder.value) cell.backgroundColor = AppColor.navigationTitle.value } } else { cell.lblMenuText?.textColor = AppColor.navigationBottomBorder.value if let image = UIImage(named: cellData["icon"] as! String) { cell.imgIcon.image = image.maskWithColor(AppColor.navigationBottomBorder.value) cell.backgroundColor = UIColor.clear } } cell.lblMenuText?.text = (cellData["title"] as? String)?.localize() return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30)) headerView.backgroundColor = UIColor.clear let lbltext : UILabel = UILabel(frame: CGRect(x: 10, y:5, width: headerView.bounds.size.width, height: 20)) lbltext.textColor = AppColor.navigationBottomBorder.value lbltext.text = ((arrMenuData[section] as! NSDictionary)["title"] as? String)?.localize() headerView.addSubview(lbltext) return headerView } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45.0 } }
mit
qmathe/Confetti
Event/Operator/MapIndexesToElements.swift
1
926
/**s Date: November 2017 License: MIT */ import Foundation import RxSwift public extension Observable where Element == IndexSet { /// Returns elements matching selection indexes in collection presented by the given viewpoint. public func mapToElements<E, S>(in viewpoint: CollectionViewpoint<S>) -> Observable<[E]> where E == CollectionViewpoint<S>.E { return withLatestFrom(viewpoint.collection) { (indexes: IndexSet, collection: [E]) -> [E] in return collection[indexes] } } /// Returns the element matching first selection index in collection presented by the given viewpoint. public func mapToFirstElement<E, S>(in viewpoint: CollectionViewpoint<S>) -> Observable<E?> where E == CollectionViewpoint<S>.E { return mapToElements(in: viewpoint).flatMap { (elements: [E]) -> Observable<E?> in return .just(elements.first) } } }
mit
ello/ello-ios
Sources/Networking/AnonymousAuthService.swift
1
1068
//// /// AnonymousAuthService.swift // import Moya class AnonymousAuthService { func authenticateAnonymously( success: @escaping Block, failure: @escaping ErrorBlock, noNetwork: Block ) { let endpoint: ElloAPI = .anonymousCredentials ElloProvider.moya.request(endpoint) { (result) in switch result { case let .success(moyaResponse): switch moyaResponse.statusCode { case 200...299: AuthenticationManager.shared.authenticated(isPasswordBased: false) AuthToken.storeToken(moyaResponse.data, isPasswordBased: false) success() default: let elloError = ElloProvider.generateElloError( moyaResponse.data, statusCode: moyaResponse.statusCode ) failure(elloError) } case let .failure(error): failure(error) } } } }
mit
NoryCao/zhuishushenqi
zhuishushenqi/RightSide/Topic/ViewModel/ZSFilterThemeViewModel.swift
1
1148
// // ZSFilterThemeViewModel.swift // zhuishushenqi // // Created by caony on 2019/3/22. // Copyright © 2019年 QS. All rights reserved. // import Foundation import ZSAPI class ZSFilterThemeViewModel { var items:[ZSFilterThemeModel] = [] func request(_ handler:ZSBaseCallback<Void>?) { let api = ZSAPI.tagType("" as AnyObject) zs_get(api.path, parameters: nil) { (response) in guard let books = response?["data"] as? [Any] else { handler?(nil) return } if let items = [ZSFilterThemeModel].deserialize(from: books) as? [ZSFilterThemeModel] { self.items = [] var item = ZSFilterThemeModel() item.name = "" item.tags = ["全部书单"] self.items.append(item) var itemGender = ZSFilterThemeModel() itemGender.name = "性别" itemGender.tags = ["男","女"] self.items.append(itemGender) self.items.append(contentsOf: items) } handler?(nil) } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16559-no-stacktrace.swift
11
222
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { { } extension Array { var b { class case ,
mit
steamclock/internetmap
Theme.swift
1
743
// // Theme.swift // Internet Map // // Created by Nigel Brooke on 2017-11-08. // Copyright © 2017 Peer1. All rights reserved. // import UIKit // Note: these definitions are duplocates of the one in HelperMethods.h (since it's two hard to share them given how they are set up) // if changes are made, will need to be changed in both places enum Theme { static let blue = UIColor(red: 68.0 / 255.0, green: 144.0 / 255.0, blue: 206.0 / 255.0, alpha: 1.0) static let primary = Theme.blue static let fontNameLight = "NexaLight" static func settingsItemBackgroundImage() -> UIImage { return UIDevice.current.userInterfaceIdiom == .phone ? UIImage(named: "iphone-bg.png")! : UIImage(named: "ipad-bg.png")! } }
mit
kuler90/OrangeFramework
Source/Extensions/Core/Localization/Localization+OFExtension.swift
1
606
import Foundation /// localized string for current locale from .stringdict (firstly) and .strings files public func OFLocalized(formatOrKey: String, _ args: CVarArgType...) -> String { return formatOrKey.of_localized() } public extension String { /// localized string for current locale from .stringdict (firstly) and .strings files public func of_localized(args: CVarArgType...) -> String { let step1 = NSBundle.mainBundle().localizedStringForKey(self, value: "", table: nil) let step2 = String(format: step1, locale: NSLocale.currentLocale(), arguments: args) return step2 } }
mit
norio-nomura/HMAC
Tests/HMACTests/HMACTests.swift
1
19386
// // HMACTests.swift // HMACTests // // Created by 野村 憲男 on 1/23/15. // // Copyright (c) 2015 Norio Nomura // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import HMAC import Base32 class HMACTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: https://tools.ietf.org/html/rfc2202 func test_RFC2202_Hmac_MD5_TestCase1() { let key = Array<UInt8>(repeating: 0x0b, count: 16) let data = "Hi There" let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "9294727a3638bb1c13f48ef8158bfc9d" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase2() { let key = "Jefe" let data = "what do ya want for nothing?" let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "750c783e6ab0b503eaa86e310a5db738" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase3() { let key = Array<UInt8>(repeating: 0xAA, count: 16) let data = Array<UInt8>(repeating: 0xDD, count: 50) let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "56be34521d144c88dbb8c733f0e8b3f6" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase4() { let key = base16Decode("0102030405060708090a0b0c0d0e0f10111213141516171819")! let data = Array<UInt8>(repeating: 0xcd, count: 50) let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "697eaf0aca3a3aea3a75164746ffaa79" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase5() { let key = base16Decode("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c")! let data = "Test With Truncation" let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "56461ef2342edc00f9bab995690efd4c" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase6() { let key = Array<UInt8>(repeating: 0xaa, count: 80) let data = "Test Using Larger Than Block-Size Key - Hash Key First" let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_MD5_TestCase7() { let key = Array<UInt8>(repeating: 0xaa, count: 80) let data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" let hmacMD5 = base16Encode(HMAC(algorithm: .md5, key: key).update(data).final(), uppercase: false) let expect = "6f630fad67cda0ee1fb1f562db3aa53e" XCTAssertEqual(hmacMD5, expect) } func test_RFC2202_Hmac_SHA1_TestCase1() { let key = Array<UInt8>(repeating: 0x0b, count: 20) let data = "Hi There" let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "b617318655057264e28bc0b6fb378c8ef146be00" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase2() { let key = "Jefe" let data = "what do ya want for nothing?" let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase3() { let key = Array<UInt8>(repeating: 0xAA, count: 20) let data = Array<UInt8>(repeating: 0xDD, count: 50) let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "125d7342b9ac11cd91a39af48aa17b4f63f175d3" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase4() { let key = base16Decode("0102030405060708090a0b0c0d0e0f10111213141516171819")! let data = Array<UInt8>(repeating: 0xcd, count: 50) let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "4c9007f4026250c6bc8414f9bf50c86c2d7235da" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase5() { let key = base16Decode("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c")! let data = "Test With Truncation" let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase6() { let key = Array<UInt8>(repeating: 0xaa, count: 80) let data = "Test Using Larger Than Block-Size Key - Hash Key First" let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "aa4ae5e15272d00e95705637ce8a3b55ed402112" XCTAssertEqual(hmacSHA1, expect) } func test_RFC2202_Hmac_SHA1_TestCase7() { let key = Array<UInt8>(repeating: 0xaa, count: 80) let data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" let hmacSHA1 = base16Encode(HMAC(algorithm: .sha1, key: key).update(data).final(), uppercase: false) let expect = "e8e99d0f45237d786d6bbaa7965c7808bbff1a91" XCTAssertEqual(hmacSHA1, expect) } // MARK: http://www.ietf.org/rfc/rfc4231.txt func test_RFC4231_Hmac_TestCase1() { let key = Array<UInt8>(repeating: 0x0b, count: 20) let data = base16Decode("4869205468657265")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "896fb1128abbdf196832107cd49df33f" + "47b4b1169912ba4f53684b22") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "b0344c61d8db38535ca8afceaf0bf12b" + "881dc200c9833da726e9376c2e32cff7") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "afd03944d84895626b0825f4ab46907f" + "15f9dadbe4101ec682aa034c7cebc59c" + "faea9ea9076ede7f4af152e8b2fa9cb6") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "87aa7cdea5ef619d4ff0b4241a1d6cb0" + "2379f4e2ce4ec2787ad0b30545e17cde" + "daa833b7d6b8a702038b274eaea3f4e4" + "be9d914eeb61f1702e696c203a126854") } func test_RFC4231_Hmac_TestCase2() { let key = base16Decode("4a656665")! let data = base16Decode( "7768617420646f2079612077616e7420" + "666f72206e6f7468696e673f")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "a30e01098bc6dbbf45690f3a7e9e6d0f" + "8bbea2a39e6148008fd05e44") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "5bdcc146bf60754e6a042426089575c7" + "5a003f089d2739839dec58b964ec3843") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "af45d2e376484031617f78d2b58a6b1b" + "9c7ef464f5a01b47e42ec3736322445e" + "8e2240ca5e69e2c78b3239ecfab21649") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "164b7a7bfcf819e2e395fbe73b56e0a3" + "87bd64222e831fd610270cd7ea250554" + "9758bf75c05a994a6d034f65f8f0e6fd" + "caeab1a34d4a6b4b636e070a38bce737") } func test_RFC4231_Hmac_TestCase3() { let key = base16Decode( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaa")! let data = base16Decode( "dddddddddddddddddddddddddddddddd" + "dddddddddddddddddddddddddddddddd" + "dddddddddddddddddddddddddddddddd" + "dddd")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "7fb3cb3588c6c1f6ffa9694d7d6ad264" + "9365b0c1f65d69d1ec8333ea") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "773ea91e36800e46854db8ebd09181a7" + "2959098b3ef8c122d9635514ced565fe") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "88062608d3e6ad8a0aa2ace014c8a86f" + "0aa635d947ac9febe83ef4e55966144b" + "2a5ab39dc13814b94e3ab6e101a34f27") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "fa73b0089d56a284efb0f0756c890be9" + "b1b5dbdd8ee81a3655f83e33b2279d39" + "bf3e848279a722c806b485a47e67c807" + "b946a337bee8942674278859e13292fb") } func test_RFC4231_Hmac_TestCase4() { let key = base16Decode( "0102030405060708090a0b0c0d0e0f10" + "111213141516171819")! let data = base16Decode( "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcd")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "6c11506874013cac6a2abc1bb382627c" + "ec6a90d86efc012de7afec5a") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "82558a389a443c0ea4cc819899f2083a" + "85f0faa3e578f8077a2e3ff46729665b") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "3e8a69b7783c25851933ab6290af6ca7" + "7a9981480850009cc5577c6e1f573b4e" + "6801dd23c4a7d679ccf8a386c674cffb") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "b0ba465637458c6990e5a8c5f61d4af7" + "e576d97ff94b872de76f8050361ee3db" + "a91ca5c11aa25eb4d679275cc5788063" + "a5f19741120c4f2de2adebeb10a298dd") } func test_RFC4231_Hmac_TestCase5() { let key = base16Decode( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" + "0c0c0c0c")! let data = base16Decode( "546573742057697468205472756e6361" + "74696f6e")! XCTAssertTrue( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false) .hasPrefix("0e2aea68a90c8d37c988bcdb9fca6fa8")) XCTAssertTrue( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false) .hasPrefix("a3b6167473100ee06e0c796c2955552b")) XCTAssertTrue( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false) .hasPrefix("3abf34c3503b2a23a46efc619baef897")) XCTAssertTrue( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false) .hasPrefix("415fad6271580a531d4179bc891d87a6")) } func test_RFC4231_Hmac_TestCase6() { let key = base16Decode( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa")! let data = base16Decode( "54657374205573696e67204c61726765" + "72205468616e20426c6f636b2d53697a" + "65204b6579202d2048617368204b6579" + "204669727374")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "95e9a0db962095adaebe9b2d6f0dbce2" + "d499f112f2d2b7273fa6870e") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "60e431591ee0b67f0d8a26aacbf5b77f" + "8e0bc6213728c5140546040f0ee37f54") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "4ece084485813e9088d2c63a041bc5b4" + "4f9ef1012a2b588f3cd11f05033ac4c6" + "0c2ef6ab4030fe8296248df163f44952") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "80b24263c7c1a3ebb71493c1dd7be8b4" + "9b46d1f41b4aeec1121b013783f8f352" + "6b56d037e05f2598bd0fd2215d6a1e52" + "95e64f73f63f0aec8b915a985d786598") } func test_RFC4231_Hmac_TestCase7() { let key = base16Decode( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa")! let data = base16Decode( "54686973206973206120746573742075" + "73696e672061206c6172676572207468" + "616e20626c6f636b2d73697a65206b65" + "7920616e642061206c61726765722074" + "68616e20626c6f636b2d73697a652064" + "6174612e20546865206b6579206e6565" + "647320746f2062652068617368656420" + "6265666f7265206265696e6720757365" + "642062792074686520484d414320616c" + "676f726974686d2e")! XCTAssertEqual( base16Encode(HMAC(algorithm: .sha224, key: key).update(data).final(), uppercase: false), "3a854166ac5d9f023f54d517d0b39dbd" + "946770db9c2b95c9f6f565d1") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha256, key: key).update(data).final(), uppercase: false), "9b09ffa71b942fcb27635fbcd5b0e944" + "bfdc63644f0713938a7f51535c3a35e2") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha384, key: key).update(data).final(), uppercase: false), "6617178e941f020d351e2f254e8fd32c" + "602420feb0b8fb9adccebb82461e99c5" + "a678cc31e799176d3860e6110c46523e") XCTAssertEqual( base16Encode(HMAC(algorithm: .sha512, key: key).update(data).final(), uppercase: false), "e37b6a775dc87dbaa4dfa9f96e5e3ffd" + "debd71f8867289865df5a32d20cdc944" + "b6022cac3c4982b10d5eeb55c3e4de15" + "134676fb6de0446065c97440fa8c6a58") } func test_RFC4231_Hmac_TestCase7_multipartUpdates() { let key = base16Decode( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa")! let dataStringArray = [ "54686973206973206120746573742075", "73696e672061206c6172676572207468", "616e20626c6f636b2d73697a65206b65", "7920616e642061206c61726765722074", "68616e20626c6f636b2d73697a652064", "6174612e20546865206b6579206e6565", "647320746f2062652068617368656420", "6265666f7265206265696e6720757365", "642062792074686520484d414320616c", "676f726974686d2e" ] let expects: [(HMAC.Algorithm, String)] = [ (.sha224, "3a854166ac5d9f023f54d517d0b39dbd" + "946770db9c2b95c9f6f565d1"), (.sha256, "9b09ffa71b942fcb27635fbcd5b0e944" + "bfdc63644f0713938a7f51535c3a35e2"), (.sha384, "6617178e941f020d351e2f254e8fd32c" + "602420feb0b8fb9adccebb82461e99c5" + "a678cc31e799176d3860e6110c46523e"), (.sha512, "e37b6a775dc87dbaa4dfa9f96e5e3ffd" + "debd71f8867289865df5a32d20cdc944" + "b6022cac3c4982b10d5eeb55c3e4de15" + "134676fb6de0446065c97440fa8c6a58") ] for (algorithm, expect) in expects { let hmac = HMAC(algorithm: algorithm, key: key) for dataString in dataStringArray { let data = dataString.base16DecodedData! _ = hmac.update(data) } XCTAssertEqual(base16Encode(hmac.final(), uppercase: false), expect) } } }
mit
shadanan/mado
Antlr4Runtime/Sources/Antlr4/misc/extension/TokenExtension.swift
1
1654
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. // // TokenExtension.swift // Antlr.swift // // Created by janyou on 15/9/4. // import Foundation extension Token { static public var INVALID_TYPE: Int { return 0 } /// During lookahead operations, this "token" signifies we hit rule end ATN state /// and did not follow it despite needing to. static public var EPSILON: Int { return -2 } static public var MIN_USER_TOKEN_TYPE: Int { return 1 } static public var EOF: Int { return -1 } //IntStream.EOF /// All tokens go to the parser (unless skip() is called in that rule) /// on a particular "channel". The parser tunes to a particular channel /// so that whitespace etc... can go to the parser on a "hidden" channel. static public var DEFAULT_CHANNEL: Int { return 0 } /// Anything on different channel than DEFAULT_CHANNEL is not parsed /// by parser. static public var HIDDEN_CHANNEL: Int { return 1 } /// This is the minimum constant value which can be assigned to a /// user-defined token channel. /// /// <p> /// The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are /// assigned to the predefined channels {@link #DEFAULT_CHANNEL} and /// {@link #HIDDEN_CHANNEL}.</p> /// /// - seealso: org.antlr.v4.runtime.Token#getChannel() static public var MIN_USER_CHANNEL_VALUE: Int { return 2 } }
mit
ifeherva/HSTracker
HSTracker/ArenaHelper/ArenaHelperSync.swift
2
3646
// // ArenaHelperSync.swift // HSTracker // // Created by Benjamin Michotte on 10/04/17. // Copyright © 2017 Benjamin Michotte. All rights reserved. // import Foundation class ArenaHelperSync { private static var latestVersion: String? private static var url = "https://raw.githubusercontent.com/rembound/Arena-Helper/master/data" static func checkTierList(splashscreen: Splashscreen) { DispatchQueue.main.async { splashscreen.display(NSLocalizedString("Loading Arena card tiers", comment: ""), indeterminate: true) } let url = "\(self.url)/version.json" let semaphore = DispatchSemaphore(value: 0) let http = Http(url: url) http.json(method: .get) { json in if let json: [String: String] = json as? [String: String] { self.latestVersion = json["tierlist"] } semaphore.signal() } _ = semaphore.wait(timeout: DispatchTime.distantFuture) } static func isOutdated() -> Bool { guard let latest = self.latestVersion else { return true } guard let actual = UserDefaults.standard.string(forKey: "arena_helper_version") else { return true } logger.info("Latest card tiers version: \(latest), HSTracker build: \(actual)") return latest.compare(actual, options: .numeric) == .orderedDescending } static func jsonFilesAreValid() -> Bool { let jsonFile = Paths.arenaJson.appendingPathComponent("cardtier.json") guard let jsonData = try? Data(contentsOf: jsonFile) else { logger.error("\(jsonFile) is not a valid file") return false } if (try? JSONSerialization .jsonObject(with: jsonData, options: []) as? [[String: Any]]) == nil { logger.error("\(jsonFile) is not a valid file") return false } return true } static func downloadTierList(splashscreen: Splashscreen) { guard let latest = self.latestVersion else { return } DispatchQueue.main.async { splashscreen.increment(String(format: NSLocalizedString("Downloading %@", comment: ""), "cardtier.json")) } let semaphore = DispatchSemaphore(value: 0) let cardTierUrl = "\(self.url)/cardtier.json" var hasError = false if let url = URL(string: cardTierUrl) { URLSession.shared .dataTask(with: url) { data, response, error in if let response = response as? HTTPURLResponse, response.statusCode != 200 { hasError = true logger.error("Can not download \(cardTierUrl) " + "-> statusCode : \(response.statusCode)") } else if let error = error { hasError = true logger.error("\(error)") } else if let data = data { let dir = Paths.arenaJson let dest = dir.appendingPathComponent("cardtier.json") logger.info("Saving \(cardTierUrl) to \(dest)") try? data.write(to: dest, options: [.atomic]) } semaphore.signal() }.resume() } _ = semaphore.wait(timeout: DispatchTime.distantFuture) if !hasError { UserDefaults.standard.set(latest, forKey: "arena_helper_version") } } }
mit
ChristianKienle/highway
Sources/Git/Git.swift
1
1023
import Foundation import ZFile import Url import SourceryAutoProtocols /// Git namespace public protocol GitToolProtocol: AutoMockable { /// sourcery:inline:GitTool.AutoGenerateProtocol func addAll(at url: FolderProtocol) throws func commit(at url: FolderProtocol, message: String) throws func pushToMaster(at url: FolderProtocol) throws func pushTagsToMaster(at url: FolderProtocol) throws func pull(at url: FolderProtocol) throws func currentTag(at url: FolderProtocol) throws -> String func clone(with options: CloneOptions) throws /// sourcery:end } public struct CloneOptions: AutoMockable { // MARK: - Properties public let remoteUrl: String public let localPath: FolderProtocol public let performMirror: Bool // MARK: - Init public init(remoteUrl: String, localPath: FolderProtocol, performMirror: Bool = false) { self.remoteUrl = remoteUrl self.localPath = localPath self.performMirror = performMirror } }
mit
jamalping/XPUtil
XPUtil/UIKit/UIAlertViewController+Extension.swift
1
843
// // UIAlertViewController+Extension.swift // XPUtilExample // // Created by Apple on 2019/6/5. // Copyright © 2019年 xyj. All rights reserved. // import UIKit extension UIAlertController { static func alert(with title:String,message:String,confirTitle:String = "确定",cancle:(()->Void)?,confir:(()->Void)?) ->UIAlertController{ let alert = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertController.Style.alert) let action1 = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (_) in cancle?() } let action2 = UIAlertAction.init(title: confirTitle, style: UIAlertAction.Style.default) { (_) in confir?() } alert.addAction(action1) alert.addAction(action2) return alert } }
mit
christophhagen/Signal-iOS
SignalMessaging/views/CommonStrings.swift
1
3592
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Strings re-used in multiple places should be added here. */ @objc public class CommonStrings: NSObject { @objc static public let dismissButton = NSLocalizedString("DISMISS_BUTTON_TEXT", comment: "Short text to dismiss current modal / actionsheet / screen") @objc static public let cancelButton = NSLocalizedString("TXT_CANCEL_TITLE", comment:"Label for the cancel button in an alert or action sheet.") @objc static public let retryButton = NSLocalizedString("RETRY_BUTTON_TEXT", comment:"Generic text for button that retries whatever the last action was.") } @objc public class MessageStrings: NSObject { @objc static public let newGroupDefaultTitle = NSLocalizedString("NEW_GROUP_DEFAULT_TITLE", comment: "Used in place of the group name when a group has not yet been named.") } @objc public class CallStrings: NSObject { @objc static public let callStatusFormat = NSLocalizedString("CALL_STATUS_FORMAT", comment: "embeds {{Call Status}} in call screen label. For ongoing calls, {{Call Status}} is a seconds timer like 01:23, otherwise {{Call Status}} is a short text like 'Ringing', 'Busy', or 'Failed Call'") @objc static public let confirmAndCallButtonTitle = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_CALL_ACTION", comment: "alert button text to confirm placing an outgoing call after the recipients Safety Number has changed.") @objc static public let callBackAlertTitle = NSLocalizedString("CALL_USER_ALERT_TITLE", comment: "Title for alert offering to call a user.") @objc static public let callBackAlertMessageFormat = NSLocalizedString("CALL_USER_ALERT_MESSAGE_FORMAT", comment: "Message format for alert offering to call a user. Embeds {{the user's display name or phone number}}.") @objc static public let callBackAlertCallButton = NSLocalizedString("CALL_USER_ALERT_CALL_BUTTON", comment: "Label for call button for alert offering to call a user.") // MARK: Notification actions @objc static public let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action") @objc static public let showThreadButtonTitle = NSLocalizedString("SHOW_THREAD_BUTTON_TITLE", comment: "notification action") // MARK: Missed Call Notification @objc static public let missedCallNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL", comment: "notification title") @objc static public let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITH_NAME", comment: "notification title. Embeds {{caller's name or phone number}}") // MARK: Missed with changed identity notification (for not previously verified identity) @objc static public let missedCallWithIdentityChangeNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITHOUT_CALLER_NAME", comment: "notification title") @objc static public let missedCallWithIdentityChangeNotificationBodyWithCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITH_CALLER_NAME", comment: "notification title. Embeds {{caller's name or phone number}}") } @objc public class SafetyNumberStrings: NSObject { @objc static public let confirmSendButton = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_SEND_ACTION", comment: "button title to confirm sending to a recipient whose safety number recently changed") }
gpl-3.0
gmoral/SwiftTraining2016
Training_Swift/SearchPeople.swift
1
1716
// // SearchPeople.swift // Training_Swift // // Created by Guillermo Moral on 3/8/16. // Copyright © 2016 Guillermo Moral. All rights reserved. // import UIKit import SwiftyJSON enum ParseError: ErrorType { case Empty } class SearchPeople { var id: String? var firstname: String? var lastname: String? var title:String? var avatar: UIImage? var avatarBase64EncodedString: String? required init?(json: JSON) { id = json["_id"].string! firstname = json["firstname"].string! lastname = json["lastname"].string! title = json["title"].string! do { avatarBase64EncodedString = try parseAvatar(json) } catch { avatarBase64EncodedString = "" } if !avatarBase64EncodedString!.isEmpty { let decodedData = NSData(base64EncodedString: avatarBase64EncodedString!, options: NSDataBase64DecodingOptions(rawValue: 0)) let decodedimage = UIImage(data: decodedData!) avatar = decodedimage! as UIImage } else { avatar = UIImage(named: "Avatar.png") } } lazy var fullName: String = { guard let tmpFirstName = self.firstname, let tmpLastName = self.lastname where !tmpFirstName.isEmpty && !tmpLastName.isEmpty else { return "" } return (tmpFirstName + " " + tmpLastName) }() private func parseAvatar(json: JSON) throws -> String { guard let anAvatar = json["thumb"].string else { throw ParseError.Empty } return anAvatar } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27386-swift-cantype-isobjcexistentialtypeimpl.swift
1
460
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let i{ {class c g{??{ func a{let i>a?{ {func let{{func g{ a=f
apache-2.0
hanhailong/practice-swift
Courses/stanford/stanford/cs193p/2015/Cassini/Cassini/ImageViewController.swift
3
2909
// // ImageViewController.swift // Cassini // // Created by Domenico on 11.04.15. // License: MIT // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { var imageURL: NSURL?{ didSet{ image = nil // Fetch the image if I am onscreen if view.window != nil{ fetchImage() } } } private func fetchImage(){ if let url = imageURL{ // Start animating the spinner spinner?.startAnimating() // Get the QUEUE identifier let qos = Int(QOS_CLASS_USER_INITIATED.value) // Dispatch the queue dispatch_async(dispatch_get_global_queue(qos, 0)){ () -> Void in let imageData = NSData(contentsOfURL: url) // Need to dispatch the result to the main queue because we are modifying the UI dispatch_async(dispatch_get_main_queue()) { () -> Void in // Checking if this url is the last requested url if url == self.imageURL{ if imageData != nil{ self.image = UIImage(data: imageData!) }else{ self.image = nil } } } } } } @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var scrollView: UIScrollView!{ didSet{ // Need to set the content size of the scroll view scrollView.contentSize = imageView.frame.size // Set the delegate for the scrollView scrollView.delegate = self // Set the zoom scrollView.minimumZoomScale = 0.3 scrollView.maximumZoomScale = 1 } } // ScrollView function from UIScrollViewDelegate func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } private var imageView = UIImageView() private var image: UIImage?{ get{ return imageView.image } set{ imageView.image = newValue // Expand the frame to fit imageView.sizeToFit() // Set the content size of the scroll view scrollView?.contentSize = imageView.frame.size // Stop animating spinner?.stopAnimating() } } override func viewDidLoad(){ super.viewDidLoad() view.addSubview(imageView) } override func viewWillAppear(animated:Bool){ super.viewWillAppear(animated) // If I was offscreen and the image has not been fetched before if image == nil{ fetchImage() } } }
mit
mobilabsolutions/jenkins-ios
JenkinsiOS/Model/JenkinsAPI/Computer/MonitorData.swift
1
1358
// // MonitorData.swift // JenkinsiOS // // Created by Robert on 12.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation class MonitorData { /// The number of avaible bytes of physical memory var availablePhysicalMemory: Double? /// The number of available bytes of swap space var availableSwapSpace: Double? /// The total number of bytes of physical memory var totalPhysicalMemory: Double? /// The total number of bytes of swap space var totalSwapSpace: Double? /// Initialize a MonitorData object /// /// - parameter json: The json from which to initialize the monitor data /// /// - returns: An initialized MonitorData object init(json: [String: AnyObject]) { for partJson in json { if let dataJson = partJson.value as? [String: AnyObject] { availablePhysicalMemory = dataJson[Constants.JSON.availablePhysicalMemory] as? Double ?? availablePhysicalMemory availableSwapSpace = dataJson[Constants.JSON.availableSwapSpace] as? Double ?? availableSwapSpace totalPhysicalMemory = dataJson[Constants.JSON.totalPhysicalMemory] as? Double ?? totalPhysicalMemory totalSwapSpace = dataJson[Constants.JSON.totalSwapSpace] as? Double ?? totalSwapSpace } } } }
mit
tardieu/swift
test/DebugInfo/closure.swift
4
824
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} func foldl1<T>(_ list: [T], _ function: (_ a: T, _ b: T) -> T) -> T { assert(list.count > 1) var accumulator = list[0] for i in 1 ..< list.count { accumulator = function(accumulator, list[i]) } return accumulator } var a = [Int64](repeating: 0, count: 10) for i in 0..<10 { a[i] = Int64(i) } // A closure is not an artificial function (the last i32 0). // CHECK: !DISubprogram({{.*}}linkageName: "_T07closures5Int64VAC_ACtcfU_",{{.*}} line: 20,{{.*}} scopeLine: 20, // CHECK: !DILocalVariable(name: "$0", arg: 1{{.*}} line: [[@LINE+2]], // CHECK: !DILocalVariable(name: "$1", arg: 2{{.*}} line: [[@LINE+1]], var sum:Int64 = foldl1(a, { $0 + $1 }) markUsed(sum)
apache-2.0
googlemaps/last-mile-fleet-solution-samples
ios_driverapp_samples/LMFSDriverSampleAppTests/ModelTests.swift
1
3036
/* * Copyright 2022 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import XCTest @testable import LMFSDriverSampleApp class ModelsTests: XCTestCase { private var modelData = ModelData() override func setUpWithError() throws { modelData = ModelData(filename: "test_manifest") } func testSetTaskStatus() throws { let stop1 = modelData.stops[0] let tasks = modelData.tasks(stop: stop1) XCTAssertEqual(tasks.count, 3) XCTAssertEqual(tasks[0].outcome, .pending) XCTAssertEqual(tasks[1].outcome, .pending) XCTAssertEqual(tasks[2].outcome, .pending) XCTAssertEqual(stop1.taskStatus, .pending) let navigationState1 = try XCTUnwrap(modelData.navigationState) XCTAssertEqual(stop1, navigationState1.upcomingStop) modelData.setTaskStatus(task: tasks[0], newStatus: .completed) XCTAssertEqual(tasks[0].outcome, .completed) modelData.setTaskStatus(task: tasks[1], newStatus: .completed) XCTAssertEqual(tasks[1].outcome, .completed) modelData.setTaskStatus(task: tasks[2], newStatus: .completed) XCTAssertEqual(tasks[2].outcome, .completed) XCTAssertEqual(stop1.taskStatus, .completed) let navigationState2 = try XCTUnwrap(modelData.navigationState) XCTAssertNotEqual(navigationState2.upcomingStop, stop1) modelData.setTaskStatus(task: tasks[1], newStatus: .couldNotComplete) XCTAssertEqual(tasks[1].outcome, .couldNotComplete) XCTAssertEqual(stop1.taskStatus, .couldNotComplete) } /// Flip the first 2 stops. func testMoveStops() throws { let stopBeforeMove = modelData.stops[0] let indexSet = IndexSet(integer: 0) modelData.moveStops(source: indexSet, destination: 2) let stopAfterMove = modelData.stops[1] XCTAssertEqual(stopBeforeMove, stopAfterMove) XCTAssertEqual(stopBeforeMove.order, 2) let navigationState = try XCTUnwrap(modelData.navigationState) XCTAssertNotEqual(stopBeforeMove, navigationState.upcomingStop) } // Tests the bug that caused b/221304932: Make sure the `id` property of a ModelData.Stop is // globally unique, not just unique within the Manifest/vehicle. func testGloballyUniqueStopId() throws { let firstStops = Set(modelData.stops.map { $0.id }) // test_manifest_2.json is identical to test_manifest.json except for vehicle id. let modelData2 = ModelData(filename: "test_manifest_2") let secondStops = Set(modelData2.stops.map { $0.id }) XCTAssertTrue(firstStops.intersection(secondStops).isEmpty) } }
apache-2.0
iida-hayato/Moya-SwiftyJSONMapper
Source/ReactiveCocoa/SignalProducer+SwiftyJSONMapper.swift
1
1496
// // SignalProducer+SwiftyJSONMapper.swift // // Created by Antoine van der Lee on 26/01/16. // Copyright © 2016 Antoine van der Lee. All rights reserved. // import ReactiveCocoa import Moya import SwiftyJSON /// Extension for processing Responses into Mappable objects through ObjectMapper extension SignalProducerType where Value == Moya.Response, Error == Moya.Error { /// Maps data received from the signal into an object which implements the ALSwiftyJSONAble protocol. /// If the conversion fails, the signal errors. public func mapObject<T: ALSwiftyJSONAble>(type: T.Type) -> SignalProducer<T, Error> { return producer.flatMap(.Latest) { response -> SignalProducer<T, Error> in return unwrapThrowable { try response.mapObject(T) } } } /// Maps data received from the signal into an array of objects which implement the ALSwiftyJSONAble protocol. /// If the conversion fails, the signal errors. public func mapArray<T: ALSwiftyJSONAble>(type: T.Type) -> SignalProducer<[T], Error> { return producer.flatMap(.Latest) { response -> SignalProducer<[T], Error> in return unwrapThrowable { try response.mapArray(T) } } } } /// Maps throwable to SignalProducer private func unwrapThrowable<T>(throwable: () throws -> T) -> SignalProducer<T, Moya.Error> { do { return SignalProducer(value: try throwable()) } catch { return SignalProducer(error: error as! Moya.Error) } }
mit
boruil/SwiftSmallestApp
SwiftSmallestApp/SwiftSmallestAppTests/SwiftSmallestAppTests.swift
1
935
// // SwiftSmallestAppTests.swift // SwiftSmallestAppTests // // Created by Borui "Andy" Li on 7/17/14. // Copyright (c) 2014 Borui "Andy" Li. All rights reserved. // import UIKit import XCTest class SwiftSmallestAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/DgmTypePickerContainer.swift
2
593
// // DgmTypePickerContainer.swift // Neocom // // Created by Artem Shimanski on 11/30/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures enum DgmTypePickerContainer: Assembly { typealias View = DgmTypePickerContainerViewController case `default` func instantiate(_ input: View.Input) -> Future<View> { switch self { case .default: let controller = UIStoryboard.fitting.instantiateViewController(withIdentifier: "DgmTypePickerContainerViewController") as! View controller.input = input return .init(controller) } } }
lgpl-2.1
lorentey/swift
test/SILGen/keypaths.swift
3
28399
// RUN: %target-swift-emit-silgen -parse-stdlib -module-name keypaths %s | %FileCheck %s import Swift struct S<T> { var x: T let y: String var z: C<T> var computed: C<T> { fatalError() } var observed: C<T> { didSet { fatalError() } } var reabstracted: () -> () } class C<T> { final var x: T final let y: String final var z: S<T> var nonfinal: S<T> var computed: S<T> { fatalError() } var observed: S<T> { didSet { fatalError() } } final var reabstracted: () -> () init() { fatalError() } } extension C { var `extension`: S<T> { fatalError() } } protocol P { var x: Int { get } var y: String { get set } } extension P { var z: String { return y } var w: String { get { return "" } nonmutating set { } } } struct T { var a: (Int, String) let b: (f: String, g: Int) let c: (x: C<Int>, y: C<String>) } /* TODO: When we support superclass requirements on protocols, we should test * this case as well. protocol PoC : C<Int> {} */ // CHECK-LABEL: sil hidden [ossa] @{{.*}}storedProperties func storedProperties<T>(_: T) { // CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T> _ = \S<T>.x // CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T> _ = \S<T>.y // CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T> _ = \S<T>.z.x // CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T> _ = \C<T>.x // CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T> _ = \C<T>.y // CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T> _ = \C<T>.z.x // CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T> _ = \C<T>.z.z.y } // CHECK-LABEL: sil hidden [ossa] @{{.*}}computedProperties func computedProperties<T: P>(_: T) { // CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $S<τ_0_0>, // CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @$s8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0>, // CHECK-SAME: setter @$s8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>, @in_guaranteed C<τ_0_0>) -> () // CHECK-SAME: ) <T> _ = \C<T>.nonfinal // CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: gettable_property $S<τ_0_0>, // CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @$s8keypaths1CC8computedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0> // CHECK-SAME: ) <T> _ = \C<T>.computed // CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $S<τ_0_0>, // CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @$s8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0>, // CHECK-SAME: setter @$s8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>, @in_guaranteed C<τ_0_0>) -> () // CHECK-SAME: ) <T> _ = \C<T>.observed _ = \C<T>.nonfinal.x _ = \C<T>.computed.x _ = \C<T>.observed.x _ = \C<T>.z.computed _ = \C<T>.z.observed _ = \C<T>.observed.x // CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $() -> (), // CHECK-SAME: id ##C.reabstracted, // CHECK-SAME: getter @$s8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out @callee_guaranteed () -> @out (), // CHECK-SAME: setter @$s8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed @callee_guaranteed () -> @out (), @in_guaranteed C<τ_0_0>) -> () // CHECK-SAME: ) <T> _ = \C<T>.reabstracted // CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>, // CHECK-SAME: id @$s8keypaths1SV8computedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>, // CHECK-SAME: getter @$s8keypaths1SV8computedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out C<τ_0_0> // CHECK-SAME: ) <T> _ = \S<T>.computed // CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; // CHECK-SAME: settable_property $C<τ_0_0>, // CHECK-SAME: id @$s8keypaths1SV8observedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>, // CHECK-SAME: getter @$s8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out C<τ_0_0>, // CHECK-SAME: setter @$s8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>, @inout S<τ_0_0>) -> () // CHECK-SAME: ) <T> _ = \S<T>.observed _ = \S<T>.z.nonfinal _ = \S<T>.z.computed _ = \S<T>.z.observed _ = \S<T>.computed.x _ = \S<T>.computed.y // CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; // CHECK-SAME: settable_property $() -> (), // CHECK-SAME: id ##S.reabstracted, // CHECK-SAME: getter @$s8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out @callee_guaranteed () -> @out (), // CHECK-SAME: setter @$s8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed @callee_guaranteed () -> @out (), @inout S<τ_0_0>) -> () // CHECK-SAME: ) <T> _ = \S<T>.reabstracted // CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $τ_0_0; // CHECK-SAME: gettable_property $Int, // CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int, // CHECK-SAME: getter @$s8keypaths1PP1xSivpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out Int // CHECK-SAME: ) <T> _ = \T.x // CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $τ_0_0; // CHECK-SAME: settable_property $String, // CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String, // CHECK-SAME: getter @$s8keypaths1PP1ySSvpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out String, // CHECK-SAME: setter @$s8keypaths1PP1ySSvpAaBRzlxTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed String, @inout τ_0_0) -> () // CHECK-SAME: ) <T> _ = \T.y // CHECK: keypath $KeyPath<T, String>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $τ_0_0; // CHECK-SAME: gettable_property $String, // CHECK-SAME: id @$s8keypaths1PPAAE1zSSvg _ = \T.z } struct Concrete: P { var x: Int var y: String } // CHECK-LABEL: sil hidden [ossa] @$s8keypaths35keyPathsWithSpecificGenericInstanceyyF func keyPathsWithSpecificGenericInstance() { // CHECK: keypath $KeyPath<Concrete, String>, ( // CHECK-SAME: gettable_property $String, // CHECK-SAME: id @$s8keypaths1PPAAE1zSSvg // CHECK-SAME: getter @$s8keypaths1PPAAE1zSSvpAA8ConcreteVTK : $@convention(thin) (@in_guaranteed Concrete) -> @out String _ = \Concrete.z _ = \S<Concrete>.computed } class AA<T> { var a: Int { get { return 0 } set { } } } class BB<U, V>: AA<V> { } func keyPathForInheritedMember() { _ = \BB<Int, String>.a } func keyPathForExistentialMember() { _ = \P.x _ = \P.y _ = \P.z _ = \P.w } struct OptionalFields { var x: S<Int>? } struct OptionalFields2 { var y: OptionalFields? } // CHECK-LABEL: sil hidden [ossa] @$s8keypaths18keyPathForOptionalyyF func keyPathForOptional() { // CHECK: keypath $WritableKeyPath<OptionalFields, S<Int>>, ( // CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>; // CHECK-SAME: optional_force : $S<Int>) _ = \OptionalFields.x! // CHECK: keypath $KeyPath<OptionalFields, Optional<String>>, ( // CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>; // CHECK-SAME: optional_chain : $S<Int>; // CHECK-SAME: stored_property #S.y : $String; // CHECK-SAME: optional_wrap : $Optional<String>) _ = \OptionalFields.x?.y // CHECK: keypath $KeyPath<OptionalFields2, Optional<S<Int>>>, ( // CHECK-SAME: root $OptionalFields2; // CHECK-SAME: stored_property #OptionalFields2.y : $Optional<OptionalFields>; // CHECK-SAME: optional_chain : $OptionalFields; // CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>) _ = \OptionalFields2.y?.x } class StorageQualified { weak var tooWeak: StorageQualified? unowned var disowned: StorageQualified init() { fatalError() } } final class FinalStorageQualified { weak var tooWeak: StorageQualified? unowned var disowned: StorageQualified init() { fatalError() } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}keyPathForStorageQualified func keyPathForStorageQualified() { // CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, Optional<StorageQualified>>, // CHECK-SAME: settable_property $Optional<StorageQualified>, id #StorageQualified.tooWeak!getter.1 _ = \StorageQualified.tooWeak // CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, StorageQualified>, // CHECK-SAME: settable_property $StorageQualified, id #StorageQualified.disowned!getter.1 _ = \StorageQualified.disowned // CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, Optional<StorageQualified>>, // CHECK-SAME: settable_property $Optional<StorageQualified>, id ##FinalStorageQualified.tooWeak _ = \FinalStorageQualified.tooWeak // CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, StorageQualified>, // CHECK-SAME: settable_property $StorageQualified, id ##FinalStorageQualified.disowned _ = \FinalStorageQualified.disowned } struct IUOProperty { var iuo: IUOBlob! } struct IUOBlob { var x: Int subscript(y: String) -> String { get { return y } set {} } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}11iuoKeyPaths func iuoKeyPaths() { // CHECK: = keypath $WritableKeyPath<IUOProperty, Int>, // CHECK-SAME: stored_property #IUOProperty.iuo // CHECK-SAME: optional_force // CHECK-SAME: stored_property #IUOBlob.x _ = \IUOProperty.iuo.x // CHECK: = keypath $WritableKeyPath<IUOProperty, Int>, // CHECK-SAME: stored_property #IUOProperty.iuo // CHECK-SAME: optional_force // CHECK-SAME: stored_property #IUOBlob.x _ = \IUOProperty.iuo!.x } class Bass: Hashable { static func ==(_: Bass, _: Bass) -> Bool { return false } func hash(into hasher: inout Hasher) {} } class Treble: Bass { } struct Subscripts<T> { subscript() -> T { get { fatalError() } set { fatalError() } } subscript(generic x: T) -> T { get { fatalError() } set { fatalError() } } subscript(concrete x: String) -> String { get { fatalError() } set { fatalError() } } subscript(x: String, y: String) -> String { get { fatalError() } set { fatalError() } } subscript<U>(subGeneric z: U) -> U { get { fatalError() } set { fatalError() } } subscript(mutable x: T) -> T { get { fatalError() } set { fatalError() } } subscript(bass: Bass) -> Bass { get { return bass } set { } } } struct SubscriptDefaults1 { subscript(x: Int = 0) -> Int { get { fatalError() } set { fatalError() } } subscript(x: Int, y: Int, z: Int = 0) -> Int { get { fatalError() } set { fatalError() } } subscript(x: Bool, bool y: Bool = false) -> Bool { get { fatalError() } set { fatalError() } } subscript(bool x: Bool, y: Int, z: Int = 0) -> Int { get { fatalError() } set { fatalError() } } } struct SubscriptDefaults2 { subscript(x: Int? = nil) -> Int { get { fatalError() } set { fatalError() } } } struct SubscriptDefaults3 { subscript(x: Int = #line) -> Int { get { fatalError() } set { fatalError() } } } struct SubscriptDefaults4 { subscript<T : Numeric>(x x: T, y y: T = 0) -> T { get { fatalError() } set { fatalError() } } } struct SubscriptDefaults5 { subscript<T : ExpressibleByStringLiteral>(x x: T, y y: T = #function) -> T { get { fatalError() } set { fatalError() } } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}10subscripts1x1y1syx_q_SStSHRzSHR_r0_lF func subscripts<T: Hashable, U: Hashable>(x: T, y: U, s: String) { _ = \Subscripts<T>.[] _ = \Subscripts<T>.[generic: x] _ = \Subscripts<T>.[concrete: s] _ = \Subscripts<T>.[s, s] _ = \Subscripts<T>.[subGeneric: s] _ = \Subscripts<T>.[subGeneric: x] _ = \Subscripts<T>.[subGeneric: y] _ = \Subscripts<U>.[] _ = \Subscripts<U>.[generic: y] _ = \Subscripts<U>.[concrete: s] _ = \Subscripts<U>.[s, s] _ = \Subscripts<U>.[subGeneric: s] _ = \Subscripts<U>.[subGeneric: x] _ = \Subscripts<U>.[subGeneric: y] _ = \Subscripts<String>.[] _ = \Subscripts<String>.[generic: s] _ = \Subscripts<String>.[concrete: s] _ = \Subscripts<String>.[s, s] _ = \Subscripts<String>.[subGeneric: s] _ = \Subscripts<String>.[subGeneric: x] _ = \Subscripts<String>.[subGeneric: y] _ = \Subscripts<T>.[s, s].count _ = \Subscripts<T>.[Bass()] _ = \Subscripts<T>.[Treble()] _ = \SubscriptDefaults1.[] _ = \SubscriptDefaults1.[0] _ = \SubscriptDefaults1.[0, 0] _ = \SubscriptDefaults1.[0, 0, 0] _ = \SubscriptDefaults1.[false] _ = \SubscriptDefaults1.[false, bool: false] _ = \SubscriptDefaults1.[bool: false, 0] _ = \SubscriptDefaults1.[bool: false, 0, 0] _ = \SubscriptDefaults2.[] _ = \SubscriptDefaults2.[0] _ = \SubscriptDefaults3.[] _ = \SubscriptDefaults3.[0] _ = \SubscriptDefaults4.[x: 0] _ = \SubscriptDefaults4.[x: 0, y: 0] _ = \SubscriptDefaults5.[x: ""] _ = \SubscriptDefaults5.[x: "", y: ""] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}check_default_subscripts func check_default_subscripts() { // CHECK: [[INTX:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0 // CHECK: [[IX:%[0-9]+]] = apply %{{[0-9]+}}([[INTX]], {{.*}} // CHECK: [[INTY:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0 // CHECK: [[IY:%[0-9]+]] = apply %{{[0-9]+}}([[INTY]], {{.*}} // CHECK: [[KEYPATH:%[0-9]+]] = keypath $WritableKeyPath<SubscriptDefaults4, Int>, (root $SubscriptDefaults4; settable_property $Int, id @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluig : $@convention(method) <τ_0_0 where τ_0_0 : Numeric> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults4) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTK : $@convention(thin) (@in_guaranteed SubscriptDefaults4, UnsafeRawPointer) -> @out Int, setter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTk : $@convention(thin) (@in_guaranteed Int, @inout SubscriptDefaults4, UnsafeRawPointer) -> (), indices [%$0 : $Int : $Int, %$1 : $Int : $Int], indices_equals @$sS2iTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2iTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[IX]], [[IY]]) _ = \SubscriptDefaults4.[x: 0, y: 0] // CHECK: [[INTINIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0 // CHECK: [[I:%[0-9]+]] = apply %{{[0-9]+}}([[INTINIT]], {{.*}} // CHECK: [[DFN:%[0-9]+]] = function_ref @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipfA0_ : $@convention(thin) <τ_0_0 where τ_0_0 : Numeric> () -> @out τ_0_0 // CHECK: [[ALLOC:%[0-9]+]] = alloc_stack $Int // CHECK: apply [[DFN]]<Int>([[ALLOC]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Numeric> () -> @out τ_0_0 // CHECK: [[LOAD:%[0-9]+]] = load [trivial] [[ALLOC]] : $*Int // CHECK: [[KEYPATH:%[0-9]+]] = keypath $WritableKeyPath<SubscriptDefaults4, Int>, (root $SubscriptDefaults4; settable_property $Int, id @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluig : $@convention(method) <τ_0_0 where τ_0_0 : Numeric> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults4) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTK : $@convention(thin) (@in_guaranteed SubscriptDefaults4, UnsafeRawPointer) -> @out Int, setter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTk : $@convention(thin) (@in_guaranteed Int, @inout SubscriptDefaults4, UnsafeRawPointer) -> (), indices [%$0 : $Int : $Int, %$1 : $Int : $Int], indices_equals @$sS2iTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2iTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[I]], [[LOAD]]) _ = \SubscriptDefaults4.[x: 0] // CHECK: [[STRX_LIT:%[0-9]+]] = string_literal utf8 "" // CHECK: [[STRX:%[0-9]+]] = apply %{{[0-9]+}}([[STRX_LIT]], {{.*}} // CHECK: [[STRY_LIT:%[0-9]+]] = string_literal utf8 "check_default_subscripts()" // CHECK: [[DEF_ARG:%[0-9]+]] = apply %{{[0-9]+}}([[STRY_LIT]], {{.*}} // CHECK: keypath $WritableKeyPath<SubscriptDefaults5, String>, (root $SubscriptDefaults5; settable_property $String, id @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults5) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptDefaults5, UnsafeRawPointer) -> @out String, setter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTk : $@convention(thin) (@in_guaranteed String, @inout SubscriptDefaults5, UnsafeRawPointer) -> (), indices [%$0 : $String : $String, %$1 : $String : $String], indices_equals @$sS2STH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2STh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[STRX]], [[DEF_ARG]]) _ = \SubscriptDefaults5.[x: ""] // CHECK: [[STRX_LIT:%[0-9]+]] = string_literal utf8 "" // CHECK: [[STRX:%[0-9]+]] = apply %{{[0-9]+}}([[STRX_LIT]], {{.*}} // CHECK: [[STRY_LIT:%[0-9]+]] = string_literal utf8 "" // CHECK: [[STRY:%[0-9]+]] = apply %{{[0-9]+}}([[STRY_LIT]], {{.*}} // CHECK: keypath $WritableKeyPath<SubscriptDefaults5, String>, (root $SubscriptDefaults5; settable_property $String, id @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults5) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptDefaults5, UnsafeRawPointer) -> @out String, setter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTk : $@convention(thin) (@in_guaranteed String, @inout SubscriptDefaults5, UnsafeRawPointer) -> (), indices [%$0 : $String : $String, %$1 : $String : $String], indices_equals @$sS2STH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2STh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[STRX]], [[STRY]]) _ = \SubscriptDefaults5.[x: "", y: ""] } struct SubscriptVariadic1 { subscript(x: Int...) -> Int { x[0] } } struct SubscriptVariadic2 { subscript<T : ExpressibleByStringLiteral>(x: T...) -> T { x[0] } } struct SubscriptVariadic3<T : ExpressibleByStringLiteral> { subscript(x: T...) -> T { x[0] } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}test_variadics func test_variadics() { // CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 3 // CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]]) // CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer) // CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]]) _ = \SubscriptVariadic1.[1, 2, 3] // CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 1 // CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]]) // CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer) // CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]]) _ = \SubscriptVariadic1.[1] // CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 0 // CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]]) // CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer) // CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]]) _ = \SubscriptVariadic1.[] _ = \SubscriptVariadic2.["", "1"] _ = \SubscriptVariadic2.[""] // CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 2 // CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<String>([[ARR_COUNT]]) // CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<String>, Builtin.RawPointer) // CHECK: keypath $KeyPath<SubscriptVariadic2, String>, (root $SubscriptVariadic2; gettable_property $String, id @$s8keypaths18SubscriptVariadic2Vyxxd_tcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@guaranteed Array<τ_0_0>, SubscriptVariadic2) -> @out τ_0_0, getter @$s8keypaths18SubscriptVariadic2Vyxxd_tcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptVariadic2, UnsafeRawPointer) -> @out String, indices [%$0 : $Array<String> : $Array<String>], indices_equals @$sSaySSGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySSGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]]) _ = \SubscriptVariadic2.["", #function] _ = \SubscriptVariadic3<String>.[""] _ = \SubscriptVariadic3<String>.["", "1"] _ = \SubscriptVariadic3<String>.[] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}subclass_generics func subclass_generics<T: C<Int>, U: C<V>, V/*: PoC*/>(_: T, _: U, _: V) { _ = \T.x _ = \T.z _ = \T.computed _ = \T.extension _ = \U.x _ = \U.z _ = \U.computed _ = \U.extension /* _ = \V.x _ = \V.z _ = \V.computed _ = \V.extension */ _ = \(C<Int> & P).x _ = \(C<Int> & P).z _ = \(C<Int> & P).computed _ = \(C<Int> & P).extension _ = \(C<V> & P).x _ = \(C<V> & P).z _ = \(C<V> & P).computed _ = \(C<V> & P).extension /* TODO: When we support superclass requirements on protocols, we should test * this case as well. _ = \PoC.x _ = \PoC.z _ = \PoC.computed _ = \PoC.extension */ } // CHECK-LABEL: sil hidden [ossa] @{{.*}}identity func identity<T>(_: T) { // CHECK: keypath $WritableKeyPath<T, T>, <τ_0_0> ({{.*}}root $τ_0_0) <T> let _: WritableKeyPath<T, T> = \T.self // CHECK: keypath $WritableKeyPath<Array<T>, Array<T>>, <τ_0_0> ({{.*}}root $Array<τ_0_0>) <T> let _: WritableKeyPath<[T], [T]> = \[T].self // CHECK: keypath $WritableKeyPath<String, String>, ({{.*}}root $String) let _: WritableKeyPath<String, String> = \String.self } // CHECK-LABEL: sil hidden [ossa] @{{.*}}tuples func tuples(_: T) { // CHECK: keypath $WritableKeyPath<T, Int>, (root $T; stored_property #T.a : $(Int, String); tuple_element #0 : $Int) let _: WritableKeyPath<T, Int> = \T.a.0 // CHECK: keypath $WritableKeyPath<T, String>, (root $T; stored_property #T.a : $(Int, String); tuple_element #1 : $String) let _: WritableKeyPath<T, String> = \T.a.1 // CHECK: keypath $KeyPath<T, String>, (root $T; stored_property #T.b : $(f: String, g: Int); tuple_element #0 : $String) let _: KeyPath<T, String> = \T.b.f // CHECK: keypath $KeyPath<T, Int>, (root $T; stored_property #T.b : $(f: String, g: Int); tuple_element #1 : $Int) let _: KeyPath<T, Int> = \T.b.g // CHECK: keypath $KeyPath<T, C<Int>>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>) let _: KeyPath<T, C<Int>> = \T.c.x // CHECK: keypath $KeyPath<T, C<String>>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #1 : $C<String>) let _: KeyPath<T, C<String>> = \T.c.y // CHECK: keypath $ReferenceWritableKeyPath<T, Int>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>; stored_property #C.x : $Int) let _: ReferenceWritableKeyPath<T, Int> = \T.c.x.x // CHECK: keypath $KeyPath<T, String>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>; stored_property #C.y : $String) let _: KeyPath<T, String> = \T.c.x.y } // CHECK-LABEL: sil hidden [ossa] @{{.*}}tuples_generic func tuples_generic<T, U, V>(_: T, _: U, _: V) { typealias TUC = (T, U, C<V>) // CHECK: keypath $WritableKeyPath<(T, U, C<V>), T>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #0 : $τ_0_0) <T, U, V> let _: WritableKeyPath<TUC, T> = \TUC.0 // CHECK: keypath $WritableKeyPath<(T, U, C<V>), U>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #1 : $τ_0_1) <T, U, V> let _: WritableKeyPath<TUC, U> = \TUC.1 // CHECK: keypath $ReferenceWritableKeyPath<(T, U, C<V>), V>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #2 : $C<τ_0_2>; stored_property #C.x : $τ_0_2) <T, U, V> let _: ReferenceWritableKeyPath<TUC, V> = \TUC.2.x // CHECK: keypath $KeyPath<(T, U, C<V>), String>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #2 : $C<τ_0_2>; stored_property #C.y : $String) <T, U, V> let _: KeyPath<TUC, String> = \TUC.2.y }
apache-2.0
svedm/SweetyViperDemo
SweetyViperDemo/SweetyViperDemo/Classes/PresentationLayer/UserStories/MainUserStory/Module/Second/Interactor/SecondInteractor.swift
1
258
// // SecondSecondInteractor.swift // SweetyViperDemo // // Created by Svetoslav Karasev on 14/02/2017. // Copyright © 2017 Svedm. All rights reserved. // class SecondInteractor: SecondInteractorInput { weak var output: SecondInteractorOutput! }
mit
AliSoftware/SwiftGen
Sources/TestUtils/Fixtures/Generated/YAML/inline-swift5/all-publicAccess.swift
4
1574
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length // MARK: - YAML Files // swiftlint:disable identifier_name line_length number_separator type_body_length public enum YAMLFiles { public enum Documents { public enum Document1 { public static let items: [String] = ["Mark McGwire", "Sammy Sosa", "Ken Griffey"] } public enum Document2 { public static let items: [String] = ["Chicago Cubs", "St Louis Cardinals"] } } public enum GroceryList { public static let items: [String] = ["Eggs", "Bread", "Milk"] } public enum Mapping { public static let car: Any? = nil public static let doors: Int = 5 public static let flags: [Bool] = [true, false, true] public static let foo: [String: Any] = ["bar": "banana", "baz": "orange"] public static let hello: String = "world" public static let mixed: [Any] = ["one", 2, true] public static let mixed2: [Any] = [0.1, 2, true] public static let names: [String] = ["John", "Peter", "Nick"] public static let newLayout: Bool = true public static let one: Int = 1 public static let primes: [Int] = [2, 3, 5, 7] public static let quickSearch: Bool = false public static let weight: Double = 33.3 public static let zero: Int = 0 } public enum Version { public static let value: String = "1.2.3.beta.4" } } // swiftlint:enable identifier_name line_length number_separator type_body_length
mit
cotkjaer/SilverbackFramework
SilverbackFramework/UIColor.swift
1
3491
// // UIColor.swift // SilverbackFramework // // Created by Christian Otkjær on 20/04/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import UIKit //MARK: - Random extension UIColor { public static func lightestGrayColor() -> UIColor { return UIColor(white: 0.9, alpha: 1.0) } } //MARK: - Random extension UIColor { public static func randomOpaqueColor() -> UIColor { return UIColor( red: CGFloat.random(lower: 0, upper: 1), green: CGFloat.random(lower: 0, upper: 1), blue: CGFloat.random(lower: 0, upper: 1), alpha: 1 ) } public static func randomColor() -> UIColor { return UIColor( red: CGFloat.random(lower: 0, upper: 1), green: CGFloat.random(lower: 0, upper: 1), blue: CGFloat.random(lower: 0, upper: 1), alpha: CGFloat.random(lower: 0, upper: 1) ) } } //MARK: - Alpha public extension UIColor { var alpha : CGFloat { var alpha : CGFloat = 0 getWhite(nil, alpha: &alpha) return alpha } var opaque : Bool { return alpha > 0.999 } } //MARK: - HSB public extension UIColor { private var hsbComponents : (CGFloat, CGFloat, CGFloat, CGFloat) { var h : CGFloat = 0 var s : CGFloat = 0 var b : CGFloat = 0 var a : CGFloat = 0 getHue(&h, saturation: &s, brightness: &b, alpha: &a) return (h,s,b,a) } var hue: CGFloat { return hsbComponents.0 } func withHue(hue: CGFloat) -> UIColor { let hsba = hsbComponents return UIColor(hue: hue, saturation: hsba.1, brightness: hsba.2, alpha: hsba.3) } var saturation: CGFloat { return hsbComponents.1 } func withSaturation(saturation: CGFloat) -> UIColor { let hsba = hsbComponents return UIColor(hue: hsba.0, saturation: saturation, brightness: hsba.2, alpha: hsba.3) } var brightness: CGFloat { return hsbComponents.2 } func withBrightness(brightness: CGFloat) -> UIColor { let hsba = hsbComponents return UIColor(hue: hsba.0, saturation: hsba.1, brightness: brightness, alpha: hsba.3) } } //MARK: - Brightness public extension UIColor { var isBright: Bool { return brightness > 0.75 } var isDark: Bool { return brightness < 0.25 } func brighterColor(factor: CGFloat = 0.2) -> UIColor { return withBrightness(brightness + (1 - brightness) * factor) } func darkerColor(factor: CGFloat = 0.2) -> UIColor { return withBrightness(brightness - (brightness) * factor) } } //MARK: - Image public extension UIColor { public var image: UIImage { let rect = CGRectMake(0, 0, 1, 1) UIGraphicsBeginImageContextWithOptions(rect.size, opaque, 0) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, self.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
touchopia/debuggingfun
completed/DebuggingFun/DebuggingFun/PopupModelViewController.swift
1
487
// // PopupModelViewController.swift // DebuggingFun // // Created by Phil Wright on 11/1/17. // Copyright © 2017 Touchopia, LLC. All rights reserved. // import UIKit class PopupModelViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } // MARK: - Action Methods @IBAction func dismissTapped(_ sender: UIButton) { print("dismissTapped") self.dismiss(animated: true, completion: nil) } }
gpl-3.0
ftdjsxo/SNOperation
Example/Tests/Tests.swift
1
761
import UIKit import XCTest import SNOperation class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
vermont42/Conjugar
Conjugar/RatingsFetcher.swift
1
2262
// // RatingsFetcher.swift // Conjugar // // Created by Joshua Adams on 3/1/19. // Copyright © 2019 Josh Adams. All rights reserved. // import Foundation struct RatingsFetcher { static let iTunesID = "1236500467" static let errorMessage = "Fetching failed." private static let urlInitializationMessage = " URL could not be initializaed." static var iTunesURL: URL { guard let iTunesURL = URL(string: "https://itunes.apple.com/lookup?id=\(iTunesID)") else { fatalError("iTunes" + urlInitializationMessage) } return iTunesURL } static var reviewURL: URL { guard let reviewURL = URL(string: "https://itunes.apple.com/app/conjugar/id\(iTunesID)?action=write-review") else { fatalError("Rate/review" + urlInitializationMessage) } return reviewURL } static func fetchRatingsDescription(completion: @escaping (String) -> ()) { let request = URLRequest(url: RatingsFetcher.iTunesURL) let task = Current.session.dataTask(with: request) { (responseData, _, error) in if error != nil { completion(errorMessage) return } else if let responseData = responseData { guard let json = try? JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any], let results = json["results"] as? [[String: Any]], results.count == 1 else { completion(errorMessage) return } let ratingsCount = (results[0])["userRatingCountForCurrentVersion"] as? Int ?? 0 let description: String let exhortation = " ¡Sé la primera o el primero!" switch ratingsCount { case 0: description = Localizations.Settings.noRating + exhortation case 1: description = Localizations.Settings.oneRating + " " + Localizations.Settings.addYours default: description = String(format: Localizations.Settings.multipleRatings, ratingsCount) + " " + Localizations.Settings.addYours } completion(description) } } task.resume() } static func stubData(ratingsCount: Int) -> Data { return Data("{ \"resultCount\":1, \"results\": [ { \"userRatingCountForCurrentVersion\": \(ratingsCount) } ] }".utf8) } }
agpl-3.0
jdanthinne/PIImageCache
PIImageCache/PIImageCache/PIImageCacheExtensions.swift
2
998
// https://github.com/pixel-ink/PIImageCache import UIKit public extension NSURL { public func getImageWithCache() -> UIImage? { return PIImageCache.shared.get(self) } public func getImageWithCache(cache: PIImageCache) -> UIImage? { return cache.get(self) } } public extension UIImageView { public func imageOfURL(url: NSURL) { PIImageCache.shared.get(url) { [weak self] img in self?.image = img } } public func imageOfURL(url: NSURL, cache: PIImageCache) { cache.get(url) { [weak self] img in self?.image = img } } public func imageOfURL(url: NSURL, then:(Bool)->Void) { PIImageCache.shared.get(url) { [weak self] img in let isOK = img != nil self?.image = img then(isOK) } } public func imageOfURL(url: NSURL, cache: PIImageCache, then:(Bool)->Void) { cache.get(url) { [weak self] img in let isOK = img != nil self?.image = img then(isOK) } } }
mit
arsonik/AKYamahaAV
Source/YamahaAV.swift
1
3934
// // YamahaAV.swift // Pods // // Created by Florian Morello on 11/11/15. // // import Foundation import Alamofire import HTMLReader public class YamahaAV : NSObject { private let baseURL: URL public private(set) var mainZonePower:Bool! public private(set) var mainZoneSleep:Bool! public private(set) var mainZoneVolume:Int! public private(set) var mainZoneInput:String! private var timer:Timer? private let updateNotificationName = "YamahaUpdated" private var listeners:Int = 0 { didSet{ listeners = max(0, listeners) if listeners == 0 { // stop auto update timer?.invalidate() } else if listeners == 1 && (timer == nil || timer?.isValid == false) { timer = Timer(timeInterval: 2, target: self, selector: Selector(("poll:")), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes) } } } public init(host:String) { baseURL = URL(string: "http://\(host)/YamahaRemoteControl/ctrl")! super.init() } public func startListening(_ observer: NSObject, selector: Selector) { NotificationCenter.default.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: updateNotificationName), object: self) listeners += 1 timer?.fire() } public func stopListening(observer: NSObject){ listeners -= 1 NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: updateNotificationName), object: self) } internal func poll(timer: Timer) { let payload = "<YAMAHA_AV cmd=\"GET\"><Main_Zone><Basic_Status>GetParam</Basic_Status></Main_Zone></YAMAHA_AV>" post(payload: payload) { [weak self] (result, error) -> Void in if let str = result, let ss = self { let xml = HTMLDocument(string: str) if let vol = (xml.nodes(matchingSelector: "Volume Lvl Val").first)?.textContent { ss.mainZoneVolume = Int(vol) } if let value = (xml.nodes(matchingSelector: "Power_Control Power").first)?.textContent { ss.mainZonePower = value == "On" } if let value = (xml.nodes(matchingSelector: "Power_Control Sleep").first)?.textContent { ss.mainZoneSleep = value == "On" } if let value = (xml.nodes(matchingSelector: "Input_Sel").first)?.textContent { ss.mainZoneInput = value } NotificationCenter.default.post(name: NSNotification.Name(rawValue: ss.updateNotificationName), object: self) } else { print(error) } } } public func setMainZonePower(on: Bool) -> Request { return post(payload: "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Power_Control><Power>\(on ? "On" : "Standby")</Power></Power_Control></Main_Zone></YAMAHA_AV>") } public func setMainZoneInput(input: String) -> Request { return post(payload: "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Input><Input_Sel>\(input)</Input_Sel></Input></Main_Zone></YAMAHA_AV>") } public func setMainZoneVolume(value:Int) -> Request { let vol = Int((round((Float(value) / 10) * 2) / 2) * 10) mainZoneVolume = vol //<YAMAHA_AV cmd="PUT"><Main_Zone><Volume><Lvl><Val>-300</Val><Exp>1</Exp><Unit>dB</Unit></Lvl></Volume></Main_Zone></YAMAHA_AV> let payload = "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Volume><Lvl><Val>\(vol)</Val><Exp>1</Exp><Unit>dB</Unit></Lvl></Volume></Main_Zone></YAMAHA_AV>" return post(payload: payload) } private func post(payload:String, completion:((String?, Error?) -> Void)! = nil) -> Request { var request = URLRequest(url: baseURL as URL) request.setValue("text/xml", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = payload.data(using: String.Encoding.utf8) return Alamofire.request(request).responseString { (response) -> Void in completion?(response.result.value, response.result.error) } } }
mit
sharath-cliqz/browser-ios
Client/Frontend/Browser/SwipeAnimator.swift
2
5568
/* 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 struct SwipeAnimationParameters { let totalRotationInDegrees: Double let deleteThreshold: CGFloat let totalScale: CGFloat let totalAlpha: CGFloat let minExitVelocity: CGFloat let recenterAnimationDuration: TimeInterval } private let DefaultParameters = SwipeAnimationParameters( totalRotationInDegrees: 10, deleteThreshold: 80, totalScale: 0.9, totalAlpha: 0, minExitVelocity: 800, recenterAnimationDuration: 0.15) protocol SwipeAnimatorDelegate: class { func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) } class SwipeAnimator: NSObject { weak var delegate: SwipeAnimatorDelegate? weak var container: UIView! weak var animatingView: UIView! fileprivate var prevOffset: CGPoint! fileprivate let params: SwipeAnimationParameters var containerCenter: CGPoint { return CGPoint(x: container.frame.width / 2, y: container.frame.height / 2) } init(animatingView: UIView, container: UIView, params: SwipeAnimationParameters = DefaultParameters) { self.animatingView = animatingView self.container = container self.params = params super.init() let panGesture = UIPanGestureRecognizer(target: self, action: #selector(SwipeAnimator.SELdidPan(_:))) container.addGestureRecognizer(panGesture) panGesture.delegate = self } } //MARK: Private Helpers extension SwipeAnimator { fileprivate func animateBackToCenter() { UIView.animate(withDuration: params.recenterAnimationDuration, animations: { self.animatingView.transform = CGAffineTransform.identity self.animatingView.alpha = 1 }) } fileprivate func animateAwayWithVelocity(_ velocity: CGPoint, speed: CGFloat) { // Calculate the edge to calculate distance from let translation = velocity.x >= 0 ? container.frame.width : -container.frame.width let timeStep = TimeInterval(abs(translation) / speed) self.delegate?.swipeAnimator(self, viewWillExitContainerBounds: self.animatingView) UIView.animate(withDuration: timeStep, animations: { self.animatingView.transform = self.transformForTranslation(translation) self.animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation)) }, completion: { finished in if finished { self.animatingView.alpha = 0 } }) } fileprivate func transformForTranslation(_ translation: CGFloat) -> CGAffineTransform { let swipeWidth = container.frame.size.width let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * M_PI) // Determine rotation / scaling amounts by the distance to the edge let rotation = (translation / swipeWidth) * totalRotationInRadians let scale = 1 - (abs(translation) / swipeWidth) * (1 - params.totalScale) let rotationTransform = CGAffineTransform(rotationAngle: rotation) let scaleTransform = CGAffineTransform(scaleX: scale, y: scale) let translateTransform = CGAffineTransform(translationX: translation, y: 0) return rotationTransform.concatenating(scaleTransform).concatenating(translateTransform) } fileprivate func alphaForDistanceFromCenter(_ distance: CGFloat) -> CGFloat { let swipeWidth = container.frame.size.width return 1 - (distance / swipeWidth) * (1 - params.totalAlpha) } } //MARK: Selectors extension SwipeAnimator { @objc func SELdidPan(_ recognizer: UIPanGestureRecognizer!) { let translation = recognizer.translation(in: container) switch (recognizer.state) { case .began: prevOffset = containerCenter case .changed: animatingView.transform = transformForTranslation(translation.x) animatingView.alpha = alphaForDistanceFromCenter(abs(translation.x)) prevOffset = CGPoint(x: translation.x, y: 0) case .cancelled: animateBackToCenter() case .ended: let velocity = recognizer.velocity(in: container) // Bounce back if the velocity is too low or if we have not reached the threshold yet let speed = max(abs(velocity.x), params.minExitVelocity) if (speed < params.minExitVelocity || abs(prevOffset.x) < params.deleteThreshold) { animateBackToCenter() } else { animateAwayWithVelocity(velocity, speed: speed) } default: break } } func close(_ right: Bool) { let direction = CGFloat(right ? -1 : 1) animateAwayWithVelocity(CGPoint(x: -direction * params.minExitVelocity, y: 0), speed: direction * params.minExitVelocity) } @objc func SELcloseWithoutGesture() -> Bool { close(false) return true } } extension SwipeAnimator: UIGestureRecognizerDelegate { @objc func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool { let cellView = recognizer.view as UIView! let panGesture = recognizer as! UIPanGestureRecognizer let translation = panGesture.translation(in: cellView?.superview!) return fabs(translation.x) > fabs(translation.y) } }
mpl-2.0
naokuro/sticker
Carthage/Checkouts/RapidFire/RapidFire/RapidFire.Setting.swift
1
1465
// // RapidFire.Setting.swift // RapidFire // // Created by keygx on 2016/11/19. // Copyright © 2016年 keygx. All rights reserved. // import Foundation extension RapidFire { public enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" } public struct PartData { public var name: String public var filename: String public var value: Data public var mimeType: String public init(name: String, filename: String, value: Data, mimeType: String) { self.name = name self.filename = filename self.value = value self.mimeType = mimeType } } class RequestSetting { var method: HTTPMethod? var baseUrl: String? var path: String? var headers: [String: String]? var query: [String: String]? var bodyParams: [String: String]? var bodyData: Data? var json: [String: Any]? var partDataParams: [String: String]? var partDataBinary: [PartData]? var timeoutInterval: TimeInterval? var retryCount: Int = 0 var retryInterval: Int = 15 var completionHandler: ((RapidFire.Response) -> Void)? } }
mit
Darshanptl7500/DPParallaxCell
DPParallaxCell/DPParallaxCell.swift
1
2357
// // DPParallaxCell.swift // DPParallaxCell // // Created by Darshan Patel on 7/29/15. // Copyright (c) 2015 Darshan Patel. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Darshan Patel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class DPParallaxCell: UITableViewCell { @IBOutlet weak var imgParallax: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func cellParallax(tableView: UITableView!,view: UIView!) { let rect = tableView.convertRect(self.frame, toView: view) let distanceFromCenter = (CGRectGetHeight(view.frame)/2) - CGRectGetMinY(rect) let difference = CGRectGetHeight(self.imgParallax.frame) - CGRectGetHeight(self.frame) let move = (distanceFromCenter / CGRectGetHeight(view.frame)) * difference var imageRect = self.imgParallax.frame imageRect.origin.y = -(difference/2) + move self.imgParallax.frame = imageRect } }
mit
lukevanin/onthemap
OnTheMap/PaddedTextField.swift
1
1094
// // PaddedTextField.swift // OnTheMap // // Created by Luke Van In on 2017/01/14. // Copyright © 2017 Luke Van In. All rights reserved. // // Text field with internal padding. Padding creates additional white-space around the input text which aids usability. // Used on all input fields. // import UIKit class PaddedTextField: UITextField { var padding = CGSize(width: 16.0, height: 4.0) override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 4 } override func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: padding.width, dy: padding.height) } override func layoutSubviews() { super.layoutSubviews() let diameter = min(bounds.width, bounds.height) layer.cornerRadius = diameter * 0.5 } }
mit
ijovi23/JvPunchIO
JvPunchIO-Recorder/Pods/FileKit/Sources/NSDataFile.swift
2
2381
// // DataFile.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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 /// A representation of a filesystem data file. /// /// The data type is NSData. public typealias NSDataFile = File<NSData> extension File where DataType: NSData { /// Reads the file and returns its data. /// - Parameter options: A mask that specifies write options /// described in `NSData.ReadingOptions`. /// /// - Throws: `FileKitError.ReadFromFileFail` /// - Returns: The data read from file. public func read(_ options: NSData.ReadingOptions) throws -> NSData { return try NSData.read(from: path, options: options) } /// Writes data to the file. /// /// - Parameter data: The data to be written to the file. /// - Parameter options: A mask that specifies write options /// described in `NSData.WritingOptions`. /// /// - Throws: `FileKitError.WriteToFileFail` /// public func write(_ data: NSData, options: NSData.WritingOptions) throws { do { try data.write(toFile: self.path._safeRawValue, options: options) } catch { throw FileKitError.writeToFileFail(path: self.path) } } }
mit
arnaudbenard/my-npm
my-npm/ModuleDetailViewController.swift
2
6448
// // ModuleDetailViewController.swift // my-npm // // Created by Arnaud Benard on 28/07/2015. // Copyright (c) 2015 Arnaud Benard. All rights reserved. // import UIKit import Charts class ModuleDetailViewController: UIViewController, ChartViewDelegate { @IBOutlet var ModuleDetailView: UIView! @IBOutlet weak var chartView: LineChartView! @IBOutlet weak var monthCountLabel: UILabel! @IBOutlet weak var weekCountLabel: UILabel! @IBOutlet weak var dayCountLabel: UILabel! let npm = npmAPI() let blueColor = UIColor(red:0.34, green:0.72, blue:1.00, alpha:1.0) var moduleName: String = "" var days: [String] = [String]() var downloads: [Double] = [Double]() var dataEntries: [ChartDataEntry] = [] override func viewDidLoad() { super.viewDidLoad() // Invalid module name if count(moduleName) == 0 { return } self.fetchGraphData(moduleName) self.fetchGlobalStat(moduleName) chartView.delegate = self; chartView.descriptionText = ""; chartView.noDataTextDescription = "Data will be loaded soon." chartView.noDataText = "" chartView.infoTextColor = UIColor.whiteColor() chartView.drawGridBackgroundEnabled = false // remove gray bg // lagging when there're a lot of data points chartView.pinchZoomEnabled = false chartView.doubleTapToZoomEnabled = false chartView.scaleXEnabled = false chartView.scaleYEnabled = false } override func viewDidAppear(animated: Bool) { self.navigationController?.navigationBar.topItem?.title = moduleName } private func setData(xAxis: [String], yAxis: [Double]) { var chartDataY = yAxis for i in 0..<chartDataY.count { let dataEntry = ChartDataEntry(value: chartDataY[i], xIndex: i) dataEntries.append(dataEntry) } let chartDataSet = LineChartDataSet(yVals: dataEntries, label: "Downloads per day") // line graph style chartDataSet.cubicIntensity = 0.05 chartDataSet.drawCubicEnabled = true chartDataSet.drawCircleHoleEnabled = false chartDataSet.circleRadius = CGFloat(0.0) chartDataSet.setColor(UIColor.whiteColor()) chartDataSet.highlightEnabled = false chartDataSet.lineWidth = 1 chartDataSet.drawValuesEnabled = false let chartData = LineChartData(xVals: xAxis, dataSet: chartDataSet) chartView.data = chartData // Hide label on the right let yAxisRight = chartView.getAxis(ChartYAxis.AxisDependency.Right) yAxisRight.drawLabelsEnabled = false yAxisRight.drawGridLinesEnabled = false yAxisRight.drawAxisLineEnabled = false // Format Y axis labels let yAxisLeft = chartView.getAxis(ChartYAxis.AxisDependency.Left) yAxisLeft.valueFormatter = BigNumberFormatter() yAxisLeft.drawGridLinesEnabled = false chartView.drawBordersEnabled = false chartView.leftAxis.customAxisMin = max(0.0, chartView.data!.yMin - 1.0) chartView.leftAxis.customAxisMax = chartView.data!.yMax + 1.0 chartView.leftAxis.labelCount = 6 chartView.leftAxis.startAtZeroEnabled = false chartView.leftAxis.drawGridLinesEnabled = true chartView.leftAxis.gridColor = UIColor.whiteColor() let smallFont = UIFont(name: "HelveticaNeue-Light" , size: 10)! chartView.leftAxis.labelFont = smallFont chartView.leftAxis.labelTextColor = UIColor.whiteColor() chartView.leftAxis.drawAxisLineEnabled = false chartView.xAxis.labelFont = smallFont chartView.xAxis.labelPosition = .Bottom chartView.xAxis.gridColor = UIColor.whiteColor() chartView.xAxis.labelTextColor = UIColor.whiteColor() chartView.xAxis.avoidFirstLastClippingEnabled = true chartView.xAxis.drawAxisLineEnabled = false } private func formatDayLabel(day: String) -> String { // Format from npm api: YYYY-MM-DD let toDateFormatter = NSDateFormatter() toDateFormatter.dateFormat = "YYYY-MM-dd" // String to date let dayDate = toDateFormatter.dateFromString(day)! let labelFormatter = NSDateFormatter() labelFormatter.dateFormat = "d MMM yyyy" let dateFormatted = labelFormatter.stringFromDate(dayDate) return dateFormatted } private func getCurrentDateAsString() -> String { let date = NSDate() let calendar = NSCalendar.currentCalendar() let toStringFormatter = NSDateFormatter() toStringFormatter.dateFormat = "YYYY-MM-dd" let dateFormatted = toStringFormatter.stringFromDate(date) return dateFormatted } private func fetchGraphData(name: String) { let today = getCurrentDateAsString() npm.fetchRange(name, start: "2013-01-04", end: today) { response, _ in if let range = response { for data in range { if let dls = data["downloads"] as? Double, let day = data["day"] as? String { self.downloads.append(dls) self.days.append(self.formatDayLabel(day)) } } self.setData(self.days, yAxis: self.downloads) self.chartView.setNeedsDisplay() } } } private func fetchGlobalStat(name: String) { // Get ready for the worst code I wrote. Yolo async -> Needs to be refactored with promises ASAP npm.fetchModule(name, period: .LastMonth) { response, _ in if let downloads = response!["downloads"] as? Double { self.monthCountLabel.text = downloads.toDecimalStyle } } npm.fetchModule(name, period: .LastWeek) { response, _ in if let downloads = response!["downloads"] as? Double { self.weekCountLabel.text = downloads.toDecimalStyle } } npm.fetchModule(name, period: .LastDay) { response, _ in if let downloads = response!["downloads"] as? Double { self.dayCountLabel.text = downloads.toDecimalStyle } } } }
mit
1ceBrick/MacVideoOpener
VideoOpener/AppDelegate.swift
1
391
// // AppDelegate.swift // VideoOpener // // Created by Stas Chmilenko on 01.07.17. // Copyright © 2017 Stas Chmilenko. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { } func applicationWillTerminate(_ aNotification: Notification) { } }
mit
FengDeng/RxGitHubAPI
RxGitHubAPI/RxGitHubAPI/YYCommitCommentEvent.swift
1
308
// // YYCommitCommentEvent.swift // RxGitHubAPI // // Created by 邓锋 on 16/2/2. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYCommitCommentEvent : NSObject{ public private(set) var action = "" public private(set) var comment = YYCommitComment() }
apache-2.0
nathantannar4/InputBarAccessoryView
Example/Sources/Cells/ImageCell.swift
1
1831
// // ImageCell.swift // Example // // Copyright © 2017-2020 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 1/29/18. // import UIKit class ImageCell: UICollectionViewCell { class var reuseIdentifier: String { return "ImageCell" } let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { addSubview(imageView) imageView.contentMode = .scaleAspectFit } override func layoutSubviews() { super.layoutSubviews() imageView.frame = bounds } }
mit
joerocca/GitHawk
Pods/Tabman/Sources/Tabman/TabmanBar/Components/Indicator/Styles/TabmanLineIndicator.swift
1
2228
// // TabmanLineIndicator.swift // Tabman // // Created by Merrick Sapsford on 20/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit public extension TabmanIndicator { /// Weight of the indicator line. /// /// - thin: Thin - 1pt /// - normal: Normal - 2pt /// - thick: Thick - 4pt public enum LineWeight: CGFloat { case thin = 1.0 case normal = 2.0 case thick = 4.0 } } internal class TabmanLineIndicator: TabmanIndicator { // // MARK: Properties // /// The thickness of the indicator line. /// /// Default is .normal public var weight: LineWeight = TabmanBar.Appearance.defaultAppearance.indicator.lineWeight ?? .normal { didSet { guard weight != oldValue else { return } self.invalidateIntrinsicContentSize() self.superview?.setNeedsLayout() self.superview?.layoutIfNeeded() self.delegate?.indicator(requiresLayoutInvalidation: self) } } /// Whether to use rounded corners for the indicator line. /// /// Default is false public var useRoundedCorners: Bool = TabmanBar.Appearance.defaultAppearance.indicator.useRoundedCorners ?? false { didSet { self.setNeedsLayout() } } /// The color of the indicator line. override public var tintColor: UIColor! { didSet { self.backgroundColor = tintColor } } override public var intrinsicContentSize: CGSize { return CGSize(width: 0.0, height: self.weight.rawValue) } // // MARK: Lifecycle // public override func constructIndicator() { self.tintColor = TabmanBar.Appearance.defaultAppearance.indicator.color } override public func layoutSubviews() { super.layoutSubviews() self.layoutIfNeeded() self.layer.cornerRadius = useRoundedCorners ? self.bounds.size.height / 2.0 : 0.0 } override func itemTransitionType() -> TabmanItemTransition.Type? { return TabmanItemColorCrossfadeTransition.self } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/02089-swift-typechecker-resolvetypeincontext.swift
11
471
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse enum A : b protocol b { protocol a { typealias f : e = T>?) -> { } typealias e
apache-2.0
psobot/hangover
Hangover/Dictionary+Swifter.swift
1
3111
// // Dictionary+Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 String { func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String { let charactersToBeEscaped = ":/?&=;+!@#$()',*" as CFStringRef let charactersToLeaveUnescaped = "[]." as CFStringRef let str = self as NSString let result = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str as CFString, charactersToLeaveUnescaped, charactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) as NSString return result as String } } extension Dictionary { func filter(predicate: Element -> Bool) -> Dictionary { var filteredDictionary = Dictionary() for (key, value) in self { if predicate(key, value) { filteredDictionary[key] = value } } return filteredDictionary } func queryStringWithEncoding() -> String { var parts = [String]() for (key, value) in self { let keyString: String = "\(key)" let valueString: String = "\(value)" let query: String = "\(keyString)=\(valueString)" parts.append(query) } return "&".join(parts) } func urlEncodedQueryStringWithEncoding(encoding: NSStringEncoding) -> String { var parts = [String]() for (key, value) in self { let keyString: String = "\(key)".urlEncodedStringWithEncoding(encoding) let valueString: String = "\(value)".urlEncodedStringWithEncoding(encoding) let query: String = "\(keyString)=\(valueString)" parts.append(query) } return "&".join(parts) } } infix operator +| {} func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> { var map = Dictionary<K,V>() for (k, v) in left { map[k] = v } for (k, v) in right { map[k] = v } return map }
mit
weipin/Cycles
Tests/Cycle+ConvenienceTests.swift
1
4769
// // Cycle+ConvenienceTests.swift // // Copyright (c) 2014 Weipin Xia // // 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 CyclesTouch class CycleConvenienceTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGETShouldWork() { var expection = self.expectationWithDescription("") var URLString = t_("hello") Cycle.get(URLString, completionHandler: {(cycle, error) in XCTAssertNil(error) XCTAssertEqual(cycle.response.text!, "Hello World"); XCTAssertEqual(cycle.response!.statusCode!, 200); expection.fulfill() }) self.waitForExpectationsWithTimeout(Timeout, handler: nil) } func testGETWithParametersShouldWork() { var expection = self.expectationWithDescription("") var URLString = t_("echo") Cycle.get(URLString, parameters: ["content": ["helloworld"]], completionHandler: {(cycle, error) in XCTAssertNil(error) XCTAssertEqual(cycle.response.text!, "helloworld"); XCTAssertEqual(cycle.response!.statusCode!, 200); expection.fulfill() }) self.waitForExpectationsWithTimeout(Timeout, handler: nil) } func testPOSTShouldWork() { var expection = self.expectationWithDescription("") var URLStrng = t_("dumpupload/") var requestObject = NSDictionary(object: "v1", forKey: "k1") Cycle.post(URLStrng, requestObject: requestObject, requestProcessors: [JSONProcessor()], responseProcessors: [JSONProcessor()], completionHandler: {(cycle, error) in XCTAssertNil(error) var dict = cycle.response.object as? NSDictionary XCTAssertNotNil(dict) var value = dict!.objectForKey("k1") as? String XCTAssertNotNil(value) XCTAssertEqual(value!, "v1") expection.fulfill() }) self.waitForExpectationsWithTimeout(Timeout, handler: nil) } func testUploadShouldWork() { var data = "Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var expection = self.expectationWithDescription("") var URLString = t_("dumpupload/") Cycle.upload(URLString, data: data!, completionHandler: { (cycle, error) in XCTAssertNil(error) XCTAssertEqual(cycle.response.text!, "Hello World") expection.fulfill() }) self.waitForExpectationsWithTimeout(Timeout, handler: nil) } func testDownloadShouldWork() { var expection = self.expectationWithDescription("") var URLString = t_("echo?content=helloworld") Cycle.download(URLString, downloadFileHandler: {(cycle, location) in XCTAssertNotNil(location) var content = NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding, error: nil) XCTAssertEqual(content!, "helloworld") }, completionHandler: {(cycle, error) in XCTAssertNil(error) expection.fulfill() }) self.waitForExpectationsWithTimeout(Timeout, handler: nil) } }
mit