repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rambler-ios/RamblerConferences
Carthage/Checkouts/rides-ios-sdk/source/UberRides/Request.swift
1
7148
// // Request.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. 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. /** * Struct that packages the response from an executed NSURLRequest. */ @objc(UBSDKResponse) public class Response: NSObject { /// String representing JSON response data. public var data: NSData? /// HTTP status code of response. public var statusCode: Int /// Response metadata. public var response: NSHTTPURLResponse? /// NSError representing an optional error. public var error: RidesError? /** Initialize a Response object. - parameter data: Data returned from server. - parameter response: Provides response metadata, such as HTTP headers and status code. - parameter error: Indicates why the request failed, or nil if the request was successful. */ init(data: NSData?, statusCode: Int, response: NSHTTPURLResponse?, error: RidesError?) { self.data = data self.response = response self.statusCode = statusCode self.error = error } /** - returns: string representation of JSON data. */ func toJSONString() -> NSString { guard let data = data else { return "" } return NSString(data: data, encoding: NSUTF8StringEncoding)! } } /// Class to create and execute NSURLRequests. class Request: NSObject { let session: NSURLSession? let endpoint: UberAPI let urlRequest: NSMutableURLRequest let serverToken: NSString? let bearerToken: NSString? /** Initialize a request object. - parameter hostURL: Host URL string for API. - parameter session: NSURLSession to execute request with. - parameter endpoint: UberAPI conforming endpoint. - parameter serverToken: Developer's server token. */ init(session: NSURLSession?, endpoint: UberAPI, serverToken: NSString? = nil, bearerToken: NSString? = nil) { self.session = session self.endpoint = endpoint self.urlRequest = NSMutableURLRequest() self.serverToken = serverToken self.bearerToken = bearerToken } /** Creates a URL based off the endpoint requested. Function asserts for valid URL. - returns: constructed NSURL or nil if construction failed. */ func requestURL() -> NSURL? { let components = NSURLComponents(string: endpoint.host)! components.path = endpoint.path components.queryItems = endpoint.query return components.URL } /** Adds HTTP Headers to the request. */ private func addHeaders() { urlRequest.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding") if let token = bearerToken { urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: Header.Authorization.rawValue) } else if let token = serverToken { urlRequest.setValue("Token \(token)", forHTTPHeaderField: Header.Authorization.rawValue) } if let headers = endpoint.headers { for (header,value) in headers { urlRequest.setValue(value, forHTTPHeaderField: header) } } } /** Prepares the NSURLRequest by adding necessary fields. */ func prepare() { urlRequest.URL = requestURL() urlRequest.HTTPMethod = endpoint.method.rawValue urlRequest.HTTPBody = endpoint.body addHeaders() } /** Performs all steps to execute request (construct URL, add headers, etc). - parameter completion: completion handler for returned Response. */ func execute(completion: (response: Response) -> Void) { guard let session = session else { return } prepare() let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in let httpResponse: NSHTTPURLResponse? = response as? NSHTTPURLResponse var statusCode: Int = 0 var ridesError: RidesError? // Handle HTTP errors. errorCheck: if httpResponse != nil { statusCode = httpResponse!.statusCode if statusCode <= 299 { break errorCheck } let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)! if statusCode >= 400 && statusCode <= 499 { ridesError = ModelMapper<RidesClientError>().mapFromJSON(jsonString) } else if (statusCode >= 500 && statusCode <= 599) { ridesError = ModelMapper<RidesServerError>().mapFromJSON(jsonString) } else { ridesError = ModelMapper<RidesUnknownError>().mapFromJSON(jsonString) } ridesError?.status = statusCode } // Any other errors. if response == nil || error != nil { ridesError = RidesUnknownError() if let error = error { ridesError!.title = error.domain ridesError!.status = error.code } else { ridesError!.title = "Request could not complete" ridesError!.code = "request_error" } } let ridesResponse = Response(data: data, statusCode: statusCode, response: httpResponse, error: ridesError) completion(response: ridesResponse) }) task.resume() } /** * Cancel data tasks if needed. */ func cancelTasks() { guard let session = session else { return } session.getTasksWithCompletionHandler({ data, upload, download in for task in data { task.cancel() } }) } }
mit
d604adfa424051051eeb131647f7687b
34.557214
119
0.606268
5.259014
false
false
false
false
acchou/RxGmail
Example/RxGmail/LabelViewController.swift
1
1127
import UIKit import RxSwift import RxCocoa import RxGmail class LabelViewController: UITableViewController { let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let inputs = LabelViewModelInputs () let outputs = global.labelViewModel(inputs) tableView.dataSource = nil outputs.labels.bindTo(tableView.rx.items(cellIdentifier: "Label")) { row, label, cell in cell.textLabel?.text = label.name } .disposed(by: disposeBag) tableView.rx .modelSelected(Label.self) .subscribe(onNext: { self.performSegue(withIdentifier: "ShowLabelDetail", sender: $0) }) .disposed(by: disposeBag) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let labelDetailVC = segue.destination as! LabelDetailViewController labelDetailVC.selectedLabel = sender as! Label } }
mit
f35568c47af1e380b0d77e786d52839d
27.897436
96
0.648625
5.146119
false
false
false
false
Soryu/DummyCalendarEvents
DummyCalendarEvents/ViewController.swift
1
10221
// // ViewController.swift // DummyCalendarEvents // // Created by Stanley Rost on 14.08.15. // Copyright © 2015 soryu2. All rights reserved. // import UIKit import EventKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var calendarPickerView: UIPickerView! @IBOutlet weak var startDatePickerView: UIDatePicker! @IBOutlet weak var intervalSlider: UISlider! @IBOutlet weak var intervalValueLabel: UILabel! @IBOutlet weak var minStartTimeSlider: UISlider! @IBOutlet weak var minStartTimeValueLabel: UILabel! @IBOutlet weak var maxStartTimeSlider: UISlider! @IBOutlet weak var maxStartTimeValueLabel: UILabel! @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var durationValueLabel: UILabel! @IBOutlet weak var allDayProbabilitySlider: UISlider! @IBOutlet weak var allDayProbabilityValueLabel: UILabel! let eventStore = EKEventStore() var calendars:Array<EKCalendar> = [] var isWorking = false { didSet { navigationItem.rightBarButtonItem?.enabled = !isWorking } } // TODO: Other calendar types besides Gregorian let timeCalendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian)! override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem?.enabled = false switch EKEventStore.authorizationStatusForEntityType(.Event) { case .NotDetermined: eventStore .requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.setupView() }) }) case .Authorized: setupView() default: break } intervalSlider.value = 60 minStartTimeSlider.value = 8 * 4 maxStartTimeSlider.value = 17 * 4 durationSlider.value = 3 * 4 allDayProbabilitySlider.value = 0.1 updateIntervalLabel() updateMinStartTimeLabel() updateMaxStartTimeLabel() updateDurationLabel() updateAllDayProbabilityLabel() } func setupView() { calendars = eventStore.calendarsForEntityType(.Event) .filter({ !$0.immutable }) .sort({ $0.title < $1.title }) navigationItem.rightBarButtonItem?.enabled = calendars.count > 0 calendarPickerView.reloadAllComponents() } // MARK: Work func createDummyEventsInCalendar(eventCalendar:EKCalendar, fromDate:NSDate, interval:Int, minStartQuarterHour:Int, maxStartQuarterHour:Int, maxDuration:Int, allDayProbability:Float) throws -> Int { var numberOfEventsCreated = 0 let titles = ["Meeting", "Party", "BBQ", "Pick up kids", "Cleaning", "Dinner", "Lunch", "Buy presents", "Dance", "Reminder", "Call X"] // sanity, cannot have finish before start let sanitizedMaxStartQuarterHour = max(maxStartQuarterHour, minStartQuarterHour) var numberOfLoops = Int(Double(interval) * 1.5) while numberOfLoops-- > 0 { // TODO: clean up casting when using arc4random_uniform? how? let title = titles[Int(arc4random_uniform(UInt32(titles.count)))] let day = Int(arc4random_uniform(UInt32(interval))) let startQuarterHour = minStartQuarterHour + Int(arc4random_uniform(UInt32(sanitizedMaxStartQuarterHour - minStartQuarterHour))) let durationInQuarterHours = 1 + Int(arc4random_uniform(UInt32(maxDuration))) let allDay = Float(arc4random_uniform(1000)) / 1000 < allDayProbability var startDate = timeCalendar.dateBySettingHour(0, minute:0, second:0, ofDate:fromDate, options:[])! startDate = timeCalendar.dateByAddingUnit(.Day, value:day, toDate:startDate, options:[])! if !allDay { startDate = timeCalendar.dateBySettingHour(startQuarterHour / 4, minute:(startQuarterHour % 4) * 15, second:0, ofDate:startDate, options:[])! } let components = NSDateComponents() // confusing to use let, I change it components.hour = durationInQuarterHours / 4; components.minute = (durationInQuarterHours % 4) * 15; let endDate = timeCalendar.dateByAddingComponents(components, toDate:startDate, options:[])! let event = EKEvent.init(eventStore: eventStore) // confusing to use let, I change it event.calendar = eventCalendar; event.title = title; event.startDate = startDate; event.endDate = endDate; event.allDay = allDay; do { try eventStore.saveEvent(event, span: .ThisEvent) numberOfEventsCreated++ } catch let error as NSError { NSLog("%@", error) } } try eventStore.commit() return numberOfEventsCreated; } // MARK: Actions @IBAction func goButtonPressed(sender: AnyObject) { isWorking = true let calendarRow = calendarPickerView.selectedRowInComponent(0) let calendar = calendars[calendarRow] let startDate = startDatePickerView.date; let interval = Int(floor(intervalSlider.value)) let minStartQuarterHour = Int(floor(minStartTimeSlider.value)) let maxStartQuarterHour = Int(floor(maxStartTimeSlider.value)) let duration = Int(floor(durationSlider.value)) let allDayProbability = floor(allDayProbabilitySlider.value * 1000) / 1000 // TODO: work on bg thread and show progress let benchmarkStartDate = NSDate() let message:String do { let numberOfEventsCreated:Int try numberOfEventsCreated = createDummyEventsInCalendar(calendar, fromDate: startDate, interval:interval, minStartQuarterHour: minStartQuarterHour, maxStartQuarterHour:maxStartQuarterHour, maxDuration:duration, allDayProbability:allDayProbability) message = NSString(format: "%zd events created in %.1f seconds", numberOfEventsCreated, NSDate().timeIntervalSinceDate(benchmarkStartDate)) as String } catch let error as NSError { message = error.localizedDescription } let alert = UIAlertController(title: "Done", message: message, preferredStyle: .Alert) // confusing to use let, I change it alert.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) isWorking = false } @IBAction func intervalSliderChanged(sender: AnyObject) { updateIntervalLabel() } @IBAction func minStartTimeSliderChanged(sender: AnyObject) { updateMinStartTimeLabel() } @IBAction func maxStartTimeSliderChanged(sender: AnyObject) { updateMaxStartTimeLabel() } @IBAction func durationSliderChanged(sender: AnyObject) { updateDurationLabel() } @IBAction func allDayProbabilitySliderChanged(sender: AnyObject) { updateAllDayProbabilityLabel() } // MARK: UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return max(calendars.count, 1) } // MARK: UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if calendars.count == 0 { return "<No calendars>" } return calendars[row].title } // MARK: Helpers func dateFromQuarterHours(numberOfQuarterHours:NSInteger) -> NSDate { let date = NSDate.init(timeIntervalSinceReferenceDate: 0) return timeCalendar.dateBySettingHour(numberOfQuarterHours / 4, minute: (numberOfQuarterHours % 4) * 15, second: 0, ofDate: date, options: [])! } // TODO: dateFormatter should be a property func dateFormatter() -> NSDateFormatter { let formatter = NSDateFormatter() // confusing to use let, I change it formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("jjmm", options: 0, locale: timeCalendar.locale) return formatter } // MARK: UI/ViewModel func updateIntervalLabel() { let interval = floor(intervalSlider.value) intervalValueLabel.text = "\(interval)" } func updateMinStartTimeLabel() { let numberOfQuarterHours = Int(floor(minStartTimeSlider.value)) let date = dateFromQuarterHours(numberOfQuarterHours) minStartTimeValueLabel.text = dateFormatter().stringFromDate(date) } func updateMaxStartTimeLabel() { let numberOfQuarterHours = Int(floor(maxStartTimeSlider.value)) let date = dateFromQuarterHours(numberOfQuarterHours) maxStartTimeValueLabel.text = dateFormatter().stringFromDate(date) } func updateDurationLabel() { let numberOfQuarterHours = Int(floor(durationSlider.value)) let components = NSDateComponents() components.hour = numberOfQuarterHours / 4 components.minute = (numberOfQuarterHours % 4) * 15 let formatter = NSDateComponentsFormatter() formatter.allowedUnits = [.Hour, .Minute] formatter.unitsStyle = .Full durationValueLabel.text = formatter.stringFromDateComponents(components) } func updateAllDayProbabilityLabel() { let value = floor(self.allDayProbabilitySlider.value * 1000) / 1000 allDayProbabilityValueLabel.text = NSString(format:"%.1lf %%", value * 100) as String } }
mit
47d85d6dd1d7d02d55c4151812927832
36.712177
201
0.640607
5.143432
false
false
false
false
MainasuK/hitokoto
hitokoto/hitokoto/HitokotoData/HitokotoData.swift
1
3063
// // HitokotoData.swift // // // Created by Cirno MainasuK on 2015-5-8. // // import Foundation // Create an error type that you'll use later enum HitokotoDataInitializationError: ErrorType { case InvalidHitokotoData(identifier: String, data: AnyObject?) } struct HitokotoData { // You don't really need to use a class here since it's just a data structure. A struct would be much better on performance in Swift. Also as always, use as strict scope as possible. let hitokoto: String let source: String let category: String let author: String let like: Int let date: String let catname: String let id: Int init(hitokotoDictionary: [String: NSObject]) throws { // Create a throwable initializer rather than using forced unwrapping let jsonResult = hitokotoDictionary print(jsonResult) // Create constants that you'll use more than once let hitokotoIdentifier = "hitokoto" let sourceIdentifier = "source" let categoryIdentifier = "cat" let authorIdentifier = "author" let likeIdentifier = "like" let dateIdentifier = "date" let catnameIdentifier = "catname" let idIdentifier = "id" // Make sure every thing you need in the dictionary is valid guard let hitokoto = jsonResult[hitokotoIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: hitokotoIdentifier, data: jsonResult[hitokotoIdentifier]) } guard let source = jsonResult[sourceIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: sourceIdentifier, data: jsonResult[sourceIdentifier]) } guard let category = jsonResult[categoryIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: categoryIdentifier, data: jsonResult[categoryIdentifier]) } guard let author = jsonResult[authorIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: authorIdentifier, data: jsonResult[authorIdentifier]) } guard let like = jsonResult[likeIdentifier] as? Int else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: likeIdentifier, data: jsonResult[likeIdentifier]) } guard let date = jsonResult[dateIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: dateIdentifier, data: jsonResult[dateIdentifier]) } guard let catname = jsonResult[catnameIdentifier] as? String else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: catnameIdentifier, data: jsonResult[catnameIdentifier]) } guard let id = jsonResult[idIdentifier] as? Int else { throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: idIdentifier, data: jsonResult[idIdentifier]) } // Initialize self.hitokoto = hitokoto self.source = source self.category = category self.author = author self.like = like self.date = date self.catname = catname self.id = id } }
mit
6c0af0b78935f3e25d3b33d5d568350b
38.269231
204
0.751224
4.019685
false
false
false
false
turekj/ReactiveTODO
ReactiveTODOTests/Classes/DataAccess/Impl/TODONoteDataAccessObjectSpec.swift
1
7736
@testable import ReactiveTODOFramework import Nimble import Quick import RealmSwift class TODONoteDataAccessObjectSpec: QuickSpec { override func spec() { describe("TODONoteDataAccessObject") { let factory = TODONoteFactoryMock() let sut = TODONoteDataAccessObject(factory: factory) context("When creating a TODONote") { it("Should save created note in database") { let realm = try! Realm() factory.guid = "FACTORY_GUID" factory.completed = true sut.createTODONote(NSDate(timeIntervalSince1970: 444), note: "Creanote", priority: Priority.Urgent) expect(realm.objects(TODONote.self).count).to(equal(1)) expect(realm.objects(TODONote.self).first).toNot(beNil()) expect(realm.objects(TODONote.self).first?.guid) .to(equal("FACTORY_GUID")) expect(realm.objects(TODONote.self).first?.date) .to(equal(NSDate(timeIntervalSince1970: 444))) expect(realm.objects(TODONote.self).first?.note) .to(equal("Creanote")) expect(realm.objects(TODONote.self).first?.priority) .to(equal(Priority.Urgent)) expect(realm.objects(TODONote.self).first?.completed) .to(beTrue()) } it("Should return created note") { factory.guid = "CREATED_GUID" factory.completed = true let result = sut.createTODONote( NSDate(timeIntervalSince1970: 444), note: "Creanote", priority: Priority.Urgent) expect(result.guid).to(equal("CREATED_GUID")) expect(result.note).to(equal("Creanote")) expect(result.date).to( equal(NSDate(timeIntervalSince1970: 444))) expect(result.priority).to(equal(Priority.Urgent)) expect(result.completed).to(beTrue()) } } context("When returning note by GUID") { it("Should return correct note") { let realm = try! Realm() let firstNote = TODONote() firstNote.guid = "note_1_guid" firstNote.date = NSDate(timeIntervalSince1970: 222) firstNote.note = "Note One" firstNote.priority = .Urgent firstNote.completed = false let secondNote = TODONote() secondNote.guid = "note_2_guid" secondNote.date = NSDate(timeIntervalSince1970: 111) secondNote.note = "Note Two" secondNote.priority = .Urgent secondNote.completed = false try! realm.write { realm.add(firstNote) realm.add(secondNote) } let note = sut.getNote("note_2_guid") expect(note).toNot(beNil()) expect(note?.guid).to(equal("note_2_guid")) expect(note?.date).to(equal(NSDate(timeIntervalSince1970: 111))) expect(note?.note).to(equal("Note Two")) expect(note?.priority).to(equal(Priority.Urgent)) expect(note?.completed).to(beFalse()) } } context("When returning current TODONotes") { it("Should return notes that are not complete") { let realm = try! Realm() let completedNote = TODONote() completedNote.guid = "AWESOME_UNIQUE_GUID" completedNote.date = NSDate(timeIntervalSince1970: 1970) completedNote.note = "Awesome Note" completedNote.priority = .Urgent completedNote.completed = true let notCompletedNote = TODONote() notCompletedNote.guid = "AWESOME_UNIQUE_GUID_NOT_COMPLETED" notCompletedNote.date = NSDate(timeIntervalSince1970: 111) notCompletedNote.note = "Awesome Not Completed Note" notCompletedNote.priority = .Low notCompletedNote.completed = false try! realm.write { realm.add(completedNote) realm.add(notCompletedNote) } let notes = sut.getCurrentTODONotes() expect(notes.count).to(equal(1)) expect(notes.first?.guid) .to(equal("AWESOME_UNIQUE_GUID_NOT_COMPLETED")) expect(notes.first?.date) .to(equal(NSDate(timeIntervalSince1970: 111))) expect(notes.first?.note) .to(equal("Awesome Not Completed Note")) expect(notes.first?.priority).to(equal(Priority.Low)) expect(notes.first?.completed).to(beFalse()) } it("Should order notes by ascending date") { let realm = try! Realm() let firstNote = TODONote() firstNote.guid = "note_1_date" firstNote.date = NSDate(timeIntervalSince1970: 222) firstNote.note = "Note One" firstNote.priority = .Urgent firstNote.completed = false let secondNote = TODONote() secondNote.guid = "note_2_date" secondNote.date = NSDate(timeIntervalSince1970: 111) secondNote.note = "Note Two" secondNote.priority = .Urgent secondNote.completed = false try! realm.write { realm.add(firstNote) realm.add(secondNote) } let notes = sut.getCurrentTODONotes() expect(notes.count).to(equal(2)) expect(notes.first?.guid) .to(equal("note_2_date")) expect(notes.last?.guid) .to(equal("note_1_date")) } } context("When marking note as completed") { it("Should set completed flag to true") { let realm = try! Realm() let note = TODONote() note.guid = "completed_test_guid" note.date = NSDate(timeIntervalSince1970: 222) note.note = "Note to complete" note.priority = .Urgent note.completed = false try! realm.write { realm.add(note) } sut.completeTODONote("completed_test_guid") let noteQuery = realm.objects(TODONote.self) .filter("guid = 'completed_test_guid'") expect(noteQuery.count).to(equal(1)) expect(noteQuery.first?.guid) .to(equal("completed_test_guid")) expect(noteQuery.first?.completed).to(beTrue()) } } } } }
mit
d3dbcaf8633bec4d370a94c5d1fa977b
42.706215
84
0.472725
5.549498
false
false
false
false
e78l/swift-corelibs-foundation
TestFoundation/FTPServer.swift
1
11599
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // #if !os(Windows) //This is a very rudimentary FTP server written plainly for testing URLSession FTP Implementation. import Dispatch #if canImport(Glibc) import Glibc #elseif canImport(Darwin) import Darwin #endif class _FTPSocket { private var listenSocket: Int32! private var socketAddress = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1) private var socketAddress1 = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1) private var connectionSocket: Int32! var dataSocket: Int32! // data socket for communication var dataSocketPort: UInt16! // data socket port, should be sent as part of header private func isNotMinusOne(r: CInt) -> Bool { return r != -1 } private func isZero(r: CInt) -> Bool { return r == 0 } private func attempt(_ name: String, file: String = #file, line: UInt = #line, valid: (CInt) -> Bool, _ b: @autoclosure () -> CInt) throws -> CInt { let r = b() guard valid(r) else { throw ServerError(operation: name, errno: r, file: file, line: line) } return r } init(port: UInt16) throws { #if os(Linux) let SOCKSTREAM = Int32(SOCK_STREAM.rawValue) #else let SOCKSTREAM = SOCK_STREAM #endif listenSocket = try attempt("socket", valid: isNotMinusOne, socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP))) var on: Int = 1 _ = try attempt("setsockopt", valid: isZero, setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int>.size))) let sa = createSockaddr(port) socketAddress.initialize(to: sa) try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, { let addr = UnsafePointer<sockaddr>($0) _ = try attempt("bind", valid: isZero, bind(listenSocket, addr, socklen_t(MemoryLayout<sockaddr>.size))) }) dataSocket = try attempt("socket", valid: isNotMinusOne, socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP))) var on1: Int = 1 _ = try attempt("setsockopt", valid: isZero, setsockopt(dataSocket, SOL_SOCKET, SO_REUSEADDR, &on1, socklen_t(MemoryLayout<Int>.size))) let sa1 = createSockaddr(port+1) socketAddress1.initialize(to: sa1) try socketAddress1.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, { let addr = UnsafeMutablePointer<sockaddr>($0) _ = try attempt("bind", valid: isZero, bind(dataSocket, addr, socklen_t(MemoryLayout<sockaddr>.size))) var sockLen = socklen_t(MemoryLayout<sockaddr>.size) _ = try attempt("listen", valid: isZero, listen(dataSocket, SOMAXCONN)) // Open the data port asynchronously. Port should be opened before ESPV header communication. DispatchQueue(label: "delay").async { do { self.dataSocket = try self.attempt("accept", valid: self.isNotMinusOne, accept(self.dataSocket, addr, &sockLen)) self.dataSocketPort = sa1.sin_port } catch { NSLog("Could not open data port.") } } }) } private func createSockaddr(_ port: UInt16) -> sockaddr_in { // Listen on the loopback address so that OSX doesnt pop up a dialog // asking to accept incoming connections if the firewall is enabled. let addr = UInt32(INADDR_LOOPBACK).bigEndian let netPort = port.bigEndian #if os(Linux) return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0)) #elseif os(Android) return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), __pad: (0,0,0,0,0,0,0,0)) #else return sockaddr_in(sin_len: 0, sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0)) #endif } func acceptConnection(notify: ServerSemaphore) throws { _ = try attempt("listen", valid: isZero, listen(listenSocket, SOMAXCONN)) try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, { let addr = UnsafeMutablePointer<sockaddr>($0) var sockLen = socklen_t(MemoryLayout<sockaddr>.size) notify.signal() connectionSocket = try attempt("accept", valid: isNotMinusOne, accept(listenSocket, addr, &sockLen)) }) } func readData() throws -> String { var buffer = [UInt8](repeating: 0, count: 4096) _ = try attempt("read", valid: isNotMinusOne, CInt(read(connectionSocket, &buffer, 4096))) return String(cString: &buffer) } func readDataOnDataSocket() throws -> String { var buffer = [UInt8](repeating: 0, count: 4096) _ = try attempt("read", valid: isNotMinusOne, CInt(read(dataSocket, &buffer, 4096))) return String(cString: &buffer) } func writeRawData(_ data: Data) throws { _ = try data.withUnsafeBytes { ptr in try attempt("write", valid: isNotMinusOne, CInt(write(connectionSocket, ptr, data.count))) } } func writeRawData(socket data: Data) throws -> Int32 { var bytesWritten: Int32 = 0 _ = try data.withUnsafeBytes { ptr in bytesWritten = try attempt("write", valid: isNotMinusOne, CInt(write(dataSocket, ptr, data.count))) } return bytesWritten } func shutdown() { close(connectionSocket) close(listenSocket) close(dataSocket) } } class _FTPServer { let socket: _FTPSocket let commandPort: UInt16 init(port: UInt16) throws { commandPort = port socket = try _FTPSocket(port: port) } public class func create(port: UInt16) throws -> _FTPServer { return try _FTPServer(port: port) } public func listen(notify: ServerSemaphore) throws { try socket.acceptConnection(notify: notify) } public func stop() { socket.shutdown() } // parse header information and respond accordingly public func parseHeaderData() throws { let saveData = """ FTP implementation to test FTP upload, download and data tasks. Instead of sending a file, we are sending the hardcoded data.We are going to test FTP data, download and upload tasks with delegates & completion handlers. Creating the data here as we need to pass the count as part of the header.\r\n """.data(using: String.Encoding.utf8) let dataCount = saveData?.count let read = try socket.readData() if read.contains("anonymous") { try respondWithRawData(with: "331 Please specify the password.\r\n") } else if read.contains("PASS") { try respondWithRawData(with: "230 Login successful.\r\n") } else if read.contains("PWD") { try respondWithRawData(with: "257 \"/\"\r\n") } else if read.contains("EPSV") { try respondWithRawData(with: "229 Entering Extended Passive Mode (|||\(commandPort+1)|).\r\n") } else if read.contains("TYPE I") { try respondWithRawData(with: "200 Switching to Binary mode.\r\n") } else if read.contains("SIZE") { try respondWithRawData(with: "213 \(dataCount!)\r\n") } else if read.contains("RETR") { try respondWithRawData(with: "150 Opening BINARY mode data, connection for test.txt (\(dataCount!) bytes).\r\n") // Send data here through data port do { let dataWritten = try respondWithData(with: saveData!) if dataWritten != -1 { // Send the end header on command port try respondWithRawData(with: "226 Transfer complete.\r\n") } } catch { NSLog("Transfer failed.") } } else if read.contains("STOR") { // Request is for upload. As we are only dealing with data, just read the data and ignore try respondWithRawData(with: "150 Ok to send data.\r\n") // Read data from the data socket and respond with completion header after the transfer do { _ = try readDataOnDataSocket() try respondWithRawData(with: "226 Transfer complete.\r\n") } catch { NSLog("Transfer failed.") } } } public func respondWithRawData(with string: String) throws { try self.socket.writeRawData(string.data(using: String.Encoding.utf8)!) } public func respondWithData(with data: Data) throws -> Int32 { return try self.socket.writeRawData(socket: data) } public func readDataOnDataSocket() throws -> String { return try self.socket.readDataOnDataSocket() } } public class TestFTPURLSessionServer { let ftpServer: _FTPServer public init (port: UInt16) throws { ftpServer = try _FTPServer.create(port: port) } public func start(started: ServerSemaphore) throws { started.signal() try ftpServer.listen(notify: started) } public func parseHeaderAndRespond() throws { try ftpServer.parseHeaderData() } func writeStartHeaderData() throws { try ftpServer.respondWithRawData(with: "220 (vsFTPd 2.3.5)\r\n") } func stop() { ftpServer.stop() } } class LoopbackFTPServerTest: XCTestCase { static var serverPort: Int = -1 override class func setUp() { super.setUp() func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { let start = 21961 // 21961 for port in start...(start+100) { //we must find at least one port to bind do { serverPort = port let test = try TestFTPURLSessionServer(port: UInt16(port)) try test.start(started: condition) try test.writeStartHeaderData() // Welcome message to start the transfer for _ in 1...7 { try test.parseHeaderAndRespond() } test.stop() } catch let err as ServerError { if err.operation == "bind" { continue } throw err } } } let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } let timeout = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 2_000_000_000) serverReady.wait(timeout: timeout) } } #endif
apache-2.0
bd455ced0473b4316e2f1d1bd1e5981d
39.414634
157
0.599448
4.292746
false
true
false
false
ben-ng/swift
test/Constraints/function.swift
1
2643
// RUN: %target-typecheck-verify-swift func f0(_ x: Float) -> Float {} func f1(_ x: Float) -> Float {} func f2(_ x: @autoclosure () -> Float) {} var f : Float _ = f0(f0(f)) _ = f0(1) _ = f1(f1(f)) f2(f) f2(1.0) func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool { return rhs() } // Function returns func weirdCast<T, U>(_ x: T) -> U {} func ff() -> (Int) -> (Float) { return weirdCast } // Block <-> function conversions var funct: (Int) -> Int = { $0 } var block: @convention(block) (Int) -> Int = funct funct = block block = funct // Application of implicitly unwrapped optional functions var optFunc: ((String) -> String)! = { $0 } var s: String = optFunc("hi") // <rdar://problem/17652759> Default arguments cause crash with tuple permutation func testArgumentShuffle(_ first: Int = 7, third: Int = 9) { } testArgumentShuffle(third: 1, 2) // expected-error {{unnamed argument #2 must precede argument 'third'}} {{21-29=2}} {{31-32=third: 1}} func rejectsAssertStringLiteral() { assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} } // <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads func process(_ line: UInt = #line, _ fn: () -> Void) {} func process(_ line: UInt = #line) -> Int { return 0 } func dangerous() throws {} func test() { process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}} try dangerous() test() } } // <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic class A { func a(_ text:String) { } func a(_ text:String, something:Int?=nil) { } } A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}} // <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type func r22451001() -> AnyObject {} print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}} // SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler // SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any' func sr590(_ x: Any) {} // expected-note {{'sr590' declared here}} sr590(3,4) // expected-error {{extra argument in call}} sr590() // expected-error {{missing argument for parameter #1 in call}} // Make sure calling with structural tuples still works. sr590(()) sr590((1, 2))
apache-2.0
ee3001dee7f6dd74e1d2dc4c49a2f1e0
30.094118
152
0.666667
3.436931
false
false
false
false
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorView.swift
1
16603
// // KRActivityIndicatorView.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa /** Enum of animation types used for activity indicator view. - Blank: Blank animation. - BallPulse: BallPulse animation. - BallGridPulse: BallGridPulse animation. - BallClipRotate: BallClipRotate animation. - SquareSpin: SquareSpin animation. - BallClipRotatePulse: BallClipRotatePulse animation. - BallClipRotateMultiple: BallClipRotateMultiple animation. - BallPulseRise: BallPulseRise animation. - BallRotate: BallRotate animation. - CubeTransition: CubeTransition animation. - BallZigZag: BallZigZag animation. - BallZigZagDeflect: BallZigZagDeflect animation. - BallTrianglePath: BallTrianglePath animation. - BallScale: BallScale animation. - LineScale: LineScale animation. - LineScaleParty: LineScaleParty animation. - BallScaleMultiple: BallScaleMultiple animation. - BallPulseSync: BallPulseSync animation. - BallBeat: BallBeat animation. - LineScalePulseOut: LineScalePulseOut animation. - LineScalePulseOutRapid: LineScalePulseOutRapid animation. - BallScaleRipple: BallScaleRipple animation. - BallScaleRippleMultiple: BallScaleRippleMultiple animation. - BallSpinFadeLoader: BallSpinFadeLoader animation. - LineSpinFadeLoader: LineSpinFadeLoader animation. - TriangleSkewSpin: TriangleSkewSpin animation. - Pacman: Pacman animation. - BallGridBeat: BallGridBeat animation. - SemiCircleSpin: SemiCircleSpin animation. - BallRotateChase: BallRotateChase animation. - Orbit: Orbit animation. - AudioEqualizer: AudioEqualizer animation. */ public enum KRActivityIndicatorType: Int { /** Blank. - returns: Instance of KRActivityIndicatorAnimationBlank. */ case blank /** BallPulse. - returns: Instance of KRActivityIndicatorAnimationBallPulse. */ case ballPulse /** BallGridPulse. - returns: Instance of KRActivityIndicatorAnimationBallGridPulse. */ case ballGridPulse /** BallClipRotate. - returns: Instance of KRActivityIndicatorAnimationBallClipRotate. */ case ballClipRotate /** SquareSpin. - returns: Instance of KRActivityIndicatorAnimationSquareSpin. */ case squareSpin /** BallClipRotatePulse. - returns: Instance of KRActivityIndicatorAnimationBallClipRotatePulse. */ case ballClipRotatePulse /** BallClipRotateMultiple. - returns: Instance of KRActivityIndicatorAnimationBallClipRotateMultiple. */ case ballClipRotateMultiple /** BallPulseRise. - returns: Instance of KRActivityIndicatorAnimationBallPulseRise. */ case ballPulseRise /** BallRotate. - returns: Instance of KRActivityIndicatorAnimationBallRotate. */ case ballRotate /** CubeTransition. - returns: Instance of KRActivityIndicatorAnimationCubeTransition. */ case cubeTransition /** BallZigZag. - returns: Instance of KRActivityIndicatorAnimationBallZigZag. */ case ballZigZag /** BallZigZagDeflect - returns: Instance of KRActivityIndicatorAnimationBallZigZagDeflect */ case ballZigZagDeflect /** BallTrianglePath. - returns: Instance of KRActivityIndicatorAnimationBallTrianglePath. */ case ballTrianglePath /** BallScale. - returns: Instance of KRActivityIndicatorAnimationBallScale. */ case ballScale /** LineScale. - returns: Instance of KRActivityIndicatorAnimationLineScale. */ case lineScale /** LineScaleParty. - returns: Instance of KRActivityIndicatorAnimationLineScaleParty. */ case lineScaleParty /** BallScaleMultiple. - returns: Instance of KRActivityIndicatorAnimationBallScaleMultiple. */ case ballScaleMultiple /** BallPulseSync. - returns: Instance of KRActivityIndicatorAnimationBallPulseSync. */ case ballPulseSync /** BallBeat. - returns: Instance of KRActivityIndicatorAnimationBallBeat. */ case ballBeat /** LineScalePulseOut. - returns: Instance of KRActivityIndicatorAnimationLineScalePulseOut. */ case lineScalePulseOut /** LineScalePulseOutRapid. - returns: Instance of KRActivityIndicatorAnimationLineScalePulseOutRapid. */ case lineScalePulseOutRapid /** BallScaleRipple. - returns: Instance of KRActivityIndicatorAnimationBallScaleRipple. */ case ballScaleRipple /** BallScaleRippleMultiple. - returns: Instance of KRActivityIndicatorAnimationBallScaleRippleMultiple. */ case ballScaleRippleMultiple /** BallSpinFadeLoader. - returns: Instance of KRActivityIndicatorAnimationBallSpinFadeLoader. */ case ballSpinFadeLoader /** LineSpinFadeLoader. - returns: Instance of KRActivityIndicatorAnimationLineSpinFadeLoader. */ case lineSpinFadeLoader /** TriangleSkewSpin. - returns: Instance of KRActivityIndicatorAnimationTriangleSkewSpin. */ case triangleSkewSpin /** Pacman. - returns: Instance of KRActivityIndicatorAnimationPacman. */ case pacman /** BallGridBeat. - returns: Instance of KRActivityIndicatorAnimationBallGridBeat. */ case ballGridBeat /** SemiCircleSpin. - returns: Instance of KRActivityIndicatorAnimationSemiCircleSpin. */ case semiCircleSpin /** BallRotateChase. - returns: Instance of KRActivityIndicatorAnimationBallRotateChase. */ case ballRotateChase /** Orbit. - returns: Instance of KRActivityIndicatorAnimationOrbit. */ case orbit /** AudioEqualizer. - returns: Instance of KRActivityIndicatorAnimationAudioEqualizer. */ case audioEqualizer static let allTypes = (blank.rawValue ... audioEqualizer.rawValue).map{ KRActivityIndicatorType(rawValue: $0)! } func animation() -> KRActivityIndicatorAnimationDelegate { switch self { case .blank: return KRActivityIndicatorAnimationBlank() case .ballPulse: return KRActivityIndicatorAnimationBallPulse() case .ballGridPulse: return KRActivityIndicatorAnimationBallGridPulse() case .ballClipRotate: return KRActivityIndicatorAnimationBallClipRotate() case .squareSpin: return KRActivityIndicatorAnimationSquareSpin() case .ballClipRotatePulse: return KRActivityIndicatorAnimationBallClipRotatePulse() case .ballClipRotateMultiple: return KRActivityIndicatorAnimationBallClipRotateMultiple() case .ballPulseRise: return KRActivityIndicatorAnimationBallPulseRise() case .ballRotate: return KRActivityIndicatorAnimationBallRotate() case .cubeTransition: return KRActivityIndicatorAnimationCubeTransition() case .ballZigZag: return KRActivityIndicatorAnimationBallZigZag() case .ballZigZagDeflect: return KRActivityIndicatorAnimationBallZigZagDeflect() case .ballTrianglePath: return KRActivityIndicatorAnimationBallTrianglePath() case .ballScale: return KRActivityIndicatorAnimationBallScale() case .lineScale: return KRActivityIndicatorAnimationLineScale() case .lineScaleParty: return KRActivityIndicatorAnimationLineScaleParty() case .ballScaleMultiple: return KRActivityIndicatorAnimationBallScaleMultiple() case .ballPulseSync: return KRActivityIndicatorAnimationBallPulseSync() case .ballBeat: return KRActivityIndicatorAnimationBallBeat() case .lineScalePulseOut: return KRActivityIndicatorAnimationLineScalePulseOut() case .lineScalePulseOutRapid: return KRActivityIndicatorAnimationLineScalePulseOutRapid() case .ballScaleRipple: return KRActivityIndicatorAnimationBallScaleRipple() case .ballScaleRippleMultiple: return KRActivityIndicatorAnimationBallScaleRippleMultiple() case .ballSpinFadeLoader: return KRActivityIndicatorAnimationBallSpinFadeLoader() case .lineSpinFadeLoader: return KRActivityIndicatorAnimationLineSpinFadeLoader() case .triangleSkewSpin: return KRActivityIndicatorAnimationTriangleSkewSpin() case .pacman: return KRActivityIndicatorAnimationPacman() case .ballGridBeat: return KRActivityIndicatorAnimationBallGridBeat() case .semiCircleSpin: return KRActivityIndicatorAnimationSemiCircleSpin() case .ballRotateChase: return KRActivityIndicatorAnimationBallRotateChase() case .orbit: return KRActivityIndicatorAnimationOrbit() case .audioEqualizer: return KRActivityIndicatorAnimationAudioEqualizer() //default: // return KRActivityIndicatorAnimationLineScalePulseOut() } } } /// Activity indicator view with nice animations public final class KRActivityIndicatorView: NSView { /// Default type. Default value is .BallSpinFadeLoader. public static var DEFAULT_TYPE: KRActivityIndicatorType = .blank /// Default color. Default value is NSColor.white. public static var DEFAULT_COLOR = NSColor.white /// Default padding. Default value is 0.0 - 0% padding public static var DEFAULT_PADDING: CGFloat = 0.0 /// Default size of activity indicator view in UI blocker. Default value is 60x60. public static var DEFAULT_BLOCKER_SIZE = CGSize(width: 60, height: 60) /// Default display time threshold to actually display UI blocker. Default value is 0 ms. public static var DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD = 0 /// Default minimum display time of UI blocker. Default value is 0 ms. public static var DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME = 0 /// Default message displayed in UI blocker. Default value is nil. public static var DEFAULT_BLOCKER_MESSAGE: String? = nil /// Default font of message displayed in UI blocker. Default value is bold system font, size 20. public static var DEFAULT_BLOCKER_MESSAGE_FONT = NSFont.boldSystemFont(ofSize: 20) /// Default background color of UI blocker. Default value is UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) public static var DEFAULT_BLOCKER_BACKGROUND_COLOR = NSColor(red: 0, green: 0, blue: 0, alpha: 0.5) /// Animation type. public var type: KRActivityIndicatorType = KRActivityIndicatorView.DEFAULT_TYPE @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'type' instead.") @IBInspectable var typeName: String { get { return getTypeName() } set { _setTypeName(newValue) } } /// Color of activity indicator view. @IBInspectable public var color: NSColor = KRActivityIndicatorView.DEFAULT_COLOR /// Padding of activity indicator view. @IBInspectable public var padding: CGFloat = KRActivityIndicatorView.DEFAULT_PADDING /// Current status of animation, read-only. @available(*, deprecated) public var animating: Bool { return isAnimating } /// Current status of animation, read-only. public private(set) var isAnimating: Bool = false /** Returns an object initialized from data in a given unarchiver. self, initialized using the data in decoder. - parameter decoder: an unarchiver object. - returns: self, initialized using the data in decoder. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //backgroundColor = NSColor.clear isHidden = true } /** Create a activity indicator view. Appropriate KRActivityIndicatorView.DEFAULT_* values are used for omitted params. - parameter frame: view's frame. - parameter type: animation type. - parameter color: color of activity indicator view. - parameter padding: padding of activity indicator view. - returns: The activity indicator view. */ public init(frame: CGRect, type: KRActivityIndicatorType? = nil, color: NSColor? = nil, padding: CGFloat? = nil) { self.type = type ?? KRActivityIndicatorView.DEFAULT_TYPE self.color = color ?? KRActivityIndicatorView.DEFAULT_COLOR self.padding = padding ?? KRActivityIndicatorView.DEFAULT_PADDING super.init(frame: frame) isHidden = true } /** Returns the natural size for the receiving view, considering only properties of the view itself. A size indicating the natural size for the receiving view based on its intrinsic properties. - returns: A size indicating the natural size for the receiving view based on its intrinsic properties. */ public override var intrinsicContentSize : CGSize { return CGSize(width: bounds.width, height: bounds.height) } /** Start animating. */ public final func startAnimating() { isHidden = false isAnimating = true layer?.speed = 1 //self.type = KRActivityIndicatorView.DEFAULT_TYPE setUpAnimation() } /** Stop animating. */ public final func stopAnimating() { isHidden = true isAnimating = false layer?.sublayers?.removeAll() } // MARK: Internal func _setTypeName(_ typeName: String) { for item in KRActivityIndicatorType.allTypes { if String(describing: item).caseInsensitiveCompare(typeName) == ComparisonResult.orderedSame { type = item break } } } func getTypeName() -> String { return String(describing: type) } // MARK: Privates private final func setUpAnimation() { if(layer == nil){ layer = CALayer() } self.wantsLayer = true let animation: KRActivityIndicatorAnimationDelegate = type.animation() //var animationRect = UIEdgeInsetsInsetRect(frame, NSEdgeInsetsMake(padding, padding, padding, padding)) // TODO: CGRectInset alternative for padding... var animationRect = CGRect(x: padding, y: padding, width: frame.size.width - padding, height: frame.size.height - padding) let minEdge = min(animationRect.width, animationRect.height) layer?.sublayers = nil animationRect.size = CGSize(width: minEdge, height: minEdge) animation.setUpAnimation(in: layer!, size: animationRect.size, color: color) } }
mit
68d41e798911991d146b432a78439f19
32.883673
130
0.67283
5.564008
false
false
false
false
webim/webim-client-sdk-ios
Example/Tests/MessageImplTests.swift
1
29283
// // MessageImplTests.swift // WebimClientLibrary_Tests // // Created by Nikita Lazarev-Zubov on 20.02.18. // Copyright © 2018 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation @testable import WebimClientLibrary import XCTest class MessageImplTests: XCTestCase { // MARK: - Tests func testToString() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let expectedString = """ MessageImpl { serverURLString = http://demo.webim.ru, ID = id, operatorID = nil, senderAvatarURLString = nil, senderName = Name, type = visitorMessage, text = Text, timeInMicrosecond = 0, attachment = nil, historyMessage = false, currentChatID = nil, historyID = nil, rawText = nil, read = false } """ XCTAssertEqual(message.toString(), expectedString) } func testGetSenderAvatarURL() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertNil(message.getSenderAvatarFullURL()) } func testGetSendStatus() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertEqual(message.getSendStatus(), MessageSendStatus.sent) } func testIsEqual() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message1 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id1", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message2 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name1", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message3 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text1", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message4 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .operatorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message5 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) let message6 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: true, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertFalse(message.isEqual(to: message1)) XCTAssertFalse(message.isEqual(to: message2)) XCTAssertFalse(message.isEqual(to: message3)) XCTAssertFalse(message.isEqual(to: message4)) XCTAssertTrue(message.isEqual(to: message5)) XCTAssertFalse(message.isEqual(to: message6)) } // MARK: MessageSource tests func testAssertIsCurrentChat() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertNoThrow(try message.getSource().assertIsCurrentChat()) } func testAssertIsHistory() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertThrowsError(try message.getSource().assertIsHistory()) } func testGetHistoryID() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertNil(message.getHistoryID()) } func testGetCurrentChatID() { let currentChatID = "id" let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: currentChatID, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertEqual(currentChatID, message.getCurrentChatID()) } func testGetSenderAvatarFullURL() { let baseURLString = "http://demo.webim.ru" let avatarURLString = "/image.jpg" let message = MessageImpl(serverURLString: baseURLString, id: "id", serverSideID: nil, keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: avatarURLString, senderName: "Name", sendStatus: .sent, sticker: nil, type: .visitorMessage, rawData: nil, data: nil, text: "Text", timeInMicrosecond: 0, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false, messageIsEdited: false, visitorReactionInfo: nil, visitorCanReact: nil, visitorChangeReaction: nil) XCTAssertEqual(URL(string: (baseURLString + avatarURLString)), message.getSenderAvatarFullURL()) } } // MARK: - class MessageAttachmentTests: XCTestCase { // MARK: - Tests func testInit() { let messageAttachment = FileInfoImpl(urlString: "/image.jpg", size: 1, filename: "image", contentType: "image/jpeg", guid: "image123", fileUrlCreator: nil) XCTAssertEqual(messageAttachment.getContentType(), "image/jpeg") XCTAssertEqual(messageAttachment.getFileName(), "image") XCTAssertEqual(messageAttachment.getSize(), 1) XCTAssertEqual(messageAttachment.getURL(), URL(string: "/image.jpg")!) XCTAssertEqual(messageAttachment.getGuid(), "image123") } } // MARK: - class ImageInfoImplTests: XCTestCase { // MARK: - Tests func testInit() { let pageID = "page_id" let authorizationToken = "auth_token" let authorizationData = AuthorizationData(pageID: pageID, authorizationToken: authorizationToken) let SERVER_URL_STRING = "https://demo.webim.ru" let userDefaultsKey = "userDefaultsKey" let execIfNotDestroyedHandlerExecutor = ExecIfNotDestroyedHandlerExecutor(sessionDestroyer: SessionDestroyer(userDefaultsKey: userDefaultsKey), queue: DispatchQueue.main) let internalErrorListener = InternalErrorListenerForTests() let actionRequestLoop = ActionRequestLoopForTests(completionHandlerExecutor: execIfNotDestroyedHandlerExecutor, internalErrorListener: internalErrorListener) let deltaRequestLoop = DeltaRequestLoop(deltaCallback: DeltaCallback(currentChatMessageMapper: CurrentChatMessageMapper(withServerURLString: SERVER_URL_STRING), historyMessageMapper: HistoryMessageMapper(withServerURLString: SERVER_URL_STRING), userDefaultsKey: userDefaultsKey), completionHandlerExecutor: execIfNotDestroyedHandlerExecutor, sessionParametersListener: nil, internalErrorListener: internalErrorListener, baseURL: SERVER_URL_STRING, title: "title", location: "location", appVersion: nil, visitorFieldsJSONString: nil, providedAuthenticationTokenStateListener: nil, providedAuthenticationToken: nil, deviceID: "id", deviceToken: nil, remoteNotificationSystem: nil, visitorJSONString: nil, sessionID: nil, prechat: nil, authorizationData: authorizationData) let webimClient = WebimClient(withActionRequestLoop: actionRequestLoop, deltaRequestLoop: deltaRequestLoop, webimActions: WebimActionsImpl(baseURL: SERVER_URL_STRING, actionRequestLoop: actionRequestLoop)) let fileUrlCreator = FileUrlCreator(webimClient: webimClient, serverURL: SERVER_URL_STRING) let imageInfo = ImageInfoImpl(withThumbURLString: "https://demo.webim.ru/thumb.jpg", fileUrlCreator: fileUrlCreator, filename: "thumb.jpg", guid: "123", width: 100, height: 200) XCTAssertEqual(imageInfo.getWidth(), 100) XCTAssertEqual(imageInfo.getHeight(), 200) } }
mit
c5ea768cc3d303ee34276e88ca88a25d
49.140411
168
0.367461
7.411288
false
false
false
false
julienbodet/wikipedia-ios
WMF Framework/Theme.swift
1
19288
import Foundation public extension UIColor { @objc public convenience init(_ hex: Int, alpha: CGFloat) { let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let g = CGFloat((hex & 0xFF00) >> 8) / 255.0 let b = CGFloat(hex & 0xFF) / 255.0 self.init(red: r, green: g, blue: b, alpha: alpha) } @objc(initWithHexInteger:) public convenience init(_ hex: Int) { self.init(hex, alpha: 1) } @objc public class func wmf_colorWithHex(_ hex: Int) -> UIColor { return UIColor(hex) } fileprivate static let defaultShadow = UIColor(white: 0, alpha: 0.25) fileprivate static let pitchBlack = UIColor(0x101418) fileprivate static let base10 = UIColor(0x222222) fileprivate static let base20 = UIColor(0x54595D) fileprivate static let base30 = UIColor(0x72777D) fileprivate static let base50 = UIColor(0xA2A9B1) fileprivate static let base70 = UIColor(0xC8CCD1) fileprivate static let base80 = UIColor(0xEAECF0) fileprivate static let base90 = UIColor(0xF8F9FA) fileprivate static let base100 = UIColor(0xFFFFFF) fileprivate static let red30 = UIColor(0xB32424) fileprivate static let red50 = UIColor(0xCC3333) fileprivate static let red75 = UIColor(0xFF6E6E) fileprivate static let yellow50 = UIColor(0xFFCC33) fileprivate static let green50 = UIColor(0x00AF89) fileprivate static let blue10 = UIColor(0x2A4B8D) fileprivate static let blue50 = UIColor(0x3366CC) fileprivate static let lightBlue = UIColor(0xEAF3FF) fileprivate static let mesosphere = UIColor(0x43464A) fileprivate static let thermosphere = UIColor(0x2E3136) fileprivate static let stratosphere = UIColor(0x6699FF) fileprivate static let exosphere = UIColor(0x27292D) fileprivate static let accent = UIColor(0x00AF89) fileprivate static let accent10 = UIColor(0x2A4B8D) fileprivate static let amate = UIColor(0xE1DAD1) fileprivate static let parchment = UIColor(0xF8F1E3) fileprivate static let masi = UIColor(0x646059) fileprivate static let papyrus = UIColor(0xF0E6D6) fileprivate static let kraft = UIColor(0xCBC8C1) fileprivate static let osage = UIColor(0xFF9500) fileprivate static let darkSearchFieldBackground = UIColor(0x8E8E93, alpha: 0.12) fileprivate static let lightSearchFieldBackground = UIColor(0xFFFFFF, alpha: 0.15) fileprivate static let masi60PercentAlpha = UIColor(0x646059, alpha:0.6) fileprivate static let black50PercentAlpha = UIColor(0x000000, alpha:0.5) fileprivate static let black75PercentAlpha = UIColor(0x000000, alpha:0.75) fileprivate static let white20PercentAlpha = UIColor(white: 1, alpha:0.2) fileprivate static let base70At55PercentAlpha = base70.withAlphaComponent(0.55) @objc public static let wmf_darkGray = UIColor(0x4D4D4B) @objc public static let wmf_lightGray = UIColor(0x9AA0A7) @objc public static let wmf_gray = UIColor.base70 @objc public static let wmf_lighterGray = UIColor.base80 @objc public static let wmf_lightestGray = UIColor(0xF5F5F5) // also known as refresh gray @objc public static let wmf_darkBlue = UIColor.blue10 @objc public static let wmf_blue = UIColor.blue50 @objc public static let wmf_lightBlue = UIColor.lightBlue @objc public static let wmf_green = UIColor.green50 @objc public static let wmf_lightGreen = UIColor(0xD5FDF4) @objc public static let wmf_red = UIColor.red50 @objc public static let wmf_lightRed = UIColor(0xFFE7E6) @objc public static let wmf_yellow = UIColor.yellow50 @objc public static let wmf_lightYellow = UIColor(0xFEF6E7) @objc public static let wmf_orange = UIColor(0xFF5B00) @objc public static let wmf_purple = UIColor(0x7F4AB3) @objc public static let wmf_lightPurple = UIColor(0xF3E6FF) @objc public func wmf_hexStringIncludingAlpha(_ includeAlpha: Bool) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) var hexString = String(format: "%02X%02X%02X", Int(255.0 * r), Int(255.0 * g), Int(255.0 * b)) if (includeAlpha) { hexString = hexString.appendingFormat("%02X", Int(255.0 * a)) } return hexString } @objc public var wmf_hexString: String { return wmf_hexStringIncludingAlpha(false) } } @objc(WMFColors) public class Colors: NSObject { fileprivate static let light = Colors(baseBackground: .base80, midBackground: .base90, paperBackground: .base100, chromeBackground: .base100, popoverBackground: .base100, subCellBackground: .base100, overlayBackground: .black50PercentAlpha, batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .lightBlue, overlayText: .base20, searchFieldBackground: .darkSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .base30, tertiaryText: .base70, disabledText: .base80, disabledLink: .lightBlue, chromeText: .base20, link: .blue50, accent: .green50, border: .base70, shadow: .base80, chromeShadow: .defaultShadow, cardShadow: .base10, secondaryAction: .blue10, icon: nil, iconBackground: nil, destructive: .red50, error: .red50, warning: .osage, unselected: .base50, blurEffectStyle: .extraLight, blurEffectBackground: .clear) fileprivate static let sepia = Colors(baseBackground: .amate, midBackground: .papyrus, paperBackground: .parchment, chromeBackground: .parchment, popoverBackground: .base100, subCellBackground: .papyrus, overlayBackground: .masi60PercentAlpha, batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .lightBlue, overlayText: .base20, searchFieldBackground: .darkSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .masi, tertiaryText: .masi, disabledText: .base80, disabledLink: .lightBlue, chromeText: .base20, link: .blue50, accent: .green50, border: .kraft, shadow: .kraft, chromeShadow: .base20, cardShadow: .kraft, secondaryAction: .accent10, icon: .masi, iconBackground: .amate, destructive: .red30, error: .red30, warning: .osage, unselected: .masi, blurEffectStyle: .extraLight, blurEffectBackground: .clear) fileprivate static let dark = Colors(baseBackground: .base10, midBackground: .exosphere, paperBackground: .thermosphere, chromeBackground: .mesosphere, popoverBackground: .base10, subCellBackground: .exosphere, overlayBackground: .black75PercentAlpha, batchSelectionBackground: .accent10, referenceHighlightBackground: .clear, hintBackground: .pitchBlack, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .thermosphere, primaryText: .base90, secondaryText: .base70, tertiaryText: .base70, disabledText: .base70, disabledLink: .lightBlue, chromeText: .base90, link: .stratosphere, accent: .green50, border: .mesosphere, shadow: .base10, chromeShadow: .base10, cardShadow: .base10, secondaryAction: .accent10, icon: .base70, iconBackground: .exosphere, destructive: .red75, error: .red75, warning: .yellow50, unselected: .base70, blurEffectStyle: .dark, blurEffectBackground: .base70At55PercentAlpha) fileprivate static let black = Colors(baseBackground: .pitchBlack, midBackground: .base10, paperBackground: .black, chromeBackground: .base10, popoverBackground: .base10, subCellBackground: .base10, overlayBackground: .black75PercentAlpha, batchSelectionBackground: .accent10, referenceHighlightBackground: .white20PercentAlpha, hintBackground: .thermosphere, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .thermosphere, primaryText: .base90, secondaryText: .base70, tertiaryText: .base70, disabledText: .base70, disabledLink: .lightBlue, chromeText: .base90, link: .stratosphere, accent: .green50, border: .mesosphere, shadow: .base10, chromeShadow: .base10, cardShadow: .base30, secondaryAction: .accent10, icon: .base70, iconBackground: .exosphere, destructive: .red75, error: .red75, warning: .yellow50, unselected: .base70, blurEffectStyle: .dark, blurEffectBackground: .base70At55PercentAlpha) fileprivate static let widget = Colors(baseBackground: .clear, midBackground: .clear, paperBackground: .clear, chromeBackground: .clear, popoverBackground: .clear, subCellBackground: .clear, overlayBackground: UIColor(white: 1.0, alpha: 0.4), batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .clear, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .base10, tertiaryText: .base20, disabledText: .base30, disabledLink: .lightBlue, chromeText: .base20, link: .accent10, accent: .green50, border: UIColor(white: 0, alpha: 0.15) , shadow: .base80, chromeShadow: .base80, cardShadow: .black, secondaryAction: .blue10, icon: nil, iconBackground: nil, destructive: .red50, error: .red50, warning: .yellow50, unselected: .base50, blurEffectStyle: .extraLight, blurEffectBackground: .clear) @objc public let baseBackground: UIColor @objc public let midBackground: UIColor @objc public let subCellBackground: UIColor @objc public let paperBackground: UIColor @objc public let popoverBackground: UIColor @objc public let chromeBackground: UIColor @objc public let chromeShadow: UIColor @objc public let overlayBackground: UIColor @objc public let batchSelectionBackground: UIColor @objc public let referenceHighlightBackground: UIColor @objc public let hintBackground: UIColor @objc public let overlayText: UIColor @objc public let primaryText: UIColor @objc public let secondaryText: UIColor @objc public let tertiaryText: UIColor @objc public let disabledText: UIColor @objc public let disabledLink: UIColor @objc public let chromeText: UIColor @objc public let link: UIColor @objc public let accent: UIColor @objc public let secondaryAction: UIColor @objc public let destructive: UIColor @objc public let warning: UIColor @objc public let error: UIColor @objc public let unselected: UIColor @objc public let border: UIColor @objc public let shadow: UIColor @objc public let cardShadow: UIColor @objc public let icon: UIColor? @objc public let iconBackground: UIColor? @objc public let searchFieldBackground: UIColor @objc public let keyboardBarSearchFieldBackground: UIColor @objc public let linkToAccent: Gradient @objc public let blurEffectStyle: UIBlurEffectStyle @objc public let blurEffectBackground: UIColor //Someday, when the app is all swift, make this class a struct. init(baseBackground: UIColor, midBackground: UIColor, paperBackground: UIColor, chromeBackground: UIColor, popoverBackground: UIColor, subCellBackground: UIColor, overlayBackground: UIColor, batchSelectionBackground: UIColor, referenceHighlightBackground: UIColor, hintBackground: UIColor, overlayText: UIColor, searchFieldBackground: UIColor, keyboardBarSearchFieldBackground: UIColor, primaryText: UIColor, secondaryText: UIColor, tertiaryText: UIColor, disabledText: UIColor, disabledLink: UIColor, chromeText: UIColor, link: UIColor, accent: UIColor, border: UIColor, shadow: UIColor, chromeShadow: UIColor, cardShadow: UIColor, secondaryAction: UIColor, icon: UIColor?, iconBackground: UIColor?, destructive: UIColor, error: UIColor, warning: UIColor, unselected: UIColor, blurEffectStyle: UIBlurEffectStyle, blurEffectBackground: UIColor) { self.baseBackground = baseBackground self.midBackground = midBackground self.subCellBackground = subCellBackground self.paperBackground = paperBackground self.popoverBackground = popoverBackground self.chromeBackground = chromeBackground self.chromeShadow = chromeShadow self.cardShadow = cardShadow self.overlayBackground = overlayBackground self.batchSelectionBackground = batchSelectionBackground self.hintBackground = hintBackground self.referenceHighlightBackground = referenceHighlightBackground self.overlayText = overlayText self.searchFieldBackground = searchFieldBackground self.keyboardBarSearchFieldBackground = keyboardBarSearchFieldBackground self.primaryText = primaryText self.secondaryText = secondaryText self.tertiaryText = tertiaryText self.disabledText = disabledText self.disabledLink = disabledLink self.chromeText = chromeText self.link = link self.accent = accent self.border = border self.shadow = shadow self.icon = icon self.iconBackground = iconBackground self.linkToAccent = Gradient(startColor: link, endColor: accent) self.error = error self.warning = warning self.destructive = destructive self.secondaryAction = secondaryAction self.unselected = unselected self.blurEffectStyle = blurEffectStyle self.blurEffectBackground = blurEffectBackground } } @objc(WMFTheme) public class Theme: NSObject { @objc public static let standard = Theme.light @objc public let colors: Colors @objc public let isDark: Bool @objc public var preferredStatusBarStyle: UIStatusBarStyle { return isDark ? .lightContent : .default } @objc public var scrollIndicatorStyle: UIScrollViewIndicatorStyle { return isDark ? .white : .black } @objc public var blurEffectStyle: UIBlurEffectStyle { return isDark ? .dark : .light } @objc public var keyboardAppearance: UIKeyboardAppearance { return isDark ? .dark : .light } @objc public lazy var navigationBarBackgroundImage: UIImage = { return UIImage.wmf_image(from: colors.paperBackground) }() @objc public lazy var navigationBarShadowImage: UIImage = { return #imageLiteral(resourceName: "transparent-pixel") }() static func roundedRectImage(with color: UIColor, cornerRadius: CGFloat, width: CGFloat? = nil, height: CGFloat? = nil) -> UIImage? { let minDimension = 2 * cornerRadius + 1 let rect = CGRect(x: 0, y: 0, width: width ?? minDimension, height: height ?? minDimension) let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(rect.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor) let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) path.fill() let capInsets = UIEdgeInsetsMake(cornerRadius, cornerRadius, cornerRadius, cornerRadius) let image = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: capInsets) UIGraphicsEndImageContext() return image } @objc public lazy var searchFieldBackgroundImage: UIImage? = { return Theme.roundedRectImage(with: colors.searchFieldBackground, cornerRadius: 10, height: 36) }() @objc public lazy var navigationBarTitleTextAttributes: [NSAttributedStringKey: Any] = { return [NSAttributedStringKey.foregroundColor: colors.chromeText] }() @objc public let imageOpacity: CGFloat @objc public let name: String @objc public let displayName: String @objc public let multiSelectIndicatorImage: UIImage? fileprivate static let lightMultiSelectIndicator = UIImage(named: "selected", in: Bundle.main, compatibleWith:nil) fileprivate static let darkMultiSelectIndicator = UIImage(named: "selected-dark", in: Bundle.main, compatibleWith:nil) @objc public static let light = Theme(colors: .light, imageOpacity: 1, multiSelectIndicatorImage: Theme.lightMultiSelectIndicator, isDark: false, name: "standard", displayName: WMFLocalizedString("theme-default-display-name", value: "Default", comment: "Default theme name presented to the user")) @objc public static let sepia = Theme(colors: .sepia, imageOpacity: 1, multiSelectIndicatorImage: Theme.lightMultiSelectIndicator, isDark: false, name: "sepia", displayName: WMFLocalizedString("theme-sepia-display-name", value: "Sepia", comment: "Sepia theme name presented to the user")) @objc public static let dark = Theme(colors: .dark, imageOpacity: 1, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "dark", displayName: WMFLocalizedString("theme-dark-display-name", value: "Dark", comment: "Dark theme name presented to the user")) @objc public static let darkDimmed = Theme(colors: .dark, imageOpacity: 0.65, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "dark-dimmed", displayName: Theme.dark.displayName) @objc public static let black = Theme(colors: .black, imageOpacity: 1, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "black", displayName: WMFLocalizedString("theme-black-display-name", value: "Black", comment: "Black theme name presented to the user")) @objc public static let blackDimmed = Theme(colors: .black, imageOpacity: 0.65, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "black-dimmed", displayName: Theme.black.displayName) @objc public static let widget = Theme(colors: .widget, imageOpacity: 1, multiSelectIndicatorImage: nil, isDark: false, name: "", displayName: "") init(colors: Colors, imageOpacity: CGFloat, multiSelectIndicatorImage: UIImage?, isDark: Bool, name: String, displayName: String) { self.colors = colors self.imageOpacity = imageOpacity self.name = name self.displayName = displayName self.multiSelectIndicatorImage = multiSelectIndicatorImage self.isDark = isDark } fileprivate static let themesByName = [Theme.light.name: Theme.light, Theme.dark.name: Theme.dark, Theme.sepia.name: Theme.sepia, Theme.darkDimmed.name: Theme.darkDimmed, Theme.black.name: Theme.black, Theme.blackDimmed.name: Theme.blackDimmed] @objc(withName:) public class func withName(_ name: String?) -> Theme? { guard let name = name else { return nil } return themesByName[name] } @objc public func withDimmingEnabled(_ isDimmingEnabled: Bool) -> Theme { guard let baseName = name.components(separatedBy: "-").first else { return self } let adjustedName = isDimmingEnabled ? "\(baseName)-dimmed" : baseName return Theme.withName(adjustedName) ?? self } } @objc(WMFThemeable) public protocol Themeable : NSObjectProtocol { @objc(applyTheme:) func apply(theme: Theme) //this might be better as a var theme: Theme { get set } - common VC superclasses could check for viewIfLoaded and call an update method in the setter. This would elminate the need for the viewIfLoaded logic in every applyTheme: }
mit
4949f81fdaeb91b4eb5116e08aeb9651
57.984709
965
0.734602
4.30728
false
false
false
false
brokenhandsio/AWSwift
Sources/AWSwift/DynamoDb/DynamoDbTable.swift
1
4091
public struct DynamoDbTable { // MARK: - Properties // TOOD sort out access let tableName: String let partitionKey: String let sortKey: String? let connectionManager: ConnectionManager // MARK: - Initialiser /** Initialiser for a table in DynamoDb. You can use the table object to perform all the actions you need that involve tables, such as creation and deletion of tables, putting items, deleting items etc - Parameters: - tableName: The name of the table - partitionKey: The name of the partition key - sortKey: The name of the optional sort key - connectionManager: The connectionManager to connect to DynamoDb */ public init(tableName: String, partitionKey: String, sortKey: String?, connectionManager: ConnectionManager) { self.tableName = tableName self.partitionKey = partitionKey self.sortKey = sortKey self.connectionManager = connectionManager } } // MARK = DynamoDbAction // TODO documentation extension DynamoDbTable: DynamoDbItemAction { public func putItem(item: [String : Any], condition: String, conditionAttributes: [String : [String : String]], completion: @escaping ((String?, AwsRequestErorr?) -> Void)) { let request = [ "TableName": tableName, "Item": item, "ConditionExpression": condition, "ExpressionAttributeValues": conditionAttributes ] as [String: Any] connectionManager.request(request, method: .post, service: DynamoDbService.putItem) { (response, error) in completion(response, error) } } public func getItem(keyValues: DynamoDbTableKeyValues, completion: @escaping ((String?, AwsRequestErorr?) -> Void)) { var key = [ partitionKey: [ "S": keyValues.partitionKeyValue ] ] if let sortKey = sortKey { guard let sortKeyValue = keyValues.sortKeyValue else { fatalError("Table has sort key but no sort key specified") } key[sortKey] = ["S" :sortKeyValue] } let request = [ "TableName": tableName, "Key": key ] as [String: Any] connectionManager.request(request, method: .post, service: DynamoDbService.getItem) { (response, error) in completion(response, error) } } public func deleteItem(keyValue: DynamoDbTableKeyValues, conditionExpression: String?, returnValues: DynamoDbReturnValue?, completion: @escaping ((String?, AwsRequestErorr?) -> Void)) { // Check valid return value if let returnValues = returnValues { switch returnValues { case .none, .allOld: break default: // Invalid return type completion(nil, AwsRequestErorr.failed(message: "Invalid return value for delete")) } } var key = [ partitionKey: [ "S": keyValue.partitionKeyValue ] ] if let sortKey = sortKey { guard let sortKeyValue = keyValue.sortKeyValue else { fatalError("Table has sort key but no sort key specified") } key[sortKey] = ["S" :sortKeyValue] } var request = [ "TableName": tableName, "Key": key ] as [String: Any] if let conditionExpression = conditionExpression { request["ConditionExpression"] = conditionExpression } if let returnValues = returnValues { request["ReturnValues"] = returnValues.rawValue } connectionManager.request(request, method: .post, service: DynamoDbService.deleteItem) { (resposne, error) in completion(resposne, error) } } }
mit
fe1048328616d672466b341d2e117317
32.532787
189
0.573454
5.12015
false
false
false
false
werner-freytag/DockTime
DockTime/DockTimeAppDelegate.swift
1
6504
// The MIT License // // Copyright 2012-2021 Werner Freytag // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import AppKit @NSApplicationMain class DockTimeAppDelegate: NSObject, NSApplicationDelegate { private let defaultBundleIdentifier = "io.pecora.DockTime-ClockBundle-BigSur" private let clockBundles = Bundle.paths(forResourcesOfType: "clockbundle", inDirectory: Bundle.main.builtInPlugInsPath!) .compactMap { Bundle(path: $0) } .sorted(by: { $0.bundleName! < $1.bundleName! }) .filter { guard let principalClass = $0.principalClass else { assertionFailure("Missing principalClass for bundle \(String(describing: $0.bundleIdentifier)).") return false } guard let clockViewClass = principalClass as? NSView.Type else { assertionFailure("\(String(describing: principalClass)) is not an NSView.") return false } return true } private var updateInterval = UpdateInterval.second { didSet { lastRefreshDate = nil } } private lazy var clockMenuItems: [NSMenuItem] = { clockBundles.enumerated() .map { index, bundle in let keyEquivalent: String = { switch index { case 0 ..< 9: return String(index + 1) case 9: return "0" default: return "" } }() let item = NSMenuItem(title: bundle.bundleName!, action: #selector(didSelectClockMenuItem(_:)), keyEquivalent: keyEquivalent) item.target = self item.state = bundle.bundleIdentifier == currentClockBundle?.bundleIdentifier ? .on : .off return item } }() private lazy var showSecondsMenuItem: NSMenuItem = { let item = NSMenuItem(title: NSLocalizedString("Show seconds", comment: "Show seconds menu item title"), action: #selector(didSelectShowSecondsMenuItem(_:)), keyEquivalent: ",") item.target = self item.state = UserDefaults.shared.showSeconds ? .on : .off return item }() private lazy var menu: NSMenu = { let menu = NSMenu(title: NSLocalizedString("Model", comment: "")) for item in clockMenuItems { menu.addItem(item) } menu.addItem(.separator()) menu.addItem(showSecondsMenuItem) return menu }() private var currentClockBundle: Bundle? { didSet { guard let clockBundle = currentClockBundle, let clockViewClass = clockBundle.principalClass as? NSView.Type else { return assertionFailure() } NSLog("Loading \(clockViewClass) of bundle \(clockBundle.bundleIdentifier!)") let updateIntervalString = clockBundle.object(forInfoDictionaryKey: "DTUpdateInterval") as? String ?? "" updateInterval = UpdateInterval(updateIntervalString) ?? .second dockTile.contentView = clockViewClass.init(frame: .zero) } } private var refreshTimer: Timer! private var lastRefreshDate: Date? private let dockTile = NSApp.dockTile func applicationWillFinishLaunching(_: Notification) { currentClockBundle = clockBundles.first(where: { $0.bundleIdentifier == UserDefaults.standard.selectedClockBundle }) ?? clockBundles.first(where: { $0.bundleIdentifier == defaultBundleIdentifier }) ?? clockBundles.first! refreshTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(refreshDockTile), userInfo: nil, repeats: true) let menuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") menuItem.submenu = menu NSApp.mainMenu?.addItem(menuItem) } func applicationDockMenu(_: NSApplication) -> NSMenu? { return menu } @objc func didSelectClockMenuItem(_ menuItem: NSMenuItem!) { guard let index = clockMenuItems.firstIndex(of: menuItem) else { return } UserDefaults.standard.selectedClockBundle = clockBundles[index].bundleIdentifier for item in clockMenuItems { item.state = item == menuItem ? .on : .off } currentClockBundle = clockBundles[index] dockTile.display() } @objc func didSelectShowSecondsMenuItem(_ menuItem: NSMenuItem!) { let showSeconds = menuItem.state == .off UserDefaults.shared.showSeconds = showSeconds NSLog("Toggle Show Seconds: \(showSeconds)") menuItem.state = showSeconds ? .on : .off lastRefreshDate = nil } var requiresRefresh: Bool { let date = Date() defer { lastRefreshDate = date } guard let lastRefreshDate = lastRefreshDate else { return true } let calendar = Calendar.current switch updateInterval { case .minute: return calendar.dateComponents([.hour, .minute], from: date) != calendar.dateComponents([.hour, .minute], from: lastRefreshDate) case .second: return calendar.dateComponents([.hour, .minute, .second], from: date) != calendar.dateComponents([.hour, .minute, .second], from: lastRefreshDate) case .continual: return true } } @objc func refreshDockTile() { guard requiresRefresh else { return } dockTile.display() } }
mit
ecdbffa000aa8043a277ec95e162ba95
37.714286
185
0.644219
4.968678
false
false
false
false
sabensm/playgrounds
optionals.playground/Contents.swift
1
1403
//: Playground - noun: a place where people can play import UIKit //The Question Mark defines the variable as an optional -- it may or may not have a value var lotteryWinnings: Int? if lotteryWinnings != nil { print(lotteryWinnings!) } lotteryWinnings = 1000 //This is the prefered method of handling the optionals. Anytime a variable has a quesion mark, we should use if let if let winnings = lotteryWinnings { print(winnings) } class Car { var model: String? } //Multiple if/let statement var vehicle: Car? vehicle = Car () vehicle?.model = "Bronco" if let v = vehicle, let m = v.model { print(m) } //Another Example with an if/let along with a conditional var cars: [Car]? cars = [Car] () if let carArray = cars where carArray.count > 0 { // Only execute if not nil and more than 0 elements } else { cars?.append(Car()) print(cars?.count) } //Implicitly Unwrapped Optional class Person { private var _age: Int! var age: Int { if _age == nil { _age = 15 } return _age } func setAge(newAge: Int) { self._age = newAge } } var jack = Person() print(jack.age) //Initializing properties without ? ! class Dog { var species: String init(someSpecies: String) { self.species = someSpecies } } var lab = Dog(someSpecies: "Black Lab") print(lab.species)
mit
357f503b1b76fae3a7ddf77d5b089668
16.5375
116
0.637206
3.551899
false
false
false
false
mentrena/SyncKit
SyncKit/Classes/CoreData/CoreDataStack.swift
1
3889
// // CoreDataStack.swift // SyncKit // // Created by Manuel Entrena on 02/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import Foundation import CoreData /// Encapsulates a Core Data stack. This predates `NSPersistentContainer` and it's basically the same. @objc public class CoreDataStack: NSObject { @objc public private(set) var managedObjectContext: NSManagedObjectContext! @objc public private(set) var persistentStoreCoordinator: NSPersistentStoreCoordinator! @objc public private(set) var store: NSPersistentStore! @objc public let storeType: String @objc public let storeURL: URL? @objc public let useDispatchImmediately: Bool @objc public let model: NSManagedObjectModel @objc public let concurrencyType: NSManagedObjectContextConcurrencyType /// Create a new Core Data stack. /// - Parameters: /// - storeType: Store type, such as NSSQLiteStoreType. /// - model: model to be used for the stack. /// - storeURL: `URL` for the store location. Optional. /// - concurrencyType: Default is `privateQueueConcurrencyType` /// - dispatchImmediately: Used for testing. @objc public init(storeType: String, model: NSManagedObjectModel, storeURL: URL?, concurrencyType: NSManagedObjectContextConcurrencyType = .privateQueueConcurrencyType, dispatchImmediately: Bool = false) { self.storeType = storeType self.storeURL = storeURL self.useDispatchImmediately = dispatchImmediately self.model = model self.concurrencyType = concurrencyType super.init() initializeStack() loadStore() } /// Winds down the stack and deletes the store. @objc public func deleteStore() { managedObjectContext.performAndWait { self.managedObjectContext.reset() } if let storeURL = storeURL { try? persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: storeType, options: nil) } managedObjectContext = nil store = nil } private func ensureStoreDirectoryExists() { guard let storeURL = storeURL else { return } let storeDirectory = storeURL.deletingLastPathComponent() if FileManager.default.fileExists(atPath: storeDirectory.path) == false { try! FileManager.default.createDirectory(at: storeDirectory, withIntermediateDirectories: true, attributes: nil) } } private func initializeStack() { ensureStoreDirectoryExists() persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) if useDispatchImmediately { managedObjectContext = QSManagedObjectContext(concurrencyType: concurrencyType) } else { managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType) } managedObjectContext.performAndWait { self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator self.managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy } } private func loadStore() { guard store == nil else { return } let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] store = try! persistentStoreCoordinator.addPersistentStore(ofType: storeType, configurationName: nil, at: storeURL, options: options) } }
mit
827f04f59f9ffcf3390d9774312dc524
39.926316
113
0.63606
6.270968
false
false
false
false
nanthi1990/SwiftCharts
Examples/Examples/TrackerExample.swift
2
3054
// // TrackerExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class TrackerExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints = [(2, 2), (4, 4), (7, 1), (8, 11), (12, 3)].map{ChartPoint(x: ChartAxisValueDouble($0.0, labelSettings: labelSettings), y: ChartAxisValueDouble($0.1))} let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 1, animDelay: 0) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let trackerLayerSettings = ChartPointsLineTrackerLayerSettings(thumbSize: Env.iPad ? 30 : 20, thumbCornerRadius: Env.iPad ? 16 : 10, thumbBorderWidth: Env.iPad ? 4 : 2, infoViewFont: ExamplesDefaults.fontWithSize(Env.iPad ? 26 : 16), infoViewSize: CGSizeMake(Env.iPad ? 400 : 160, Env.iPad ? 70 : 40), infoViewCornerRadius: Env.iPad ? 30 : 15) let chartPointsTrackerLayer = ChartPointsLineTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, lineColor: UIColor.blackColor(), animDuration: 1, animDelay: 2, settings: trackerLayerSettings) var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLineLayer, chartPointsTrackerLayer ] ) self.view.addSubview(chart.view) self.chart = chart } }
apache-2.0
0d80c5fc61ba16931c30b4c5f43bec42
51.655172
351
0.697446
5.202726
false
false
false
false
tensorflow/swift-models
Support/FileManagement.swift
1
6295
// Copyright 2019 The TensorFlow Authors. 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 Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif /// Creates a directory at a path, if missing. If the directory exists, this does nothing. /// /// - Parameters: /// - path: The path of the desired directory. public func createDirectoryIfMissing(at path: String) throws { guard !FileManager.default.fileExists(atPath: path) else { return } try FileManager.default.createDirectory( atPath: path, withIntermediateDirectories: true, attributes: nil) } /// Downloads a remote file and places it either within a target directory or at a target file name. /// If `destination` has been explicitly specified as a directory (setting `isDirectory` to true /// when appending the last path component), the file retains its original name and is placed within /// this directory. If `destination` isn't marked in this fashion, the file is saved as a file named /// after `destination` and its last path component. If the encompassing directory is missing in /// either case, it is created. /// /// - Parameters: /// - source: The remote URL of the file to download. /// - destination: Either the local directory to place the file in, or the local filename. public func download(from source: URL, to destination: URL) throws { let destinationFile: String if destination.hasDirectoryPath { try createDirectoryIfMissing(at: destination.path) let fileName = source.lastPathComponent destinationFile = destination.appendingPathComponent(fileName).path } else { try createDirectoryIfMissing(at: destination.deletingLastPathComponent().path) destinationFile = destination.path } let downloadedFile = try Data(contentsOf: source) try downloadedFile.write(to: URL(fileURLWithPath: destinationFile)) } /// Collect all file URLs under a folder `url`, potentially recursing through all subfolders. /// Optionally filters some extension (only jpeg or txt files for instance). /// /// - Parameters: /// - url: The folder to explore. /// - recurse: Will explore all subfolders if set to `true`. /// - extensions: Only keeps URLs with extensions in that array if it's provided public func collectURLs( under directory: URL, recurse: Bool = false, filtering extensions: [String]? = nil ) -> [URL] { var files: [URL] = [] do { let dirContents = try FileManager.default.contentsOfDirectory( at: directory, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]) for content in dirContents { if content.hasDirectoryPath && recurse { files += collectURLs(under: content, recurse: recurse, filtering: extensions) } else if content.isFileURL && (extensions == nil || extensions!.contains(content.pathExtension.lowercased())) { files.append(content) } } } catch { fatalError("Could not explore this folder: \(error)") } return files } /// Extracts a compressed file to a specified directory. This keys off of either the explicit /// file extension or one determined from the archive to determine which unarchiving method to use. /// This optionally deletes the original archive when done. /// /// - Parameters: /// - archive: The source archive file, assumed to be on the local filesystem. /// - localStorageDirectory: A directory that the archive will be unpacked into. /// - fileExtension: An optional explicitly-specified file extension for the archive, determining /// how it is unpacked. /// - deleteArchiveWhenDone: Whether or not the original archive is deleted when the extraction /// process has been completed. This defaults to false. public func extractArchive( at archive: URL, to localStorageDirectory: URL, fileExtension: String? = nil, deleteArchiveWhenDone: Bool = false ) { let archivePath = archive.path #if os(macOS) var binaryLocation = "/usr/bin/" #else var binaryLocation = "/bin/" #endif let toolName: String let arguments: [String] let adjustedPathExtension: String if archive.path.hasSuffix(".tar.gz") { adjustedPathExtension = "tar.gz" } else { adjustedPathExtension = archive.pathExtension } switch fileExtension ?? adjustedPathExtension { case "gz": toolName = "gunzip" arguments = [archivePath] case "tar": toolName = "tar" arguments = ["xf", archivePath, "-C", localStorageDirectory.path] case "tar.gz", "tgz": toolName = "tar" arguments = ["xzf", archivePath, "-C", localStorageDirectory.path] case "zip": binaryLocation = "/usr/bin/" toolName = "unzip" arguments = ["-qq", archivePath, "-d", localStorageDirectory.path] default: printError( "Unable to find archiver for extension \(fileExtension ?? adjustedPathExtension).") exit(-1) } let toolLocation = "\(binaryLocation)\(toolName)" let task = Process() task.executableURL = URL(fileURLWithPath: toolLocation) task.arguments = arguments do { try task.run() task.waitUntilExit() } catch { printError("Failed to extract \(archivePath) with error: \(error)") exit(-1) } if FileManager.default.fileExists(atPath: archivePath) && deleteArchiveWhenDone { do { try FileManager.default.removeItem(atPath: archivePath) } catch { printError("Could not remove archive, error: \(error)") exit(-1) } } }
apache-2.0
7c27fe554354dd657868b46cf7972d91
38.34375
101
0.676251
4.649188
false
false
false
false
broccolii/Demos
DEMO02-LoginAnimation/LoginAnimation/SwiftClass/LoginAnimationButton.swift
1
9553
// // LoginAnimationButton.swift // LoginAnimation // // Created by Broccoli on 16/6/28. // Copyright © 2016年 youzan. All rights reserved. // import UIKit class LoginAnimationButton: UIButton { typealias AnimationCompletion = Void -> Void var failedBackgroundColor = UIColor.redColor() private var shrinkDuration: CFTimeInterval = 0.1 private var expandDuration: CFTimeInterval = 0.3 private var shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) private var expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05) private var spinerLayer: SpinerLayer! private var defaultBackgroundColor = UIColor(red: 4/255.0, green: 186/255.0, blue: 215/255.0, alpha: 1) private var animationCompletion: AnimationCompletion? override init(frame: CGRect) { super.init(frame: frame) setupLayer() setupTargetAction() } func failedAnimation(WithCompletion completion: AnimationCompletion) { animationCompletion = completion let shrinkAnimation = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnimation.fromValue = CGRectGetHeight(bounds) shrinkAnimation.toValue = CGRectGetWidth(bounds) shrinkAnimation.duration = shrinkDuration shrinkAnimation.timingFunction = shrinkCurve shrinkAnimation.fillMode = kCAFillModeForwards shrinkAnimation.removedOnCompletion = false defaultBackgroundColor = backgroundColor! let backgroundColorAniamtion = CABasicAnimation(keyPath: "backgroundColor") backgroundColorAniamtion.toValue = failedBackgroundColor.CGColor backgroundColorAniamtion.duration = shrinkDuration backgroundColorAniamtion.timingFunction = shrinkCurve backgroundColorAniamtion.fillMode = kCAFillModeForwards backgroundColorAniamtion.removedOnCompletion = false let keyframeAnimation = CAKeyframeAnimation(keyPath: "position") let originPoint = layer.position keyframeAnimation.values = [NSValue(CGPoint: CGPoint(x: originPoint.x, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)), NSValue(CGPoint: CGPoint(x: originPoint.x, y: originPoint.y))] keyframeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) keyframeAnimation.duration = 0.5 keyframeAnimation.delegate = self layer.position = originPoint layer.addAnimation(shrinkAnimation, forKey: shrinkAnimation.keyPath) layer.addAnimation(backgroundColorAniamtion, forKey: backgroundColorAniamtion.keyPath) layer.addAnimation(keyframeAnimation, forKey: keyframeAnimation.keyPath) spinerLayer.stopAnimation() userInteractionEnabled = true } func succeedAnimation(WithCompletion completion: AnimationCompletion) { animationCompletion = completion let expandAnimation = CABasicAnimation(keyPath: "transform.scale") expandAnimation.fromValue = 1.0 expandAnimation.toValue = 33.0 expandAnimation.timingFunction = expandCurve expandAnimation.duration = expandDuration expandAnimation.delegate = self expandAnimation.fillMode = kCAFillModeForwards expandAnimation.removedOnCompletion = false layer.addAnimation(expandAnimation, forKey: expandAnimation.keyPath) spinerLayer.stopAnimation() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - animation delegate extension LoginAnimationButton { override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if let basicAnimation = anim as? CABasicAnimation where basicAnimation.keyPath == "transform.scale" { userInteractionEnabled = true if animationCompletion != nil { animationCompletion!() } // NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(didStopAnimation), userInfo: nil, repeats: true) } } } private extension LoginAnimationButton { func setupLayer() { spinerLayer = SpinerLayer(frame: frame) layer.addSublayer(spinerLayer) layer.cornerRadius = CGRectGetHeight(bounds) / 2 clipsToBounds = true } func setupTargetAction() { addTarget(self, action: #selector(scaleToSmall), forControlEvents: [.TouchDown, .TouchDragEnter]) addTarget(self, action: #selector(scaleAnimation), forControlEvents: .TouchUpInside) addTarget(self, action: #selector(scaleToDefault), forControlEvents: .TouchDragExit) } @objc func scaleToSmall() { transform = CGAffineTransformMakeScale(1, 1) layer.backgroundColor = self.backgroundColor?.CGColor UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .LayoutSubviews, animations: { self.transform = CGAffineTransformMakeScale(0.9, 0.9) }, completion: nil) } @objc func scaleAnimation() { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .LayoutSubviews, animations: { self.transform = CGAffineTransformMakeScale(1, 1) }, completion: nil) beginAniamtion() } @objc func scaleToDefault() { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.4, options: .LayoutSubviews, animations: { self.transform = CGAffineTransformMakeScale(1, 1) }, completion: nil) } @objc func didStopAnimation() { layer.removeAllAnimations() } func beginAniamtion() { // if CGColorEqualToColor(layer.backgroundColor, failedBackgroundColor.CGColor) { revertBackgroundColor() // } layer.addSublayer(spinerLayer) let shrinkAnimation = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnimation.fromValue = CGRectGetWidth(bounds) shrinkAnimation.toValue = CGRectGetHeight(bounds) shrinkAnimation.duration = shrinkDuration shrinkAnimation.timingFunction = shrinkCurve shrinkAnimation.fillMode = kCAFillModeForwards shrinkAnimation.removedOnCompletion = false layer.addAnimation(shrinkAnimation, forKey: shrinkAnimation.keyPath) spinerLayer.beginAnimation() userInteractionEnabled = false } func revertBackgroundColor() { let backgroundColorAniamtion = CABasicAnimation(keyPath: "backgroundColor") backgroundColorAniamtion.toValue = defaultBackgroundColor.CGColor backgroundColorAniamtion.duration = shrinkDuration backgroundColorAniamtion.timingFunction = shrinkCurve backgroundColorAniamtion.fillMode = kCAFillModeForwards backgroundColorAniamtion.removedOnCompletion = false layer.addAnimation(backgroundColorAniamtion, forKey: "revertBackgroundColor") } } class SpinerLayer: CAShapeLayer { required init(frame: CGRect) { super.init() let radius = CGRectGetHeight(frame) / 4 self.frame = CGRect(x: 0, y: 0, width: CGRectGetHeight(frame), height: CGRectGetHeight(frame)) let center = CGPoint(x: CGRectGetHeight(frame) / 2, y: CGRectGetMidY(bounds)) let startAngle = CGFloat(-M_PI_2) let endAngle = CGFloat(M_PI * 2 - M_PI_2) let clockwise = true path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise).CGPath fillColor = nil strokeColor = UIColor.whiteColor().CGColor lineWidth = 1 strokeEnd = 0.4 hidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func beginAnimation() { hidden = false let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotateAnimation.fromValue = 0 rotateAnimation.toValue = M_PI * 2 rotateAnimation.duration = 0.4 rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) rotateAnimation.repeatCount = HUGE rotateAnimation.fillMode = kCAFillModeForwards rotateAnimation.removedOnCompletion = false addAnimation(rotateAnimation, forKey: rotateAnimation.keyPath) } func stopAnimation() { hidden = true removeAllAnimations() } }
mit
44669014aea77c76076969b23525fed0
41.444444
144
0.658534
5.447804
false
false
false
false
StanDimitroff/SDDropdown
Example/Tests/Tests.swift
1
1160
// https://github.com/Quick/Quick import Quick import Nimble import SDDropdown class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
61207214f313593228be88e2d30499d0
22.08
60
0.357886
5.521531
false
false
false
false
Dibel/androidtool-mac
AndroidTool/Util.swift
1
4378
// // Util.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Foundation import AppKit class Util { var deviceWidth:CGFloat = 373 var deviceHeight:CGFloat = 127 // view is self.view func changeWindowSize(window:NSWindow, view:NSView, addHeight:CGFloat=0, addWidth:CGFloat=0) { var frame = window.frame frame.size = CGSizeMake(frame.size.width+addWidth, frame.size.height+addHeight) frame.origin.y -= addHeight window.setFrame(frame, display: true, animate: true) view.frame.size.height += addHeight view.frame.origin.y -= addHeight } // func changeWindowHeight(window:NSWindow, view:NSView, newHeight:CGFloat=0) { // var frame = window.frame // frame.size = CGSizeMake(frame.size.width, newHeight) //// frame.origin.y -= newHeight // window.setFrame(frame, display: true, animate: true) // view.frame.size.height += newHeight // view.frame.origin.y -= newHeight // } func changeWindowHeight(window:NSWindow, view:NSView, newHeight:CGFloat=0) { var frame = window.frame frame.origin.y += frame.size.height; // origin.y is top Y coordinate now frame.origin.y -= newHeight // new Y coordinate for the origin frame.size.height = newHeight frame.size = CGSizeMake(frame.size.width, newHeight) window.setFrame(frame, display: true, animate: true) } func showNotification(title:String, moreInfo:String, sound:Bool=true) -> Void { let unc = NSUserNotificationCenter.defaultUserNotificationCenter() let notification = NSUserNotification() notification.title = title notification.informativeText = moreInfo if sound == true { notification.soundName = NSUserNotificationDefaultSoundName } unc.deliverNotification(notification) } func getSupportFolderScriptPath() -> String { let fileM = NSFileManager.defaultManager() let supportFolder:String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] let folder = "\(supportFolder)/AndroidTool" let scriptFolder = "\(folder)/UserScripts" if !fileM.fileExistsAtPath(folder) { do { try fileM.createDirectoryAtPath(folder, withIntermediateDirectories: false, attributes: nil) } catch _ { } do { try fileM.createDirectoryAtPath(scriptFolder, withIntermediateDirectories: false, attributes: nil) } catch _ { } // copy files from UserScriptsInception to this new folder - TODO: Take all, not just bugreport let inceptionScript = NSBundle.mainBundle().pathForResource("Take Bugreport", ofType: "sh") do { try fileM.copyItemAtPath(inceptionScript!, toPath: "\(scriptFolder)/Take Bugreport.sh") } catch _ { } } return scriptFolder } func revealScriptsFolder(){ let folder = getSupportFolderScriptPath() NSWorkspace.sharedWorkspace().openFile(folder) } func getFilesInScriptFolder(folder:String) -> [String]? { let fileM = NSFileManager.defaultManager() var files = [String]() let someFiles = fileM.enumeratorAtPath(folder) while let file = someFiles?.nextObject() as? String { if file != ".DS_Store" { files.append(file) } } return files } func isMavericks() -> Bool { if #available(OSX 10.10, *) { return NSProcessInfo.processInfo().operatingSystemVersion.minorVersion != 10 ? true : false } else { // Fallback on earlier versions return false } } func restartRefreshingDeviceList(){ NSNotificationCenter.defaultCenter().postNotificationName("unSuspendAdb", object: self, userInfo:nil) } func stopRefreshingDeviceList(){ NSNotificationCenter.defaultCenter().postNotificationName("suspendAdb", object: self, userInfo:nil) } }
apache-2.0
16db599b2ee6ffe454c8e95d87b31be0
33.746032
170
0.625857
4.837569
false
false
false
false
karavakis/simply_counted
File.swift
1
10016
//// //// ClientViewController.swift //// simply_counted //// //// Created by Jennifer Karavakis on 8/19/16. //// Copyright © 2017 Jennifer Karavakis. All rights reserved. //// // //import UIKit //import LocalAuthentication // //class ClientViewController: UIViewController, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, //UIPickerViewDataSource, UIPickerViewDelegate { // @IBOutlet weak var clientNameLabel: UILabel! // @IBOutlet weak var passesLabel: UILabel! // @IBOutlet weak var checkInDatePicker: UIDatePicker! // @IBOutlet weak var checkInButton: UIButton! // @IBOutlet weak var imageView: UIImageView! // @IBOutlet weak var passTextField: UITextField! // // // Hideable // @IBOutlet weak var unlockMoreOptionsLabel: UIButton! // @IBOutlet weak var addClassPassButton: UIButton! // @IBOutlet weak var removeClassPathButton: UIButton! // @IBOutlet weak var addClassPassesButtons: UISegmentedControl! // @IBOutlet weak var deleteUserButton: UIButton! // // var client : Client? = nil // var allowNegative = false // var ifAddClicked = true // // override func viewDidLoad() { // super.viewDidLoad() // // Do any additional setup after loading the view, typically from a nib. // toggleMoreOptions() // populateClientInfo() // setupDatePicker() // setupPickerView() // } // // override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // self.view.endEditing(true) // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // /*********************/ // /* Setup Date Picker */ // /*********************/ // func setupDatePicker() { // let today = NSDate() // checkInDatePicker.setDate(today, animated: true) // checkInDatePicker.maximumDate = today // } // // /************************/ // /* Populate Client Info */ // /************************/ // func populateClientInfo() { // if let client : Client = client { // clientNameLabel.text = client.name // passesLabel.text = "Passes Remaining: " + String(client.passes) // } // } // // /*********************/ // /* Update Class Pass */ // /*********************/ // func setupPickerView() { // let pickerView = UIPickerView() // pickerView.delegate = self // passTextField.inputView = pickerView // // let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil) // let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(ClientViewController.donePressed)) // let pickerToolbar = UIToolbar(frame: CGRectMake(0, self.view.frame.size.height/6, self.view.frame.size.width, 40.0)) // pickerToolbar.setItems([flexSpace, doneButton], animated: true) // passTextField.inputAccessoryView = pickerToolbar // // passTextField.text = "1" // } // // func donePressed() { // passTextField.resignFirstResponder() // if let passes = passTextField.text { // if let passNumber = Int(passes) { // addPassActivity(passNumber) // } // } // } // // func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { // return 1 // } // // func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // return 99 // } // // func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { // return String(row + 1) // } // // func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // passTextField.text = String(row + 1) // } // // func addPassActivity(passes : Int) { // if let client = self.client { // let changedPasses = ifAddClicked ? passes : passes * -1 // client.addPasses(changedPasses) // populateClientInfo() // // let addString = "The " + String(changedPasses) + " class pass was added successfully." // let wasWere = changedPasses == -1 ? " was" : "es were" // let removeString = String(changedPasses * -1) + " class pass" + wasWere + " removed successfully." // let message = ifAddClicked ? addString : removeString // // // let passAddedAlert = UIAlertController(title: "Pass Added", message: message, preferredStyle: UIAlertControllerStyle.Alert) // passAddedAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in // })) // // presentViewController(passAddedAlert, animated: true, completion: nil) // } // } // // func updateClassPath() { // var changedPasses = 0 // switch addClassPassesButtons.selectedSegmentIndex { // case 0: // changedPasses = 1 // case 1: // changedPasses = 12 // case 2: // changedPasses = 20 // case 3: // changedPasses = 30 // default: // changedPasses = 0 // break; // } // if(changedPasses == 0) { // passTextField.becomeFirstResponder() // } // else { // addPassActivity(changedPasses) // } // } // // @IBAction func addClassPass(sender: AnyObject) { // ifAddClicked = true // updateClassPath() // } // // @IBAction func removeClassPath(sender: AnyObject) { // ifAddClicked = false // updateClassPath() // } // // // /*********************/ // /* Authenticate User */ // /*********************/ // // @IBAction func unlockOptions(sender: AnyObject) { // let context = LAContext() // // context.evaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason: "Please authenticate to proceed.") { [weak self] (success, error) in // // guard success else { // dispatch_async(dispatch_get_main_queue()) { // // show something here to block the user from continuing // } // // return // } // // dispatch_async(dispatch_get_main_queue()) { // // do something here to continue loading your app, e.g. call a delegate method // self!.toggleMoreOptions() // } // } // } // // func toggleMoreOptions() { // addClassPassButton.hidden = !addClassPassButton.hidden // removeClassPathButton.hidden = !removeClassPathButton.hidden // addClassPassesButtons.hidden = !addClassPassesButtons.hidden // unlockMoreOptionsLabel.hidden = !addClassPassesButtons.hidden // deleteUserButton.hidden = !unlockMoreOptionsLabel.hidden // allowNegative = !addClassPassesButtons.hidden // } // // // /*******************/ // /* Load Table View */ // /*******************/ // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return 1 // } // // func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // if let client : Client = client { // return client.activities.count // } // return 0 // } // // func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> SimpleLabelTableViewCell { // var cell : SimpleLabelTableViewCell // cell = tableView.dequeueReusableCellWithIdentifier("CheckInCell") as! SimpleLabelTableViewCell // // if let client : Client = client { // let dateFormatter = NSDateFormatter() // dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle // dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle // cell.label.text = dateFormatter.stringFromDate(client.activities[indexPath.row].date) // } // // return cell // } // // func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // return true // } // // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // if (segue.identifier == "CheckInClicked") { // if let client = client { // if (client.passes <= 0 && !allowNegative) { // let noPassesAlert = UIAlertController(title: "Error", message: "Please load passes before checking in.", preferredStyle: UIAlertControllerStyle.Alert) // noPassesAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in // })) // // presentViewController(noPassesAlert, animated: true, completion: nil) // } // else { // client.checkIn(checkInDatePicker.date) // } // } // } // if (segue.identifier == "DeleteClicked") { // if let client = client { // let deleteAlert = UIAlertController(title: "Warning", message: "You are about to delete this user. This action cannot be undone.", preferredStyle: UIAlertControllerStyle.Alert) // deleteAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in // func deleteSuccess() { // segue.perform() // } // client.deleteClient(deleteSuccess) // })) // deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in // //Do nothing // })) // // presentViewController(deleteAlert, animated: true, completion: nil) // } // } // } //} //
apache-2.0
c6587fce4fa3ead42d1a97485d20fafc
36.935606
194
0.583625
4.326134
false
false
false
false
ohwutup/ReactiveCocoa
ReactiveCocoaTests/UIKit/UIButtonSpec.swift
1
1617
import Quick import Nimble import ReactiveSwift import ReactiveCocoa import UIKit import enum Result.NoError class UIButtonSpec: QuickSpec { override func spec() { var button: UIButton! weak var _button: UIButton? beforeEach { button = UIButton(frame: .zero) _button = button } afterEach { button = nil expect(_button).to(beNil()) } it("should accept changes from bindings to its titles under different states") { let firstTitle = "First title" let secondTitle = "Second title" let (pipeSignal, observer) = Signal<String, NoError>.pipe() button.reactive.title <~ SignalProducer(pipeSignal) button.setTitle("", for: .selected) button.setTitle("", for: .highlighted) observer.send(value: firstTitle) expect(button.title(for: UIControlState())) == firstTitle expect(button.title(for: .highlighted)) == "" expect(button.title(for: .selected)) == "" observer.send(value: secondTitle) expect(button.title(for: UIControlState())) == secondTitle expect(button.title(for: .highlighted)) == "" expect(button.title(for: .selected)) == "" } it("should execute the `pressed` action upon receiving a `touchUpInside` action message.") { button.isEnabled = true button.isUserInteractionEnabled = true let pressed = MutableProperty(false) let action = Action<(), Bool, NoError> { _ in SignalProducer(value: true) } pressed <~ SignalProducer(action.values) button.reactive.pressed = CocoaAction(action) expect(pressed.value) == false button.sendActions(for: .touchUpInside) expect(pressed.value) == true } } }
mit
984df82ff837006e7f9393b8b36feb52
25.508197
94
0.695733
3.75174
false
false
false
false
scottrhoyt/Cider
Tests/CiderTests/AlbumTests.swift
1
5230
// // AlbumTests.swift // CiderTests // // Created by Scott Hoyt on 8/1/17. // Copyright © 2017 Scott Hoyt. All rights reserved. // import XCTest @testable import Cider class AlbumTests: XCTestCase { func testAlbumFromSearch() throws { let search = try fixture(ResponseRoot<SearchResults>.self, name: "search") let album = search.results!.albums!.data![0] XCTAssertEqual(album.id, "900721190") XCTAssertEqual(album.type, .albums) XCTAssertEqual(album.href, "/v1/catalog/us/albums/900721190") XCTAssertNil(album.relationships) let attributes = album.attributes! XCTAssertEqual(attributes.artistName, "James Brown") XCTAssertEqual(attributes.name, "20 All-Time Greatest Hits!") XCTAssertEqual(attributes.copyright, "℗ 1991 Universal Records, a Division of UMG Recordings, Inc.") XCTAssertEqual(attributes.genreNames, ["Soul", "Music", "R&B/Soul", "Funk"]) XCTAssertEqual(attributes.isComplete, true) XCTAssertEqual(attributes.isSingle, false) XCTAssertEqual(attributes.releaseDate, "1991-10-22") XCTAssertEqual(attributes.trackCount, 20) XCTAssertEqual(attributes.url, URL(string: "https://itunes.apple.com/us/album/20-all-time-greatest-hits/id900721190")!) XCTAssertEqual(attributes.artwork.bgColor, "ffffff") XCTAssertEqual(attributes.artwork.height, 1400) XCTAssertEqual(attributes.artwork.textColor1, "0a0a09") XCTAssertEqual(attributes.artwork.textColor2, "2a240f") XCTAssertEqual(attributes.artwork.textColor3, "3b3b3a") XCTAssertEqual(attributes.artwork.textColor4, "544f3f") XCTAssertEqual(attributes.artwork.url, "https://example.mzstatic.com/image/thumb/Music4/v4/76/85/e5/7685e5c8-9346-88db-95ff-af87bf84151b/source/{w}x{h}bb.jpg") XCTAssertEqual(attributes.artwork.width, 1400) XCTAssertEqual(attributes.playParams?.id, "900721190") XCTAssertEqual(attributes.playParams?.kind, "album") XCTAssertNil(attributes.editorialNotes) } func testAlbumFromFetch() throws { let fetch = try fixture(ResponseRoot<Album>.self, name: "album") let album = fetch.data![0] XCTAssertEqual(album.id, "310730204") XCTAssertEqual(album.type, .albums) XCTAssertEqual(album.href, "/v1/catalog/us/albums/310730204") let attributes = album.attributes! XCTAssertEqual(attributes.artistName, "Bruce Springsteen") XCTAssertEqual(attributes.name, "Born to Run") XCTAssertEqual(attributes.copyright, "℗ 1975 Bruce Springsteen") XCTAssertEqual(attributes.genreNames, [ "Rock", "Music", "Arena Rock", "Rock & Roll", "Pop", "Pop/Rock" ]) XCTAssertEqual(attributes.isComplete, true) XCTAssertEqual(attributes.isSingle, false) XCTAssertEqual(attributes.releaseDate, "1975-08-25") XCTAssertEqual(attributes.trackCount, 8) XCTAssertEqual(attributes.url, URL(string: "https://itunes.apple.com/us/album/born-to-run/id310730204")!) XCTAssertEqual(attributes.artwork.bgColor, "ffffff") XCTAssertEqual(attributes.artwork.height, 1500) XCTAssertEqual(attributes.artwork.textColor1, "0c0b09") XCTAssertEqual(attributes.artwork.textColor2, "2a2724") XCTAssertEqual(attributes.artwork.textColor3, "3d3c3a") XCTAssertEqual(attributes.artwork.textColor4, "555250") XCTAssertEqual(attributes.artwork.url, "https://example.mzstatic.com/image/thumb/Music3/v4/2d/02/4a/2d024aaa-4547-ca71-7ba1-b8f5e1d98256/source/{w}x{h}bb.jpg") XCTAssertEqual(attributes.artwork.width, 1500) XCTAssertEqual(attributes.playParams?.id, "310730204") XCTAssertEqual(attributes.playParams?.kind, "album") XCTAssertEqual(attributes.editorialNotes?.standard, "Springsteen's third album was the one that broke it all open for him, planting his tales of Jersey girls, cars, and nights spent sleeping on the beach firmly in the Top Five. He shot for an unholy hybrid of Orbison, Dylan and Spector — and actually reached it. \"Come take my hand,\" he invited in the opening lines. \"We're ridin' out tonight to case the Promised Land.\" Soon after this album, he'd discover the limits of such dreams, but here, it's a wide-open road: Even the tales of petty crime (\"Meeting Across the River\") and teen-gang violence (\"Jungleland\") are invested with all the wit and charm you can handle. Bruce's catalog is filled with one-of-a-kind albums from <i>The Wild, The Innocent and the E Street Shuffle</i> to <i>The Ghost of Tom Joad</i>. Forty years on, <i>Born to Run</i> still sits near the very top of that stack.") XCTAssertEqual(attributes.editorialNotes?.short, "Springsteen's third album was the one that broke it all open for him.") } } #if os(Linux) extension AlbumTests { static var allTests: [(String, (AlbumTests) -> () throws -> Void)] { return [ ("testAlbumFromSearch", testAlbumFromSearch), ("testAlbumFromFetch", testAlbumFromFetch), ] } } #endif
mit
6c88acd7ca0324f19b54cb2e072b535d
50.205882
913
0.690982
3.91823
false
true
false
false
Finb/V2ex-Swift
Model/Moya/Observable+Extension.swift
1
7297
// // Observable+Extension.swift // V2ex-Swift // // Created by huangfeng on 2018/6/11. // Copyright © 2018 Fin. All rights reserved. // import UIKit import RxSwift import ObjectMapper import SwiftyJSON import Moya import Ji public enum ApiError : Swift.Error { case Error(info: String) case AccountBanned(info: String) case LoginPermissionRequired(info: String) case needs2FA(info: String) //需要两步验证 case needsCloudflareChecking(info: String) //需要 Cloudflare 检查 } extension Swift.Error { func rawString() -> String { guard let err = self as? ApiError else { return self.localizedDescription } switch err { case let .Error(info): return info case let .AccountBanned(info): return info case let .LoginPermissionRequired(info): return info case .needs2FA(let info): return info case .needsCloudflareChecking(let info): return info } } } //MARK: - JSON解析相关 extension Observable where Element: Moya.Response { /// 过滤 HTTP 错误,例如超时,请求失败等 func filterHttpError() -> Observable<Element> { return filter{ response in if (200...209) ~= response.statusCode { return true } if 503 == response.statusCode { if let jiHtml = Ji(htmlData: response.data) { if let titleNode = jiHtml.xPath("/html/head/title")?.first , let content = titleNode.content, content.hasPrefix("Just a moment") { throw ApiError.needsCloudflareChecking(info: "需要Cloudflare检查") } } } throw ApiError.Error(info: "网络错误") } } /// 过滤逻辑错误,例如协议里返回 错误CODE func filterResponseError() -> Observable<JSON> { return filterHttpError().map({ (response) -> JSON in var json: JSON do { json = try JSON(data: response.data) } catch { json = JSON(NSNull()) } var code = 200 var msg = "" if let codeStr = json["code"].rawString(), let c = Int(codeStr) { code = c } if json["msg"].exists() { msg = json["msg"].rawString()! } else if json["message"].exists() { msg = json["message"].rawString()! } else if json["info"].exists() { msg = json["info"].rawString()! } else if json["description"].exists() { msg = json["description"].rawString()! } if (code == 200 || code == 99999 || code == 80001 || code == 1){ return json } switch code { default: throw ApiError.Error(info: msg) } }) } /// 将Response 转换成 JSON Model /// /// - Parameters: /// - typeName: 要转换的Model Class /// - dataPath: 从哪个节点开始转换,例如 ["data","links"] func mapResponseToObj<T: Mappable>(_ typeName: T.Type , dataPath:[String] = [] ) -> Observable<T> { return filterResponseError().map{ json in var rootJson = json if dataPath.count > 0{ rootJson = rootJson[dataPath] } if let model: T = self.resultFromJSON(json: rootJson) { return model } else{ throw ApiError.Error(info: "json 转换失败") } } } /// 将Response 转换成 JSON Model Array func mapResponseToObjArray<T: Mappable>(_ type: T.Type, dataPath:[String] = [] ) -> Observable<[T]> { return filterResponseError().map{ json in var rootJson = json; if dataPath.count > 0{ rootJson = rootJson[dataPath] } var result = [T]() guard let jsonArray = rootJson.array else{ return result } for json in jsonArray{ if let jsonModel: T = self.resultFromJSON(json: json) { result.append(jsonModel) } else{ throw ApiError.Error(info: "json 转换失败") } } return result } } private func resultFromJSON<T: Mappable>(jsonString:String) -> T? { return T(JSONString: jsonString) } private func resultFromJSON<T: Mappable>(json:JSON) -> T? { if let str = json.rawString(){ return resultFromJSON(jsonString: str) } return nil } } //MARK: - Ji 解析相关 extension Observable where Element: Moya.Response { /// 过滤业务逻辑错误 func filterJiResponseError() -> Observable<Ji> { return filterHttpError().map({ (response: Element) -> Ji in if response.response?.url?.path == "/signin" && response.request?.url?.path != "/signin" { throw ApiError.LoginPermissionRequired(info: "查看的内容需要登录!") } if response.response?.url?.path == "/2fa" { //需要两步验证 throw ApiError.needs2FA(info: "需要两步验证") } if let jiHtml = Ji(htmlData: response.data) { return jiHtml } else { throw ApiError.Error(info: "Failed to serialize response.") } }) } /// 将Response 转成成 Ji Model Array func mapResponseToJiArray<T: HtmlModelArrayProtocol>(_ type: T.Type) -> Observable<[T]> { return filterJiResponseError().map{ ji in return type.createModelArray(ji: ji) as! [T] } } /// 将Response 转成成 Ji Model func mapResponseToJiModel<T: HtmlModelProtocol>(_ type: T.Type) -> Observable<T> { return filterJiResponseError().map{ ji in return type.createModel(ji: ji) as! T } } /// 在将 Ji 对象转换成 Model 之前,可能需要先获取 Ji 对象的数据 /// 例如获取我的收藏帖子列表时,除了需要将 Ji 数据 转换成 TopicListModel /// 还需要额外获取最大页码,这个最大页面就从这个方法中获得 func getJiDataFirst(hander:@escaping ((_ ji: Ji) -> Void)) -> Observable<Ji> { return filterJiResponseError().map({ (response: Ji) -> Ji in hander(response) return response }) } } //调用 getJiDataFirst() 方法后可调用的方法 extension Observable where Element: Ji { func mapResponseToJiArray<T: HtmlModelArrayProtocol>(_ type: T.Type) -> Observable<[T]> { return map{ ji in return type.createModelArray(ji: ji) as! [T] } } /// 将Response 转成成 Ji Model func mapResponseToJiModel<T: HtmlModelProtocol>(_ type: T.Type) -> Observable<T> { return map{ ji in return type.createModel(ji: ji) as! T } } }
mit
22d24404d136cba64202bd374fc40ac1
30.369863
150
0.525473
4.359137
false
false
false
false
Jean-Daniel/PhoneNumberKit
PhoneNumberKit/NSRegularExpression+Swift.swift
2
3211
// // NSRegularExpression+Swift.swift // PhoneNumberKit // // Created by David Beck on 8/15/16. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation extension String { func nsRange(from range: Range<String.Index>) -> NSRange { let utf16view = self.utf16 let from = range.lowerBound.samePosition(in: utf16view) ?? self.startIndex let to = range.upperBound.samePosition(in: utf16view) ?? self.endIndex return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to)) } func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } } extension NSRegularExpression { func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) self.enumerateMatches(in: string, options: options, range: nsRange, using: block) } func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> [NSTextCheckingResult] { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.matches(in: string, options: options, range: nsRange) } func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Int { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.numberOfMatches(in: string, options: options, range: nsRange) } func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> NSTextCheckingResult? { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.firstMatch(in: string, options: options, range: nsRange) } func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Range<String.Index>? { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) let match = self.rangeOfFirstMatch(in: string, options: options, range: nsRange) return string.range(from: match) } func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, withTemplate templ: String) -> String { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.stringByReplacingMatches(in: string, options: options, range: nsRange, withTemplate: templ) } }
mit
f68e424531760260cc299061b6ae8335
41.8
248
0.731776
3.848921
false
false
false
false
XRedcolor/noahhotel
noahhotel/Pods/CocoaLumberjack/Classes/CocoaLumberjack.swift
78
4944
// Software License Agreement (BSD License) // // Copyright (c) 2014-2015, Deusty, LLC // All rights reserved. // // Redistribution and use of this software 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. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. import Foundation import CocoaLumberjack extension DDLogFlag { public static func fromLogLevel(logLevel: DDLogLevel) -> DDLogFlag { return DDLogFlag(logLevel.rawValue) } ///returns the log level, or the lowest equivalant. public func toLogLevel() -> DDLogLevel { if let ourValid = DDLogLevel(rawValue: self.rawValue) { return ourValid } else { let logFlag = self if logFlag & .Verbose == .Verbose { return .Verbose } else if logFlag & .Debug == .Debug { return .Debug } else if logFlag & .Info == .Info { return .Info } else if logFlag & .Warning == .Warning { return .Warning } else if logFlag & .Error == .Error { return .Error } else { return .Off } } } } extension DDMultiFormatter { public var formatterArray: [DDLogFormatter] { return self.formatters as! [DDLogFormatter] } } public var defaultDebugLevel = DDLogLevel.Verbose public func resetDefaultDebugLevel() { defaultDebugLevel = DDLogLevel.Verbose } public func SwiftLogMacro(isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, tag: AnyObject? = nil, @autoclosure #string: () -> String) { if level.rawValue & flg.rawValue != 0 { // Tell the DDLogMessage constructor to copy the C strings that get passed to it. Using string interpolation to prevent integer overflow warning when using StaticString.stringValue let logMessage = DDLogMessage(message: string(), level: level, flag: flg, context: context, file: "\(file)", function: "\(function)", line: line, tag: tag, options: .CopyFile | .CopyFunction, timestamp: nil) DDLog.log(isAsynchronous, message: logMessage) } } public func DDLogDebug(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Debug, context: context, file: file, function: function, line: line, tag: tag, string: logText) } public func DDLogInfo(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Info, context: context, file: file, function: function, line: line, tag: tag, string: logText) } public func DDLogWarn(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Warning, context: context, file: file, function: function, line: line, tag: tag, string: logText) } public func DDLogVerbose(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Verbose, context: context, file: file, function: function, line: line, tag: tag, string: logText) } public func DDLogError(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Error, context: context, file: file, function: function, line: line, tag: tag, string: logText) } /// Analogous to the C preprocessor macro THIS_FILE public func CurrentFileName(fileName: StaticString = __FILE__) -> String { // Using string interpolation to prevent integer overflow warning when using StaticString.stringValue return "\(fileName)".lastPathComponent.stringByDeletingPathExtension }
mit
fd7c5f58f1eb2cd813e2d5c139aa7a97
53.32967
270
0.680825
4.321678
false
false
false
false
bastiangardel/EasyPayClientSeller
TB_Client_Seller/TB_Client_Seller/ViewControllerReceiptToPay.swift
1
4862
// // ReceiptToPayViewController.swift // TB_Client_Seller // // Created by Bastian Gardel on 27.06.16. // // Copyright © 2016 Bastian Gardel // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit import SwiftQRCode import BButton import MBProgressHUD import SCLAlertView // ** Class ViewControllerReceiptToPay ** // // View Receipt to pay Controller // // Author: Bastian Gardel // Version: 1.0 class ViewControllerReceiptToPay: UIViewController { var toPass: CheckoutDTO? @IBOutlet weak var ReceiptIDLabel: UILabel! @IBOutlet weak var qrcode: UIImageView! @IBOutlet weak var returnButton: BButton! @IBOutlet weak var amountLabel: UILabel! var httpsSession = HTTPSSession.sharedInstance var receipt: ReceiptPayDTO? var hud: MBProgressHUD? //View initialisation override func viewDidLoad() { super.viewDidLoad() returnButton.color = UIColor.bb_dangerColorV2() returnButton.setStyle(BButtonStyle.BootstrapV2) returnButton.setType(BButtonType.Danger) returnButton.addAwesomeIcon(FAIcon.FAAngleDoubleLeft, beforeTitle: true) qrcode.image = QRCode.generateImage((toPass?.uuid)!, avatarImage: UIImage(named: "avatar"), avatarScale: 0.3) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewControllerReceiptToPay.quitView(_:)), name: "quitView", object: nil) hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud?.labelText = "Receipt Loading in progress" hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)! httpsSession.getReceiptToPay((toPass?.uuid)!){ (success: Bool, errorDescription:String, receiptPayDTO : ReceiptPayDTO?) in self.hud!.hide(true) if(success) { self.receipt = receiptPayDTO self.amountLabel.text = "CHF " + String(format: "%.02f", (self.receipt?.amount)!) self.ReceiptIDLabel.text = "Receipt ID: " + (self.receipt?.id?.description)! } else { let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!, kTextFont: UIFont(name: "HelveticaNeue", size: 30)!, kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!, kWindowWidth: 500.0, kWindowHeight: 500.0, kTitleHeight: 50, showCloseButton: false ) let alertView = SCLAlertView(appearance: appearance) alertView.addButton("Return to menu"){ self.performSegueWithIdentifier("returnMenuSegue", sender: self) } alertView.showError("Receipt Loading Error", subTitle: errorDescription) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Quit view action func quitView(notification: NSNotification) { print(notification.userInfo!["aps"]!["uuid"]) if(notification.userInfo!["uuid"]! as? String == toPass?.uuid){ self.performSegueWithIdentifier("returnMenuSegue", sender: self) } } //Click on Return button handler @IBAction func returnMenuAction(sender: AnyObject) { self.performSegueWithIdentifier("returnMenuSegue", sender: self) } //Prepare transfer value for next view override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "returnMenuSegue") { let svc = segue.destinationViewController as! ViewControllerCheckoutMenu; svc.toPass = toPass } } }
mit
62a5f24b4b3fd9163616c871557d5122
33.475177
153
0.664884
4.784449
false
false
false
false
chenyunguiMilook/VisualDebugger
Sources/VisualDebugger/extensions/CGPoint+Behavior.swift
1
2519
// // CGPoint+Behavior.swift // VisualDebugger // // Created by chenyungui on 2018/3/19. // import Foundation import CoreGraphics #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif let kPointRadius: CGFloat = 3 extension CGPoint { func getBezierPath(radius: CGFloat) -> AppBezierPath { let x = (self.x - radius/2.0) let y = (self.y - radius/2.0) let rect = CGRect(x: x, y: y, width: radius, height: radius) return AppBezierPath(ovalIn: rect) } var length:CGFloat { return sqrt(self.x * self.x + self.y * self.y) } func normalized(to length:CGFloat = 1) -> CGPoint { let len = length/self.length return CGPoint(x: self.x * len, y: self.y * len) } } func +(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y) } func -(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x - p2.x, y: p1.y - p2.y) } func calculateAngle(_ point1:CGPoint, _ point2:CGPoint) -> CGFloat { return atan2(point2.y - point1.y, point2.x - point1.x) } func calculateDistance(_ point1:CGPoint, _ point2:CGPoint) -> CGFloat { let x = point2.x - point1.x let y = point2.y - point1.y return sqrt(x*x + y*y) } func calculateCenter(_ point1:CGPoint, _ point2:CGPoint) -> CGPoint { return CGPoint(x: point1.x+(point2.x-point1.x)/2.0, y: point1.y+(point2.y-point1.y)/2.0) } extension Array where Element == CGPoint { public var bounds:CGRect { guard let pnt = self.first else { return CGRect.zero } var (minX, maxX, minY, maxY) = (pnt.x, pnt.x, pnt.y, pnt.y) for point in self { minX = point.x < minX ? point.x : minX minY = point.y < minY ? point.y : minY maxX = point.x > maxX ? point.x : maxX maxY = point.y > maxY ? point.y : maxY } return CGRect(x: minX, y: minY, width: (maxX-minX), height: (maxY-minY)) } } // MARK: - Point extension CGPoint : Debuggable { public var bounds: CGRect { return CGRect(origin: self, size: .zero) } public func debug(in coordinate: CoordinateSystem, color: AppColor?) { let newPoint = self * coordinate.matrix let path = newPoint.getBezierPath(radius: kPointRadius) let color = color ?? coordinate.getNextColor() let shapeLayer = CAShapeLayer(path: path.cgPath, strokeColor: nil, fillColor: color, lineWidth: 0) coordinate.addSublayer(shapeLayer) } }
mit
7752883cdd627529a4556b619134ff13
26.086022
106
0.607384
3.246134
false
false
false
false
zybug/firefox-ios
Client/Frontend/Home/ReaderPanel.swift
12
22123
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import ReadingList import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44) static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorTopOffset: CGFloat = 36.75 // half of the cell - half of the height of the asset static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize, weight: UIFontWeightMedium) static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight) static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035) static let DeleteButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight) static let DeleteButtonTitleColor = UIColor.whiteColor() static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1) static let MarkAsReadButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight) static let MarkAsReadButtonTitleColor = UIColor.whiteColor() static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenHeaderFont = UIFont.boldSystemFontOfSize(UIConstants.DeviceFontSize - 1) static let WelcomeScreenHeaderTextColor = UIColor.darkGrayColor() static let WelcomeScreenItemFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight) static let WelcomeScreenItemTextColor = UIColor.grayColor() static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: SWTableViewCell { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url: NSURL = NSURL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal) if let text = markAsReadButton.titleLabel?.text { markAsReadAction.name = text } updateAccessibilityLabel() } } private var deleteAction: UIAccessibilityCustomAction! private var markAsReadAction: UIAccessibilityCustomAction! let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! let deleteButton: UIButton! let markAsReadButton: UIButton! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() deleteButton = UIButton() markAsReadButton = UIButton() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clearColor() separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = UIEdgeInsetsZero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = UIViewContentMode.ScaleAspectFit readStatusImageView.snp_makeConstraints { (make) -> () in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorTopOffset) make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor titleLabel.numberOfLines = 2 titleLabel.font = ReadingListTableViewCellUX.TitleLabelFont titleLabel.snp_makeConstraints { (make) -> () in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec } contentView.addSubview(hostnameLabel) hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor hostnameLabel.numberOfLines = 1 hostnameLabel.font = ReadingListTableViewCellUX.HostnameLabelFont hostnameLabel.snp_makeConstraints { (make) -> () in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.left.right.equalTo(self.titleLabel) } deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor deleteButton.titleLabel?.font = ReadingListTableViewCellUX.DeleteButtonTitleFont deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal) deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets deleteAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.DeleteButtonTitleText, target: self, selector: "deleteActionActivated") rightUtilityButtons = [deleteButton] markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor markAsReadButton.titleLabel?.font = ReadingListTableViewCellUX.MarkAsReadButtonTitleFont markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal) markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets markAsReadAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.MarkAsReadButtonTitleText, target: self, selector: "markAsReadActionActivated") leftUtilityButtons = [markAsReadButton] accessibilityCustomActions = [deleteAction, markAsReadAction] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] private func simplifiedHostnameFromURL(url: NSURL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return hostname.substringFromIndex(hostname.startIndex.advancedBy(prefix.characters.count)) } } return hostname } @objc private func markAsReadActionActivated() -> Bool { self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0) return true } @objc private func deleteActionActivated() -> Bool { self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0) return true } private func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate { weak var homePanelDelegate: HomePanelDelegate? = nil var profile: Profile! private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() private var records: [ReadingListClientRecord]? init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil) } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = ReadingListTableViewCellUX.RowHeight tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.separatorColor = UIConstants.SeparatorColor tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() view.backgroundColor = UIConstants.PanelBackgroundColor if let result = profile.readingList?.getAvailableRecords() where result.isSuccess { records = result.successValue // If no records have been added yet, we display the empty state if records?.count == 0 { tableView.scrollEnabled = false view.addSubview(emptyStateOverlayView) } } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationFirefoxAccountChanged: refreshReadingList() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count if let result = profile.readingList?.getAvailableRecords() where result.isSuccess { records = result.successValue if records?.count == 0 { tableView.scrollEnabled = false if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) } } else { if prevNumberOfRecords == 0 { tableView.scrollEnabled = true emptyStateOverlayView.removeFromSuperview() } } self.tableView.reloadData() } } private func createEmptyStateOverview() -> UIView { let overlayView = UIView(frame: tableView.bounds) overlayView.backgroundColor = UIColor.whiteColor() // Unknown why this does not work with autolayout overlayView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] let containerView = UIView() overlayView.addSubview(containerView) let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel")) containerView.addSubview(logoImageView) logoImageView.snp_makeConstraints { make in make.centerX.equalTo(containerView) make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).priorityHigh() // Sets proper top constraint for iPhone 6 in portait and iPads. make.centerY.equalTo(overlayView.snp_centerY).offset(-180).priorityMedium() // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView.snp_top).offset(50).priorityHigh() } let welcomeLabel = UILabel() containerView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = NSTextAlignment.Center welcomeLabel.font = ReadingListPanelUX.WelcomeScreenHeaderFont welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp_makeConstraints { make in make.centerX.equalTo(containerView) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) make.top.equalTo(logoImageView.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) // Sets proper center constraint for iPhones in landscape. make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).offset(-40).priorityHigh() } let readerModeLabel = UILabel() containerView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = ReadingListPanelUX.WelcomeScreenItemFont readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readerModeLabel.numberOfLines = 0 readerModeLabel.snp_makeConstraints { make in make.top.equalTo(welcomeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.left.equalTo(welcomeLabel.snp_left) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) containerView.addSubview(readerModeImageView) readerModeImageView.snp_makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.right.equalTo(welcomeLabel.snp_right) } let readingListLabel = UILabel() containerView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = ReadingListPanelUX.WelcomeScreenItemFont readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readingListLabel.numberOfLines = 0 readingListLabel.snp_makeConstraints { make in make.top.equalTo(readerModeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.left.equalTo(welcomeLabel.snp_left) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) containerView.addSubview(readingListImageView) readingListImageView.snp_makeConstraints { make in make.centerY.equalTo(readingListLabel) make.right.equalTo(welcomeLabel.snp_right) } containerView.snp_makeConstraints { make in // Let the container wrap around the content make.top.equalTo(logoImageView.snp_top) make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset) make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(overlayView) } return overlayView } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell cell.delegate = self if let record = records?[indexPath.row] { cell.title = record.title cell.url = NSURL(string: record.url)! cell.unread = record.unread } return cell } func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) { if let cell = cell as? ReadingListTableViewCell { cell.hideUtilityButtonsAnimated(true) if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] { if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess { // TODO This is a bit odd because the success value of the update is an optional optional Record if let successValue = result.successValue, updatedRecord = successValue { records?[indexPath.row] = updatedRecord tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } } } } func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) { if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] { if let result = profile.readingList?.deleteRecord(record) where result.isSuccess { records?.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) // reshow empty state if no records left if records?.count == 0 { view.addSubview(emptyStateOverlayView) } } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) { // Mark the item as read profile.readingList?.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.Bookmark homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType) } } }
mpl-2.0
5e3d20ff2fc0b9da7abc3c255157d2f4
48.381696
333
0.709262
5.863504
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/AccountStore.swift
1
5463
// // Wire // Copyright (C) 2017 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 private let log = ZMSLog(tag: "Accounts") /// Persistence layer for `Account` objects. /// Objects are stored in files named after their identifier like this: /// /// ``` /// - Root url passed to init /// - Accounts /// - 47B3C313-E3FA-4DE4-8DBE-5BBDB6A0A14B /// - 0F5771BB-2103-4E45-9ED2-E7E6B9D46C0F /// ``` public final class AccountStore: NSObject { private static let directoryName = "Accounts" private let fileManager = FileManager.default private let directory: URL // The url to the directory in which accounts are stored in /// Creates a new `AccountStore`. /// `Account` objects will be stored in a subdirectory of the passed in url. /// - parameter root: The root url in which the storage will use to store its data public required init(root: URL) { directory = root.appendingPathComponent(AccountStore.directoryName) super.init() FileManager.default.createAndProtectDirectory(at: directory) } // MARK: - Storing and Retrieving /// Loads all stored accounts. /// - returns: All accounts stored in this `AccountStore`. func load() -> Set<Account> { return Set<Account>(loadURLs().compactMap(Account.load)) } /// Tries to load a stored account with the given `UUID`. /// - parameter uuid: The `UUID` of the user the account belongs to. /// - returns: The `Account` stored for the passed in `UUID`, or `nil` otherwise. func load(_ uuid: UUID) -> Account? { return Account.load(from: url(for: uuid)) } /// Stores an `Account` in the account store. /// - parameter account: The account which should be saved (or updated). /// - returns: Whether or not the operation was successful. @discardableResult func add(_ account: Account) -> Bool { do { try account.write(to: url(for: account)) return true } catch { log.error("Unable to store account \(account), error: \(error)") return false } } /// Deletes an `Account` from the account store. /// - parameter account: The account which should be deleted. /// - returns: Whether or not the operation was successful. @discardableResult func remove(_ account: Account) -> Bool { do { guard contains(account) else { return false } try fileManager.removeItem(at: url(for: account)) return true } catch { log.error("Unable to delete account \(account), error: \(error)") return false } } /// Deletes the persistence layer of an `AccountStore` from the file system. /// Mostly useful for cleaning up after tests or for complete account resets. /// - parameter root: The root url of the store that should be deleted. @discardableResult static func delete(at root: URL) -> Bool { do { try FileManager.default.removeItem(at: root.appendingPathComponent(directoryName)) return true } catch { log.error("Unable to remove all accounts at \(root): \(error)") return false } } /// Check if an `Account` is already stored in this `AccountStore`. /// - parameter account: The account which should be deleted. /// - returns: Whether or not the account is stored in this `AccountStore`. func contains(_ account: Account) -> Bool { return fileManager.fileExists(atPath: url(for: account).path) } // MARK: - Private Helper /// Loads the urls to all stored accounts. /// - returns: The urls to all accounts stored in this `AccountStore`. private func loadURLs() -> Set<URL> { do { let uuidName: (String) -> Bool = { UUID(uuidString: $0) != nil } let paths = try fileManager.contentsOfDirectory(atPath: directory.path) return Set<URL>(paths.filter(uuidName).map(directory.appendingPathComponent)) } catch { log.error("Unable to load accounts from \(directory), error: \(error)") return [] } } /// Create a local url for an `Account` inside this `AccountStore`. /// - parameter account: The account for which the url should be generated. /// - returns: The `URL` for the given account. private func url(for account: Account) -> URL { return url(for: account.userIdentifier) } /// Create a local url for an `Account` with the given `UUID` inside this `AccountStore`. /// - parameter uuid: The uuid of the user for which the url should be generated. /// - returns: The `URL` for the given uuid. private func url(for uuid: UUID) -> URL { return directory.appendingPathComponent(uuid.uuidString) } }
gpl-3.0
5c4231b480c4a51358928541a39379da
38.875912
94
0.646714
4.349522
false
false
false
false
hi-hu/Hu-Tumbler
Hu-Tumbler/MainContainerViewController.swift
1
5183
// // MainContainerViewController.swift // Hu-Tumbler // // Created by Hi_Hu on 3/6/15. // Copyright (c) 2015 hi_hu. All rights reserved. // import UIKit class MainContainerViewController: UIViewController { @IBOutlet weak var mainContainerVC: UIView! @IBOutlet weak var exploreImage: UIImageView! @IBOutlet weak var loginBtn: UIButton! // array of tab controller buttons @IBOutlet var tabControlButtons: [UIButton]! // array holding the views var vcArray = [UIViewController]() var homeVC: HomeViewController! var searchVC: TrendingViewController! var composeVC: ComposeViewController! var accountVC: AccountViewController! var activityVC: SearchViewController! // index defaulted to home var selectedIndex: Int! = 0 // custom transitions var composeTransition: FadeTransition! var loginTransition: LoginTransition! override func viewDidLoad() { super.viewDidLoad() // set the status bar style to light UIApplication.sharedApplication().statusBarStyle = .LightContent // view controller instantiation var storyboard = UIStoryboard(name: "Main", bundle: nil) homeVC = storyboard.instantiateViewControllerWithIdentifier("homeSBID") as HomeViewController searchVC = storyboard.instantiateViewControllerWithIdentifier("trendingSBID") as TrendingViewController composeVC = storyboard.instantiateViewControllerWithIdentifier("composeSBID") as ComposeViewController accountVC = storyboard.instantiateViewControllerWithIdentifier("accountSBID") as AccountViewController activityVC = storyboard.instantiateViewControllerWithIdentifier("searchSBID") as SearchViewController // add the instantiated views into the array vcArray = [homeVC, searchVC, accountVC, activityVC] // default to homepage displayContentController(mainContainerVC, content: homeVC) tabControlButtons[0].selected = true // animate the explore bubble to bob up and down UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { () -> Void in self.exploreImage.center.y = self.exploreImage.center.y - 6 }) { (Bool) -> Void in // code } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tabBtnDidPress(sender: AnyObject) { var oldIndex = selectedIndex selectedIndex = sender.tag if selectedIndex != 0 { loginBtn.hidden = true } else { loginBtn.hidden = false } if selectedIndex == 1 { exploreImage.hidden = true } // deactivate button and remove current view tabControlButtons[oldIndex].selected = false hideContentController(mainContainerVC, content: vcArray[oldIndex]) // activate button add new selected view tabControlButtons[selectedIndex].selected = true displayContentController(mainContainerVC, content: vcArray[selectedIndex]) } // perform custom segue @IBAction func composeDidPress(sender: AnyObject) { performSegueWithIdentifier("composeSegue", sender: self) } @IBAction func loginDidPress(sender: AnyObject) { performSegueWithIdentifier("loginSegue", sender: self) } // add a subbview to the specified container func displayContentController(container: UIView, content: UIViewController) { addChildViewController(content) mainContainerVC.addSubview(content.view) content.didMoveToParentViewController(self) } // remove a subview from the specified container func hideContentController(container: UIView, content: UIViewController) { content.willMoveToParentViewController(nil) content.view.removeFromSuperview() content.removeFromParentViewController() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationViewController = segue.destinationViewController as UIViewController if segue.identifier == "composeSegue" { // instantiate the transition composeTransition = FadeTransition() composeTransition.duration = 0.3 destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom destinationViewController.transitioningDelegate = composeTransition } else if segue.identifier == "loginSegue" { // instantiate the transition loginTransition = LoginTransition() loginTransition.duration = 0.3 destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom destinationViewController.transitioningDelegate = loginTransition } } }
mit
16881bb938ec52a453d5a049863de266
35.244755
154
0.675285
5.957471
false
false
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Other/SPFooterButtonsView.swift
1
4355
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPFooterActionsView: SPView { var sectionLabels = SPSectionLabelsView() private var buttons: [SPFooterActionButton] = [] private var separators: [SPSeparatorView] = [] override func commonInit() { super.commonInit() self.backgroundColor = UIColor.clear self.sectionLabels.titleLabel.text = "Actions" self.addSubview(self.sectionLabels) } func addButton(title: String, titleColor: UIColor, target: @escaping ()->()) { let button = SPFooterActionButton() button.setTitle(title, color: titleColor) button.target { target() } self.buttons.append(button) self.addSubview(button) let separator = SPSeparatorView() self.separators.append(separator) self.addSubview(separator) } func button(for id: Int) -> SPFooterActionButton? { if (self.buttons.count - 1) < id { return nil } return self.buttons[id] } func layout(origin: CGPoint, width: CGFloat) { self.frame.origin = origin self.frame.set(width: width) self.layoutSubviews() } func layout(y: CGFloat, width: CGFloat) { self.layout(origin: CGPoint.init(x: 19, y: y), width: width) } override func layoutSubviews() { super.layoutSubviews() self.sectionLabels.layout(origin: CGPoint.zero, width: self.frame.width) let buttonHeight: CGFloat = 50 var yPositionButton: CGFloat = self.sectionLabels.frame.bottomY + 12 if !self.buttons.isEmpty { for i in 0...(buttons.count - 1) { let button = self.buttons[i] let separator = self.separators[i] separator.frame.origin.x = 0 separator.frame.origin.y = yPositionButton separator.frame.set(width: self.frame.width) button.frame = CGRect.init(x: 0, y: yPositionButton, width: self.frame.width, height: buttonHeight) yPositionButton += buttonHeight } self.frame.set(height: yPositionButton) } } } class SPFooterActionButton: SPButton { var rightIconView: UIView? { willSet { self.rightIconView?.removeFromSuperview() } didSet { if let view = self.rightIconView { self.addSubview(view) self.layoutSubviews() } } } override func commonInit() { super.commonInit() self.setTitleColor(SPNativeColors.blue) self.titleLabel?.font = UIFont.system(weight: .regular, size: 21) self.contentHorizontalAlignment = .left } override func layoutSubviews() { super.layoutSubviews() let sideSize: CGFloat = self.frame.height * 0.36 self.rightIconView?.frame = CGRect.init(x: 0, y: 0, width: sideSize, height: sideSize) self.rightIconView?.center.y = self.frame.height / 2 self.rightIconView?.frame.bottomX = self.frame.width - sideSize / 3 } }
mit
92acabc976a7c13e9a70c68f4ba1e0ed
34.983471
115
0.629536
4.597677
false
false
false
false
Mobelux/MONK
MONKTests/Tests/UploadTaskTests.swift
1
26326
// // UploadTaskTests.swift // MONK // // MIT License // // Copyright (c) 2017 Mobelux // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest @testable import MONK class UploadTaskTests: XCTestCase { private let networkController = NetworkController(serverTrustSettings: nil) override func tearDown() { super.tearDown() networkController.cancelAllTasks() } func testUploadJSONTask() { let expectation = self.expectation(description: "Network request") let url = URL(string: "http://httpbin.org/post")! let json = try! DataHelper.data(for: .posts1).json() let dataToUpload = UploadableData.json(json: json) XCTAssertFalse(dataToUpload.isMultiPart, "Multipart data was not expected") let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } let responseWhatWePosted = responseJSON["json"] XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing") XCTAssert((responseWhatWePosted as! JSON) == json, "The JSON we posted is not what we got back") XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } func testPUTUploadJSONTask() { let expectation = self.expectation(description: "Network request") let url = URL(string: "http://httpbin.org/put")! let json = try! DataHelper.data(for: .posts1).json() let dataToUpload = UploadableData.json(json: json) XCTAssertFalse(dataToUpload.isMultiPart, "Multipart data was not expected") let request = DataRequest(url: url, httpMethod: .put(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } let responseWhatWePosted = responseJSON["json"] XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing") XCTAssert((responseWhatWePosted as! JSON) == json, "The JSON we posted is not what we got back") XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } func testUploadImageFromURLTask() { let expectation = self.expectation(description: "Network request") let imageURL = DataHelper.imageURL(for: .compiling) let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .file(url: imageURL)) let dataToUpload = UploadableData.files(files: [file]) let url = URL(string: "http://httpbin.org/post")! let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files") XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } func testUploadJSONAndImageFromURLTask() { let expectation = self.expectation(description: "Network request") let json = try! DataHelper.data(for: .posts1).json() let imageURL = DataHelper.imageURL(for: .compiling) let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .file(url: imageURL)) let dataToUpload = UploadableData.jsonAndFiles(json: json, files: [file]) let url = URL(string: "http://httpbin.org/post")! let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } let responseWhatWePosted = responseJSON["form"] as? JSON XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing") XCTAssert(responseWhatWePosted!.keys.elementsEqual(json.keys), "The JSON we posted is not what we got back") XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files") XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } func testUploadJSONAndImageFromDataTask() { let expectation = self.expectation(description: "Network request") let json = try! DataHelper.data(for: .posts1).json() let imageData = DataHelper.imageData(for: .compiling) let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .data(data: imageData)) let dataToUpload = UploadableData.jsonAndFiles(json: json, files: [file]) XCTAssert(dataToUpload.isMultiPart, "Multipart data expected") let url = URL(string: "http://httpbin.org/post")! let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } let responseWhatWePosted = responseJSON["form"] as? JSON XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing") XCTAssert(responseWhatWePosted!.keys.elementsEqual(json.keys), "The JSON we posted is not what we got back") XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files") XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } func testUploadImageFromRawData() { let expectation = self.expectation(description: "Network request") let imageData = DataHelper.imageData(for: .compiling) let dataToUpload = UploadableData.data(data: imageData, contentType: ContentType.png) let url = URL(string: "http://httpbin.org/post")! let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload)) let task = networkController.data(with: request) var downloadProgressCalled = false var uploadProgressCalled = false task.addCompletion { (result) in switch result { case .failure(let error): XCTAssert(false, "Error found: \(String(describing: error))") expectation.fulfill() case .success(let statusCode, let responseData, let cached): XCTAssert(statusCode == 200, "Invalid status code found") XCTAssertNotNil(responseData, "Data was nil") switch cached { case .notCached: break case .fromCache, .updatedCache: XCTAssert(false, "We should not have used the cache") } guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return } XCTAssert(FileValidator.validate(uploadedData: dataToUpload, response: responseJSON), "Uploaded data don't match recieved data") XCTAssert(downloadProgressCalled, "Download progress was never called") XCTAssert(uploadProgressCalled, "Upload progress was never called") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { let mutableTask = task as! MutableDataTask XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated") XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated") XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated") expectation.fulfill() }) } } task.addProgress { (progress) in XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set") XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") downloadProgressCalled = true } task.addUploadProgress { (progress) in XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set") XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match") XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match") XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match") XCTAssertNotNil(progress.progress, "Progress was nil") XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes") uploadProgressCalled = true } task.resume() waitForExpectations(timeout: TestConstants.testTimeout, handler: nil) } }
mit
8cbbf1287749578c6b565ce66e5f200f
54.190776
150
0.632645
5.319458
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/server/TKDeparturesProvider.swift
1
4001
// // TKDeparturesProvider.swift // TripKit // // Created by Adrian Schönig on 01.11.20. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // #if canImport(CoreData) import Foundation import CoreData @objc public class TKDeparturesProvider: NSObject { private override init() { super.init() } } // MARK: - API to Core Data extension TKDeparturesProvider { public static func addDepartures(_ departures: TKAPI.Departures, to stops: [StopLocation]) -> Bool { guard let context = stops.first?.managedObjectContext else { return false } var addedStops = false // First, we process optional parent information let lookup = Dictionary(grouping: stops) { $0.stopCode } for parent in departures.parentStops ?? [] { if let existing = lookup[parent.code]?.first { addedStops = existing.update(from: parent) || addedStops } else { assertionFailure("Got a parent that we didn't ask for: \(parent)") } } // Next, we collect the existing stops to add content to let flattened = stops.flatMap { return [$0] + ($0.children ?? []) } let candidates = Dictionary(grouping: flattened) { $0.stopCode } // Now, we can add all the stops var addedCount = 0 for embarkation in departures.embarkationStops { guard let stop = candidates[embarkation.stopCode]?.first else { assertionFailure("Got an embarkation but no stop to add it to: \(embarkation). Stops: \(candidates)") continue } for serviceModel in embarkation.services { addedCount += 1 let service = Service(from: serviceModel, into: context) service.addVisits(StopVisits.self, from: serviceModel, at: stop) } } assert(addedCount > 0, "No embarkations in \(departures)") // Insert all the alerts, and make sure that the stops point // to them, too TKAPIToCoreDataConverter.updateOrAddAlerts(departures.alerts, in: context) departures.stops?.forEach { let hashCodes = $0.alertHashCodes guard !hashCodes.isEmpty else { return } lookup[$0.code]?.forEach { $0.alertHashCodes = hashCodes.map(NSNumber.init) } } return addedStops } public static func addDepartures(_ departures: TKAPI.Departures, into context: NSManagedObjectContext) -> Set<String> { // First, we make sure we have all the stops let stops = (departures.stops ?? []) .map { TKAPIToCoreDataConverter.insertNewStopLocation(from: $0, into: context) } // Next, we collect the existing stops to add content to let flattened = stops.flatMap { return [$0] + ($0.children ?? []) } let candidates = Dictionary(grouping: flattened) { $0.stopCode } // Now, we can add all the stops var pairIdentifieres = Set<String>() for embarkation in departures.embarkationStops { guard let startStop = candidates[embarkation.stopCode]?.first else { TKLog.info("Got an embarkation but no stop to add it to: \(embarkation). Stops: \(candidates)") continue } for serviceModel in embarkation.services { guard let endStopCode = serviceModel.endStopCode, let endStop = candidates[endStopCode]?.first else { TKLog.info("Got an disembarkation but no stop to add it to: \(embarkation). Stops: \(candidates)") continue } let service = Service(from: serviceModel, into: context) if let entry = service.addVisits(DLSEntry.self, from: serviceModel, at: startStop) { entry.pairIdentifier = "\(embarkation.stopCode)-\(endStopCode)" entry.endStop = endStop pairIdentifieres.insert(entry.pairIdentifier) } } } // assert(!pairIdentifieres.isEmpty, "No embarkations in \(departures)") TKAPIToCoreDataConverter.updateOrAddAlerts(departures.alerts, in: context) return pairIdentifieres } } #endif
apache-2.0
1b79b88a4ac40f0edbc867b8b3b69b76
32.049587
121
0.651913
4.152648
false
false
false
false
apple/swift-argument-parser
Sources/ArgumentParserTestHelpers/TestHelpers.swift
1
13844
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import ArgumentParser import ArgumentParserToolInfo import XCTest @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension CollectionDifference.Change { var offset: Int { switch self { case .insert(let offset, _, _): return offset case .remove(let offset, _, _): return offset } } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension CollectionDifference.Change: Comparable where ChangeElement: Equatable { public static func < (lhs: Self, rhs: Self) -> Bool { guard lhs.offset == rhs.offset else { return lhs.offset < rhs.offset } switch (lhs, rhs) { case (.remove, .insert): return true case (.insert, .remove): return false default: return true } } } // extensions to the ParsableArguments protocol to facilitate XCTestExpectation support public protocol TestableParsableArguments: ParsableArguments { var didValidateExpectation: XCTestExpectation { get } } public extension TestableParsableArguments { mutating func validate() throws { didValidateExpectation.fulfill() } } // extensions to the ParsableCommand protocol to facilitate XCTestExpectation support public protocol TestableParsableCommand: ParsableCommand, TestableParsableArguments { var didRunExpectation: XCTestExpectation { get } } public extension TestableParsableCommand { mutating func run() throws { didRunExpectation.fulfill() } } extension XCTestExpectation { public convenience init(singleExpectation description: String) { self.init(description: description) expectedFulfillmentCount = 1 assertForOverFulfill = true } } public func AssertResultFailure<T, U: Error>( _ expression: @autoclosure () -> Result<T, U>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { switch expression() { case .success: let msg = message() XCTFail(msg.isEmpty ? "Incorrectly succeeded" : msg, file: file, line: line) case .failure: break } } public func AssertErrorMessage<A>(_ type: A.Type, _ arguments: [String], _ errorMessage: String, file: StaticString = #file, line: UInt = #line) where A: ParsableArguments { do { _ = try A.parse(arguments) XCTFail("Parsing should have failed.", file: file, line: line) } catch { // We expect to hit this path, i.e. getting an error: XCTAssertEqual(A.message(for: error), errorMessage, file: file, line: line) } } public func AssertFullErrorMessage<A>(_ type: A.Type, _ arguments: [String], _ errorMessage: String, file: StaticString = #file, line: UInt = #line) where A: ParsableArguments { do { _ = try A.parse(arguments) XCTFail("Parsing should have failed.", file: (file), line: line) } catch { // We expect to hit this path, i.e. getting an error: XCTAssertEqual(A.fullMessage(for: error), errorMessage, file: (file), line: line) } } public func AssertParse<A>(_ type: A.Type, _ arguments: [String], file: StaticString = #file, line: UInt = #line, closure: (A) throws -> Void) where A: ParsableArguments { do { let parsed = try type.parse(arguments) try closure(parsed) } catch { let message = type.message(for: error) XCTFail("\"\(message)\" — \(error)", file: (file), line: line) } } public func AssertParseCommand<A: ParsableCommand>(_ rootCommand: ParsableCommand.Type, _ type: A.Type, _ arguments: [String], file: StaticString = #file, line: UInt = #line, closure: (A) throws -> Void) { do { let command = try rootCommand.parseAsRoot(arguments) guard let aCommand = command as? A else { XCTFail("Command is of unexpected type: \(command)", file: (file), line: line) return } try closure(aCommand) } catch { let message = rootCommand.message(for: error) XCTFail("\"\(message)\" — \(error)", file: file, line: line) } } public func AssertEqualStrings(actual: String, expected: String, file: StaticString = #file, line: UInt = #line) { // If the input strings are not equal, create a simple diff for debugging... guard actual != expected else { // Otherwise they are equal, early exit. return } // Split in the inputs into lines. let actualLines = actual.split(separator: "\n", omittingEmptySubsequences: false) let expectedLines = expected.split(separator: "\n", omittingEmptySubsequences: false) // If collectionDifference is available, use it to make a nicer error message. if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { // Compute the changes between the two strings. let changes = actualLines.difference(from: expectedLines).sorted() // Render the changes into a diff style string. var diff = "" var expectedLines = expectedLines[...] for change in changes { if expectedLines.startIndex < change.offset { for line in expectedLines[..<change.offset] { diff += " \(line)\n" } expectedLines = expectedLines[change.offset...].dropFirst() } switch change { case .insert(_, let line, _): diff += "- \(line)\n" case .remove(_, let line, _): diff += "+ \(line)\n" } } for line in expectedLines { diff += " \(line)\n" } XCTFail("Strings are not equal.\n\(diff)", file: file, line: line) } else { XCTAssertEqual( actualLines.count, expectedLines.count, "Strings have different numbers of lines.", file: file, line: line) for (actualLine, expectedLine) in zip(actualLines, expectedLines) { XCTAssertEqual(actualLine, expectedLine, file: file, line: line) } } } public func AssertHelp<T: ParsableArguments>( _ visibility: ArgumentVisibility, for _: T.Type, equals expected: String, file: StaticString = #file, line: UInt = #line ) { let flag: String let includeHidden: Bool switch visibility { case .default: flag = "--help" includeHidden = false case .hidden: flag = "--help-hidden" includeHidden = true case .private: XCTFail("Should not be called.", file: file, line: line) return default: XCTFail("Unrecognized visibility.", file: file, line: line) return } do { _ = try T.parse([flag]) XCTFail(file: file, line: line) } catch { let helpString = T.fullMessage(for: error) AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line) } let helpString = T.helpMessage(includeHidden: includeHidden, columns: nil) AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line) } public func AssertHelp<T: ParsableCommand, U: ParsableCommand>( _ visibility: ArgumentVisibility, for _: T.Type, root _: U.Type, equals expected: String, file: StaticString = #file, line: UInt = #line ) { let includeHidden: Bool switch visibility { case .default: includeHidden = false case .hidden: includeHidden = true case .private: XCTFail("Should not be called.", file: file, line: line) return default: XCTFail("Unrecognized visibility.", file: file, line: line) return } let helpString = U.helpMessage( for: T.self, includeHidden: includeHidden, columns: nil) AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line) } public func AssertDump<T: ParsableArguments>( for _: T.Type, equals expected: String, file: StaticString = #file, line: UInt = #line ) throws { do { _ = try T.parse(["--experimental-dump-help"]) XCTFail(file: file, line: line) } catch { let dumpString = T.fullMessage(for: error) try AssertJSONEqualFromString(actual: dumpString, expected: expected, for: ToolInfoV0.self) } try AssertJSONEqualFromString(actual: T._dumpHelp(), expected: expected, for: ToolInfoV0.self) } public func AssertJSONEqualFromString<T: Codable & Equatable>(actual: String, expected: String, for type: T.Type) throws { let actualJSONData = try XCTUnwrap(actual.data(using: .utf8)) let actualDumpJSON = try XCTUnwrap(JSONDecoder().decode(type, from: actualJSONData)) let expectedJSONData = try XCTUnwrap(expected.data(using: .utf8)) let expectedDumpJSON = try XCTUnwrap(JSONDecoder().decode(type, from: expectedJSONData)) XCTAssertEqual(actualDumpJSON, expectedDumpJSON) } extension XCTest { public var debugURL: URL { let bundleURL = Bundle(for: type(of: self)).bundleURL return bundleURL.lastPathComponent.hasSuffix("xctest") ? bundleURL.deletingLastPathComponent() : bundleURL } public func AssertExecuteCommand( command: String, expected: String? = nil, exitCode: ExitCode = .success, file: StaticString = #file, line: UInt = #line) throws { try AssertExecuteCommand( command: command.split(separator: " ").map(String.init), expected: expected, exitCode: exitCode, file: file, line: line) } public func AssertExecuteCommand( command: [String], expected: String? = nil, exitCode: ExitCode = .success, file: StaticString = #file, line: UInt = #line) throws { #if os(Windows) throw XCTSkip("Unsupported on this platform") #endif let arguments = Array(command.dropFirst()) let commandName = String(command.first!) let commandURL = debugURL.appendingPathComponent(commandName) guard (try? commandURL.checkResourceIsReachable()) ?? false else { XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.", file: file, line: line) return } #if !canImport(Darwin) || os(macOS) let process = Process() if #available(macOS 10.13, *) { process.executableURL = commandURL } else { process.launchPath = commandURL.path } process.arguments = arguments let output = Pipe() process.standardOutput = output let error = Pipe() process.standardError = error if #available(macOS 10.13, *) { guard (try? process.run()) != nil else { XCTFail("Couldn't run command process.", file: file, line: line) return } } else { process.launch() } process.waitUntilExit() let outputData = output.fileHandleForReading.readDataToEndOfFile() let outputActual = String(data: outputData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines) let errorData = error.fileHandleForReading.readDataToEndOfFile() let errorActual = String(data: errorData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines) if let expected = expected { AssertEqualStrings( actual: errorActual + outputActual, expected: expected, file: file, line: line) } XCTAssertEqual(process.terminationStatus, exitCode.rawValue, file: file, line: line) #else throw XCTSkip("Not supported on this platform") #endif } public func AssertJSONOutputEqual( command: String, expected: String, file: StaticString = #file, line: UInt = #line ) throws { #if os(Windows) throw XCTSkip("Unsupported on this platform") #endif let splitCommand = command.split(separator: " ") let arguments = splitCommand.dropFirst().map(String.init) let commandName = String(splitCommand.first!) let commandURL = debugURL.appendingPathComponent(commandName) guard (try? commandURL.checkResourceIsReachable()) ?? false else { XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.", file: file, line: line) return } #if !canImport(Darwin) || os(macOS) let process = Process() if #available(macOS 10.13, *) { process.executableURL = commandURL } else { process.launchPath = commandURL.path } process.arguments = arguments let output = Pipe() process.standardOutput = output let error = Pipe() process.standardError = error if #available(macOS 10.13, *) { guard (try? process.run()) != nil else { XCTFail("Couldn't run command process.", file: file, line: line) return } } else { process.launch() } process.waitUntilExit() let outputString = try XCTUnwrap(String(data: output.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)) XCTAssertTrue(error.fileHandleForReading.readDataToEndOfFile().isEmpty, "Error occurred with `--experimental-dump-help`") try AssertJSONEqualFromString(actual: outputString, expected: expected, for: ToolInfoV0.self) #else throw XCTSkip("Not supported on this platform") #endif } public func AssertGenerateManual( multiPage: Bool, command: String, expected: String, file: StaticString = #file, line: UInt = #line ) throws { #if os(Windows) throw XCTSkip("Unsupported on this platform") #endif let commandURL = debugURL.appendingPathComponent(command) var command = [ "generate-manual", commandURL.path, "--date", "1996-05-12", "--section", "9", "--authors", "Jane Appleseed", "--authors", "<[email protected]>", "--authors", "The Appleseeds<[email protected]>", "--output-directory", "-", ] if multiPage { command.append("--multi-page") } try AssertExecuteCommand( command: command, expected: expected, exitCode: .success, file: file, line: line) } }
apache-2.0
76386e5b9bd80e899ef35275efb04e2b
30.312217
205
0.66091
4.174962
false
false
false
false
wtanuw/WTLibrary-iOS
WTLibrary-iOS/Swift/ButtonExtender.swift
1
1777
// // ButtonExtender.swift // IBButtonExtender // // Created by Ashish on 08/08/15. // Copyright (c) 2015 Ashish. All rights reserved. // import UIKit import QuartzCore @IBDesignable open class ButtonExtender: UIButton { //MARK: PROPERTIES @IBInspectable open var borderColor: UIColor = UIColor.white { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable open var borderWidth: CGFloat = 1.0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable open var cornurRadius: CGFloat = 1.0 { didSet { layer.cornerRadius = cornurRadius clipsToBounds = true } } //MARK: Initializers override public init(frame : CGRect) { super.init(frame : frame) setup() configure() } convenience public init() { self.init(frame:CGRect.zero) setup() configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() configure() } override open func awakeFromNib() { super.awakeFromNib() setup() configure() } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() configure() } func setup() { layer.borderColor = UIColor.white.cgColor layer.borderWidth = 1.0 layer.cornerRadius = 1.0 } func configure() { layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth layer.cornerRadius = cornurRadius } override open func layoutSubviews() { super.layoutSubviews() } }
mit
c35d6f5628db8cf00db12397e4d4bd7d
20.938272
66
0.576252
4.895317
false
true
false
false
SwiftyVK/SwiftyVK
Example/AppDelegate.swift
2
1461
import SwiftyVK var vkDelegateReference : SwiftyVKDelegate? #if os(iOS) import UIKit @UIApplicationMain final class AppDelegate : UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { vkDelegateReference = VKDelegateExample() return true } @available(iOS 9.0, *) func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:] ) -> Bool { let app = options[.sourceApplication] as? String VK.handle(url: url, sourceApplication: app) return true } func application( _ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any ) -> Bool { VK.handle(url: url, sourceApplication: sourceApplication) return true } } #elseif os(macOS) import Cocoa @NSApplicationMain final class AppDelegate : NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { vkDelegateReference = VKDelegateExample() } } #endif
mit
23fe0f7e263d9b00938bb1044de7c973
26.055556
101
0.575633
5.774704
false
false
false
false
karloscarweber/SwiftFoundations-Examples
Chapter1/TickTackToe/TickTackToe/ViewController.swift
1
3547
// // ViewController.swift // TickTackToe // // Created by Karl Oscar Weber on 6/20/15. // Copyright (c) 2015 Swift Foundations. All rights reserved. // import UIKit class ViewController: UIViewController { /* remember, you must initialize all of your instance variables before calling super.init If you don't do it here you can do it in the init() method. */ var button1 = UIButton() var button2 = UIButton() var button3 = UIButton() var button4 = UIButton() var button5 = UIButton() var button6 = UIButton() var button7 = UIButton() var button8 = UIButton() var button9 = UIButton() var buttons: Array<UIButton> = [UIButton]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } init() { // add all of the buttons to the array buttons.append(button1) buttons.append(button2) buttons.append(button3) buttons.append(button4) buttons.append(button5) buttons.append(button6) buttons.append(button7) buttons.append(button8) buttons.append(button9) // always call the designated initialiser of the super class super.init(nibName: nil, bundle: nil) // now we can layout buttons and stuff. self.layoutButtons() } /* I like to create a sub method to layout user interface elements. Doing so keeps the init method nice and clean. */ func layoutButtons() { print("layoutButtons called.\n") print("Say hello to my little friend.") let screen = UIScreen.mainScreen().bounds let screenThirdHeight = screen.height / 3 let screenThirdWidth = screen.width / 3 /* We should really use AutoLayout, but because this is a beginners book We'll just use Calculated rectangles. */ self.button1.frame = CGRectMake(0, 0, screenThirdWidth, screenThirdWidth) self.button2.frame = CGRectMake(screenThirdWidth, 0, screenThirdWidth, screenThirdWidth) self.button3.frame = CGRectMake(screenThirdWidth*2, 0, screenThirdWidth, screenThirdWidth) self.button4.frame = CGRectMake(0, screenThirdWidth, screenThirdWidth, screenThirdWidth) self.button5.frame = CGRectMake(screenThirdWidth, screenThirdWidth, screenThirdWidth, screenThirdWidth) self.button6.frame = CGRectMake(screenThirdWidth*2, screenThirdWidth, screenThirdWidth, screenThirdWidth) self.button7.frame = CGRectMake(0, screenThirdWidth*2, screenThirdWidth, screenThirdWidth) self.button8.frame = CGRectMake(screenThirdWidth, screenThirdWidth*2, screenThirdWidth, screenThirdWidth) self.button9.frame = CGRectMake(screenThirdWidth*2, screenThirdWidth*2, screenThirdWidth, screenThirdWidth) // button5.backgroundColor = UIColor.blueColor() for button in buttons { button.layer.borderWidth = 2.0 button.layer.borderColor = UIColor.blackColor().CGColor self.view.addSubview(button) } } /* Not often used methods down here */ required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3e3a87a10d0e5b9aab98701fc4dca462
33.77451
115
0.6521
4.472888
false
false
false
false
wangyuxianglove/TestKitchen1607
Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/recommend(推荐)/view/IngreLikeCell.swift
1
2819
// // IngreLikeCell.swift // Testkitchen1607 // // Created by qianfeng on 16/10/25. // Copyright © 2016年 zhb. All rights reserved. // import UIKit class IngreLikeCell: UITableViewCell { var jumpClosure:IngreJumpClourse? //数据 var listModel:IngreRecommendWidgetList? { didSet{ showData() } } //显示数据 private func showData(){ if listModel?.widget_data?.count>1{ //循坏显示文字图片 for var i in 0..<((listModel?.widget_data?.count)!-1){ //图片 let imageData=listModel?.widget_data![i] if imageData?.type=="image"{ let imageTag=200+i/2 let imageView=contentView .viewWithTag(imageTag) if imageView?.isKindOfClass(UIImageView)==true{ let tmpImageView=imageView as! UIImageView //数据 let url=NSURL(string:(imageData?.content)!) tmpImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named:"sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } //文字 let textData=listModel?.widget_data![i+1] if textData?.type=="text" { let label=contentView.viewWithTag(300+i/2) if label?.isKindOfClass(UILabel)==true{ let tmplabel=label as! UILabel tmplabel.text=textData?.content } } i+=1 } } } @IBAction func clickBtn(sender: UIButton) { let index=sender.tag-100 if index*2<listModel?.widget_data?.count{ let data=listModel?.widget_data![index*2] if data?.link != nil && jumpClosure != nil{ jumpClosure!((data?.link)!) } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } //创建cell的方法 class func creatLikeCellFor(tableView:UITableView,atIndexPath indexPatn:NSIndexPath,listModel:IngreRecommendWidgetList?)->IngreLikeCell{ let cellId="IngreLikeCellId" var cell=tableView.dequeueReusableCellWithIdentifier(cellId)as? IngreLikeCell if nil==cell{ cell=NSBundle.mainBundle().loadNibNamed("IngreLikeCell", owner: nil, options: nil).last as?IngreLikeCell } cell?.listModel=listModel return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
9698438a11bb1e4023b37c335fbb0161
30.431818
168
0.550976
4.878307
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Networking/Backend/BackendGetIntroEligibilityTests.swift
1
6743
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // BackendGetIntroEligibilityTests.swift // // Created by Nacho Soto on 3/7/22. import Foundation import Nimble import XCTest @testable import RevenueCat class BackendGetIntroEligibilityTests: BaseBackendTests { override func createClient() -> MockHTTPClient { super.createClient(#file) } func testEmptyEligibilityCheckDoesNothing() { var error: NSError?? self.backend.offerings.getIntroEligibility(appUserID: Self.userID, receiptData: Data(), productIdentifiers: []) { error = $1 as NSError? } expect(error).toEventually(equal(.some(nil))) expect(self.httpClient.calls.count) == 0 } func testPostsProductIdentifiers() throws { self.httpClient.mock( requestPath: .getIntroEligibility(appUserID: Self.userID), response: .init(statusCode: .success, response: ["producta": true, "productb": false, "productd": NSNull()]) ) var eligibility: [String: IntroEligibility]? let products = ["producta", "productb", "productc", "productd"] self.offerings.getIntroEligibility(appUserID: Self.userID, receiptData: Data(1...3), productIdentifiers: products, completion: {(productEligibility, error) in expect(error).to(beNil()) eligibility = productEligibility }) expect(self.httpClient.calls).toEventually(haveCount(1)) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?.keys).to(contain(products)) expect(eligibility?["producta"]?.status) == .eligible expect(eligibility?["productb"]?.status) == .ineligible expect(eligibility?["productc"]?.status) == .unknown expect(eligibility?["productd"]?.status) == .unknown } func testEligibilityUnknownIfError() { self.httpClient.mock( requestPath: .getIntroEligibility(appUserID: Self.userID), response: .init(statusCode: .invalidRequest, response: Self.serverErrorResponse) ) var eligibility: [String: IntroEligibility]? let products = ["producta", "productb", "productc"] self.offerings.getIntroEligibility(appUserID: Self.userID, receiptData: Data.init(1...2), productIdentifiers: products, completion: {(productEligibility, error) in expect(error).to(beNil()) eligibility = productEligibility }) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?["producta"]?.status) == .unknown expect(eligibility?["productb"]?.status) == .unknown expect(eligibility?["productc"]?.status) == .unknown } func testEligibilityUnknownIfMissingAppUserID() { self.httpClient.mock( requestPath: .getIntroEligibility(appUserID: ""), response: .init(error: .unexpectedResponse(nil)) ) var eligibility: [String: IntroEligibility]? let products = ["producta"] var eventualError: BackendError? self.backend.offerings.getIntroEligibility(appUserID: "", receiptData: Data.init(1...2), productIdentifiers: products, completion: {(productEligibility, error) in eventualError = error eligibility = productEligibility }) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?["producta"]?.status) == IntroEligibilityStatus.unknown expect(eventualError) == .missingAppUserID() eligibility = nil eventualError = nil self.offerings.getIntroEligibility(appUserID: " ", receiptData: Data.init(1...2), productIdentifiers: products, completion: {(productEligibility, error) in eventualError = error eligibility = productEligibility }) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?["producta"]?.status) == IntroEligibilityStatus.unknown expect(eventualError) == .missingAppUserID() } func testEligibilityUnknownIfUnknownError() { let error: NetworkError = .networkError(NSError(domain: "myhouse", code: 12, userInfo: nil)) self.httpClient.mock( requestPath: .getIntroEligibility(appUserID: Self.userID), response: .init(error: error) ) var eligibility: [String: IntroEligibility]? let products = ["producta", "productb", "productc"] self.offerings.getIntroEligibility(appUserID: Self.userID, receiptData: Data.init(1...2), productIdentifiers: products, completion: {(productEligbility, error) in expect(error).to(beNil()) eligibility = productEligbility }) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?["producta"]?.status) == .unknown expect(eligibility?["productb"]?.status) == .unknown expect(eligibility?["productc"]?.status) == .unknown } func testEligibilityUnknownIfNoReceipt() { var eligibility: [String: IntroEligibility]? let products = ["producta", "productb", "productc"] self.offerings.getIntroEligibility(appUserID: Self.userID, receiptData: Data(), productIdentifiers: products, completion: {(productEligibility, error) in expect(error).to(beNil()) eligibility = productEligibility }) expect(eligibility).toEventuallyNot(beNil()) expect(eligibility?["producta"]?.status) == .unknown expect(eligibility?["productb"]?.status) == .unknown expect(eligibility?["productc"]?.status) == .unknown } }
mit
830dfafe04cb46520d351d33d2f19952
37.976879
100
0.567255
5.486574
false
true
false
false
moromi/StringValidator
Sources/LengthValidator.swift
1
985
// // LengthValidator.swift // // Created by Takahiro Ooishi // Copyright (c) 2016 moromi. All rights reserved. // Released under the MIT license. // import Foundation public struct LengthValidator: Validator { private let range: CountableClosedRange<Int> private let ignoreWhitespaces: Bool private let allowBlank: Bool private let allowNil: Bool public init(range: CountableClosedRange<Int>, ignoreWhitespaces: Bool = false, allowBlank: Bool = false, allowNil: Bool = false) { self.range = range self.ignoreWhitespaces = ignoreWhitespaces self.allowBlank = allowBlank self.allowNil = allowNil } public func validate(_ string: String?) -> Bool { if allowNil && string == nil { return true } guard var string = string else { return false } if allowBlank && string.isEmpty { return true } if ignoreWhitespaces { string = string.trimmingCharacters(in: .whitespaces) } return range.contains(string.count) } }
mit
d05796522f7ad1bc7ab90f8a5d2673e0
27.970588
132
0.704569
4.264069
false
false
false
false
gvsucis/mobile-app-dev-book
iOS/ch13/TraxyApp/TraxyApp/JournalEntryConfirmationViewController.swift
5
6489
// // JournalEntryConfirmationViewController.swift // TraxyApp // // Created by Jonathan Engelsma on 4/11/17. // Copyright © 2017 Jonathan Engelsma. All rights reserved. // import UIKit import Eureka protocol AddJournalEntryDelegate : class { func save(entry: JournalEntry) } var previewImage : UIImage? class JournalEntryConfirmationViewController: FormViewController { var imageToConfirm : UIImage? weak var delegate : AddJournalEntryDelegate? var type : EntryType? var entry : JournalEntry? var journal : Journal! override func viewDidLoad() { super.viewDidLoad() previewImage = imageToConfirm let textRowValidationUpdate : (TextRow.Cell, TextRow) -> () = { cell, row in if !row.isValid { cell.titleLabel?.textColor = .red } else { cell.titleLabel?.textColor = .black } } TextRow.defaultCellUpdate = textRowValidationUpdate TextRow.defaultOnRowValidationChanged = textRowValidationUpdate let dateRowValidationUpdate : (DateRow.Cell, DateRow) -> () = { cell, row in if !row.isValid { cell.textLabel?.textColor = .red } else { cell.textLabel?.textColor = .black } } DateRow.defaultCellUpdate = dateRowValidationUpdate DateRow.defaultOnRowValidationChanged = dateRowValidationUpdate let labelRowValidationUpdate : (LabelRow.Cell, LabelRow) -> () = { cell, row in if !row.isValid { cell.textLabel?.textColor = .red } else { cell.textLabel?.textColor = .black } } LabelRow.defaultCellUpdate = labelRowValidationUpdate LabelRow.defaultOnRowValidationChanged = labelRowValidationUpdate var textEntryLabel = "Enter caption" if self.type == .text { textEntryLabel = "Enter text entry" self.navigationItem.title = "Text Entry" } var caption : String = "" var date : Date = self.journal.startDate! if let e = self.entry { caption = e.caption! date = e.date! } else { self.entry = JournalEntry(key: nil, type: self.type, caption: caption, url: "", thumbnailUrl: "", date: date, lat: 0.0, lng: 0.0) } form = Section() { $0.tag = "FirstSection" if self.type != .text && self.type != .audio { $0.header = HeaderFooterView<MediaPreviewView>(.class) } } <<< TextAreaRow(textEntryLabel){ row in row.placeholder = textEntryLabel row.value = caption row.tag = "CaptionTag" row.add(rule: RuleRequired()) } +++ Section("Date and Location Recorded") <<< DateTimeInlineRow(){ row in row.title = "Date" row.value = date row.tag = "DateTag" row.maximumDate = self.journal.endDate row.minimumDate = self.journal.startDate row.dateFormatter?.dateStyle = .medium row.dateFormatter?.timeStyle = .short row.add(rule: RuleRequired()) } <<< LabelRow () { row in row.title = "Location" row.value = "Tap for current" row.tag = "LocTag" var rules = RuleSet<String>() rules.add(rule: RuleClosure(closure: { (loc) -> ValidationError? in if loc == "Tap to search" { return ValidationError(msg: "You must select a location") } else { return nil } })) row.add(ruleSet:rules) }.onCellSelection { cell, row in print("TODO: will finish this next chapter!") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) { _ = self.navigationController?.popViewController(animated: true) } @IBAction func saveButtonPressed(_ sender: UIBarButtonItem) { if let del = self.delegate { let (caption,date,_) = self.extractFormValues() if var e = self.entry { e.caption = caption e.date = date del.save(entry: e) } } _ = self.navigationController?.popViewController(animated: true) } func extractFormValues() -> (String, Date, String) { let captionRow: TextAreaRow! = form.rowBy(tag: "CaptionTag") //let locRow: LabelRow! = form.rowBy(tag: "LocTag") let dateRow : DateTimeInlineRow! = form.rowBy(tag: "DateTag") let locationRow : LabelRow! = form.rowBy(tag: "LocTag") let caption = captionRow.value! as String //let location = locRow.value! as String let date = dateRow.value! as Date let loc = locationRow.value! as String return (caption,date,loc) } class MediaPreviewView: UIView { override init(frame: CGRect) { super.init(frame: frame) // size image view to a third of available vertical space. let screenSize: CGRect = UIScreen.main.bounds let width = screenSize.width let height = screenSize.height / 3.0 var image : UIImage if let img = previewImage { image = img } else { image = UIImage() } let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFill imageView.frame = CGRect(x: 0, y: 0, width: width, height: height) self.frame = CGRect(x: 0, y: 0, width: width, height: height) self.clipsToBounds = true self.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
gpl-3.0
7103c8c189dccb8f19da904fff773249
33.510638
96
0.534217
5.029457
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Band Pass Filter.xcplaygroundpage/Contents.swift
1
1887
//: ## Band Pass Filter //: Band-pass filters allow audio above a specified frequency range and //: bandwidth to pass through to an output. The center frequency is the starting point //: from where the frequency limit is set. Adjusting the bandwidth sets how far out //: above and below the center frequency the frequency band should be. //: Anything above that band should pass through. import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true //: Next, we'll connect the audio sources to a band pass filter var filter = AKBandPassFilter(player) filter.centerFrequency = 5000 // Hz filter.bandwidth = 600 // Cents AudioKit.output = filter AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Band Pass Filter") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: filter)) addSubview(AKPropertySlider( property: "Center Frequency", format: "%0.1f Hz", value: filter.centerFrequency, minimum: 20, maximum: 22050, color: AKColor.greenColor() ) { sliderValue in filter.centerFrequency = sliderValue }) addSubview(AKPropertySlider( property: "Bandwidth", format: "%0.1f Hz", value: filter.bandwidth, minimum: 100, maximum: 1200, color: AKColor.redColor() ) { sliderValue in filter.bandwidth = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
7a90ee4e6ad86be75fd19be1bff10c8c
29.934426
86
0.669316
5.018617
false
false
false
false
blstream/TOZ_iOS
TOZ_iOS/TabBarViewController.swift
1
2327
// // TabBarViewController.swift // TOZ_iOS // // Copyright © 2017 intive. All rights reserved. // import UIKit final class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(switchAccountTab), name: .backendAuthStateChanged, object: nil) switchAccountTab() } @objc func switchAccountTab() { // When user signs in/out remove last viewcontroller(s) from viewControllers // so the correct one(s) can be added later if self.viewControllers?.count == 5 { self.viewControllers?.remove(at: 4) self.viewControllers?.remove(at: 3) } else if self.viewControllers?.count == 4 { self.viewControllers?.remove(at: 3) } var viewControllers: [UIViewController] = self.viewControllers! let accountStoryboard: UIStoryboard = UIStoryboard(name: "Account", bundle: nil) let accountTabBarItemIcon = UITabBarItem(title: "KONTO", image: UIImage(named: "tab-bar-user.png"), selectedImage: UIImage(named: "tab-bar-user.png")) var targetNavigationController: UIViewController let calendarStoryboard: UIStoryboard = UIStoryboard(name: "Calendar", bundle: nil) let calendarTabBarItemIcon = UITabBarItem(title: "GRAFIK", image: UIImage(named: "tab-bar-cal.png"), selectedImage: UIImage(named: "tab-bar-cal.png")) let calendarNavigationController: UIViewController if BackendAuth.shared.token != nil { targetNavigationController = accountStoryboard.instantiateViewController(withIdentifier: "ChangePasswordNavigationController") calendarNavigationController = calendarStoryboard.instantiateViewController(withIdentifier: "CalendarNavigationController") calendarNavigationController.tabBarItem = calendarTabBarItemIcon viewControllers.append(calendarNavigationController) } else { targetNavigationController = accountStoryboard.instantiateViewController(withIdentifier: "LoginNavigationController") } targetNavigationController.tabBarItem = accountTabBarItemIcon viewControllers.append(targetNavigationController) self.viewControllers = viewControllers } }
apache-2.0
4eb365f266b885b9adbfd5f33eac3d6e
44.607843
158
0.715821
5.334862
false
false
false
false
kaunteya/ProgressKit
InDeterminate/Spinner.swift
1
3192
// // Spinner.swift // ProgressKit // // Created by Kauntey Suryawanshi on 28/07/15. // Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved. // import Foundation import Cocoa @IBDesignable open class Spinner: IndeterminateAnimation { var basicShape = CAShapeLayer() var containerLayer = CAShapeLayer() var starList = [CAShapeLayer]() var animation: CAKeyframeAnimation = { var animation = CAKeyframeAnimation(keyPath: "transform.rotation") animation.repeatCount = .infinity animation.calculationMode = .discrete return animation }() @IBInspectable open var starSize:CGSize = CGSize(width: 6, height: 15) { didSet { notifyViewRedesigned() } } @IBInspectable open var roundedCorners: Bool = true { didSet { notifyViewRedesigned() } } @IBInspectable open var distance: CGFloat = CGFloat(20) { didSet { notifyViewRedesigned() } } @IBInspectable open var starCount: Int = 10 { didSet { notifyViewRedesigned() } } @IBInspectable open var duration: Double = 1 { didSet { animation.duration = duration } } @IBInspectable open var clockwise: Bool = false { didSet { notifyViewRedesigned() } } override func configureLayers() { super.configureLayers() containerLayer.frame = self.bounds containerLayer.cornerRadius = frame.width / 2 self.layer?.addSublayer(containerLayer) animation.duration = duration } override func notifyViewRedesigned() { super.notifyViewRedesigned() starList.removeAll(keepingCapacity: true) containerLayer.sublayers = nil animation.values = [Double]() var i = 0.0 while i < 360 { var iRadian = CGFloat(i * Double.pi / 180.0) if clockwise { iRadian = -iRadian } animation.values?.append(iRadian) let starShape = CAShapeLayer() starShape.cornerRadius = roundedCorners ? starSize.width / 2 : 0 let centerLocation = CGPoint(x: frame.width / 2 - starSize.width / 2, y: frame.width / 2 - starSize.height / 2) starShape.frame = CGRect(origin: centerLocation, size: starSize) starShape.backgroundColor = foreground.cgColor starShape.anchorPoint = CGPoint(x: 0.5, y: 0) var rotation: CATransform3D = CATransform3DMakeTranslation(0, 0, 0.0); rotation = CATransform3DRotate(rotation, -iRadian, 0.0, 0.0, 1.0); rotation = CATransform3DTranslate(rotation, 0, distance, 0.0); starShape.transform = rotation starShape.opacity = Float(360 - i) / 360 containerLayer.addSublayer(starShape) starList.append(starShape) i = i + Double(360 / starCount) } } override func startAnimation() { containerLayer.add(animation, forKey: "rotation") } override func stopAnimation() { containerLayer.removeAllAnimations() } }
mit
403a16b6b818d4e085365b6b0b0315a8
27
123
0.602757
4.792793
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestMarkerDA.swift
1
3003
// // QuestMarkerDA.swift // AwesomeCore // // Created by Antonio on 12/15/17. // //import Foundation // //class QuestMarkerDA { // // // MARK: - Parser // // func parseToCoreData(_ marker: QuestMarker, result: @escaping (CDMarker) -> Void) { // AwesomeCoreDataAccess.shared.backgroundContext.perform { // let cdMarker = self.parseToCoreData(marker) // result(cdMarker) // } // } // // private func parseToCoreData(_ marker: QuestMarker) -> CDMarker { // // guard let markerId = marker.id else { // fatalError("CDMarker object can't be created without id.") // } // let p = predicate(markerId, marker.assetId ?? "") // let cdMarker = CDMarker.getObjectAC(predicate: p, createIfNil: true) as! CDMarker // // cdMarker.id = marker.id // cdMarker.name = marker.name // cdMarker.status = marker.status // cdMarker.time = marker.time // return cdMarker // } // // func parseFromCoreData(_ cdMarker: CDMarker) -> QuestMarker { // return QuestMarker( // id: cdMarker.id, // name: cdMarker.name, // status: cdMarker.status, // time: cdMarker.time, // assetId: cdMarker.asset?.id // ) // } // // // MARK: - Fetch // // func loadBy(markerId: String, assetId: String, result: @escaping (CDMarker?) -> Void) { // func perform() { // let p = predicate(markerId, assetId) // guard let cdMarker = CDMarker.listAC(predicate: p).first as? CDMarker else { // result(nil) // return // } // result(cdMarker) // } // AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in // perform() // }) // } // // // MARK: - Helpers // // /// Extract the given QuestMarker array as a NSSet (CoreData) objects. // /// - Important: _This method must be called from within a BackgroundContext._ // /// // /// - Parameter questMarkers: Array of QuestMarkers // /// - Returns: a NSSet of CoreData CDMarkers or an empty NSSet. // func extractCDMarkers(_ questMarkers: [QuestMarker]?) -> NSSet { // var markers = NSSet() // guard let questMarkers = questMarkers else { return markers } // for qm in questMarkers { // markers = markers.adding(parseToCoreData(qm)) as NSSet // } // return markers // } // // func extractQuestMarkers(_ questMarkers: NSSet?) -> [QuestMarker]? { // guard let questMarkers = questMarkers else { return nil } // var markers = [QuestMarker]() // for qm in questMarkers { // markers.append(parseFromCoreData(qm as! CDMarker)) // } // return markers // } // // private func predicate(_ markerId: String, _ assetId: String) -> NSPredicate { // return NSPredicate(format: "id == %@ AND asset.id == %@", markerId, assetId) // } // //}
mit
800bd6551320769c8509ac442c187e95
32
93
0.57043
3.716584
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/ViewModel/Home/HomeViewModel.swift
1
1517
// // HotViewModel.swift // MyApp // // Created by asiantech on 8/9/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import MVVM import RealmSwift import RealmS final class HomeViewModel: MVVM.ViewModel { // MARK: - Properties enum GetItemResult { case success case failure(Error) } typealias GetItemCompletion = (GetItemResult) -> Void var index = 0 var menus: Results<Menu>? // MARK: - Public func numberOfSections() -> Int { return 1 } func numberOfItems(inSection section: Int) -> Int { guard let menus = menus else { return 0 } return menus[index].menuItems.count } func viewModelForItem(at indexPath: IndexPath) -> HomeCellViewModel { guard let menus = menus else { fatalError("Please call `fetch()` first.") } if indexPath.row <= menus[index].menuItems.count { return HomeCellViewModel(item: menus[index].menuItems[indexPath.row]) } return HomeCellViewModel(item: nil) } func fetch(id: Int) { self.index = id menus = RealmS().objects(Menu.self) } func getItem(completion: @escaping GetItemCompletion) { Api.Item.itemQuery { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(_): completion(.success) } } } }
mit
67912b90c09478b6f517ee154e9f8e6d
22.6875
81
0.583113
4.432749
false
false
false
false
networkextension/SFSocket
SFSocket/HTTPProxyServer/GCDProxyServer.swift
1
3071
import Foundation import CocoaAsyncSocket /// Proxy server which listens on some port by GCDAsyncSocket. /// /// This shoule be the base class for any concrete implemention of proxy server (e.g., HTTP or SOCKS5) which needs to listen on some port. open class GCDProxyServer: ProxyServer, GCDAsyncSocketDelegate { fileprivate let listenQueue: DispatchQueue = DispatchQueue(label: "NEKit.GCDProxyServer.listenQueue", attributes: []) fileprivate var listenSocket: GCDAsyncSocket! fileprivate var pendingSocket: [GCDTCPSocket] = [] fileprivate var canHandleNewSocket: Bool { return Opt.ProxyActiveSocketLimit <= 0 || tunnels.value.count < Opt.ProxyActiveSocketLimit } /** Start the proxy server which creates a GCDAsyncSocket listening on specific port. - throws: The error occured when starting the proxy server. */ override open func start() throws { listenSocket = GCDAsyncSocket(delegate: self, delegateQueue: listenQueue) try listenSocket.accept(onInterface: address?.presentation, port: port.value) try super.start() } /** Stop the proxy server. */ override open func stop() { listenQueue.sync { for socket in self.pendingSocket { socket.disconnect() } } pendingSocket.removeAll() listenSocket?.setDelegate(nil, delegateQueue: nil) listenSocket?.disconnect() listenSocket = nil super.stop() } /** Delegate method to handle the newly accepted GCDTCPSocket. Only this method should be overrided in any concrete implemention of proxy server which listens on some port with GCDAsyncSocket. - parameter socket: The accepted socket. */ func handleNewGCDSocket(_ socket: GCDTCPSocket) { } /** GCDAsyncSocket delegate callback. - parameter sock: The listening GCDAsyncSocket. - parameter newSocket: The accepted new GCDAsyncSocket. - warning: Do not call this method. This should be marked private but have to be marked public since the `GCDAsyncSocketDelegate` is public. */ open func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) { let gcdTCPSocket = GCDTCPSocket(socket: newSocket) if canHandleNewSocket { handleNewGCDSocket(gcdTCPSocket) } else { pendingSocket.append(gcdTCPSocket) NSLog("Current Pending socket \(pendingSocket.count)") } } override func tunnelDidClose(_ tunnel: Tunnel) { super.tunnelDidClose(tunnel) processPendingSocket() } func processPendingSocket() { listenQueue.async { while self.pendingSocket.count > 0 && self.canHandleNewSocket { let socket = self.pendingSocket.removeFirst() if socket.isConnected { self.handleNewGCDSocket(socket) } NSLog("Current Pending socket \(self.pendingSocket.count)") } } } }
bsd-3-clause
a5f3f8e97e2cd6dc85a8c534a95e868e
32.747253
145
0.660046
4.94525
false
false
false
false
ludoded/ReceiptBot
ReceiptBot/Scene/DetailInvoice/DetailInvoicePresenter.swift
1
4270
// // DetailInvoicePresenter.swift // ReceiptBot // // Created by Haik Ampardjian on 4/13/17. // Copyright (c) 2017 receiptbot. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit import Kingfisher protocol DetailInvoicePresenterOutput: class, Errorable, Spinnable { func displayInitial(viewModel: DetailInvoice.Setup.ViewModel) func goBack() } class DetailInvoicePresenter { weak var output: DetailInvoicePresenterOutput! // MARK: - Presentation logic func presentInitialSetup(response: DetailInvoice.Setup.Response) { switch response.invoice { case .none(let message): output.show(type: .error(message: message)) case .value(let invoice): passInitialSetup(from: invoice) } } func passInitialSetup(from invoice: SyncConvertedInvoiceResponse) { let invoiceDate = invoice.invoiceDateMobile != nil ? DateFormatters.mdySpaceFormatter.string(from: invoice.invoiceDateMobile!) : "" let dueDate = invoice.dueDate != nil ? DateFormatters.mdySpaceFormatter.string(from: invoice.dueDate!) : "" let supplierName = AppSettings.shared.config.supplierName(for: invoice.supplierId) let categoryName = AppSettings.shared.config.categoryName(for: invoice.categoryId) let paymentMethod = AppSettings.shared.config.paymentName(for: invoice.paymentMethodId) let taxPercentage = AppSettings.shared.config.taxName(for: invoice.taxPercentage) guard let imageURL = invoice.fullMediaUrl else { output.show(type: .error(message: "Can't load the image")); return } let type: DetailInvoice.Setup.InvoiceType /// If pdf if invoice.isPdf { type = .pdf(URLRequest(url: imageURL)) } else { /// If image: png, jpeg, jpg etc type = .image(ImageResource(downloadURL: imageURL)) } /// If editable let invType = RebotInvoiceStatusMapper.toFrontEnd(from: invoice.type).lowercased() let validation: DetailInvoice.Setup.Validation if invType == "processing" { validation = DetailInvoice.Setup.Validation(isEditable: false, error: nil) } else if invType == "rejected" { validation = DetailInvoice.Setup.Validation(isEditable: false, error: "This document is rejected due to: \"\(invoice.invoiceComment)\"") } else { validation = DetailInvoice.Setup.Validation(isEditable: true, error: nil) } let viewModel = DetailInvoice.Setup.ViewModel(type: type, supplierName: supplierName, invoiceDate: invoiceDate, invoiceNumber: invoice.invoiceNumber, paymentMethod: paymentMethod, category: categoryName, taxRate: taxPercentage, taxAmount: invoice.taxAmount, grossAmount: invoice.grossAmount, netAmount: invoice.netAmount, dueDate: dueDate, dueDateMin: invoice.invoiceDateMobile ?? Date(), validation: validation) output.displayInitial(viewModel: viewModel) } func presentSave(response: DetailInvoice.Save.Response) { output.stopSpinning() switch response.data { case .none(let message): output.show(type: .error(message: message)) case .value: output.goBack() } } func presentReject(response: DetailInvoice.Reject.Response) { output.stopSpinning() switch response.data { case .none(let message): output.show(type: .error(message: message)) case .value: output.goBack() } } }
lgpl-3.0
f07be32979a6ebca5b109e180cf67072
45.413043
178
0.585012
5.182039
false
false
false
false
juliensagot/JSNavigationController
JSNavigationController/Sources/JSNavigationBarController.swift
1
5120
// // JSNavigationBarController.swift // JSNavigationController // // Created by Julien Sagot on 14/05/16. // Copyright © 2016 Julien Sagot. All rights reserved. // import AppKit open class JSNavigationBarController: JSViewControllersStackManager { open var viewControllers: [NSViewController] = [] open weak var contentView: NSView? // MARK: - Initializers public init(view: NSView) { contentView = view } // MARK: - Default animations open func defaultPushAnimation() -> AnimationBlock { return { [weak self] (_, _) in let containerViewBounds = self?.contentView?.bounds ?? .zero let slideToLeftTransform = CATransform3DMakeTranslation(-containerViewBounds.width / 2, 0, 0) let slideToLeftAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToLeftAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToLeftAnimation.toValue = NSValue(caTransform3D: slideToLeftTransform) slideToLeftAnimation.duration = 0.25 slideToLeftAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToLeftAnimation.fillMode = CAMediaTimingFillMode.forwards slideToLeftAnimation.isRemovedOnCompletion = false let slideFromRightTransform = CATransform3DMakeTranslation(containerViewBounds.width / 2, 0, 0) let slideFromRightAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideFromRightAnimation.fromValue = NSValue(caTransform3D: slideFromRightTransform) slideFromRightAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideFromRightAnimation.duration = 0.25 slideFromRightAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideFromRightAnimation.fillMode = CAMediaTimingFillMode.forwards slideFromRightAnimation.isRemovedOnCompletion = false let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeInAnimation.fromValue = 0.0 fadeInAnimation.toValue = 1.0 fadeInAnimation.duration = 0.25 fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards fadeInAnimation.isRemovedOnCompletion = false let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeOutAnimation.fromValue = 1.0 fadeOutAnimation.toValue = 0.0 fadeOutAnimation.duration = 0.25 fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards fadeOutAnimation.isRemovedOnCompletion = false return ([slideToLeftAnimation, fadeOutAnimation], [slideFromRightAnimation, fadeInAnimation]) } } open func defaultPopAnimation() -> AnimationBlock { return { [weak self] (_, _) in let containerViewBounds = self?.contentView?.bounds ?? .zero let slideToRightTransform = CATransform3DMakeTranslation(-containerViewBounds.width / 2, 0, 0) let slideToRightAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToRightAnimation.fromValue = NSValue(caTransform3D: slideToRightTransform) slideToRightAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideToRightAnimation.duration = 0.25 slideToRightAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToRightAnimation.fillMode = CAMediaTimingFillMode.forwards slideToRightAnimation.isRemovedOnCompletion = false let slideToRightFromCenterTransform = CATransform3DMakeTranslation(containerViewBounds.width / 2, 0, 0) let slideToRightFromCenterAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToRightFromCenterAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToRightFromCenterAnimation.toValue = NSValue(caTransform3D: slideToRightFromCenterTransform) slideToRightFromCenterAnimation.duration = 0.35 slideToRightFromCenterAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToRightFromCenterAnimation.fillMode = CAMediaTimingFillMode.forwards slideToRightFromCenterAnimation.isRemovedOnCompletion = false let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeInAnimation.fromValue = 0.0 fadeInAnimation.toValue = 1.0 fadeInAnimation.duration = 0.25 fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards fadeInAnimation.isRemovedOnCompletion = false let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeOutAnimation.fromValue = 1.0 fadeOutAnimation.toValue = 0.0 fadeOutAnimation.duration = 0.25 fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards fadeOutAnimation.isRemovedOnCompletion = false return ([slideToRightFromCenterAnimation, fadeOutAnimation], [slideToRightAnimation, fadeInAnimation]) } } }
mit
c86e1628709193498b24387eb2069825
48.221154
114
0.813635
4.936355
false
false
false
false
vapor/vapor
Sources/Vapor/Utilities/DotEnv.swift
1
12728
#if os(Linux) import Glibc #else import Darwin #endif /// Reads dotenv (`.env`) files and loads them into the current process. /// /// let fileio: NonBlockingFileIO /// let elg: EventLoopGroup /// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait() /// for line in file.lines { /// print("\(line.key)=\(line.value)") /// } /// file.load(overwrite: true) // loads all lines into the process /// /// Dotenv files are formatted using `KEY=VALUE` syntax. They support comments using the `#` symbol. /// They also support strings, both single and double-quoted. /// /// FOO=BAR /// STRING='Single Quote String' /// # Comment /// STRING2="Double Quoted\nString" /// /// Single-quoted strings are parsed literally. Double-quoted strings may contain escaped newlines /// that will be converted to actual newlines. public struct DotEnvFile { /// Reads the dotenv files relevant to the environment and loads them into the process. /// /// let environment: Environment /// let elgp: EventLoopGroupProvider /// let fileio: NonBlockingFileIO /// let logger: Logger /// try DotEnvFile.load(for: .development, on: elgp, fileio: fileio, logger: logger) /// print(Environment.process.FOO) // BAR /// /// - parameters: /// - environment: current environment, selects which .env file to use. /// - eventLoopGroupProvider: Either provides an EventLoopGroup or tells the function to create a new one. /// - fileio: NonBlockingFileIO that is used to read the .env file(s). /// - logger: Optionally provide an existing logger. public static func load( for environment: Environment = .development, on eventLoopGroupProvider: Application.EventLoopGroupProvider = .createNew, fileio: NonBlockingFileIO, logger: Logger = Logger(label: "dot-env-loggger") ) { let eventLoopGroup: EventLoopGroup switch eventLoopGroupProvider { case .shared(let group): eventLoopGroup = group case .createNew: eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) } defer { switch eventLoopGroupProvider { case .shared: logger.trace("Running on shared EventLoopGroup. Not shutting down EventLoopGroup.") case .createNew: logger.trace("Shutting down EventLoopGroup") do { try eventLoopGroup.syncShutdownGracefully() } catch { logger.warning("Shutting down EventLoopGroup failed: \(error)") } } } // Load specific .env first since values are not overridden. DotEnvFile.load(path: ".env.\(environment.name)", on: .shared(eventLoopGroup), fileio: fileio, logger: logger) DotEnvFile.load(path: ".env", on: .shared(eventLoopGroup), fileio: fileio, logger: logger) } /// Reads the dotenv files relevant to the environment and loads them into the process. /// /// let path: String /// let elgp: EventLoopGroupProvider /// let fileio: NonBlockingFileIO /// let logger: Logger /// try DotEnvFile.load(path: path, on: elgp, fileio: filio, logger: logger) /// print(Environment.process.FOO) // BAR /// /// - parameters: /// - path: Absolute or relative path of the dotenv file. /// - eventLoopGroupProvider: Either provides an EventLoopGroup or tells the function to create a new one. /// - fileio: NonBlockingFileIO that is used to read the .env file(s). /// - logger: Optionally provide an existing logger. public static func load( path: String, on eventLoopGroupProvider: Application.EventLoopGroupProvider = .createNew, fileio: NonBlockingFileIO, logger: Logger = Logger(label: "dot-env-loggger") ) { let eventLoopGroup: EventLoopGroup switch eventLoopGroupProvider { case .shared(let group): eventLoopGroup = group case .createNew: eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) } defer { switch eventLoopGroupProvider { case .shared: logger.trace("Running on shared EventLoopGroup. Not shutting down EventLoopGroup.") case .createNew: logger.trace("Shutting down EventLoopGroup") do { try eventLoopGroup.syncShutdownGracefully() } catch { logger.warning("Shutting down EventLoopGroup failed: \(error)") } } } do { try load(path: path, fileio: fileio, on: eventLoopGroup.next()).wait() } catch { logger.debug("Could not load \(path) file: \(error)") } } /// Reads a dotenv file from the supplied path and loads it into the process. /// /// let fileio: NonBlockingFileIO /// let elg: EventLoopGroup /// try DotEnvFile.load(path: ".env", fileio: fileio, on: elg.next()).wait() /// print(Environment.process.FOO) // BAR /// /// Use `DotEnvFile.read` to read the file without loading it. /// /// - parameters: /// - path: Absolute or relative path of the dotenv file. /// - fileio: File loader. /// - eventLoop: Eventloop to perform async work on. /// - overwrite: If `true`, values already existing in the process' env /// will be overwritten. Defaults to `false`. public static func load( path: String, fileio: NonBlockingFileIO, on eventLoop: EventLoop, overwrite: Bool = false ) -> EventLoopFuture<Void> { return self.read(path: path, fileio: fileio, on: eventLoop) .map { $0.load(overwrite: overwrite) } } /// Reads a dotenv file from the supplied path. /// /// let fileio: NonBlockingFileIO /// let elg: EventLoopGroup /// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait() /// for line in file.lines { /// print("\(line.key)=\(line.value)") /// } /// file.load(overwrite: true) // loads all lines into the process /// print(Environment.process.FOO) // BAR /// /// Use `DotEnvFile.load` to read and load with one method. /// /// - parameters: /// - path: Absolute or relative path of the dotenv file. /// - fileio: File loader. /// - eventLoop: Eventloop to perform async work on. public static func read( path: String, fileio: NonBlockingFileIO, on eventLoop: EventLoop ) -> EventLoopFuture<DotEnvFile> { return fileio.openFile(path: path, eventLoop: eventLoop).flatMap { arg -> EventLoopFuture<ByteBuffer> in return fileio.read(fileRegion: arg.1, allocator: .init(), eventLoop: eventLoop) .flatMapThrowing { buffer in try arg.0.close() return buffer } }.map { buffer in var parser = Parser(source: buffer) return .init(lines: parser.parse()) } } /// Represents a `KEY=VALUE` pair in a dotenv file. public struct Line: CustomStringConvertible, Equatable { /// The key. public let key: String /// The value. public let value: String /// `CustomStringConvertible` conformance. public var description: String { return "\(self.key)=\(self.value)" } } /// All `KEY=VALUE` pairs found in the file. public let lines: [Line] /// Creates a new DotEnvFile init(lines: [Line]) { self.lines = lines } /// Loads this file's `KEY=VALUE` pairs into the current process. /// /// let file: DotEnvFile /// file.load(overwrite: true) // loads all lines into the process /// /// - parameters: /// - overwrite: If `true`, values already existing in the process' env /// will be overwritten. Defaults to `false`. public func load(overwrite: Bool = false) { for line in self.lines { setenv(line.key, line.value, overwrite ? 1 : 0) } } } // MARK: Parser extension DotEnvFile { struct Parser { var source: ByteBuffer init(source: ByteBuffer) { self.source = source } mutating func parse() -> [Line] { var lines: [Line] = [] while let next = self.parseNext() { lines.append(next) } return lines } private mutating func parseNext() -> Line? { self.skipSpaces() guard let peek = self.peek() else { return nil } switch peek { case .octothorpe: // comment following, skip it self.skipComment() // then parse next return self.parseNext() case .newLine: // empty line, skip self.pop() // \n // then parse next return self.parseNext() default: // this is a valid line, parse it return self.parseLine() } } private mutating func skipComment() { let commentLength: Int if let toNewLine = self.countDistance(to: .newLine) { commentLength = toNewLine + 1 // include newline } else { commentLength = self.source.readableBytes } self.source.moveReaderIndex(forwardBy: commentLength) } private mutating func parseLine() -> Line? { guard let keyLength = self.countDistance(to: .equal) else { return nil } guard let key = self.source.readString(length: keyLength) else { return nil } self.pop() // = guard let value = self.parseLineValue() else { return nil } return Line(key: key, value: value) } private mutating func parseLineValue() -> String? { let valueLength: Int if let toNewLine = self.countDistance(to: .newLine) { valueLength = toNewLine } else { valueLength = self.source.readableBytes } guard let value = self.source.readString(length: valueLength) else { return nil } guard let first = value.first, let last = value.last else { return value } // check for quoted strings switch (first, last) { case ("\"", "\""): // double quoted strings support escaped \n return value.dropFirst().dropLast() .replacingOccurrences(of: "\\n", with: "\n") case ("'", "'"): // single quoted strings just need quotes removed return value.dropFirst().dropLast() + "" default: return value } } private mutating func skipSpaces() { scan: while let next = self.peek() { switch next { case .space: self.pop() default: break scan } } } private func peek() -> UInt8? { return self.source.getInteger(at: self.source.readerIndex) } private mutating func pop() { self.source.moveReaderIndex(forwardBy: 1) } private func countDistance(to byte: UInt8) -> Int? { var copy = self.source var found = false scan: while let next = copy.readInteger(as: UInt8.self) { if next == byte { found = true break scan } } guard found else { return nil } let distance = copy.readerIndex - source.readerIndex guard distance != 0 else { return nil } return distance - 1 } } } private extension UInt8 { static var newLine: UInt8 { return 0xA } static var space: UInt8 { return 0x20 } static var octothorpe: UInt8 { return 0x23 } static var equal: UInt8 { return 0x3D } }
mit
ddb0c9f04bd962937f22c034824a0a8c
33.967033
118
0.55099
4.662271
false
false
false
false
BitBaum/Swift-Big-Integer
Tools/MG SuperSwift.swift
1
4848
/* * ———————————————————————————————————————————————————————————————————————————— * SuperSwift.swift * ———————————————————————————————————————————————————————————————————————————— * SuperSwift is a file that aims to improve the swift programming language. It * adds missing functionality and convenient syntax to make the language more * versatile. * ———————————————————————————————————————————————————————————————————————————— * Created by Marcel Kröker on 18.02.2017. * Copyright © 2017 Marcel Kröker. All rights reserved. */ import Foundation // //// ////// //MARK: - Snippets ////// //// // /* Some snippets are essential to use SuperSwift. It defines some operators that are not typeable (or too hard to find) on a normal keyboard, thus it is recommended to use snippets in your IDE or xcode to have easy access to those operators. */ // The cartesian product // Shortcut: $cp // Operator: × // The dot product, or scalar product // Shortcut: $dot // Operator: • // The element operator (same functionality as X.contains(y)) // Shortcut: $in // Operator: ∈ // The not element operator (same functionality as !X.contains(y)) // Shortcut: $notin // Operator: ∉ // //// ////// //MARK: - Overview ////// //// // /* This is an overview of all functionality of SuperSwift. */ // //// ////// //MARK: - Extensions ////// //// // public extension String { /// Returns character at index i as String. subscript(i: Int) -> String { return String(self[index(startIndex, offsetBy: i)]) } /// Returns characters in range as string. subscript(r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(start, offsetBy: r.upperBound - r.lowerBound) return String(self[start..<end]) } /// If possible, returns index of first ocurrence of char. subscript(char: Character) -> Int? { return self.index(of: char)?.encodedOffset } // Make this function work with normal ranges. mutating func removeSubrange(_ bounds: CountableClosedRange<Int>) { let start = self.index(self.startIndex, offsetBy: bounds.lowerBound) let end = self.index(self.startIndex, offsetBy: bounds.upperBound) self.removeSubrange(start...end) } // Make this function work with normal ranges. mutating func removeSubrange(_ bounds: CountableRange<Int>) { let start = self.index(self.startIndex, offsetBy: bounds.lowerBound) let end = self.index(self.startIndex, offsetBy: bounds.upperBound) self.removeSubrange(start..<end) } } // //// ////// //MARK: - Operators ////// //// // precedencegroup CartesianProductPrecedence { associativity: left lowerThan: RangeFormationPrecedence } infix operator × : CartesianProductPrecedence /** Calculate the cartesian product of two sequences. With a left precedence you can iterate over the product: // Will print all numbers from 0000 to 9999 for (((i, j), k), l) in 0...9 × 0...9 × 0...9 × 0...9 { print("\(i)\(j)\(k)\(l)") } - Parameter lhs: An array. - Parameter rhs: An array. - returns: [(l, r)] where l ∈ lhs and r ∈ rhs. */ func ×<T1: Any, T2: Any>(lhs: [T1], rhs: [T2]) -> [(T1, T2)] { var res = [(T1, T2)]() for l in lhs { for r in rhs { res.append((l, r)) } } return res } func ×(lhs: CountableRange<Int>, rhs: CountableRange<Int>) -> [(Int, Int)] { return lhs.map{$0} × rhs.map{$0} } func ×(lhs: CountableRange<Int>, rhs: CountableClosedRange<Int>) -> [(Int, Int)] { return lhs.map{$0} × rhs.map{$0} } func ×(lhs: CountableClosedRange<Int>, rhs: CountableRange<Int>) -> [(Int, Int)] { return lhs.map{$0} × rhs.map{$0} } func ×(lhs: CountableClosedRange<Int>, rhs: CountableClosedRange<Int>) -> [(Int, Int)] { return lhs.map{$0} × rhs.map{$0} } func ×<T: Any>(lhs: [T], rhs: CountableRange<Int>) -> [(T, Int)] { return lhs × rhs.map{$0} } func ×<T: Any>(lhs: [T], rhs: CountableClosedRange<Int>) -> [(T, Int)] { return lhs × rhs.map{$0} } // Better syntax for contains. Works for sets and arrays infix operator ∈ func ∈<T: Any>(lhs: T, rhs: Set<T>) -> Bool { return rhs.contains(lhs) } func ∈<T: Any & Equatable>(lhs: T, rhs: Array<T>) -> Bool { return rhs.contains(lhs) } infix operator ∉ func ∉<T: Any & Equatable>(lhs: T, rhs: Array<T>) -> Bool { return !rhs.contains(lhs) } func ∉<T: Any>(lhs: T, rhs: Set<T>) -> Bool { return !rhs.contains(lhs) }
mit
836b5a0947a9677022e3b5e63397803b
19.808612
93
0.613704
3.235863
false
false
false
false
skofgar/KGFloatingDrawer
Example/KGFloatingDrawer-Example/AppDelegate.swift
1
6472
// // AppDelegate.swift // KGDrawerViewController // // Created by Kyle Goddard on 2015-02-10. // Copyright (c) 2015 Kyle Goddard. All rights reserved. // import UIKit import KGFloatingDrawer @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let kKGDrawersStoryboardName = "Drawers" let kKGDrawerSettingsViewControllerStoryboardId = "KGDrawerSettingsViewControllerStoryboardId" let kKGDrawerWebViewViewControllerStoryboardId = "KGDrawerWebViewControllerStoryboardId" let kKGLeftDrawerStoryboardId = "KGLeftDrawerViewControllerStoryboardId" let kKGRightDrawerStoryboardId = "KGRightDrawerViewControllerStoryboardId" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = drawerViewController window?.makeKeyAndVisible() 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:. } fileprivate var _drawerViewController: KGDrawerViewController? var drawerViewController: KGDrawerViewController { get { if let viewController = _drawerViewController { return viewController } return prepareDrawerViewController() } } func prepareDrawerViewController() -> KGDrawerViewController { let drawerViewController = KGDrawerViewController() drawerViewController.centerViewController = drawerSettingsViewController() drawerViewController.leftViewController = leftViewController() drawerViewController.rightViewController = rightViewController() drawerViewController.backgroundImage = UIImage(named: "sky3") _drawerViewController = drawerViewController return drawerViewController } fileprivate func drawerStoryboard() -> UIStoryboard { let storyboard = UIStoryboard(name: kKGDrawersStoryboardName, bundle: nil) return storyboard } fileprivate func viewControllerForStoryboardId(_ storyboardId: String) -> UIViewController { let viewController: UIViewController = drawerStoryboard().instantiateViewController(withIdentifier: storyboardId) return viewController } func drawerSettingsViewController() -> UIViewController { let viewController = viewControllerForStoryboardId(kKGDrawerSettingsViewControllerStoryboardId) setStatusBarBackgroundColor(for: viewController) return viewController } func sourcePageViewController() -> UIViewController { let viewController = viewControllerForStoryboardId(kKGDrawerWebViewViewControllerStoryboardId) return viewController } fileprivate func leftViewController() -> UIViewController { let viewController = viewControllerForStoryboardId(kKGLeftDrawerStoryboardId) return viewController } fileprivate func rightViewController() -> UIViewController { let viewController = viewControllerForStoryboardId(kKGRightDrawerStoryboardId) return viewController } func toggleLeftDrawer(_ sender:AnyObject, animated:Bool) { _drawerViewController?.toggleDrawer(side: .left, animated: true, complete: { (finished) -> Void in // do nothing }) } func toggleRightDrawer(_ sender:AnyObject, animated:Bool) { _drawerViewController?.toggleDrawer(side: .right, animated: true, complete: { (finished) -> Void in // do nothing }) } func setStatusBarBackgroundColor(for viewController: UIViewController) { if let navigation = viewController as? UINavigationController { navigation.view.backgroundColor = navigation.navigationBar.barTintColor // navController.navigationBar.backgroundColor ?? } } fileprivate var _centerViewController: UIViewController? var centerViewController: UIViewController { get { if let viewController = _centerViewController { return viewController } return drawerSettingsViewController() } set { if let drawerViewController = _drawerViewController { drawerViewController.closeDrawer(side: drawerViewController.currentlyOpenedSide, animated: true) { finished in } if drawerViewController.centerViewController != newValue { drawerViewController.centerViewController = newValue } } setStatusBarBackgroundColor(for: newValue) _centerViewController = newValue } } }
mit
277fb1eadd81f132bab9568439f13f2b
42.146667
285
0.713226
6.307992
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Browser/TabToolbar.swift
1
14646
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger protocol TabToolbarProtocol: class { weak var tabToolbarDelegate: TabToolbarDelegate? { get set } var shareButton: UIButton { get } var bookmarkButton: UIButton { get } var menuButton: UIButton { get } var forwardButton: UIButton { get } var backButton: UIButton { get } var stopReloadButton: UIButton { get } var homePageButton: UIButton { get } var actionButtons: [UIButton] { get } func updateBackStatus(_ canGoBack: Bool) func updateForwardStatus(_ canGoForward: Bool) func updateBookmarkStatus(_ isBookmarked: Bool) func updateReloadStatus(_ isLoading: Bool) func updatePageStatus(_ isWebPage: Bool) } protocol TabToolbarDelegate: class { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressShare(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressHomePage(_ tabToolbar: TabToolbarProtocol, button: UIButton) } @objc open class TabToolbarHelper: NSObject { let toolbar: TabToolbarProtocol let ImageReload = UIImage.templateImageNamed("bottomNav-refresh") let ImageReloadPressed = UIImage.templateImageNamed("bottomNav-refresh") let ImageStop = UIImage.templateImageNamed("stop") let ImageStopPressed = UIImage.templateImageNamed("stopPressed") var buttonTintColor = UIColor.darkGray { didSet { setTintColor(buttonTintColor, forButtons: toolbar.actionButtons) } } var loading: Bool = false { didSet { if loading { toolbar.stopReloadButton.setImage(ImageStop, for: .normal) toolbar.stopReloadButton.setImage(ImageStopPressed, for: .highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the tab toolbar Stop button") } else { toolbar.stopReloadButton.setImage(ImageReload, for: .normal) toolbar.stopReloadButton.setImage(ImageReloadPressed, for: .highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") } } } fileprivate func setTintColor(_ color: UIColor, forButtons buttons: [UIButton]) { buttons.forEach { $0.tintColor = color } } init(toolbar: TabToolbarProtocol) { self.toolbar = toolbar super.init() toolbar.backButton.setImage(UIImage.templateImageNamed("bottomNav-back"), for: .normal) toolbar.backButton.setImage(UIImage(named: "bottomNav-backEngaged"), for: .highlighted) toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility label for the Back button in the tab toolbar.") //toolbar.backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "Accessibility hint, associated to the Back button in the tab toolbar, used by assistive technology to describe the result of a double tap.") let longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressBack(_:))) toolbar.backButton.addGestureRecognizer(longPressGestureBackButton) toolbar.backButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickBack), for: UIControlEvents.touchUpInside) toolbar.forwardButton.setImage(UIImage.templateImageNamed("bottomNav-forward"), for: .normal) toolbar.forwardButton.setImage(UIImage(named: "bottomNav-forwardEngaged"), for: .highlighted) toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the tab toolbar Forward button") //toolbar.forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "Accessibility hint, associated to the Back button in the tab toolbar, used by assistive technology to describe the result of a double tap.") let longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressForward(_:))) toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton) toolbar.forwardButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickForward), for: UIControlEvents.touchUpInside) toolbar.stopReloadButton.setImage(UIImage.templateImageNamed("bottomNav-refresh"), for: .normal) toolbar.stopReloadButton.setImage(UIImage(named: "bottomNav-refreshEngaged"), for: .highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") let longPressGestureStopReloadButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressStopReload(_:))) toolbar.stopReloadButton.addGestureRecognizer(longPressGestureStopReloadButton) toolbar.stopReloadButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickStopReload), for: UIControlEvents.touchUpInside) toolbar.shareButton.setImage(UIImage.templateImageNamed("bottomNav-send"), for: .normal) toolbar.shareButton.setImage(UIImage(named: "bottomNav-sendEngaged"), for: .highlighted) toolbar.shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Accessibility Label for the tab toolbar Share button") toolbar.shareButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickShare), for: UIControlEvents.touchUpInside) toolbar.homePageButton.setImage(UIImage.templateImageNamed("menu-Home"), for: .normal) toolbar.homePageButton.setImage(UIImage(named: "menu-Home-Engaged"), for: .highlighted) toolbar.homePageButton.accessibilityLabel = NSLocalizedString("Toolbar.OpenHomePage.AccessibilityLabel", value: "Homepage", comment: "Accessibility Label for the tab toolbar Homepage button") toolbar.homePageButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickHomePage), for: UIControlEvents.touchUpInside) toolbar.menuButton.contentMode = UIViewContentMode.center toolbar.menuButton.setImage(UIImage.templateImageNamed("bottomNav-menu"), for: .normal) toolbar.menuButton.accessibilityLabel = AppMenuConfiguration.MenuButtonAccessibilityLabel toolbar.menuButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickMenu), for: UIControlEvents.touchUpInside) toolbar.menuButton.accessibilityIdentifier = "TabToolbar.menuButton" setTintColor(buttonTintColor, forButtons: toolbar.actionButtons) } func SELdidClickBack() { toolbar.tabToolbarDelegate?.tabToolbarDidPressBack(toolbar, button: toolbar.backButton) } func SELdidLongPressBack(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBack(toolbar, button: toolbar.backButton) } } func SELdidClickShare() { toolbar.tabToolbarDelegate?.tabToolbarDidPressShare(toolbar, button: toolbar.shareButton) } func SELdidClickForward() { toolbar.tabToolbarDelegate?.tabToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func SELdidLongPressForward(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton) } } func SELdidClickBookmark() { toolbar.tabToolbarDelegate?.tabToolbarDidPressBookmark(toolbar, button: toolbar.bookmarkButton) } func SELdidLongPressBookmark(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBookmark(toolbar, button: toolbar.bookmarkButton) } } func SELdidClickMenu() { toolbar.tabToolbarDelegate?.tabToolbarDidPressMenu(toolbar, button: toolbar.menuButton) } func SELdidClickStopReload() { if loading { toolbar.tabToolbarDelegate?.tabToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton) } else { toolbar.tabToolbarDelegate?.tabToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton) } } func SELdidLongPressStopReload(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began && !loading { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressReload(toolbar, button: toolbar.stopReloadButton) } } func SELdidClickHomePage() { toolbar.tabToolbarDelegate?.tabToolbarDidPressHomePage(toolbar, button: toolbar.homePageButton) } func updateReloadStatus(_ isLoading: Bool) { loading = isLoading } } class TabToolbar: Toolbar, TabToolbarProtocol { weak var tabToolbarDelegate: TabToolbarDelegate? let shareButton: UIButton let bookmarkButton: UIButton let menuButton: UIButton let forwardButton: UIButton let backButton: UIButton let stopReloadButton: UIButton let homePageButton: UIButton let actionButtons: [UIButton] var helper: TabToolbarHelper? static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor themes[Theme.PrivateMode] = theme theme = Theme() theme.buttonTintColor = UIColor.darkGray themes[Theme.NormalMode] = theme return themes }() // This has to be here since init() calls it fileprivate override init(frame: CGRect) { // And these have to be initialized in here or the compiler will get angry backButton = UIButton() backButton.accessibilityIdentifier = "TabToolbar.backButton" forwardButton = UIButton() forwardButton.accessibilityIdentifier = "TabToolbar.forwardButton" stopReloadButton = UIButton() stopReloadButton.accessibilityIdentifier = "TabToolbar.stopReloadButton" shareButton = UIButton() shareButton.accessibilityIdentifier = "TabToolbar.shareButton" bookmarkButton = UIButton() bookmarkButton.accessibilityIdentifier = "TabToolbar.bookmarkButton" menuButton = UIButton() menuButton.accessibilityIdentifier = "TabToolbar.menuButton" homePageButton = UIButton() menuButton.accessibilityIdentifier = "TabToolbar.homePageButton" actionButtons = [backButton, forwardButton, menuButton, stopReloadButton, shareButton, homePageButton] super.init(frame: frame) self.helper = TabToolbarHelper(toolbar: self) addButtons(backButton, forwardButton, menuButton, stopReloadButton, shareButton, homePageButton) accessibilityNavigationStyle = .combined accessibilityLabel = NSLocalizedString("Navigation Toolbar", comment: "Accessibility label for the navigation toolbar displayed at the bottom of the screen.") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } func updateBookmarkStatus(_ isBookmarked: Bool) { bookmarkButton.isSelected = isBookmarked } func updateReloadStatus(_ isLoading: Bool) { helper?.updateReloadStatus(isLoading) } func updatePageStatus(_ isWebPage: Bool) { stopReloadButton.isEnabled = isWebPage shareButton.isEnabled = isWebPage } override func draw(_ rect: CGRect) { if let context = UIGraphicsGetCurrentContext() { drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0)) } } fileprivate func drawLine(_ context: CGContext, start: CGPoint, end: CGPoint) { context.setStrokeColor(UIColor.black.withAlphaComponent(0.05).cgColor) context.setLineWidth(2) context.move(to: CGPoint(x: start.x, y: start.y)) context.addLine(to: CGPoint(x: end.x, y: end.y)) context.strokePath() } } // MARK: UIAppearance extension TabToolbar { dynamic var actionButtonTintColor: UIColor? { get { return helper?.buttonTintColor } set { guard let value = newValue else { return } helper?.buttonTintColor = value } } } extension TabToolbar: Themeable { func applyTheme(_ themeName: String) { guard let theme = TabToolbar.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } actionButtonTintColor = theme.buttonTintColor! } } extension TabToolbar: AppStateDelegate { func appDidUpdateState(_ state: AppState) { let showHomepage = !HomePageAccessors.isButtonInMenu(state) homePageButton.removeFromSuperview() shareButton.removeFromSuperview() if showHomepage { homePageButton.isEnabled = HomePageAccessors.isButtonEnabled(state) addButtons(homePageButton) } else { addButtons(shareButton) } updateConstraints() } }
mpl-2.0
9bda07eebdcf5a5fe9a723e474a753a3
45.201893
259
0.728049
5.493623
false
false
false
false
zjzsliyang/Potions
Paging/Paging/LinkedList.swift
1
3797
// // LinkedList.swift // Paging // // Created by Yang Li on 24/05/2017. // Copyright © 2017 Yang Li. All rights reserved. // // Reference: https://hugotunius.se/2016/07/17/implementing-a-linked-list-in-swift.html import Foundation public class Node<T: Equatable> { typealias NodeType = Node<T> public let value: T var next: NodeType? = nil var previous: NodeType? = nil public init(value: T) { self.value = value } } extension Node: CustomStringConvertible { public var description: String { get { return "Node(\(value))" } } } public final class LinkedList<T: Equatable> { public typealias NodeType = Node<T> fileprivate var start: NodeType? { didSet { if end == nil { end = start } } } fileprivate var end: NodeType? { didSet { if start == nil { start = end } } } public fileprivate(set) var count: Int = 0 public var isEmpty: Bool { get { return count == 0 } } public init() { } public init<S: Sequence>(_ elements: S) where S.Iterator.Element == T { for element in elements { append(value: element) } } } extension LinkedList { public func append(value: T) { let previousEnd = end end = NodeType(value: value) end?.previous = previousEnd previousEnd?.next = end count += 1 } } extension LinkedList { fileprivate func iterate(block: (_ node: NodeType, _ index: Int) throws -> NodeType?) rethrows -> NodeType? { var node = start var index = 0 while node != nil { let result = try block(node!, index) if result != nil { return result } index += 1 node = node?.next } return nil } } extension LinkedList { public func nodeAt(index: Int) -> NodeType { precondition(index >= 0 && index < count, "Index \(index) out of bounds") let result = iterate { if $1 == index { return $0 } return nil } return result! } public func valueAt(index: Int) -> T { let node = nodeAt(index: index) return node.value } } extension LinkedList { public func remove(node: NodeType) { let nextNode = node.next let previousNode = node.previous if node === start && node === end { start = nil end = nil } else if node === start { start = node.next } else if node === end { end = node.previous } else { previousNode?.next = nextNode nextNode?.previous = previousNode } count -= 1 assert( (end != nil && start != nil && count >= 1) || (end == nil && start == nil && count == 0), "Internal invariant not upheld at the end of remove" ) } public func remove(atIndex index: Int) { precondition(index >= 0 && index < count, "Index \(index) out of bounds") let result = iterate { if $1 == index { return $0 } return nil } remove(node: result!) } } public struct LinkedListIterator<T: Equatable>: IteratorProtocol { public typealias Element = Node<T> fileprivate var currentNode: Element? fileprivate init(startNode: Element?) { currentNode = startNode } public mutating func next() -> LinkedListIterator.Element? { let node = currentNode currentNode = currentNode?.next return node } } extension LinkedList: Sequence { public typealias Iterator = LinkedListIterator<T> public func makeIterator() -> LinkedList.Iterator { return LinkedListIterator(startNode: start) } } extension LinkedList { func copy() -> LinkedList<T> { let newList = LinkedList<T>() for element in self { newList.append(value: element.value) } return newList } }
mit
60a9ed983fc2c2c6ea78674e4fd24141
18.978947
111
0.592729
4.046908
false
false
false
false
jspahrsummers/Pistachio
PistachioTests/LensSpec.swift
1
6623
// // LensSpec.swift // Pistachio // // Created by Robert Böhnke on 1/17/15. // Copyright (c) 2015 Robert Böhnke. All rights reserved. // import Quick import Nimble import LlamaKit import Pistachio struct Inner: Equatable { var count: Int } func == (lhs: Inner, rhs: Inner) -> Bool { return lhs.count == rhs.count } struct Outer: Equatable { var count: Int var inner: Inner init(count: Int = 0, inner: Inner = Inner(count: 0)) { self.count = count self.inner = inner } } func == (lhs: Outer, rhs: Outer) -> Bool { return lhs.count == rhs.count && lhs.inner == rhs.inner } struct OuterLenses { static let count = Lens<Outer, Int>(get: { $0.count }, set: { (inout outer: Outer, count) in outer.count = count }) static let inner = Lens<Outer, Inner>(get: { $0.inner }, set: { (inout outer: Outer, inner) in outer.inner = inner }) } struct InnerLenses { static let count = Lens<Inner, Int>(get: { $0.count }, set: { (inout inner: Inner, count) in inner.count = count }) } class LensSpec: QuickSpec { override func spec() { describe("A Lens") { let example: Outer = Outer(count: 2) let count = OuterLenses.count it("should get values") { expect(get(count, example)!).to(equal(2)) } it("should set values") { expect(set(count, example, 4)).to(equal(Outer(count: 4))) } it("should modify values") { expect(mod(count, example, { $0 + 2 })).to(equal(Outer(count: 4))) } } describe("A composed Lens") { let example = Outer(count: 0, inner: Inner(count: 2)) let innerCount = OuterLenses.inner >>> InnerLenses.count it("should get values") { expect(get(innerCount, example)!).to(equal(2)) } it("should set values") { expect(set(innerCount, example, 4)).to(equal(Outer(count: 0, inner: Inner(count: 4)))) } it("should modify values") { expect(mod(innerCount, example, { $0 + 2 })).to(equal(Outer(count: 0, inner: Inner(count: 4)))) } } describe("Lifted lenses") { context("for arrays") { let inner = [ Inner(count: 1), Inner(count: 2), Inner(count: 3), Inner(count: 4) ] let lifted = lift(InnerLenses.count) it("should get values") { let result = get(lifted, inner) expect(result).to(equal([ 1, 2, 3, 4 ])) } it("should set values") { let result = set(lifted, inner, [ 2, 4, 6, 8 ]) expect(result).to(equal([ Inner(count: 2), Inner(count: 4), Inner(count: 6), Inner(count: 8) ])) } it("should reduce the resulting array size accordingly") { // Does this make sense? let result = set(lifted, inner, [ 42 ]) expect(result).to(equal([ Inner(count: 42) ])) } } context("for results") { let inner = Inner(count: 5) let error = NSError() let lifted: Lens<Result<Inner, NSError>, Result<Int, NSError>> = lift(InnerLenses.count) it("should get values") { let result = get(lifted, success(inner)) expect(result.value).to(equal(5)) } it("should return structure failures on get") { let result = get(lifted, failure(error)) expect(result.error).to(beIdenticalTo(error)) } it("should set values") { let result = set(lifted, success(inner), success(3)) expect(result.value?.count).to(equal(3)) } it("should return structure failures on set") { let result = set(lifted, failure(error), success(3)) expect(result.error).to(beIdenticalTo(error)) } it("should return value failures on set") { let result = set(lifted, success(inner), failure(error)) expect(result.error).to(beIdenticalTo(error)) } } } describe("Transformed lenses") { let outer = Outer(count: 0) let transformed = transform(lift(OuterLenses.count), ValueTransformers.string) it("should get values") { let result = get(transformed, success(outer)) expect(result.value).to(equal("0")) } it("should set values") { let result = set(transformed, success(outer), success("2")) expect(result.value?.count).to(equal(2)) } } describe("Split lenses") { let outer = Outer(count: 2, inner: Inner(count: 4)) let inner = Inner(count: 9) let both = OuterLenses.count *** InnerLenses.count it("should get values") { let result = get(both, (outer, inner)) expect(result.0).to(equal(2)) expect(result.1).to(equal(9)) } it("should set values") { let result = set(both, (outer, inner), (12, 34)) expect(result.0.count).to(equal(12)) expect(result.0.inner.count).to(equal(4)) expect(result.1.count).to(equal(34)) } } describe("Fanned out lenses") { let example = Outer(count: 0, inner: Inner(count: 2)) let both = OuterLenses.count &&& (OuterLenses.inner >>> InnerLenses.count) it("should get values") { let result = get(both, example) expect(result.0).to(equal(0)) expect(result.1).to(equal(2)) } it("should set values") { let result = set(both, example, (12, 34)) expect(result.count).to(equal(12)) expect(result.inner.count).to(equal(34)) } } } }
mit
52baced759ce20f4b72a7ae8de566490
28.039474
111
0.474249
4.282665
false
false
false
false
Appsaurus/Infinity
InfinitySample/Main1TableViewController.swift
2
2085
// // Samples1TableViewController.swift // InfinitySample // // Created by Danis on 15/12/22. // Copyright © 2015年 danis. All rights reserved. // import UIKit enum AnimatorType: Int, CustomStringConvertible{ case Default = 0 case GIF case Circle case Arrow case Snake case Spark var description:String { switch self { case .Default: return "Default" case .GIF: return "GIF" case .Circle: return "Circle" case .Arrow: return "Arrow" case .Snake: return "Snake" case .Spark: return "Spark" } } } class Main1TableViewController: UITableViewController { var samples = [AnimatorType.Default,.GIF,.Circle,.Arrow,.Snake,.Spark] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return samples.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath) cell.textLabel?.text = samples[indexPath.row].description if indexPath.row <= 1 { cell.detailTextLabel?.text = "Built-In" }else { cell.detailTextLabel?.text = nil } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sampleVC = AddSamplesTableViewController() sampleVC.hidesBottomBarWhenPushed = true sampleVC.type = self.samples[indexPath.row] self.show(sampleVC, sender: self) } }
mit
f45865bd72a4f089a002eb5251fe7fe5
24.390244
109
0.616715
4.910377
false
false
false
false
stripe/stripe-ios
Stripe/STPPaymentMethod+BasicUI.swift
1
2517
// // STPPaymentMethod+BasicUI.swift // StripeiOS // // Created by David Estes on 6/30/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeCore @_spi(STP) import StripePayments @_spi(STP) import StripePaymentsUI import UIKit extension STPPaymentMethod: STPPaymentOption { // MARK: - STPPaymentOption @objc public var image: UIImage { if type == .card, let card = card { return STPImageLibrary.cardBrandImage(for: card.brand) } else { return STPImageLibrary.cardBrandImage(for: .unknown) } } @objc public var templateImage: UIImage { if type == .card, let card = card { return STPImageLibrary.templatedBrandImage(for: card.brand) } else { return STPImageLibrary.templatedBrandImage(for: .unknown) } } @objc public var label: String { switch type { case .card: if let card = card { let brand = STPCardBrandUtilities.stringFrom(card.brand) return "\(brand ?? "") \(card.last4 ?? "")" } else { return STPCardBrandUtilities.stringFrom(.unknown) ?? "" } case .FPX: if let fpx = fpx { return STPFPXBank.stringFrom(STPFPXBank.brandFrom(fpx.bankIdentifierCode)) ?? "" } else { fallthrough } case .USBankAccount: if let usBankAccount = usBankAccount { return String( format: String.Localized.bank_name_account_ending_in_last_4, usBankAccount.bankName, usBankAccount.last4 ) } else { fallthrough } default: return type.displayName } } @objc public var isReusable: Bool { switch type { case .card, .link, .USBankAccount: return true case .alipay, // Careful! Revisit this if/when we support recurring Alipay .AUBECSDebit, .bacsDebit, .SEPADebit, .iDEAL, .FPX, .cardPresent, .giropay, .EPS, .payPal, .przelewy24, .bancontact, .OXXO, .sofort, .grabPay, .netBanking, .UPI, .afterpayClearpay, .blik, .weChatPay, .boleto, .klarna, .linkInstantDebit, .affirm, // fall through .unknown: return false @unknown default: return false } } }
mit
6de8ca4f6923a6154bc428f6a9adcb0a
30.848101
96
0.552464
4.330465
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/01120-clang-codegen-codegenfunction-emitlvalueforfield.swift
12
2403
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } b() { } protocol d { } } } func a: A, T) { } struct A { let end = i() func a<T : a = D>?) in 0)([0x31] = T, V, 3] as String) enum b = { enum a return ") enum S<H : String { } class B { func c enum B : [Int) { protocol P { return "a()) let foo as String) -> U) extension String { class A where T -> U) -> Any) in a { func c, V>) { let v: a { } return self.d.init(T: A> S(v: a { protocol C { } protocol a { class func ^(#object1, range.c, q: } } case c(a(start: A, q: self] { [0x31] in () protocol b = { } } } return p: a { } func d, d: SequenceType> { } f = b> : Any, Any) {} extension String = b init(x() } struct B convenience init()() } protocol c { func b) typealias f : ExtensibleCollectionType>(x, range.E == [Int println(self.b { return self.E protocol A { } } } func c) { typealias B typealias B class A where d class A, T : c(T! { func i<j : A> T>() { self.c] = A, b = { c } } class B : c: A> { return $0.Type) -> { } } class a(): func b> { } extension Array { struct c : Array<T>?) -> String { } } enum A { protocol a { class a([self.b in func e() { let start = "\(i: a { protocol B { } protocol a { extension NSData { protocol c { return " } protocol b = B<T protocol A { case C typealias B { protocol P { import Foundation } class d<d == b } } var f : String = true { func g, 3] { let t: T.C> (z(range: [unowned self.startIndex) let foo as [$0 func a enum A = e(bytes: a { enum A { }) var d where B = i<T> Any) { } init() -> T : (c(T: b: Array) -> String { protocol a { } extension A { } typealias g, U.Generator.<c<T>() import Foundation } (h> String { } () class a typealias f = B func f(a(") A<Int>(z(a struct S { class func b> T>) -> Any) -> { func f<b) } return { c, let h, a) } } func compose<U>(Any, g<T>(AnyObject) + seq: e: () { struct A { case s: A { } class A = 1)) class c } func i> e: c> T>(s: a {} println(f: T) -> { } } class A? { import Foundation } protocol d = e(T, f() -> String { println(") struct c: Bool], object2: A, e, length: start, T][c<T where T>) -> (".Type) -> { } println(n: String } S.e == [] typealias e : () { } class b } protocol B { let f == g: Range<h : T] in import Foundation } import Foundation } } public var b, V, Bool) { struct X.E } let foo as BooleanType, AnyObject, T : B<Q<h
mit
0bd7846a57dfa7ce380880260f279cd4
12.653409
87
0.587599
2.469681
false
false
false
false
PETERZer/SingularityIMClient-PeterZ
SingularityIMClient-PeterZDemo/SingularityIMClient/SingularityIMClient/ChatListModel.swift
1
4895
// // ChatListModel.swift // SingularityIMClient // // Created by apple on 1/14/16. // Copyright © 2016 张勇. All rights reserved. // import UIKit class ChatListModel: NSObject { var _chat_session_id:String? var _chat_session_type:String? var _last_message:String? var _last_message_id:String? var _last_message_time:String? var _last_message_type:String? var _last_sender_id:String? var _message_count:String? var _target_id:String? var _target_name:String? var _target_online_status:String? var _target_picture:String? var chat_session_id:String?{ get{ if self._chat_session_id == nil { print("_chat_session_id没有值") return nil }else { return self._chat_session_id } } set(newChatSID){ self._chat_session_id = newChatSID } } var chat_session_type:String?{ get{ if self._chat_session_type == nil { print("_chat_session_type没有值") return nil }else { return self._chat_session_type } } set(newChatSType){ self._chat_session_type = newChatSType } } var last_message:String?{ get{ if self._last_message == nil { print("_last_message没有值") return nil }else { return self._last_message } } set(newLastMessage){ self._last_message = newLastMessage } } var last_message_id:String?{ get{ if self._last_message_id == nil { print("_last_message_id没有值") return nil }else { return self._last_message_id } } set(newLastMessageId){ self._last_message_id = newLastMessageId } } var last_message_time:String?{ get{ if self._last_message_time == nil { print("_last_message_time没有值") return nil }else { return self._last_message_time } } set(newLastMessageTime){ self._last_message_time = newLastMessageTime } } var last_message_type:String?{ get{ if self._last_message_type == nil { print("_last_message_type没有值") return nil }else { return self._last_message_type } } set(newLastMessageType){ self._last_message_type = newLastMessageType } } var last_sender_id:String?{ get{ if self._last_sender_id == nil { print("_last_sender_id没有值") return nil }else { return self._last_sender_id } } set(newLasterSenderId){ self._last_sender_id = newLasterSenderId } } var message_count:String?{ get{ if self._message_count == nil { print("_message_count没有值") return nil }else { return self._message_count } } set(newMessageCount){ self._message_count = newMessageCount } } var target_id:String?{ get{ if self._target_id == nil { print("_target_id没有值") return nil }else { return self._target_id } } set(newTargetId){ self._target_id = newTargetId } } var target_name:String?{ get{ if self._target_name == nil { print("_target_name没有值") return nil }else { return self._target_name } } set(newTargetName){ self._target_name = newTargetName } } var target_online_status:String?{ get{ if self._target_online_status == nil { print("_target_online_status没有值") return nil }else { return self._target_online_status } } set(newTargetOS){ self._target_online_status = newTargetOS } } var target_picture:String?{ get{ if self._target_picture == nil { print("_target_picture没有值") return nil }else { return self._target_picture } } set(newTargetPicture){ self._target_picture = newTargetPicture } } }
mit
92747b71c81ecf444abd82237a3b8fbf
23.586735
56
0.459734
4.502804
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/UIImageExtension.swift
1
4477
// // UIImageExtension.swift // DNSwiftProject // // Created by mainone on 16/12/20. // Copyright © 2016年 wjn. All rights reserved. // import UIKit extension UIImage { // 压缩图片 public func compressImage(rate: CGFloat) -> Data? { return UIImageJPEGRepresentation(self, rate) } // 返回图片大小 Bytes public func getSizeAsBytes() -> Int { return UIImageJPEGRepresentation(self, 1)?.count ?? 0 } // 返回图片大小 Kilobytes public func getSizeAsKilobytes() -> Int { let sizeAsBytes = getSizeAsBytes() return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0 } // 裁剪图片大小 public func scaleTo(w: CGFloat, h: CGFloat) -> UIImage { let newSize = CGSize(width: w, height: h) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } // 切圆角图片 public func roundCorners(_ cornerRadius: CGFloat) -> UIImage { let w = self.size.width * self.scale let h = self.size.height * self.scale let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(w), height: CGFloat(h)) UIGraphicsBeginImageContextWithOptions(CGSize(width: CGFloat(w), height: CGFloat(h)), false, 1.0) UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip() self.draw(in: rect) let ret = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return ret } // 添加边框 public func apply(border: CGFloat, color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0) let width = self.cgImage?.width let height = self.cgImage?.height let bits = self.cgImage?.bitsPerComponent let colorSpace = self.cgImage?.colorSpace let bitmapInfo = self.cgImage?.bitmapInfo let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!) var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) context?.setStrokeColor(red: red, green: green, blue: blue, alpha: alpha) context?.setLineWidth(border) let rect = CGRect(x: 0, y: 0, width: size.width*scale, height: size.height*scale) let inset = rect.insetBy(dx: border*scale, dy: border*scale) context?.strokeEllipse(in: inset) context?.draw(self.cgImage!, in: inset) let image = UIImage(cgImage: (context?.makeImage()!)!) UIGraphicsEndImageContext() return image } // 使用颜色生成图片 public func withColor(_ tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect context?.clip(to: rect, mask: self.cgImage!) tintColor.setFill() context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() return newImage } // 返回链接的图片 public convenience init?(urlString: String) { guard let url = URL(string: urlString) else { self.init(data: Data()) return } guard let data = try? Data(contentsOf: url) else { print("该链接没有有效的图片: \(urlString)") self.init(data: Data()) return } self.init(data: data) } // 返回一个空图片 public class func blankImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
apache-2.0
157828b61d5facb9d36074660da8f8d4
34.639344
172
0.619365
4.562434
false
false
false
false
DavadDi/flatbuffers
swift/Sources/FlatBuffers/Table.swift
1
6006
/* * Copyright 2021 Google Inc. 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 Foundation public struct Table { public private(set) var bb: ByteBuffer public private(set) var postion: Int32 public init(bb: ByteBuffer, position: Int32 = 0) { guard isLitteEndian else { fatalError("Reading/Writing a buffer in big endian machine is not supported on swift") } self.bb = bb postion = position } public func offset(_ o: Int32) -> Int32 { let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( def: Int16.self, position: Int(vtable + o))) : 0 } public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) } /// String reads from the buffer with respect to position of the current table. /// - Parameter offset: Offset of the string public func string(at offset: Int32) -> String? { directString(at: offset + postion) } /// Direct string reads from the buffer disregarding the position of the table. /// It would be preferable to use string unless the current position of the table is not needed /// - Parameter offset: Offset of the string public func directString(at offset: Int32) -> String? { var offset = offset offset += bb.read(def: Int32.self, position: Int(offset)) let count = bb.read(def: Int32.self, position: Int(offset)) let position = offset + Int32(MemoryLayout<Int32>.size) return bb.readString(at: position, count: count) } /// Reads from the buffer with respect to the position in the table. /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func readBuffer<T>(of type: T.Type, at o: Int32) -> T { directRead(of: T.self, offset: o + postion) } /// Reads from the buffer disregarding the position of the table. /// It would be used when reading from an /// ``` /// let offset = __t.offset(10) /// //Only used when the we already know what is the /// // position in the table since __t.vector(at:) /// // returns the index with respect to the position /// __t.directRead(of: Byte.self, /// offset: __t.vector(at: offset) + index * 1) /// ``` /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func directRead<T>(of type: T.Type, offset o: Int32) -> T { let r = bb.read(def: T.self, position: Int(o)) return r } public func union<T: FlatBufferObject>(_ o: Int32) -> T { let o = o + postion return directUnion(o) } public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T { T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) } public func getVector<T>(at off: Int32) -> [T]? { let o = offset(off) guard o != 0 else { return nil } return bb.readSlice(index: vector(at: o), count: vector(count: o)) } /// Vector count gets the count of Elements within the array /// - Parameter o: start offset of the vector /// - returns: Count of elements public func vector(count o: Int32) -> Int32 { var o = o o += postion o += bb.read(def: Int32.self, position: Int(o)) return bb.read(def: Int32.self, position: Int(o)) } /// Vector start index in the buffer /// - Parameter o:start offset of the vector /// - returns: the start index of the vector public func vector(at o: Int32) -> Int32 { var o = o o += postion return o + bb.read(def: Int32.self, position: Int(o)) + 4 } } extension Table { static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read( def: Int32.self, position: Int(o)) } static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 { let vTable = Int32(fbb.capacity) - o return vTable + Int32(fbb.read( def: Int16.self, position: Int(vTable + vOffset - fbb.read(def: Int32.self, position: Int(vTable))))) } static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = fbb.read(def: Int32.self, position: Int(_off2)) let startPos1 = _off1 + memorySize let startPos2 = _off2 + memorySize let minValue = min(len1, len2) for i in 0...minValue { let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) if b1 != b2 { return Int32(b2 - b1) } } return len1 - len2 } static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = Int32(key.count) let startPos1 = _off1 + memorySize let minValue = min(len1, len2) for i in 0..<minValue { let b = fbb.read(def: Int8.self, position: Int(i + startPos1)) let byte = key[Int(i)] if b != byte { return Int32(b - Int8(byte)) } } return len1 - len2 } }
apache-2.0
29d55a7293e8b03863d80ad0e5fba98b
35.180723
97
0.641525
3.432
false
false
false
false
kaojohnny/CoreStore
Sources/Fetching and Querying/Concrete Clauses/GroupBy.swift
1
3108
// // GroupBy.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // 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 CoreData // MARK: - GroupBy /** The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path. */ public struct GroupBy: QueryClause, Hashable { /** The list of key path strings to group results with */ public let keyPaths: [KeyPath] /** Initializes a `GroupBy` clause with an empty list of key path strings */ public init() { self.init([]) } /** Initializes a `GroupBy` clause with a list of key path strings - parameter keyPath: a key path string to group results with - parameter keyPaths: a series of key path strings to group results with */ public init(_ keyPath: KeyPath, _ keyPaths: KeyPath...) { self.init([keyPath] + keyPaths) } /** Initializes a `GroupBy` clause with a list of key path strings - parameter keyPaths: a list of key path strings to group results with */ public init(_ keyPaths: [KeyPath]) { self.keyPaths = keyPaths } // MARK: QueryClause public func applyToFetchRequest(fetchRequest: NSFetchRequest) { if let keyPaths = fetchRequest.propertiesToGroupBy as? [String] where keyPaths != self.keyPaths { CoreStore.log( .Warning, message: "An existing \"propertiesToGroupBy\" for the \(cs_typeName(NSFetchRequest)) was overwritten by \(cs_typeName(self)) query clause." ) } fetchRequest.propertiesToGroupBy = self.keyPaths } // MARK: Hashable public var hashValue: Int { return (self.keyPaths as NSArray).hashValue } } // MARK: - GroupBy: Equatable @warn_unused_result public func == (lhs: GroupBy, rhs: GroupBy) -> Bool { return lhs.keyPaths == rhs.keyPaths }
mit
1b7bd7d1d039ce53b0e3275cca9a875c
29.165049
155
0.654651
4.700454
false
false
false
false
ivygulch/IVGAppContainer
IVGAppContainer/source/service/UserDefaultsService.swift
1
2973
// // UserDefaultsService.swift // IVGAppContainer // // Created by Douglas Sjoquist on 3/21/16. // Copyright © 2016 Ivy Gulch LLC. All rights reserved. // import Foundation public protocol UserDefaultsServiceType { func value<T>(_ key: String, valueType: T.Type) -> T? func setValue<T>(_ value: T, forKey key: String) func removeValueForKey(_ key: String) func register(defaults: [String: Any]) } public class UserDefaultsService: UserDefaultsServiceType { public convenience init(container: ApplicationContainerType) { self.init(container: container, userDefaults: UserDefaults.standard) } public init(container: ApplicationContainerType, userDefaults: UserDefaults) { self.container = container self.userDefaults = userDefaults } public func value<T>(_ key: String, valueType: T.Type) -> T? { if T.self == String.self { return userDefaults.string(forKey: key) as! T? } else if T.self == Int.self { return userDefaults.integer(forKey: key) as? T } else if T.self == Float.self { return userDefaults.float(forKey: key) as? T } else if T.self == Double.self { return userDefaults.double(forKey: key) as? T } else if T.self == Bool.self { return userDefaults.bool(forKey: key) as? T } else if T.self == URL.self { return userDefaults.url(forKey: key) as? T } else if T.self == Date.self { if userDefaults.object(forKey: key) == nil { return nil } let timeInterval = userDefaults.double(forKey: key) as Double return Date(timeIntervalSinceReferenceDate: timeInterval) as? T } return nil } public func setValue<T>(_ value: T, forKey key: String) { if let value = value as? String { userDefaults.set(value, forKey: key) } else if let value = value as? Int { userDefaults.set(value, forKey: key) } else if let value = value as? Float { userDefaults.set(value, forKey: key) } else if let value = value as? Double { userDefaults.set(value, forKey: key) } else if let value = value as? Bool { userDefaults.set(value, forKey: key) } else if let value = value as? URL { userDefaults.set(value, forKey: key) } else if let value = value as? Date { userDefaults.set(value.timeIntervalSinceReferenceDate, forKey: key) } } public func removeValueForKey(_ key: String) { userDefaults.removeObject(forKey: key) } public func willResignActive() { userDefaults.synchronize() } public func register(defaults: [String: Any]) { userDefaults.register(defaults: defaults) } // MARK: private variables private let container: ApplicationContainerType private let userDefaults: UserDefaults }
mit
726d76c36ed04dce1d77dc3c00f6c364
32.772727
82
0.620458
4.416048
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/02134-swift-constraints-constraintsystem-matchtypes.swift
1
829
// 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 extension String { typealias f = { c func b[") var b = d(c = [c(Any) -> a { } self] = { class B : A { } return { } } protocol a { deinit { } class A, let d(Any)] == [T : a { } func e: S<T>Bool] enum B { let h == B<d, b { } } struct Q<(self.startIndex)) -> { for b : U : b<T -> : Array<Q<T> String { public subscript () { class func f<j : d { } } } } } struct c: Any, T -> String { } protocol P { A> U, Any) -> { } } struct c(f: b>
apache-2.0
207f97286eff544c4091a684307a79be
17.422222
79
0.628468
2.810169
false
false
false
false
debugsquad/nubecero
nubecero/View/Store/VStore.swift
1
8771
import UIKit class VStore:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var controller:CStore! private weak var viewSpinner:VSpinner? private weak var collectionView:UICollectionView! private let kHeaderHeight:CGFloat = 150 private let kFooterHeight:CGFloat = 70 private let kInterLine:CGFloat = 1 private let kCollectionBottom:CGFloat = 10 convenience init(controller:CStore) { self.init() clipsToBounds = true backgroundColor = UIColor.background translatesAutoresizingMaskIntoConstraints = false self.controller = controller let barHeight:CGFloat = controller.parentController.viewParent.kBarHeight let viewSpinner:VSpinner = VSpinner() self.viewSpinner = viewSpinner let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout() flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight) flow.minimumLineSpacing = kInterLine flow.minimumInteritemSpacing = 0 flow.scrollDirection = UICollectionViewScrollDirection.vertical flow.sectionInset = UIEdgeInsets(top:kInterLine, left:0, bottom:kCollectionBottom, right:0) let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow) collectionView.isHidden = true collectionView.clipsToBounds = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.register( VStoreCellNotAvailable.self, forCellWithReuseIdentifier: VStoreCellNotAvailable.reusableIdentifier) collectionView.register( VStoreCellDeferred.self, forCellWithReuseIdentifier: VStoreCellDeferred.reusableIdentifier) collectionView.register( VStoreCellNew.self, forCellWithReuseIdentifier: VStoreCellNew.reusableIdentifier) collectionView.register( VStoreCellPurchased.self, forCellWithReuseIdentifier: VStoreCellPurchased.reusableIdentifier) collectionView.register( VStoreCellPurchasing.self, forCellWithReuseIdentifier: VStoreCellPurchasing.reusableIdentifier) collectionView.register( VStoreHeader.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: VStoreHeader.reusableIdentifier) collectionView.register( VStoreFooter.self, forSupplementaryViewOfKind:UICollectionElementKindSectionFooter, withReuseIdentifier: VStoreFooter.reusableIdentifier) self.collectionView = collectionView addSubview(collectionView) addSubview(viewSpinner) let views:[String:UIView] = [ "viewSpinner":viewSpinner, "collectionView":collectionView] let metrics:[String:CGFloat] = [ "barHeight":barHeight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[viewSpinner]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-(barHeight)-[viewSpinner]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-(barHeight)-[collectionView]-0-|", options:[], metrics:metrics, views:views)) } override func layoutSubviews() { collectionView.collectionViewLayout.invalidateLayout() super.layoutSubviews() } //MARK: private private func modelAtIndex(index:IndexPath) -> MStoreItem { let itemId:MStore.PurchaseId = controller.model.references[index.section] let item:MStoreItem = controller.model.mapItems[itemId]! return item } //MARK: public func refreshStore() { DispatchQueue.main.async { [weak self] in self?.viewSpinner?.removeFromSuperview() self?.collectionView.reloadData() self?.collectionView.isHidden = false guard let errorMessage:String = self?.controller.model.error else { return } VAlert.message(message:errorMessage) } } //MARK: collection delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForFooterInSection section:Int) -> CGSize { let indexPath:IndexPath = IndexPath(item:0, section:section) let item:MStoreItem = modelAtIndex(index:indexPath) let size:CGSize if item.status?.restorable == true { size = CGSize(width:0, height:kFooterHeight) } else { size = CGSize.zero } return size } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let item:MStoreItem = modelAtIndex(index:indexPath) let cellHeight:CGFloat = item.status!.cellHeight let width:CGFloat = collectionView.bounds.maxX let size:CGSize = CGSize(width:width, height:cellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { let count:Int = controller.model.references.count return count } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let indexPath:IndexPath = IndexPath(item:0, section:section) let item:MStoreItem = modelAtIndex(index:indexPath) guard let _:MStoreItemStatus = item.status else { return 0 } return 1 } func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView { let reusable:UICollectionReusableView if kind == UICollectionElementKindSectionHeader { let item:MStoreItem = modelAtIndex(index:indexPath) let header:VStoreHeader = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VStoreHeader.reusableIdentifier, for:indexPath) as! VStoreHeader header.config(model:item) reusable = header } else { let footer:VStoreFooter = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VStoreFooter.reusableIdentifier, for:indexPath) as! VStoreFooter footer.config(controller:controller) reusable = footer } return reusable } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MStoreItem = modelAtIndex(index:indexPath) let reusableIdentifier:String = item.status!.reusableIdentifier let cell:VStoreCell = collectionView.dequeueReusableCell( withReuseIdentifier: reusableIdentifier, for:indexPath) as! VStoreCell cell.config(controller:controller, model:item) return cell } func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { return false } func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool { return false } }
mit
b2c5c9a9f6c6128c79de103abf9877dd
33.531496
165
0.633679
6.378909
false
false
false
false
KyoheiG3/RxSwift
RxExample/RxExample/Examples/GitHubSignup/UsingVanillaObservables/GitHubSignupViewController1.swift
8
3739
// // GitHubSignupViewController1.swift // RxExample // // Created by Krunoslav Zaher on 4/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class GitHubSignupViewController1 : ViewController { @IBOutlet weak var usernameOutlet: UITextField! @IBOutlet weak var usernameValidationOutlet: UILabel! @IBOutlet weak var passwordOutlet: UITextField! @IBOutlet weak var passwordValidationOutlet: UILabel! @IBOutlet weak var repeatedPasswordOutlet: UITextField! @IBOutlet weak var repeatedPasswordValidationOutlet: UILabel! @IBOutlet weak var signupOutlet: UIButton! @IBOutlet weak var signingUpOulet: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() let viewModel = GithubSignupViewModel1( input: ( username: usernameOutlet.rx.text.orEmpty.asObservable(), password: passwordOutlet.rx.text.orEmpty.asObservable(), repeatedPassword: repeatedPasswordOutlet.rx.text.orEmpty.asObservable(), loginTaps: signupOutlet.rx.tap.asObservable() ), dependency: ( API: GitHubDefaultAPI.sharedAPI, validationService: GitHubDefaultValidationService.sharedValidationService, wireframe: DefaultWireframe.sharedInstance ) ) // bind results to { viewModel.signupEnabled .subscribe(onNext: { [weak self] valid in self?.signupOutlet.isEnabled = valid self?.signupOutlet.alpha = valid ? 1.0 : 0.5 }) .addDisposableTo(disposeBag) viewModel.validatedUsername .bindTo(usernameValidationOutlet.rx.validationResult) .addDisposableTo(disposeBag) viewModel.validatedPassword .bindTo(passwordValidationOutlet.rx.validationResult) .addDisposableTo(disposeBag) viewModel.validatedPasswordRepeated .bindTo(repeatedPasswordValidationOutlet.rx.validationResult) .addDisposableTo(disposeBag) viewModel.signingIn .bindTo(signingUpOulet.rx.isAnimating) .addDisposableTo(disposeBag) viewModel.signedIn .subscribe(onNext: { signedIn in print("User signed in \(signedIn)") }) .addDisposableTo(disposeBag) //} let tapBackground = UITapGestureRecognizer() tapBackground.rx.event .subscribe(onNext: { [weak self] _ in self?.view.endEditing(true) }) .addDisposableTo(disposeBag) view.addGestureRecognizer(tapBackground) } // This is one of the reasons why it's a good idea for disposal to be detached from allocations. // If resources weren't disposed before view controller is being deallocated, signup alert view // could be presented on top of the wrong screen or could crash your app if it was being presented // while navigation stack is popping. // This will work well with UINavigationController, but has an assumption that view controller will // never be added as a child view controller. If we didn't recreate the dispose bag here, // then our resources would never be properly released. override func willMove(toParentViewController parent: UIViewController?) { if let parent = parent { if parent as? UINavigationController == nil { assert(false, "something") } } else { self.disposeBag = DisposeBag() } } }
mit
5f619d873d81f0763c3c267b678e60d8
34.6
103
0.64901
5.37069
false
false
false
false
SteveBarnegren/TweenKit
TweenKit/TweenKit/ActionScheduler.swift
1
4058
// // Scheduler.swift // TweenKit // // Created by Steve Barnegren on 18/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation import QuartzCore @objc public class ActionScheduler : NSObject { // MARK: - Public public init(automaticallyAdvanceTime: Bool = true) { self.automaticallyAdvanceTime = automaticallyAdvanceTime super.init() } /** Run an action - Parameter action: The action to run - Returns: Animation instance. You may wish to keep this, so that you can remove the animation later using the remove(animation:) method */ @discardableResult public func run(action: SchedulableAction) -> Animation { let animation = Animation(action: action) add(animation: animation) return animation } /** Adds an Animation to the scheduler. Usually you don't need to construct animations yourself, you can run the action directly. - Parameter animation: The animation to run */ public func add(animation: Animation) { animations.append(animation) animation.willStart() if automaticallyAdvanceTime { startLoop() } } /** Removes a currently running animation - Parameter animation: The animation to remove */ public func remove(animation: Animation) { guard let index = animations.firstIndex(of: animation) else { print("Can't find animation to remove") return } animation.didFinish() animations.remove(at: index) if animations.isEmpty { stopLoop() } } /** Removes all animations */ public func removeAll() { let allAnimations = animations allAnimations.forEach{ self.remove(animation: $0) } } /** The number of animations that are currently running */ public var numRunningAnimations: Int { return self.animations.count } // MARK: - Properties private var animations = [Animation]() private var animationsToRemove = [Animation]() private var displayLink: DisplayLink? private let automaticallyAdvanceTime: Bool // MARK: - Deinit deinit { stopLoop() } // MARK: - Manage Loop private func startLoop() { if displayLink != nil { return } displayLink = DisplayLink(handler: {[unowned self] (dt) in self.displayLinkCallback(dt: dt) }) } private func stopLoop() { displayLink?.invalidate() displayLink = nil } @objc private func displayLinkCallback(dt: Double) { // Update Animations step(dt: dt) } /// Advance the scheduler's time by amount dt public func step(dt: Double) { for animation in animations { // Animations containing finite time actions if animation.hasDuration { var remove = false if animation.elapsedTime + dt > animation.duration { remove = true } let newTime = (animation.elapsedTime + dt).constrained(max: animation.duration) animation.update(elapsedTime: newTime) if remove { animationsToRemove.append(animation) } } // Animations containing infinite time actions else{ let newTime = animation.elapsedTime + dt animation.update(elapsedTime: newTime) } } // Remove finished animations animationsToRemove.forEach{ remove(animation: $0) } animationsToRemove.removeAll() } }
mit
2b86113c48283832b33364613d20cdac
24.677215
140
0.55016
5.519728
false
false
false
false
jainsourabhgit/MyJohnDeereAPI-OAuth-Swift-Client
OAuthSwift/OAuthSwiftHTTPRequest.swift
1
11455
// // OAuthSwiftHTTPRequest.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation import UIKit public class OAuthSwiftHTTPRequest: NSObject, NSURLSessionDelegate { public typealias SuccessHandler = (data: NSData, response: NSHTTPURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void var URL: NSURL var HTTPMethod: String var HTTPBodyMultipart: NSData? var contentTypeMultipart: String? var request: NSMutableURLRequest? var session: NSURLSession! var headers: Dictionary<String, String> var parameters: Dictionary<String, AnyObject> var encodeParameters: Bool var dataEncoding: NSStringEncoding var timeoutInterval: NSTimeInterval var HTTPShouldHandleCookies: Bool var response: NSHTTPURLResponse! var responseData: NSMutableData var successHandler: SuccessHandler? var failureHandler: FailureHandler? convenience init(URL: NSURL) { self.init(URL: URL, method: "GET", parameters: [:]) } init(URL: NSURL, method: String, parameters: Dictionary<String, AnyObject>) { self.URL = URL self.HTTPMethod = method self.headers = [:] self.parameters = parameters self.encodeParameters = false self.dataEncoding = NSUTF8StringEncoding self.timeoutInterval = 60 self.HTTPShouldHandleCookies = false self.responseData = NSMutableData() } init(request: NSURLRequest) { self.request = request as? NSMutableURLRequest self.URL = request.URL! self.HTTPMethod = request.HTTPMethod! self.headers = [:] self.parameters = [:] self.encodeParameters = false self.dataEncoding = NSUTF8StringEncoding self.timeoutInterval = 60 self.HTTPShouldHandleCookies = false self.responseData = NSMutableData() } func start() { if (request == nil) { var error: NSError? do { self.request = try self.makeRequest() } catch let error1 as NSError { error = error1 self.request = nil } if ((error) != nil) { print(error!.localizedDescription) } } dispatch_async(dispatch_get_main_queue(), { self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue()) let task: NSURLSessionDataTask = self.session.dataTaskWithRequest(self.request!) { data, response, error -> Void in #if os(iOS) UIApplication.sharedApplication().networkActivityIndicatorVisible = false #endif self.response = response as? NSHTTPURLResponse self.responseData.length = 0 self.responseData.appendData(data!) if self.response.statusCode >= 400 { let responseString = NSString(data: self.responseData, encoding: self.dataEncoding) let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(self.response.statusCode, responseString: responseString! as String) let userInfo : [NSObject : AnyObject] = [NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": self.response.allHeaderFields] let error = NSError(domain: NSURLErrorDomain, code: self.response.statusCode, userInfo: userInfo) self.failureHandler?(error: error) return } self.successHandler?(data: self.responseData, response: self.response) } task.resume() #if os(iOS) UIApplication.sharedApplication().networkActivityIndicatorVisible = true #endif }) } public func makeRequest() throws -> NSMutableURLRequest { return try OAuthSwiftHTTPRequest.makeRequest(self.URL, method: self.HTTPMethod, headers: self.headers, parameters: self.parameters, dataEncoding: self.dataEncoding, encodeParameters: self.encodeParameters, body: self.HTTPBodyMultipart, contentType: self.contentTypeMultipart) } public class func makeRequest( URL: NSURL, method: String, headers: [String : String], parameters: Dictionary<String, AnyObject>, dataEncoding: NSStringEncoding, encodeParameters: Bool, body: NSData? = nil, contentType: String? = nil) throws -> NSMutableURLRequest { var error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil) let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = method for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(dataEncoding)) let nonOAuthParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") } if (body != nil && contentType != nil) { request.setValue(contentType!, forHTTPHeaderField: "Content-Type") //request!.setValue(self.HTTPBodyMultipart!.length.description, forHTTPHeaderField: "Content-Length") request.HTTPBody = body! } else { if nonOAuthParameters.count > 0 { if request.HTTPMethod == "GET" || request.HTTPMethod == "HEAD" || request.HTTPMethod == "DELETE" { let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding) request.URL = URL.URLByAppendingQueryString(queryString) request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") } else { if (encodeParameters) { let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding) //self.request!.URL = self.URL.URLByAppendingQueryString(queryString) request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") request.HTTPBody = queryString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) } else { var jsonError: NSError? do { let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(nonOAuthParameters, options: []) request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonData } catch let error1 as NSError { jsonError = error1 if (true) { //println(jsonError!.localizedDescription) error = jsonError } throw error } } } } } //print("\n################Request#################\n") //print("Send HTTPRequest:\(request)") //print("Send HTTPRequest-AllHeaders:\(request.allHTTPHeaderFields)") //print("\n#################################\n") return request } class func stringWithData(data: NSData, encodingName: String?) -> String { var encoding: UInt = NSUTF8StringEncoding if (encodingName != nil) { let encodingNameString = encodingName! as NSString encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingNameString)) if encoding == UInt(kCFStringEncodingInvalidId) { encoding = NSUTF8StringEncoding // by default } } return NSString(data: data, encoding: encoding)! as String } class func descriptionForHTTPStatus(status: Int, responseString: String) -> String { var s = "HTTP Status \(status)" var description: String? // http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml if status == 400 { description = "Bad Request" } if status == 401 { description = "Unauthorized" } if status == 402 { description = "Payment Required" } if status == 403 { description = "Forbidden" } if status == 404 { description = "Not Found" } if status == 405 { description = "Method Not Allowed" } if status == 406 { description = "Not Acceptable" } if status == 407 { description = "Proxy Authentication Required" } if status == 408 { description = "Request Timeout" } if status == 409 { description = "Conflict" } if status == 410 { description = "Gone" } if status == 411 { description = "Length Required" } if status == 412 { description = "Precondition Failed" } if status == 413 { description = "Payload Too Large" } if status == 414 { description = "URI Too Long" } if status == 415 { description = "Unsupported Media Type" } if status == 416 { description = "Requested Range Not Satisfiable" } if status == 417 { description = "Expectation Failed" } if status == 422 { description = "Unprocessable Entity" } if status == 423 { description = "Locked" } if status == 424 { description = "Failed Dependency" } if status == 425 { description = "Unassigned" } if status == 426 { description = "Upgrade Required" } if status == 427 { description = "Unassigned" } if status == 428 { description = "Precondition Required" } if status == 429 { description = "Too Many Requests" } if status == 430 { description = "Unassigned" } if status == 431 { description = "Request Header Fields Too Large" } if status == 432 { description = "Unassigned" } if status == 500 { description = "Internal Server Error" } if status == 501 { description = "Not Implemented" } if status == 502 { description = "Bad Gateway" } if status == 503 { description = "Service Unavailable" } if status == 504 { description = "Gateway Timeout" } if status == 505 { description = "HTTP Version Not Supported" } if status == 506 { description = "Variant Also Negotiates" } if status == 507 { description = "Insufficient Storage" } if status == 508 { description = "Loop Detected" } if status == 509 { description = "Unassigned" } if status == 510 { description = "Not Extended" } if status == 511 { description = "Network Authentication Required" } if (description != nil) { s = s + ": " + description! + ", Response: " + responseString } return s } }
mit
7eaeff2c63fab65b963abc005c52b169
43.571984
283
0.586032
5.491371
false
false
false
false
damicreabox/Git2Swift
Sources/Git2Swift/repository/Repository+Lookup.swift
1
3825
// // Repository+Lookup.swift // Git2Swift // // Created by Dami on 31/07/2016. // // import Foundation import CLibgit2 /// Git reference lookup /// /// - parameter repository: Libgit2 repository pointer /// - parameter name: Reference name /// /// - throws: GitError /// /// - returns: Libgit2 reference pointer internal func gitReferenceLookup(repository: UnsafeMutablePointer<OpaquePointer?>, name: String) throws -> UnsafeMutablePointer<OpaquePointer?> { // Find reference pointer let reference = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Lookup reference let error = git_reference_lookup(reference, repository.pointee, name) if (error != 0) { reference.deinitialize() reference.deallocate(capacity: 1) // 0 on success, GIT_ENOTFOUND, GIT_EINVALIDSPEC or an error code. switch (error) { case GIT_ENOTFOUND.rawValue : throw GitError.notFound(ref: name) case GIT_EINVALIDSPEC.rawValue: throw GitError.invalidSpec(spec: name) default: throw gitUnknownError("Unable to lookup reference \(name)", code: error) } } return reference } // MARK: - Repository extension for lookup extension Repository { /// Lookup reference /// /// - parameter name: Refrence name /// /// - throws: GitError /// /// - returns: Refernce public func referenceLookup(name: String) throws -> Reference { return try Reference(repository: self, name: name, pointer: try gitReferenceLookup(repository: pointer, name: name)) } /// Lookup a tree /// /// - parameter tree_id: Tree OID /// /// - throws: GitError /// /// - returns: Tree public func treeLookup(oid tree_id: OID) throws -> Tree { // Create tree let tree : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) var oid = tree_id.oid let error = git_tree_lookup(tree, pointer.pointee, &oid) if (error != 0) { tree.deinitialize() tree.deallocate(capacity: 1) throw gitUnknownError("Unable to lookup tree", code: error) } return Tree(repository: self, tree: tree) } /// Lookup a commit /// /// - parameter commit_id: OID /// /// - throws: GitError /// /// - returns: Commit public func commitLookup(oid commit_id: OID) throws -> Commit { // Create tree let commit : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) var oid = commit_id.oid let error = git_commit_lookup(commit, pointer.pointee, &oid) if (error != 0) { commit.deinitialize() commit.deallocate(capacity: 1) throw gitUnknownError("Unable to lookup commit", code: error) } return Commit(repository: self, pointer: commit, oid: OID(withGitOid: oid)) } /// Lookup a blob /// /// - parameter blob_id: OID /// /// - throws: GitError /// /// - returns: Blob public func blobLookup(oid blob_id: OID) throws -> Blob { // Create tree let blob : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) var oid = blob_id.oid let error = git_blob_lookup(blob, pointer.pointee, &oid) if error != 0 { blob.deinitialize() blob.deallocate(capacity: 1) throw gitUnknownError("Unable to lookup blob", code: error) } return Blob(blob: blob) } }
apache-2.0
083d2a6ca83c2abe3a442d14cbde91b6
27.333333
124
0.585098
4.569892
false
false
false
false
Foild/SugarRecord
spec/CoreData/CoreDataFetchResultsControllerTests.swift
1
2502
// // CoreDataFetchResultsControllerTests.swift // SugarRecord // // Created by Pedro Piñera Buendía on 06/10/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import XCTest import CoreData class CoreDataFetchResultsControllerTests: XCTestCase { var finder: SugarRecordFinder<NSManagedObject>? override func setUp() { super.setUp() let bundle: NSBundle = NSBundle(forClass: CoreDataObjectTests.classForCoder()) let modelPath: NSString = bundle.pathForResource("TestsDataModel", ofType: "momd")! let model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: modelPath as String))! let stack: DefaultCDStack = DefaultCDStack(databaseName: "TestDB.sqlite", model: model, automigrating: true) SugarRecord.addStack(stack) finder = SugarRecordFinder<NSManagedObject>() finder!.objectClass = CoreDataObject.self finder!.addSortDescriptor(NSSortDescriptor(key: "name", ascending: true)) finder!.setPredicate("name == test") finder!.elements = SugarRecordFinderElements.first } override func tearDown() { SugarRecord.cleanup() SugarRecord.removeDatabase() super.tearDown() } func testIfFetchedResultsControllerIsCalledWithNoCache() { let frc: NSFetchedResultsController = finder!.fetchedResultsController("name") XCTAssertNil(frc.cacheName, "Cahce name should be nil") } func testIfFetchedResultsControllerHasTheProperCache() { let frc: NSFetchedResultsController = finder!.fetchedResultsController("name", cacheName: "cachename") XCTAssertEqual(frc.cacheName!, "cachename", "The cache name should be: cachename") } func testIfTheFetchRequestPropertiesAreTheExpected() { let frc: NSFetchedResultsController = finder!.fetchedResultsController("name", cacheName: "cachename") XCTAssertEqual((frc.fetchRequest.sortDescriptors!.first! as NSSortDescriptor).key!, "name", "The sort descriptor key should be name") XCTAssertEqual((frc.fetchRequest.sortDescriptors!.first! as NSSortDescriptor).ascending, true, "The sort descriptor ascending should be true") XCTAssertEqual(frc.fetchRequest.predicate!.predicateFormat, "name == test", "The predicate format should be name == test") XCTAssertEqual(frc.fetchRequest.fetchLimit, 1, "The fetchLimit should be equal to 1") } }
mit
3623fb9504ab2c3267032a441f1a0041
41.389831
150
0.7152
5.252101
false
true
false
false
dreamsxin/swift
stdlib/public/core/CollectionOfOne.swift
1
4101
//===--- CollectionOfOne.swift - A Collection with one element ------------===// // // 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 // //===----------------------------------------------------------------------===// /// An iterator that produces one or fewer instances of `Element`. public struct IteratorOverOne<Element> : IteratorProtocol, Sequence { /// Construct an instance that generates `_element!`, or an empty /// sequence if `_element == nil`. public // @testable init(_elements: Element?) { self._elements = _elements } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. public mutating func next() -> Element? { let result = _elements _elements = nil return result } internal var _elements: Element? } /// A collection containing a single element of type `Element`. public struct CollectionOfOne<Element> : MutableCollection, RandomAccessCollection { /// Construct an instance containing just `element`. public init(_ element: Element) { self._element = element } public typealias Index = Int /// The position of the first element. public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one greater than the /// last valid subscript argument. /// /// In a `CollectionOfOne` instance, `endIndex` is always identical to /// `index(after: startIndex)`. public var endIndex: Int { return 1 } /// Always returns `endIndex`. public func index(after i: Int) -> Int { _precondition(i == startIndex) return endIndex } /// Always returns `startIndex`. public func index(before i: Int) -> Int { _precondition(i == endIndex) return startIndex } public typealias Indices = CountableRange<Int> /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> IteratorOverOne<Element> { return IteratorOverOne(_elements: _element) } /// Access the element at `position`. /// /// - Precondition: `position == 0`. public subscript(position: Int) -> Element { get { _precondition(position == 0, "Index out of range") return _element } set { _precondition(position == 0, "Index out of range") _element = newValue } } public subscript(bounds: Range<Int>) -> MutableRandomAccessSlice<CollectionOfOne<Element>> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return MutableRandomAccessSlice(base: self, bounds: bounds) } set { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) _precondition(bounds.count == newValue.count, "CollectionOfOne can't be resized") if let newElement = newValue.first { _element = newElement } } } /// The number of elements (always one). public var count: Int { return 1 } internal var _element: Element } extension CollectionOfOne : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return "CollectionOfOne(\(String(reflecting: _element)))" } } extension CollectionOfOne : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["element": _element]) } } @available(*, unavailable, renamed: "IteratorOverOne") public struct GeneratorOfOne<Element> {} extension IteratorOverOne { @available(*, unavailable, renamed: "makeIterator") public func generate() -> IteratorOverOne<Element> { Builtin.unreachable() } }
apache-2.0
0142414a3931e1b571cf949f82741985
27.678322
80
0.65862
4.501647
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MediaPicker/View/Controls/CameraControlsView.swift
1
8701
import JNWSpringAnimation import ImageSource import UIKit final class CameraControlsView: UIView, ThemeConfigurable { typealias ThemeType = MediaPickerRootModuleUITheme var onShutterButtonTap: (() -> ())? var onPhotoLibraryButtonTap: (() -> ())? var onCameraToggleButtonTap: (() -> ())? var onFlashToggle: ((Bool) -> ())? // MARK: - Subviews private let photoView = UIImageView() private let photoOverlayView = UIView() private let shutterButton = UIButton() private let cameraToggleButton = UIButton() private let flashButton = UIButton() // MARK: - Constants private let insets = UIEdgeInsets(top: 4, left: 16, bottom: 4, right: 16) private let shutterButtonMinDiameter = CGFloat(44) private let shutterButtonMaxDiameter = CGFloat(64) private let photoViewDiameter = CGFloat(44) private var photoViewPlaceholder: UIImage? // Параметры анимации кнопки съемки (подобраны ikarpov'ым) private let shutterAnimationMinScale = CGFloat(0.842939) private let shutterAnimationDamping = CGFloat(18.6888) private let shutterAnimationStiffness = CGFloat(366.715) private let shutterAnimationMass = CGFloat(0.475504) // MARK: - UIView override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white photoView.backgroundColor = .lightGray photoView.contentMode = .scaleAspectFill photoView.layer.cornerRadius = photoViewDiameter / 2 photoView.clipsToBounds = true photoView.isUserInteractionEnabled = true photoView.addGestureRecognizer(UITapGestureRecognizer( target: self, action: #selector(onPhotoViewTap(_:)) )) photoOverlayView.backgroundColor = .black photoOverlayView.alpha = 0.04 photoOverlayView.layer.cornerRadius = photoViewDiameter / 2 photoOverlayView.clipsToBounds = true photoOverlayView.isUserInteractionEnabled = false shutterButton.backgroundColor = .blue shutterButton.clipsToBounds = false shutterButton.addTarget( self, action: #selector(onShutterButtonTouchDown(_:)), for: .touchDown ) shutterButton.addTarget( self, action: #selector(onShutterButtonTouchUp(_:)), for: .touchUpInside ) flashButton.addTarget( self, action: #selector(onFlashButtonTap(_:)), for: .touchUpInside ) cameraToggleButton.addTarget( self, action: #selector(onCameraToggleButtonTap(_:)), for: .touchUpInside ) addSubview(photoView) addSubview(photoOverlayView) addSubview(shutterButton) addSubview(flashButton) addSubview(cameraToggleButton) setUpAccessibilityIdentifiers() } private func setUpAccessibilityIdentifiers() { photoView.setAccessibilityId(.photoView) shutterButton.setAccessibilityId(.shutterButton) cameraToggleButton.setAccessibilityId(.cameraToggleButton) flashButton.setAccessibilityId(.flashButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let contentHeight = bounds.inset(by: insets).size.height let shutterButtonDiameter = max(shutterButtonMinDiameter, min(shutterButtonMaxDiameter, contentHeight)) let shutterButtonSize = CGSize(width: shutterButtonDiameter, height: shutterButtonDiameter) let centerY = bounds.centerY shutterButton.frame = CGRect(origin: .zero, size: shutterButtonSize) shutterButton.center = CGPoint(x: bounds.midX, y: centerY) shutterButton.layer.cornerRadius = shutterButtonDiameter / 2 flashButton.size = CGSize.minimumTapAreaSize flashButton.centerX = bounds.right - 30 flashButton.centerY = centerY cameraToggleButton.size = CGSize.minimumTapAreaSize cameraToggleButton.centerX = flashButton.centerX - 54 cameraToggleButton.centerY = flashButton.centerY photoView.size = CGSize(width: photoViewDiameter, height: photoViewDiameter) photoView.left = bounds.left + insets.left photoView.centerY = centerY photoOverlayView.frame = photoView.frame } // MARK: - CameraControlsView func setControlsTransform(_ transform: CGAffineTransform) { flashButton.transform = transform cameraToggleButton.transform = transform photoView.transform = transform } func setLatestPhotoLibraryItemImage(_ imageSource: ImageSource?) { photoView.setImage( fromSource: imageSource, size: CGSize(width: photoViewDiameter, height: photoViewDiameter), placeholder: photoViewPlaceholder, placeholderDeferred: false ) } func setCameraControlsEnabled(_ enabled: Bool) { shutterButton.isEnabled = enabled cameraToggleButton.isEnabled = enabled flashButton.isEnabled = enabled adjustShutterButtonColor() } func setFlashButtonVisible(_ visible: Bool) { flashButton.isHidden = !visible } func setFlashButtonOn(_ isOn: Bool) { flashButton.isSelected = isOn } func setCameraToggleButtonVisible(_ visible: Bool) { cameraToggleButton.isHidden = !visible } func setShutterButtonEnabled(_ enabled: Bool) { shutterButton.isEnabled = enabled } func setPhotoLibraryButtonEnabled(_ enabled: Bool) { photoView.isUserInteractionEnabled = enabled } func setPhotoLibraryButtonVisible(_ visible: Bool) { photoOverlayView.isHidden = !visible photoView.isHidden = !visible } // MARK: - ThemeConfigurable func setTheme(_ theme: ThemeType) { self.theme = theme backgroundColor = theme.cameraControlsViewBackgroundColor flashButton.setImage(theme.flashOffIcon, for: .normal) flashButton.setImage(theme.flashOnIcon, for: .selected) cameraToggleButton.setImage(theme.cameraToggleIcon, for: .normal) photoViewPlaceholder = theme.photoPeepholePlaceholder adjustShutterButtonColor() } // MARK: - Private private var theme: MediaPickerRootModuleUITheme? @objc private func onShutterButtonTouchDown(_ button: UIButton) { animateShutterButtonToScale(shutterAnimationMinScale) } @objc private func onShutterButtonTouchUp(_ button: UIButton) { animateShutterButtonToScale(1) onShutterButtonTap?() } @objc private func onPhotoViewTap(_ tapRecognizer: UITapGestureRecognizer) { onPhotoLibraryButtonTap?() } @objc private func onFlashButtonTap(_ button: UIButton) { button.isSelected = !button.isSelected onFlashToggle?(button.isSelected) } @objc private func onCameraToggleButtonTap(_ button: UIButton) { onCameraToggleButtonTap?() } private func animateShutterButtonToScale(_ scale: CGFloat) { // Тут пишут о том, чем стандартная spring-анимация плоха: // https://medium.com/@flyosity/your-spring-animations-are-bad-and-it-s-probably-apple-s-fault-784932e51733#.jr5m2x2vl let keyPath = "transform.scale" guard let animation = JNWSpringAnimation(keyPath: keyPath) else { shutterButton.transform = CGAffineTransform(scaleX: scale, y: scale) return } animation.damping = shutterAnimationDamping animation.stiffness = shutterAnimationStiffness animation.mass = shutterAnimationMass let layer = shutterButton.layer.presentation() ?? shutterButton.layer animation.fromValue = layer.value(forKeyPath: keyPath) animation.toValue = scale shutterButton.layer.setValue(animation.toValue, forKeyPath: keyPath) shutterButton.layer.add(animation, forKey: keyPath) } private func adjustShutterButtonColor() { shutterButton.backgroundColor = shutterButton.isEnabled ? theme?.shutterButtonColor : theme?.shutterButtonDisabledColor } }
mit
05baa2143f239de145187bb0b5e1f22d
32.679688
127
0.654025
5.332096
false
false
false
false
DanielAsher/SwiftCheck
SwiftCheck/Random.swift
3
5930
// // Random.swift // SwiftCheck // // Created by Robert Widmann on 8/3/14. // Copyright (c) 2015 TypeLift. All rights reserved. // import func Darwin.time import func Darwin.rand /// Provides a standard interface to an underlying Random Value Generator of any type. It is /// analogous to `GeneratorType`, but rather than consume a sequence it uses sources of randomness /// to generate values indefinitely. public protocol RandomGeneneratorType { /// The next operation returns an Int that is uniformly distributed in the range returned by /// `genRange` (including both end points), and a new generator. var next : (Int, Self) { get } /// The genRange operation yields the range of values returned by the generator. /// /// This property must return integers in ascending order. var genRange : (Int, Int) { get } /// Splits the receiver into two distinct random value generators. var split : (Self, Self) { get } } /// A library-provided standard random number generator. public let standardRNG : StdGen = StdGen(time(nil)) public struct StdGen : RandomGeneneratorType { let seed: Int init(_ seed : Int) { self.seed = seed } public var next : (Int, StdGen) { let s = Int(time(nil)) return (Int(rand()), StdGen(s)) } public var split : (StdGen, StdGen) { let (s1, g) = self.next let (s2, _) = g.next return (StdGen(s1), StdGen(s2)) } public var genRange : (Int, Int) { return (Int.min, Int.max) } } public func newStdGen() -> StdGen { return standardRNG.split.1 } private func mkStdRNG(seed : Int) -> StdGen { return StdGen(seed) } /// Types that can generate random versions of themselves. public protocol RandomType { static func randomInRange<G : RandomGeneneratorType>(range : (Self, Self), gen : G) -> (Self, G) } /// Generates a random value from a LatticeType random type. public func random<A : protocol<LatticeType, RandomType>, G : RandomGeneneratorType>(gen : G) -> (A, G) { return A.randomInRange((A.min, A.max), gen: gen) } extension Character : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Character, Character), gen : G) -> (Character, G) { let (min, max) = range let minc = String(min).unicodeScalars.first! let maxc = String(max).unicodeScalars.first! let (val, gg) = UnicodeScalar.randomInRange((minc, maxc), gen: gen) return (Character(val), gg) } } extension UnicodeScalar : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UnicodeScalar, UnicodeScalar), gen : G) -> (UnicodeScalar, G) { let (val, gg) = UInt32.randomInRange((range.0.value, range.1.value), gen: gen) return (UnicodeScalar(val), gg) } } extension Int : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Int, Int), gen : G) -> (Int, G) { let (min, max) = range let (r, g) = gen.next let result = (r % ((max + 1) - min)) + min; return (result, g); } } extension Int8 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Int8, Int8), gen : G) -> (Int8, G) { let (min, max) = range let (r, g) = gen.next let result = (r % ((max + 1) - min)) + min; return (result, g); } } extension Int16 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Int16, Int16), gen : G) -> (Int16, G) { let (min, max) = range let (r, g) = gen.next let result = (r % ((max + 1) - min)) + min; return (result, g); } } extension Int32 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Int32, Int32), gen : G) -> (Int32, G) { let (min, max) = range let (r, g) = gen.next let result = (r % ((max + 1) - min)) + min; return (result, g); } } extension Int64 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Int64, Int64), gen : G) -> (Int64, G) { let (min, max) = range let (r, g) = gen.next let result = (r % ((max + 1) - min)) + min; return (result, g); } } extension UInt : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UInt, UInt), gen : G) -> (UInt, G) { let (min, max) = range let (r, g) = gen.next let result = (UInt(r) % ((max + 1) - min)) + min; return (result, g); } } extension UInt8 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UInt8, UInt8), gen : G) -> (UInt8, G) { let (min, max) = range let (r, g) = gen.next let result = (UInt8(r) % ((max + 1) - min)) + min; return (result, g); } } extension UInt16 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UInt16, UInt16), gen : G) -> (UInt16, G) { let (min, max) = range let (r, g) = gen.next let result = (UInt16(r) % ((max + 1) - min)) + min; return (result, g); } } extension UInt32 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UInt32, UInt32), gen : G) -> (UInt32, G) { let (min, max) = range let (r, g) = gen.next let result = (UInt32(r) % ((max + 1) - min)) + min; return (result, g); } } extension UInt64 : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (UInt64, UInt64), gen : G) -> (UInt64, G) { let (min, max) = range let (r, g) = gen.next let result = (UInt64(r) % ((max + 1) - min)) + min; return (result, g); } } extension Float : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Float, Float), gen : G) -> (Float, G) { let (min, max) = range let (r, g) = gen.next let fr = Float(r) let result = (fr % ((max + 1) - min)) + min; return (result, g); } } extension Double : RandomType { public static func randomInRange<G : RandomGeneneratorType>(range : (Double, Double), gen : G) -> (Double, G) { let (min, max) = range let (r, g) = gen.next let dr = Double(r) let result = (dr % ((max + 1) - min)) + min; return (result, g); } }
mit
14bb4ddca0461485932142151d4db5f8
27.373206
133
0.646374
2.92695
false
false
false
false
slavapestov/swift
test/SILGen/objc_enum.swift
4
2077
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen > %t.out // RUN: FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out // RUN: FileCheck -check-prefix=NEGATIVE %s < %t.out // REQUIRES: objc_interop import gizmo // CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsC // CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg8rawValueSi // CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg9hashValueSi // Non-payload enum ctors don't need to be instantiated at all. // NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions5MinceFMS_S_ // NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions12QuinceSlicedFMS_S_ // NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions15QuinceJuliennedFMS_S_ // NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions11QuinceDicedFMS_S_ var runcing: NSRuncingOptions = .Mince var raw = runcing.rawValue var eq = runcing == .QuinceSliced var hash = runcing.hashValue func testEm<E: Equatable>(x: E, _ y: E) {} func hashEm<H: Hashable>(x: H) {} func rawEm<R: RawRepresentable>(x: R) {} testEm(NSRuncingOptions.Mince, .QuinceSliced) hashEm(NSRuncingOptions.Mince) rawEm(NSRuncingOptions.Mince) rawEm(NSFungingMask.Asset) protocol Bub {} extension NSRuncingOptions: Bub {} // CHECK-32-DAG: integer_literal $Builtin.Int2048, -2147483648 // CHECK-64-DAG: integer_literal $Builtin.Int2048, 2147483648 _ = NSFungingMask.ToTheMax // CHECK-DAG: sil_witness_table shared NSRuncingOptions: RawRepresentable module gizmo // CHECK-DAG: sil_witness_table shared NSRuncingOptions: Equatable module gizmo // CHECK-DAG: sil_witness_table shared NSRuncingOptions: Hashable module gizmo // CHECK-DAG: sil_witness_table shared NSFungingMask: RawRepresentable module gizmo // CHECK-DAG: sil shared [transparent] [thunk] @_TTWOSC16NSRuncingOptionss16RawRepresentable5gizmoFS0_C // Extension conformances get linkage according to the protocol's accessibility, as normal. // CHECK-DAG: sil_witness_table hidden NSRuncingOptions: Bub module objc_enum
apache-2.0
093bd078242d6bc80b9593be5045d8fe
38.942308
105
0.776601
3.371753
false
false
false
false
exevil/Keys-For-Sketch
Source/Menu/MenuObserver.swift
1
2894
// // MenuObserver.swift // KeysForSketch // // Created by Vyacheslav Dubovitsky on 04/04/2017. // Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved. // public class MenuObserver : NSObject { @objc public static let shared = MenuObserver() let notificationCenter = NotificationCenter.default @objc public func startObserving() { notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didAddItemNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didChangeItemNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didChangeItemNotification, object: nil) } @objc public func stopObserving() { notificationCenter.removeObserver(self, name: NSMenu.didAddItemNotification, object: nil) notificationCenter.removeObserver(self, name: NSMenu.didChangeItemNotification, object: nil) notificationCenter.removeObserver(self, name: NSMenu.didChangeItemNotification, object: nil) } /// Handle received notifications. @objc func received(notification: NSNotification) { let menu = notification.object as? NSMenu // let itemIndex = notification.userInfo?["NSMenuItemIndex"] as? Int ?? -1 // let menuItem = menu?.item(at: itemIndex) if menu?.isChildOf(Const.Menu.main) ?? false { // Reload outlineView for superitem if needed. if ViewController.initialized != nil { self.cancelPreviousPerformRequiestsAndPerform(#selector(self.reloadOutlineViewItem(for:)), with: menu, afterDelay: 0.5) } // Provide debug info based on notification type switch notification.name { case NSMenu.didAddItemNotification: // inDebug { print("Did add menuItem: '\(menu?.title ?? "") -> \(menuItem?.title ?? "")' (index: \(itemIndex))") } break case NSMenu.didChangeItemNotification: // inDebug { print("Did change menuItem: '\(menu?.title ?? "") -> \(menuItem?.title ?? "")' (index: \(itemIndex))") } break case NSMenu.didRemoveItemNotification: // inDebug { print("Did remove menuItem from Menu '\(menu?.title ?? "")' at index \(itemIndex)") } break default: assertionFailure("Unexpected notification type.") } } } /// Reload ViewController's Outline View item for given menu if needed. @objc func reloadOutlineViewItem(for menu: NSMenu?) { if let superItem = menu?.superitem { ViewController.initialized?.outlineView.reloadItem(superItem, reloadChildren: true) } } }
mit
003223a59e8699d93c83d9edcd701bac
45.66129
143
0.642931
5.013865
false
false
false
false
cuappdev/podcast-ios
old/Podcast/PlayerControlsView.swift
1
11037
// // PlayerControlsView.swift // Podcast // // Created by Mark Bryan on 2/12/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit protocol PlayerControlsDelegate: class { func playerControlsDidTapPlayPauseButton() func playerControlsDidTapSkipForward() func playerControlsDidTapSkipBackward() func playerControlsDidTapSettingsButton() func playerControlsDidTapSpeed() func playerControlsDidSkipNext() func playerControlsDidScrub() func playerControlsDidEndScrub() func playerControlsDidTapMoreButton() func playerControlsDidTapRecommendButton() } class PlayerControlsView: UIView { let sliderHeight: CGFloat = 1.5 let marginSpacing: CGFloat = 24.5 let playerControlsViewHeight: CGFloat = 200 let playPauseButtonSize: CGSize = CGSize(width: 96, height: 96.5) let playPauseButtonWidthMultiplier: CGFloat = 0.21 let playPauseButtonTopOffset: CGFloat = 40.0 let skipButtonSize: CGSize = CGSize(width: 56.5, height: 20) let skipButtonWidthMultiplier: CGFloat = 0.15 let skipButtonHeightMultiplier: CGFloat = 0.354 let skipButtonSpacing: CGFloat = 40.5 let skipForwardSpacing: CGFloat = 17.5 let skipBackwardSpacing: CGFloat = 15 let skipButtonTopOffset: CGFloat = 60 let sliderTopOffset: CGFloat = 26.5 let sliderYInset: CGFloat = 132 let timeLabelSpacing: CGFloat = 8 let buttonsYInset: CGFloat = 181.5 let nextButtonSize: CGSize = CGSize(width: 12.5, height: 13) let nextButtonLeftOffset: CGFloat = 29 let nextButtonTopOffset: CGFloat = 65.1 let recommendButtonSize: CGSize = CGSize(width: 80, height: 18) let moreButtonSize: CGSize = CGSize(width: 35, height: 28) let speedButtonSize: CGSize = CGSize(width: 40, height: 18) let settingsButtonSize: CGFloat = 22 let moreButtonBottomOffset: CGFloat = 19.5 let moreButtonTrailingSpacing: CGFloat = 14.5 var slider: UISlider! var playPauseButton: UIButton! var forwardsButton: UIButton! var backwardsButton: UIButton! var rightTimeLabel: UILabel! var leftTimeLabel: UILabel! var recommendButton: FillNumberButton! var moreButton: MoreButton! var nextButton: UIButton! var speedButton: UIButton! var settingsButton: UIButton! weak var delegate: PlayerControlsDelegate? override init(frame: CGRect) { super.init(frame: frame) self.frame.size.height = playerControlsViewHeight backgroundColor = .clear slider = Slider() slider.setThumbImage(#imageLiteral(resourceName: "oval"), for: .normal) slider.minimumTrackTintColor = .sea slider.maximumTrackTintColor = .silver addSubview(slider) slider.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(marginSpacing) make.top.equalToSuperview().offset(sliderTopOffset) make.height.equalTo(sliderHeight) } slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged) slider.addTarget(self, action: #selector(endScrubbing), for: .touchUpInside) slider.addTarget(self, action: #selector(endScrubbing), for: .touchUpOutside) leftTimeLabel = UILabel(frame: .zero) leftTimeLabel.font = ._12RegularFont() leftTimeLabel.textColor = .slateGrey leftTimeLabel.textAlignment = .left addSubview(leftTimeLabel) rightTimeLabel = UILabel(frame: .zero) rightTimeLabel.font = ._12RegularFont() rightTimeLabel.textColor = .slateGrey rightTimeLabel.textAlignment = .right addSubview(rightTimeLabel) playPauseButton = UIButton(frame: .zero) playPauseButton.adjustsImageWhenHighlighted = false playPauseButton.setBackgroundImage(#imageLiteral(resourceName: "pause"), for: .selected) playPauseButton.setBackgroundImage(#imageLiteral(resourceName: "play"), for: .normal) playPauseButton.addTarget(self, action: #selector(playPauseButtonPress), for: .touchUpInside) addSubview(playPauseButton) playPauseButton.snp.makeConstraints { make in make.width.equalToSuperview().multipliedBy(playPauseButtonWidthMultiplier) make.height.equalTo(playPauseButton.snp.width) make.centerX.equalToSuperview() make.top.equalTo(slider.snp.bottom).offset(playPauseButtonTopOffset) } forwardsButton = Button() forwardsButton.setBackgroundImage(#imageLiteral(resourceName: "forward30"), for: .normal) forwardsButton.adjustsImageWhenHighlighted = false forwardsButton.addTarget(self, action: #selector(forwardButtonPress), for: .touchUpInside) addSubview(forwardsButton) forwardsButton.snp.makeConstraints { make in make.width.equalToSuperview().multipliedBy(skipButtonWidthMultiplier) make.height.equalTo(forwardsButton.snp.width).multipliedBy(skipButtonHeightMultiplier) make.top.equalTo(slider.snp.bottom).offset(skipButtonTopOffset) make.leading.equalTo(playPauseButton.snp.trailing).offset(skipForwardSpacing) } speedButton = Button() speedButton.setTitleColor(.slateGrey, for: .normal) speedButton.contentHorizontalAlignment = .left speedButton.titleLabel?.font = ._14SemiboldFont() speedButton.addTarget(self, action: #selector(speedButtonPress), for: .touchUpInside) addSubview(speedButton) speedButton.snp.makeConstraints { make in make.size.equalTo(speedButtonSize) make.leading.equalTo(slider.snp.leading) make.centerY.equalTo(forwardsButton.snp.centerY) } settingsButton = Button() settingsButton.setImage(#imageLiteral(resourceName: "settingsButton"), for: .normal) settingsButton.addTarget(self, action: #selector(settingsButtonPress), for: .touchUpInside) addSubview(settingsButton) settingsButton.snp.makeConstraints { make in make.size.equalTo(settingsButtonSize) make.centerY.equalTo(forwardsButton.snp.centerY) make.trailing.equalTo(slider.snp.trailing) } settingsButton.isHidden = false // TODO: change when we add settings to player backwardsButton = Button() backwardsButton.setBackgroundImage(#imageLiteral(resourceName: "back30"), for: .normal) backwardsButton.adjustsImageWhenHighlighted = false backwardsButton.addTarget(self, action: #selector(backwardButtonPress), for: .touchUpInside) addSubview(backwardsButton) backwardsButton.snp.makeConstraints { make in make.width.equalToSuperview().multipliedBy(skipButtonWidthMultiplier) make.height.equalTo(forwardsButton.snp.width).multipliedBy(skipButtonHeightMultiplier) make.centerY.equalTo(forwardsButton.snp.centerY) make.trailing.equalTo(playPauseButton.snp.leading).offset(0 - skipForwardSpacing) } recommendButton = FillNumberButton(type: .recommend) recommendButton.frame = CGRect(x: marginSpacing, y: self.frame.maxY - buttonsYInset, width: recommendButtonSize.width, height: recommendButtonSize.height) recommendButton.addTarget(self, action: #selector(recommendButtonTapped), for: .touchUpInside) nextButton = UIButton(frame: .zero) nextButton.setBackgroundImage(#imageLiteral(resourceName: "next"), for: .normal) nextButton.adjustsImageWhenHighlighted = false nextButton.addTarget(self, action: #selector(nextButtonPress), for: .touchUpInside) addSubview(nextButton) nextButton.snp.makeConstraints { make in make.size.equalTo(nextButtonSize) make.centerY.equalTo(forwardsButton.snp.centerY) make.trailing.equalTo(slider.snp.trailing) } nextButton.isHidden = true // Remove this once we implement a queue moreButton = MoreButton() moreButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) // increase edge insets for larger touch radius moreButton.addTarget(self, action: #selector(moreButtonTapped), for: .touchUpInside) addSubview(moreButton) moreButton.snp.makeConstraints { make in make.size.equalTo(moreButtonSize) make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).inset(moreButtonBottomOffset) make.trailing.equalToSuperview().inset(moreButtonTrailingSpacing) } leftTimeLabel.snp.makeConstraints { make in make.leading.equalToSuperview().offset(marginSpacing) make.top.equalTo(slider.snp.bottom).offset(timeLabelSpacing) } rightTimeLabel.snp.makeConstraints { make in make.trailing.equalToSuperview().inset(marginSpacing) make.top.equalTo(leftTimeLabel.snp.top) } updateUI(isPlaying: false, elapsedTime: "0:00", timeLeft: "0:00", progress: 0.0, isScrubbing: false, rate: .one) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateUI(isPlaying: Bool, elapsedTime: String, timeLeft: String, progress: Float, isScrubbing: Bool, rate: PlayerRate) { playPauseButton.isSelected = isPlaying if !isScrubbing { slider.value = progress } speedButton.setTitle(rate.toString(), for: .normal) leftTimeLabel.text = elapsedTime rightTimeLabel.text = timeLeft leftTimeLabel.sizeToFit() rightTimeLabel.sizeToFit() } @objc func playPauseButtonPress() { playPauseButton.isSelected = !playPauseButton.isSelected delegate?.playerControlsDidTapPlayPauseButton() } @objc func forwardButtonPress() { delegate?.playerControlsDidTapSkipForward() } @objc func backwardButtonPress() { delegate?.playerControlsDidTapSkipBackward() } @objc func endScrubbing() { delegate?.playerControlsDidEndScrub() } @objc func sliderValueChanged() { delegate?.playerControlsDidScrub() } @objc func speedButtonPress() { delegate?.playerControlsDidTapSpeed() } @objc func nextButtonPress() { delegate?.playerControlsDidSkipNext() } @objc func moreButtonTapped() { delegate?.playerControlsDidTapMoreButton() } @objc func recommendButtonTapped() { delegate?.playerControlsDidTapRecommendButton() } @objc func settingsButtonPress() { delegate?.playerControlsDidTapSettingsButton() } func setRecommendButtonToState(isRecommended: Bool, numberOfRecommendations: Int) { recommendButton.setupWithNumber(isSelected: isRecommended, numberOf: numberOfRecommendations) } }
mit
8f90162a76525f535b3dd11ddd2526f8
41.283525
162
0.691827
4.966697
false
false
false
false
evnaz/Design-Patterns-In-Swift
Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift
2
530
/*: 设计模式(Swift 5.0 实现) ====================== ([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)). 👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。 🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。 ## 目录 * [行为型模式](Behavioral) * [创建型模式](Creational) * [结构型模式](Structural) */ import Foundation print("您好!")
gpl-3.0
ca7529d4700c1f35d4e76b157c91a815
20.65
148
0.674365
2.624242
false
false
false
false
ESGIProjects/SwifTools
SwifTools/SwifTools/STConstraints.swift
1
5455
// // STConstraints.swift // SwifTools // // Created by Jason Pierna on 27/01/2017. // Copyright © 2017 Jason Pierna & Kévin Le. All rights reserved. // import UIKit public class STConstraints { /** * Enumerates the possible side of a constraint. */ public enum Sides { case left, right, top, bottom, leading, trailing } /** * Enumerates both size axis. */ public enum Sizes { case width, height } /** Creates a size constraint on the selected view. - parameter view: The view to constraint - parameter sizes: The desired axis - parameter value: The size value */ public static func addSizeConstraints(view: UIView, sizes: [STConstraints.Sizes], value: CGFloat) { view.translatesAutoresizingMaskIntoConstraints = false for size in sizes { switch size { case .width: view.widthAnchor.constraint(equalToConstant: value).isActive = true case .height: view.heightAnchor.constraint(equalToConstant: value).isActive = true } } } /** Creates a constraint between a view and one of its parent. - parameter parent: The view's parent - parameter child: The view ton constraint - parameter sides: The side to constraint - parameter constant: The distance between both views. */ public static func addConstraints(parent firstView: UIView, child secondView: UIView, sides: [STConstraints.Sides], constant: CGFloat) { firstView.translatesAutoresizingMaskIntoConstraints = false secondView.translatesAutoresizingMaskIntoConstraints = false for side in sides { switch side { case .left: applyXAxis(first: firstView.leftAnchor, second: secondView.leftAnchor, constant: constant) case .right: applyXAxis(first: firstView.rightAnchor, second: secondView.rightAnchor, constant: constant) case .leading: applyXAxis(first: firstView.leadingAnchor, second: secondView.leadingAnchor, constant: -constant) case .trailing: applyXAxis(first: firstView.trailingAnchor, second: secondView.trailingAnchor, constant: constant) case .top: applyYAxis(first: firstView.topAnchor, second: secondView.topAnchor, constant: -constant) case .bottom: applyYAxis(first: firstView.bottomAnchor, second: secondView.bottomAnchor, constant: constant) } } } /** Creates a constraint between a view and one of its parent. The constant is 0 by default. - parameter parent: The view's parent - parameter child: The view to constraint - parameter sides: The side to constraint */ public static func addConstraints(parent firstView: UIView, child secondView: UIView, sides: [STConstraints.Sides]) { addConstraints(parent: firstView, child: secondView, sides: sides, constant: 0) } /** Creates a constraint between two child views. The constant is 0 by default. - parameter parent: The first view. - parameter child: The second view. - parameter sides: The side to constraint (relative to the first view) */ public static func addConstraints(between firstView: UIView, and secondView: UIView, sides: [STConstraints.Sides]) { addConstraints(between: firstView, and: secondView, sides: sides, constant: 0) } /** Creates a constraint between two child views. - parameter parent: The first view. - parameter child: The second view. - parameter sides: The side to constraint (relative to the first view) - parameter constant: The distance between both views. */ public static func addConstraints(between firstView: UIView, and secondView: UIView, sides: [STConstraints.Sides], constant: CGFloat) { firstView.translatesAutoresizingMaskIntoConstraints = false secondView.translatesAutoresizingMaskIntoConstraints = false for side in sides { switch side { case .left: applyXAxis(first: firstView.leftAnchor, second: secondView.rightAnchor, constant: constant) case .right: applyXAxis(first: firstView.rightAnchor, second: secondView.leftAnchor, constant: -constant) case .leading: applyXAxis(first: firstView.leadingAnchor, second: secondView.trailingAnchor, constant: constant) case .trailing: applyXAxis(first: firstView.trailingAnchor, second: secondView.leadingAnchor, constant: constant) case .top: applyYAxis(first: firstView.topAnchor, second: secondView.bottomAnchor, constant: constant) case .bottom: applyYAxis(first: firstView.bottomAnchor, second: secondView.topAnchor, constant: -constant) } } } private static func applyXAxis(first: NSLayoutXAxisAnchor, second: NSLayoutXAxisAnchor, constant: CGFloat) { first.constraint(equalTo: second, constant: constant).isActive = true } private static func applyYAxis(first: NSLayoutYAxisAnchor, second: NSLayoutYAxisAnchor, constant: CGFloat) { first.constraint(equalTo: second, constant: constant).isActive = true } }
bsd-3-clause
540ab37ebfd734350dcef93d6326c490
40.625954
140
0.653952
5.193333
false
false
false
false
zhuozhuo/ZHChat
SwiftExample/ZHChatSwift/ZHCDemoMessagesViewController.swift
1
11530
// // ZHCDemoMessagesViewController.swift // ZHChatSwift // // Created by aimoke on 16/12/16. // Copyright © 2016年 zhuo. All rights reserved. // import UIKit import ZHChat class ZHCDemoMessagesViewController: ZHCMessagesViewController { var demoData: ZHModelData = ZHModelData.init(); var presentBool: Bool = false; override func viewDidLoad() { super.viewDidLoad() demoData.loadMessages(); self.title = "ZHCMessages"; if self.automaticallyScrollsToMostRecentMessage { self.scrollToBottom(animated: false); } // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); if self.presentBool { self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action:#selector(closePressed)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func closePressed() -> Void { self.navigationController?.dismiss(animated: true, completion: nil); } // MARK: ZHCMessagesTableViewDataSource override func senderDisplayName() -> String { return kZHCDemoAvatarDisplayNameJobs; } override func senderId() -> String { return kZHCDemoAvatarIdJobs; } override func tableView(_ tableView: ZHCMessagesTableView, messageDataForCellAt indexPath: IndexPath) -> ZHCMessageData { return self.demoData.messages.object(at: indexPath.row) as! ZHCMessageData; } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { self.demoData.messages.removeObject(at: indexPath.row); } override func tableView(_ tableView: ZHCMessagesTableView, messageBubbleImageDataForCellAt indexPath: IndexPath) -> ZHCMessageBubbleImageDataSource? { /** * You may return nil here if you do not want bubbles. * In this case, you should set the background color of your TableView view cell's textView. * * Otherwise, return your previously created bubble image data objects. */ let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage; if message.isMediaMessage { print("is mediaMessage"); } if message.senderId == self.senderId() { return self.demoData.outgoingBubbleImageData; } return self.demoData.incomingBubbleImageData; } override func tableView(_ tableView: ZHCMessagesTableView, avatarImageDataForCellAt indexPath: IndexPath) -> ZHCMessageAvatarImageDataSource? { /** * Return your previously created avatar image data objects. * * Note: these the avatars will be sized according to these values: * * Override the defaults in `viewDidLoad` */ let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage; return self.demoData.avatars.object(forKey: message.senderId) as! ZHCMessageAvatarImageDataSource?; } override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForCellTopLabelAt indexPath: IndexPath) -> NSAttributedString? { /** * This logic should be consistent with what you return from `heightForCellTopLabelAtIndexPath:` * The other label text delegate methods should follow a similar pattern. * * Show a timestamp for every 3rd message */ if (indexPath.row%3==0) { let message: ZHCMessage = (self.demoData.messages.object(at: indexPath.row) as? ZHCMessage)!; return ZHCMessagesTimestampFormatter.shared().attributedTimestamp(for: message.date); } return nil; } override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath) -> NSAttributedString? { let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage; if message.senderId == self.senderId(){ return nil; } if (indexPath.row-1)>0 { let preMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row-1) as! ZHCMessage; if preMessage.senderId == message.senderId{ return nil; } } return NSAttributedString.init(string: message.senderDisplayName); } override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForCellBottomLabelAt indexPath: IndexPath) -> NSAttributedString? { return nil; } // MARK: Adjusting cell label heights override func tableView(_ tableView: ZHCMessagesTableView, heightForCellTopLabelAt indexPath: IndexPath) -> CGFloat { /** * Each label in a cell has a `height` delegate method that corresponds to its text dataSource method */ /** * This logic should be consistent with what you return from `attributedTextForCellTopLabelAtIndexPath:` * The other label height delegate methods should follow similarly * * Show a timestamp for every 3rd message */ var labelHeight = 0.0; if indexPath.row%3 == 0 { labelHeight = Double(kZHCMessagesTableViewCellLabelHeightDefault); } return CGFloat(labelHeight); } override func tableView(_ tableView: ZHCMessagesTableView, heightForMessageBubbleTopLabelAt indexPath: IndexPath) -> CGFloat { var labelHeight = kZHCMessagesTableViewCellLabelHeightDefault; let currentMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage; if currentMessage.senderId==self.senderId(){ labelHeight = 0.0; } if ((indexPath.row - 1) > 0){ let previousMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row-1) as! ZHCMessage; if (previousMessage.senderId == currentMessage.senderId) { labelHeight = 0.0; } } return CGFloat(labelHeight); } override func tableView(_ tableView: ZHCMessagesTableView, heightForCellBottomLabelAt indexPath: IndexPath) -> CGFloat { let string: NSAttributedString? = self.tableView(tableView, attributedTextForCellBottomLabelAt: indexPath); if ((string) != nil) { return CGFloat(kZHCMessagesTableViewCellSpaceDefault); }else{ return 0.0; } } //MARK: ZHCMessagesTableViewDelegate override func tableView(_ tableView: ZHCMessagesTableView, didTapAvatarImageView avatarImageView: UIImageView, at indexPath: IndexPath) { super.tableView(tableView, didTapAvatarImageView: avatarImageView, at: indexPath); } override func tableView(_ tableView: ZHCMessagesTableView, didTapMessageBubbleAt indexPath: IndexPath) { super.tableView(tableView, didTapMessageBubbleAt: indexPath); } override func tableView(_ tableView: ZHCMessagesTableView, performAction action: Selector, forcellAt indexPath: IndexPath, withSender sender: Any?) { super.tableView(tableView, performAction: action, forcellAt: indexPath, withSender: sender); } //MARK:TableView datasource override func numberOfSections(in tableView: UITableView) -> Int { return 1; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.demoData.messages.count; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ZHCMessagesTableViewCell = super.tableView(tableView, cellForRowAt: indexPath) as! ZHCMessagesTableViewCell; self.configureCell(cell, atIndexPath: indexPath); return cell; } //MARK:Configure Cell Data func configureCell(_ cell: ZHCMessagesTableViewCell, atIndexPath indexPath: IndexPath) -> Void { let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage; if !message.isMediaMessage { if (message.senderId == self.senderId()) { cell.textView?.textColor = UIColor.black; }else{ cell.textView?.textColor = UIColor.white; } } } //MARK: Messages view controller override func didPressSend(_ button: UIButton?, withMessageText text: String, senderId: String, senderDisplayName: String, date: Date) { /** * Sending a message. Your implementation of this method should do *at least* the following: * * 1. Play sound (optional) * 2. Add new id<ZHCMessageData> object to your data source * 3. Call `finishSendingMessage` */ let message: ZHCMessage = ZHCMessage.init(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text); self.demoData.messages.add(message); self.finishSendingMessage(animated: true); } //MARK: ZHCMessagesInputToolbarDelegate override func messagesInputToolbar(_ toolbar: ZHCMessagesInputToolbar, sendVoice voiceFilePath: String, seconds senconds: TimeInterval) { let audioData: NSData = try!NSData.init(contentsOfFile: voiceFilePath); let audioItem: ZHCAudioMediaItem = ZHCAudioMediaItem.init(data: audioData as Data); let audioMessage: ZHCMessage = ZHCMessage.init(senderId: self.senderId(), displayName: self.senderDisplayName(), media: audioItem); self.demoData.messages.add(audioMessage); self.finishSendingMessage(animated: true); } //MARK: ZHCMessagesMoreViewDelegate override func messagesMoreView(_ moreView: ZHCMessagesMoreView, selectedMoreViewItemWith index: Int) { switch index { case 0://Camera self.demoData.addVideoMediaMessage(); self.messageTableView?.reloadData(); self.finishSendingMessage(); case 1://Photos self.demoData.addPhotoMediaMessage(); self.messageTableView?.reloadData(); self.finishSendingMessage(); case 2: self.demoData.addLocationMediaMessageCompletion { self.messageTableView?.reloadData(); self.finishSendingMessage(); } default: break; } } //MARK: ZHCMessagesMoreViewDataSource override func messagesMoreViewTitles(_ moreView: ZHCMessagesMoreView) -> [Any] { return ["Camera","Photos","Location"]; } override func messagesMoreViewImgNames(_ moreView: ZHCMessagesMoreView) -> [Any] { return ["chat_bar_icons_camera","chat_bar_icons_pic","chat_bar_icons_location"] } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
cb2715a8e05f8f84a94a03345527cd3f
39.875887
167
0.659669
4.983571
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/StateMachine/StateMachineVC.swift
1
3086
// // StateMachineVC.swift // Lumia // // Created by xiAo_Ju on 2019/12/31. // Copyright © 2019 黄伯驹. All rights reserved. // import UIKit class StateMachineVC: UIViewController { var statusBarStyle: UIStatusBarStyle = .default { didSet { setNeedsStatusBarAppearanceUpdate() } } override var preferredStatusBarStyle: UIStatusBarStyle { return statusBarStyle } lazy var promptLabel: UILabel = { let label = UILabel() label.textAlignment = .center return label }() enum State: Int { case off case on case broken } enum Transition: Int { case turn case cut } lazy var stateMachine: StateMachine<State, Transition> = { let stateMachine = StateMachine<State, Transition>() stateMachine.add(state: .off) { [weak self] in self?.statusBarStyle = .lightContent self?.view.backgroundColor = .black self?.promptLabel.textColor = .white self?.promptLabel.text = "Tap to turn lights on" } stateMachine.add(state: .on) { [weak self] in self?.statusBarStyle = .default self?.view.backgroundColor = .white self?.promptLabel.textColor = .black self?.promptLabel.text = "Tap to turn lights off" } stateMachine.add(state: .broken) { [weak self] in self?.statusBarStyle = .lightContent self?.view.backgroundColor = .black self?.promptLabel.textColor = .white self?.promptLabel.text = "The wire is broken :[" } stateMachine.add(transition: .turn, fromState: .off, toState: .on) stateMachine.add(transition: .turn, fromState: .on, toState: .off) stateMachine.add(transition: .cut, fromStates: [.on, .off], toState: .broken) return stateMachine }() override func loadView() { super.loadView() view.addSubview(promptLabel) promptLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ NSLayoutConstraint(item: promptLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: promptLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0) ] ) } override func viewDidLoad() { super.viewDidLoad() stateMachine.initialState = .off let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:))) view.addGestureRecognizer(tap) let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) view.addGestureRecognizer(longPress) } @objc func tap(_ sender: UITapGestureRecognizer) { stateMachine.fire(transition: .turn) } @objc func longPress(_ sender: UILongPressGestureRecognizer) { stateMachine.fire(transition: .cut) } }
mit
9728ba31a800088d89615fd36a922907
31.410526
153
0.619357
4.826019
false
false
false
false
seorenn/SRChoco
Source/StringExtensions.swift
1
3196
// // StringExtensions.swift // SRChoco // // Created by Seorenn. // Copyright (c) 2014 Seorenn. All rights reserved. // import Foundation public extension String { init(cString: UnsafePointer<Int8>) { self.init(cString: UnsafeRawPointer(cString).assumingMemoryBound(to: UInt8.self)) } subscript(index: Int) -> Character { let chrIndex: String.Index if index >= 0 { chrIndex = self.index(self.startIndex, offsetBy: index) } else { chrIndex = self.index(self.endIndex, offsetBy: index) } return self[chrIndex] } // substring with range subscript(range: Range<Int>) -> String { let start = self.index(self.startIndex, offsetBy: range.lowerBound) let end = self.index(self.startIndex, offsetBy: range.upperBound) let range: Range<Index> = start..<end return String(self[range]) } // substring with NSRange subscript(range: NSRange) -> String { if range.length <= 0 { return "" } let startIndex = range.location let endIndex = range.location + range.length return self[startIndex..<endIndex] } func substring(startIndex: Int, length: Int) -> String { return self[startIndex ..< (startIndex + length)] } func prefix(length: Int) -> String { return self.substring(startIndex: 0, length: length) } func postfix(length: Int) -> String { let si: Int = self.count - length return self.substring(startIndex: si, length: length) } func trimmedString() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } func contain(string: String, ignoreCase: Bool = false) -> Bool { let options = ignoreCase ? NSString.CompareOptions.caseInsensitive : NSString.CompareOptions() if let _ = self.range(of: string, options: options) { return true } return false } func contain(strings: Array<String>, ORMode: Bool = false, ignoreCase: Bool = false) -> Bool { for string: String in strings { if ORMode && self.contain(string: string, ignoreCase: ignoreCase) { return true } else if ORMode == false && self.contain(string: string, ignoreCase: ignoreCase) == false { return false } } if ORMode { return false } else { return true } } func array(bySplitter: String? = nil) -> [String] { if let s = bySplitter { return self.components(separatedBy: s) } else { return self.components(separatedBy: CharacterSet.whitespacesAndNewlines) } } internal static func stringWithCFStringVoidPointer(_ voidPtr: UnsafeRawPointer) -> String? { let cfstr: CFString = unsafeBitCast(voidPtr, to: CFString.self) let nsstr: NSString = cfstr return nsstr as String } } public extension Optional where Wrapped == String { var isNilOrEmpty: Bool { if self == nil { return true } return self!.isEmpty } }
mit
61cc5960c2ed5f5676f9c14887c356b5
29.438095
104
0.595119
4.47619
false
false
false
false
morpheby/aTarantula
aTarantula/views/ViewController.swift
1
6272
// // ViewController.swift // aTarantula // // Created by Ilya Mikhaltsou on 8/18/17. // Copyright © 2017 morpheby. All rights reserved. // import Cocoa import TarantulaPluginCore class ViewController: NSViewController { @objc dynamic var crawler: Crawler = Crawler() @IBOutlet var objectController: NSObjectController! @IBOutlet var secondProgressIndicator: NSProgressIndicator! @IBOutlet var tableLogView: NSTableView! override func viewDidLoad() { super.viewDidLoad() crawler.logChangeObservable ∆= self >> { s, c in s.tableLogView.noteHeightOfRows(withIndexesChanged: [c.log.count-1]) } } override func viewDidLayout() { super.viewDidLayout() if let layer = secondProgressIndicator.layer { layer.anchorPoint = CGPoint(x: 1, y: 0) layer.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0) } } @IBAction func start(_ sender: Any?) { crawler.running = true } @IBAction func stop(_ sender: Any?) { crawler.running = false } @IBAction func clearLog(_ sender: Any?) { crawler.log = [] } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch segue.identifier { case .some(.pluginDrawerSegue): crawler.running = false default: break } } override func dismissViewController(_ viewController: NSViewController) { super.dismissViewController(viewController) for (_, store) in NSApplication.shared.controller.dataLoader.stores { try? store.persistentContainer.viewContext.save() store.repository.perform { } crawler.resetLists() crawler.updateCrawllist() } } @IBAction func batch(_ sender: Any?) { // FIXME: Needs separate dialogue with batch configuration let openPanel = NSOpenPanel() openPanel.message = "Select file for batch data" openPanel.nameFieldLabel = "Batch file:" openPanel.nameFieldStringValue = "Batch job" openPanel.allowedFileTypes = nil openPanel.allowsOtherFileTypes = true openPanel.beginSheetModal(for: view.window!, completionHandler: { response in switch (response) { case .OK: self.prepareForBatch(with: openPanel.url!) default: break } }) } // FIXME: Needs separate location func prepareForBatch(with fileUrl: URL) { do { let fileData = try String(contentsOf: fileUrl) let values = Set(fileData.lazy.split(separator: "\n").map(String.init)) let batchPlugins = NSApplication.shared.controller.crawlers.flatMap { p in p as? TarantulaBatchCapable&TarantulaCrawlingPlugin } for plugin in batchPlugins { try plugin.repository?.batch { shadow in for value in values { try plugin.addInitialObject(by: value, shadowRepository: shadow) } } } for plugin in batchPlugins { plugin.configureFilter(withClosure: { (s) -> Bool in values.contains(s) }) } for (_, store) in NSApplication.shared.controller.dataLoader.stores { // wait store.repository.perform { } crawler.resetLists() crawler.updateCrawllist() } } catch let e { self.presentError(e) } } @IBAction func exporting(_ sender: Any?) { // FIXME: Needs separate dialogue with export configuration let savePanel = NSSavePanel() savePanel.message = "Select export location" savePanel.nameFieldLabel = "Export file:" savePanel.nameFieldStringValue = "Export" // FIXME: STUB savePanel.allowedFileTypes = ["json"] savePanel.allowsOtherFileTypes = false savePanel.beginSheetModal(for: view.window!, completionHandler: { response in switch (response) { case .OK: self.exportData(url: savePanel.url!) default: break } }) } // TEMP EXPORT IMPLEMENTATION BEGIN struct Container: Encodable { var value: Encodable func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } } func exportData(url: URL) { // Temporary function implementation for exporting let tempId = ExportProfile("tempIdStub") let exporters = NSApplication.shared.controller.crawlers.flatMap { p in p as? TarantulaExportable } let data = exporters.flatMap { e in e.export(for: tempId) } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted encoder.dateEncodingStrategy = .iso8601 do { let preOutput = data.map { d in Container(value: d) } let output = try encoder.encode(Array(preOutput)) try output.write(to: url) } catch let e { self.presentError(e) } } // TEMP EXPORT IMPLEMENTATION END var autoscrollLastRow = 0 func autoscrollToBottom() { if crawler.log.count >= 4, let docRect = tableLogView.enclosingScrollView?.documentVisibleRect, docRect.maxY >= tableLogView.rect(ofRow: autoscrollLastRow).minY - 20.0 { autoscrollLastRow = crawler.log.count - 1 tableLogView.scrollRowToVisible(crawler.log.count - 1) } } var rowHeights: [Int: Float] = [:] } extension ViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) { rowHeights[row] = Float((rowView.view(atColumn: 0) as! NSView).fittingSize.height) tableView.noteHeightOfRows(withIndexesChanged: [row]) autoscrollToBottom() } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return CGFloat(rowHeights[row] ?? Float(tableView.rowHeight)) } }
gpl-3.0
a3f8f9917eaa2cec14230a0acb4c7fe6
30.822335
140
0.602807
4.69588
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/ClientEventLoopPreferenceTests.swift
1
5255
/* * Copyright 2021, gRPC Authors 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 EchoImplementation import EchoModel import GRPC import NIOCore import NIOPosix import XCTest final class ClientEventLoopPreferenceTests: GRPCTestCase { private var group: MultiThreadedEventLoopGroup! private var serverLoop: EventLoop! private var clientLoop: EventLoop! private var clientCallbackLoop: EventLoop! private var server: Server! private var connection: ClientConnection! private var echo: Echo_EchoNIOClient { let options = CallOptions( eventLoopPreference: .exact(self.clientCallbackLoop), logger: self.clientLogger ) return Echo_EchoNIOClient(channel: self.connection, defaultCallOptions: options) } override func setUp() { super.setUp() self.group = MultiThreadedEventLoopGroup(numberOfThreads: 3) self.serverLoop = self.group.next() self.clientLoop = self.group.next() self.clientCallbackLoop = self.group.next() XCTAssert(self.serverLoop !== self.clientLoop) XCTAssert(self.serverLoop !== self.clientCallbackLoop) XCTAssert(self.clientLoop !== self.clientCallbackLoop) self.server = try! Server.insecure(group: self.serverLoop) .withLogger(self.serverLogger) .withServiceProviders([EchoProvider()]) .bind(host: "localhost", port: 0) .wait() self.connection = ClientConnection.insecure(group: self.clientLoop) .withBackgroundActivityLogger(self.clientLogger) .connect(host: "localhost", port: self.server.channel.localAddress!.port!) } override func tearDown() { XCTAssertNoThrow(try self.connection.close().wait()) XCTAssertNoThrow(try self.server.close().wait()) XCTAssertNoThrow(try self.group.syncShutdownGracefully()) super.tearDown() } private func assertClientCallbackEventLoop(_ eventLoop: EventLoop, line: UInt = #line) { XCTAssert(eventLoop === self.clientCallbackLoop, line: line) } func testUnaryWithDifferentEventLoop() throws { let get = self.echo.get(.with { $0.text = "Hello!" }) self.assertClientCallbackEventLoop(get.eventLoop) self.assertClientCallbackEventLoop(get.initialMetadata.eventLoop) self.assertClientCallbackEventLoop(get.response.eventLoop) self.assertClientCallbackEventLoop(get.trailingMetadata.eventLoop) self.assertClientCallbackEventLoop(get.status.eventLoop) assertThat(try get.response.wait(), .is(.with { $0.text = "Swift echo get: Hello!" })) assertThat(try get.status.wait(), .hasCode(.ok)) } func testClientStreamingWithDifferentEventLoop() throws { let collect = self.echo.collect() self.assertClientCallbackEventLoop(collect.eventLoop) self.assertClientCallbackEventLoop(collect.initialMetadata.eventLoop) self.assertClientCallbackEventLoop(collect.response.eventLoop) self.assertClientCallbackEventLoop(collect.trailingMetadata.eventLoop) self.assertClientCallbackEventLoop(collect.status.eventLoop) XCTAssertNoThrow(try collect.sendMessage(.with { $0.text = "a" }).wait()) XCTAssertNoThrow(try collect.sendEnd().wait()) assertThat(try collect.response.wait(), .is(.with { $0.text = "Swift echo collect: a" })) assertThat(try collect.status.wait(), .hasCode(.ok)) } func testServerStreamingWithDifferentEventLoop() throws { let response = self.clientCallbackLoop.makePromise(of: Void.self) let expand = self.echo.expand(.with { $0.text = "a" }) { _ in self.clientCallbackLoop.preconditionInEventLoop() response.succeed(()) } self.assertClientCallbackEventLoop(expand.eventLoop) self.assertClientCallbackEventLoop(expand.initialMetadata.eventLoop) self.assertClientCallbackEventLoop(expand.trailingMetadata.eventLoop) self.assertClientCallbackEventLoop(expand.status.eventLoop) XCTAssertNoThrow(try response.futureResult.wait()) assertThat(try expand.status.wait(), .hasCode(.ok)) } func testBidirectionalStreamingWithDifferentEventLoop() throws { let response = self.clientCallbackLoop.makePromise(of: Void.self) let update = self.echo.update { _ in self.clientCallbackLoop.preconditionInEventLoop() response.succeed(()) } self.assertClientCallbackEventLoop(update.eventLoop) self.assertClientCallbackEventLoop(update.initialMetadata.eventLoop) self.assertClientCallbackEventLoop(update.trailingMetadata.eventLoop) self.assertClientCallbackEventLoop(update.status.eventLoop) XCTAssertNoThrow(try update.sendMessage(.with { $0.text = "a" }).wait()) XCTAssertNoThrow(try update.sendEnd().wait()) XCTAssertNoThrow(try response.futureResult.wait()) assertThat(try update.status.wait(), .hasCode(.ok)) } }
apache-2.0
6db1478f78cabe7144bbb93d2ebc1509
36.007042
93
0.74862
4.321546
false
false
false
false
sjtu-meow/iOS
Meow/Article.swift
1
1167
// // article.swift // Meow // // Created by 林树子 on 2017/6/30. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import SwiftyJSON struct Article: ItemProtocol { var id: Int! var type: ItemType! var profile: Profile! var createTime: Date! var cover: URL? var title: String! var summary: String? var content: String? var likeCount: Int! var commentCount: Int! var comments: [Comment]! } extension Article: JSONConvertible { static func fromJSON(_ json: JSON) -> Article? { let item = Item.fromJSON(json)! var article = self.init() article.id = item.id article.type = item.type article.profile = item.profile article.createTime = item.createTime article.cover <- json["cover"] article.title <- json["title"] article.summary <- json["summary"] article.content <- json["content"] article.likeCount <- json["likeCount"] article.commentCount <- json["commentCount"] article.comments <- json["comments"] return article } }
apache-2.0
ee755629d9b84f63ee8d6fbc85c0ff7e
20.222222
52
0.585515
4.228782
false
false
false
false
Tatoeba/tatoeba-ios
Tatoeba/Application/AppDelegate.swift
1
2459
// // AppDelegate.swift // Tatoeba // // Created by Jack Cook on 8/5/17. // Copyright © 2017 Tatoeba. All rights reserved. // import CoreSpotlight import Fuji import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Set default values on first app launch if !TatoebaUserDefaults.bool(forKey: .defaultsConfigured) { TatoebaUserDefaults.setDefaultValues() } // Start Fuji if the user allows anonymous tracking if TatoebaUserDefaults.bool(forKey: .sendAnonymousUsageData) { do { try Fuji.shared.start() } catch { print("Fuji analytics wasn't able to start") } } // Add one to number of app launches let appLaunches = TatoebaUserDefaults.integer(forKey: .appLaunches) + 1 TatoebaUserDefaults.set(appLaunches, forKey: .appLaunches) return true } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { if #available(iOS 9.0, *) { guard userActivity.activityType == CSSearchableItemActionType, let activityId = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String, let sentenceIdString = activityId.components(separatedBy: ".").last, let sentenceId = Int(sentenceIdString) else { return false } SentenceRequest(id: sentenceId).start { sentence in guard let sentence = sentence, let sentenceController = UIStoryboard.main.instantiateViewController(withIdentifier: .sentenceController) as? SentenceViewController else { return } sentenceController.sentence = sentence guard let topController = (self.window?.rootViewController as? UINavigationController)?.viewControllers.last else { return } topController.present(sentenceController, animated: true, completion: nil) } return true } else { return false } } }
mit
d70dff0b13ffd8c5094b88a9528fbd96
36.242424
277
0.614727
5.561086
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/GradientView.swift
1
2356
// // GradientView.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-22. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import UIKit protocol GradientDrawable { func drawGradient(_ rect: CGRect) } extension UIView { func drawGradient(_ rect: CGRect) { let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [UIColor.gradientStart.cgColor, UIColor.gradientEnd.cgColor] as CFArray let locations: [CGFloat] = [0.0, 1.0] guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return } guard let context = UIGraphicsGetCurrentContext() else { return } context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: rect.height), end: CGPoint(x: rect.width, y: 0.0), options: []) } func drawGradient(start: UIColor, end: UIColor, _ rect: CGRect) { let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [start.cgColor, end.cgColor] as CFArray let locations: [CGFloat] = [0.0, 1.0] guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return } guard let context = UIGraphicsGetCurrentContext() else { return } context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: rect.width, y: 0.0), options: []) } func drawGradient(ends: UIColor, middle: UIColor, _ rect: CGRect) { let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [ends.cgColor, middle.cgColor, ends.cgColor] as CFArray let locations: [CGFloat] = [0.0, 0.5, 1.0] guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return } guard let context = UIGraphicsGetCurrentContext() else { return } context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: rect.height), options: []) } } class GradientView: UIView { override func draw(_ rect: CGRect) { drawGradient(rect) } } class DoubleGradientView: UIView { override func draw(_ rect: CGRect) { drawGradient(ends: UIColor.white.withAlphaComponent(0.1), middle: UIColor.white.withAlphaComponent(0.6), rect) } }
mit
5cff444028bfd13eb7a00bc6791aa641
40.315789
118
0.647134
4.35305
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/WebView/PrivateBrowsing.swift
2
9652
// // PrivateBrowsing.swift // Client // // Reference: https://github.com/brave/browser-ios/blob/development/brave/src/webview/PrivateBrowsing.swift import Shared import Deferred private let _singleton = PrivateBrowsing() class PrivateBrowsing { class var singleton: PrivateBrowsing { return _singleton } fileprivate(set) var isOn = false var nonprivateCookies = [HTTPCookie: Bool]() // On startup we are no longer in private mode, if there is a .public cookies file, it means app was killed in private mode, so restore the cookies file func startupCheckIfKilledWhileInPBMode() { webkitDirLocker(false) cookiesFileDiskOperation(.restorePublicBackup) } enum MoveCookies { case savePublicBackup case restorePublicBackup case deletePublicBackup } // GeolocationSites.plist cannot be blocked any other way than locking the filesystem so that webkit can't write it out // TODO: after unlocking, verify that sites from PB are not in the written out GeolocationSites.plist, based on manual testing this // doesn't seem to be the case, but more rigourous test cases are needed fileprivate func webkitDirLocker(_ lock: Bool) { let fm = FileManager.default let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let webkitDirs = [baseDir + "/WebKit", baseDir + "/Caches"] for dir in webkitDirs { do { try fm.setAttributes([FileAttributeKey.posixPermissions: (lock ? NSNumber(value: 0 as Int16) : NSNumber(value: 0o755 as Int16))], ofItemAtPath: dir) } catch { print(error) } } } fileprivate func cookiesFileDiskOperation( _ type: MoveCookies) { let fm = FileManager.default let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let cookiesDir = baseDir + "/Cookies" let originSuffix = type == .savePublicBackup ? "cookies" : ".public" do { let contents = try fm.contentsOfDirectory(atPath: cookiesDir) for item in contents { if item.hasSuffix(originSuffix) { if type == .deletePublicBackup { try fm.removeItem(atPath: cookiesDir + "/" + item) } else { var toPath = cookiesDir + "/" if type == .restorePublicBackup { toPath += NSString(string: item).deletingPathExtension } else { toPath += item + ".public" } if fm.fileExists(atPath: toPath) { do { try fm.removeItem(atPath: toPath) } catch {} } try fm.moveItem(atPath: cookiesDir + "/" + item, toPath: toPath) } } } } catch { print(error) } } func enter() { if isOn { return } isOn = true getApp().tabManager.purgeTabs(includeSelectedTab: true) self.backupNonPrivateCookies() self.setupCacheDefaults(memoryCapacity: 0, diskCapacity: 0) NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil) webkitDirLocker(true) } fileprivate var exitDeferred = Deferred<Void>() @discardableResult func exit() -> Deferred<Void> { if !isOn { let immediateExit = Deferred<Void>() immediateExit.fill(()) return immediateExit } // Since this an instance var, it needs to be used carefully. // The usage of this deferred, is async, and is generally handled, by a response to a notification // if it is overwritten, it will lead to race conditions, and generally a dropped deferment, since the // notification will be executed on _only_ the newest version of this property exitDeferred = Deferred<Void>() NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(allWebViewsKilled), name: NSNotification.Name(rawValue: kNotificationAllWebViewsDeallocated), object: nil) getApp().tabManager.purgeTabs(includeSelectedTab: true) postAsyncToMain(2) { if !self.exitDeferred.isFilled { self.allWebViewsKilled() } } isOn = false return exitDeferred } @objc func allWebViewsKilled() { struct ReentrantGuard { static var inFunc = false } if ReentrantGuard.inFunc { // This is kind of a predicament // On one hand, we cannot drop promises, // on the other, if processes are killing webviews, this could end up executing logic that should not happen // so quickly. A better refactor would be to propogate some piece of data (e.g. Bool), that indicates // the current state of promise chain (e.g. ReentrantGuard value) self.exitDeferred.fillIfUnfilled(()) return } ReentrantGuard.inFunc = true NotificationCenter.default.removeObserver(self) postAsyncToMain(0.1) { // just in case any other webkit object cleanup needs to complete self.deleteAllCookies() self.cleanStorage() self.clearShareHistory() self.webkitDirLocker(false) self.cleanProfile() self.setupCacheDefaults(memoryCapacity: 8, diskCapacity: 50) self.restoreNonPrivateCookies() self.exitDeferred.fillIfUnfilled(()) ReentrantGuard.inFunc = false } } private func setupCacheDefaults(memoryCapacity: Int, diskCapacity: Int) { // in MB URLCache.shared.memoryCapacity = memoryCapacity * 1024 * 1024; URLCache.shared.diskCapacity = diskCapacity * 1024 * 1024; } private func deleteAllCookies() { let storage = HTTPCookieStorage.shared if let cookies = storage.cookies { for cookie in cookies { storage.deleteCookie(cookie) } } } private func cleanStorage() { if let clazz = NSClassFromString("Web" + "StorageManager") as? NSObjectProtocol { if clazz.responds(to: Selector("shared" + "WebStorageManager")) { if let storage = clazz.perform(Selector("shared" + "WebStorageManager")) { let o = storage.takeUnretainedValue() o.perform(Selector("delete" + "AllOrigins")) } } } } private func clearShareHistory() { if let clazz = NSClassFromString("Web" + "History") as? NSObjectProtocol { if clazz.responds(to: Selector("optional" + "SharedHistory")) { if let webHistory = clazz.perform(Selector("optional" + "SharedHistory")) { let o = webHistory.takeUnretainedValue() o.perform(Selector("remove" + "AllItems")) } } } } private func backupNonPrivateCookies() { self.cookiesFileDiskOperation(.savePublicBackup) let storage = HTTPCookieStorage.shared if let cookies = storage.cookies { for cookie in cookies { self.nonprivateCookies[cookie] = true storage.deleteCookie(cookie) } } } private func restoreNonPrivateCookies() { self.cookiesFileDiskOperation(.deletePublicBackup) let storage = HTTPCookieStorage.shared for cookie in self.nonprivateCookies { storage.setCookie(cookie.0) } self.nonprivateCookies = [HTTPCookie: Bool]() } private func cleanProfile() { getApp().profile?.shutdown() getApp().profile?.db.reopenIfClosed() } @objc func cookiesChanged(_ info: Notification) { NotificationCenter.default.removeObserver(self) let storage = HTTPCookieStorage.shared var newCookies = [HTTPCookie]() if let cookies = storage.cookies { for cookie in cookies { if let readOnlyProps = cookie.properties { var props = readOnlyProps as [HTTPCookiePropertyKey: Any] let discard = props[HTTPCookiePropertyKey.discard] as? String if discard == nil || discard! != "TRUE" { props.removeValue(forKey: HTTPCookiePropertyKey.expires) props[HTTPCookiePropertyKey.discard] = "TRUE" storage.deleteCookie(cookie) if let newCookie = HTTPCookie(properties: props) { newCookies.append(newCookie) } } } } } for c in newCookies { storage.setCookie(c) } NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil) } }
mpl-2.0
18bb02779a2e59b08872642f29374927
37.454183
183
0.581434
5.222944
false
false
false
false
AndreMuis/TISensorTag
TISensorTag/Views/TSTSimpleKeyView.swift
1
1625
// // TSTSimpleKeyView.swift // TISensorTag // // Created by Andre Muis on 5/21/16. // Copyright © 2016 Andre Muis. All rights reserved. // import UIKit class TSTSimpleKeyView: UIView { var depressedFrame : CGRect var pressedFrame : CGRect required init?(coder aDecoder: NSCoder) { self.depressedFrame = CGRectZero self.pressedFrame = CGRectZero super.init(coder: aDecoder) } func setup() { self.depressedFrame = self.frame self.pressedFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height * TSTConstants.SimpleKeyView.depressedPercent, self.frame.size.width, self.frame.size.height * (1.0 - TSTConstants.SimpleKeyView.depressedPercent)) let cornerRadius : CGFloat = TSTConstants.SimpleKeyView.cornerRadius let bezierPath : UIBezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight], cornerRadii: CGSizeMake(cornerRadius, cornerRadius)) let shapeLayer : CAShapeLayer = CAShapeLayer() shapeLayer.frame = self.bounds shapeLayer.path = bezierPath.CGPath self.layer.mask = shapeLayer } func press() { self.frame = self.pressedFrame } func depress() { self.frame = self.depressedFrame } }
mit
25ee21573b7eefc9dffdefd2eca08645
22.536232
130
0.569581
5.075
false
false
false
false
ed-chin/EarlGrey
gem/lib/earlgrey/files/Swift-2.3/EarlGrey.swift
4
4324
// // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import EarlGrey import Foundation let greyFailureHandler = NSThread.currentThread().threadDictionary .valueForKey(kGREYFailureHandlerKey) as! GREYFailureHandler public func EarlGrey(file: String = #file, line: UInt = #line) -> EarlGreyImpl! { return EarlGreyImpl.invokedFromFile(file, lineNumber: line) } public func GREYAssert(@autoclosure expression: () -> BooleanType, reason: String) { GREYAssert(expression, reason, details: "Expected expression to be true") } public func GREYAssertTrue(@autoclosure expression: () -> BooleanType, reason: String) { GREYAssert(expression().boolValue, reason, details: "Expected the boolean expression to be true") } public func GREYAssertFalse(@autoclosure expression: () -> BooleanType, reason: String) { GREYAssert(!expression().boolValue, reason, details: "Expected the boolean expression to be false") } public func GREYAssertNotNil(@autoclosure expression: () -> Any?, reason: String) { GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil") } public func GREYAssertNil(@autoclosure expression: () -> Any?, reason: String) { GREYAssert(expression() == nil, reason, details: "Expected expression to be nil") } public func GREYAssertEqual(@autoclosure left: () -> AnyObject?, @autoclosure _ right: () -> AnyObject?, reason: String) { GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term") } public func GREYAssertNotEqual(@autoclosure left: () -> AnyObject?, @autoclosure _ right: () -> AnyObject?, reason: String) { GREYAssert(left() !== right(), reason, details: "Expected left term to not be equal to right" + " term") } public func GREYAssertEqualObjects<T : Equatable>(@autoclosure left: () -> T?, @autoclosure _ right: () -> T?, reason: String) { GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal" + " to the object of the right term") } public func GREYAssertNotEqualObjects<T : Equatable>(@autoclosure left: () -> T?, @autoclosure _ right: () -> T?, reason: String) { GREYAssert(left() != right(), reason, details: "Expected object of the left term to not be" + " equal to the object of the right term") } public func GREYFail(reason: String) { greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: "") } @available(*, deprecated=1.2.0, message="Please use GREYFAIL::withDetails instead.") public func GREYFail(reason: String, details: String) { greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } public func GREYFailWithDetails(reason: String, details: String) { greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } private func GREYAssert(@autoclosure expression: () -> BooleanType, _ reason: String, details: String) { GREYSetCurrentAsFailable() GREYWaitUntilIdle() if !expression().boolValue { greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } } private func GREYWaitUntilIdle() { GREYUIThreadExecutor.sharedInstance().drainUntilIdle() } private func GREYSetCurrentAsFailable(file: String = #file, line: UInt = #line) { let greyFailureHandlerSelector = #selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:)) if greyFailureHandler.respondsToSelector(greyFailureHandlerSelector) { greyFailureHandler.setInvocationFile!(file, andInvocationLine: line) } }
apache-2.0
d777bb4c2cc524d68caa1284c5466adb
36.6
98
0.730574
4.425793
false
false
false
false
lachatak/lift
ios/Lift/LiftServer/LiftServerURLs.swift
2
8147
import Foundation /// /// The request to the Lift server-side code /// struct LiftServerRequest { var path: String var method: Method init(path: String, method: Method) { self.path = path self.method = method } } /// /// Defines mechanism to convert a request to LiftServerRequest /// protocol LiftServerRequestConvertible { var Request: LiftServerRequest { get } } /// /// The Lift server URLs and request data mappers /// enum LiftServerURLs : LiftServerRequestConvertible { /// /// Register the user /// case UserRegister() /// /// Login the user /// case UserLogin() /// /// Adds an iOS device for the user identified by ``userId`` /// case UserRegisterDevice(/*userId: */NSUUID) /// /// Retrieves the user's profile for the ``userId`` /// case UserGetPublicProfile(/*userId: */NSUUID) /// /// Sets the user's profile for the ``userId`` /// case UserSetPublicProfile(/*userId: */NSUUID) /// /// Gets the user's profile image /// case UserGetProfileImage(/*userId: */NSUUID) /// /// Sets the user's profile image /// case UserSetProfileImage(/*userId: */NSUUID) /// /// Checks that the account is still there /// case UserCheckAccount(/*userId: */NSUUID) /// /// Get supported muscle groups /// case ExerciseGetMuscleGroups() /// /// Retrieves all the exercises for the given ``userId`` and ``date`` /// case ExerciseGetExerciseSessionsSummary(/*userId: */NSUUID, /*date: */NSDate) /// /// Retrieves all the session dates for the given ``userId`` /// case ExerciseGetExerciseSessionsDates(/*userId: */NSUUID) /// /// Retrieves all the exercises for the given ``userId`` and ``sessionId`` /// case ExerciseGetExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Deletes all the exercises for the given ``userId`` and ``sessionId`` /// case ExerciseDeleteExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts an exercise session for the given ``userId`` /// case ExerciseSessionStart(/*userId: */NSUUID) /// /// Abandons the exercise session for the given ``userId`` and ``sessionId``. /// case ExerciseSessionAbandon(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts the replay of an existing session for the given user /// case ExerciseSessionReplayStart(/*userId: */NSUUID, /* sessionId */ NSUUID) /// /// Replays the exercise session for the given ``userId`` and ``sessionId``. /// case ExerciseSessionReplayData(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Submits the data (received from the smartwatch) for the given ``userId``, ``sessionId`` /// case ExerciseSessionSubmitData(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Gets exercise classification examples for the given ``userId`` and ``sessionId`` /// case ExerciseSessionGetClassificationExamples(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Ends the session for the given ``userId`` and ``sessionId`` /// case ExerciseSessionEnd(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts the explicit exercise classification for ``userId`` and ``sessionId`` /// case ExplicitExerciseClassificationStart(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Stops the explicit exercise classification for ``userId`` and ``sessionId`` /// case ExplicitExerciseClassificationStop(/*userId: */NSUUID, /*sessionId: */NSUUID) private struct Format { private static let simpleDateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() static func simpleDate(date: NSDate) -> String { return simpleDateFormatter.stringFromDate(date) } } // MARK: URLStringConvertible var Request: LiftServerRequest { get { let r: LiftServerRequest = { switch self { case let .UserRegister: return LiftServerRequest(path: "/user", method: Method.POST) case let .UserLogin: return LiftServerRequest(path: "/user", method: Method.PUT) case .UserRegisterDevice(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/device/ios", method: Method.POST) case .UserGetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.GET) case .UserSetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.POST) case .UserCheckAccount(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/check", method: Method.GET) case .UserGetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.GET) case .UserSetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.POST) case .ExerciseGetMuscleGroups(): return LiftServerRequest(path: "/exercise/musclegroups", method: Method.GET) case .ExerciseGetExerciseSessionsSummary(let userId, let date): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)?date=\(Format.simpleDate(date))", method: Method.GET) case .ExerciseGetExerciseSessionsDates(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)", method: Method.GET) case .ExerciseGetExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.GET) case .ExerciseDeleteExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.DELETE) case .ExerciseSessionStart(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/start", method: Method.POST) case .ExerciseSessionSubmitData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.PUT) case .ExerciseSessionEnd(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/end", method: Method.POST) case .ExerciseSessionAbandon(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/abandon", method: Method.POST) case .ExerciseSessionReplayStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.POST) case .ExerciseSessionReplayData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.PUT) case .ExerciseSessionGetClassificationExamples(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.GET) case .ExplicitExerciseClassificationStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.POST) case .ExplicitExerciseClassificationStop(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.DELETE) } }() return r } } }
apache-2.0
cbd6d972a9ace57535ef14f54baada81
41.432292
214
0.640727
4.85808
false
false
false
false
mayongl/CS193P
FaceIt/FaceIt/BlinkingFaceViewController.swift
1
2319
// // BlinkingFaceViewController.swift // FaceIt // // Created by Yonglin on 15/04/2017. // Copyright © 2017 Yonglin. All rights reserved. // import UIKit class BlinkingFaceViewController: FaceViewController { var blinking = false { didSet { blinkIfNeeded() } } override func updateUI() { super.updateUI() blinking = expression.eyes == .squinting } private struct BlinkRate { static let closeDuration: TimeInterval = 0.4 static let openDuration: TimeInterval = 2.5 } func blinkIfNeeded() { if blinking && canBlink && !inABlink { faceView.eyesOpen = false inABlink = true Timer.scheduledTimer(withTimeInterval: BlinkRate.closeDuration, repeats: false) { [weak self] timer in self?.faceView.eyesOpen = true Timer.scheduledTimer(withTimeInterval: BlinkRate.openDuration , repeats: false) { [weak self] timer in self?.inABlink = false self?.blinkIfNeeded() } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private var canBlink = false private var inABlink = false override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) canBlink = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) canBlink = true blinkIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) canBlink = false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
3deb673bf1a5f833379ea42ba78aa656
25.953488
120
0.594909
5.07221
false
false
false
false
yarshure/Surf
Surf/LogListTableViewController.swift
1
22168
// // LogListTableViewController.swift // Surf // // Created by yarshure on 15/12/7. // Copyright © 2015年 yarshure. All rights reserved. // import UIKit import SFSocket import SwiftyJSON import XRuler struct SFFILE { var name:String var date:NSDate var size:Int64 init(n:String,d:NSDate,size:Int64){ name = n date = d self.size = size } var desc:String{ //print(size) if size >= 1024 && size < 1024*1024 { return "size: \(size/1024) KB" }else if size >= 1024*1024 { return "size: \(size/(1024*1024)) MB" }else { return "size: \(size) byte" } } } open class SFVPNStatisticsApp { //public static let shared = SFVPNStatistics() public var startDate = Date.init(timeIntervalSince1970: 0) public var sessionStartTime = Date() public var reportTime = Date.init(timeIntervalSince1970: 0) public var startTimes = 0 public var show:Bool = false public var totalTraffice:SFTraffic = SFTraffic() public var currentTraffice:SFTraffic = SFTraffic() public var lastTraffice:SFTraffic = SFTraffic() public var maxTraffice:SFTraffic = SFTraffic() public var wifiTraffice:SFTraffic = SFTraffic() public var cellTraffice:SFTraffic = SFTraffic() public var directTraffice:SFTraffic = SFTraffic() public var proxyTraffice:SFTraffic = SFTraffic() public var memoryUsed:UInt64 = 0 public var finishedCount:Int = 0 public var workingCount:Int = 0 public var runing:String { get { //let now = Date() let second = Int(reportTime.timeIntervalSince(sessionStartTime)) return secondToString(second: second) } } public func updateMax() { if lastTraffice.tx > maxTraffice.tx{ maxTraffice.tx = lastTraffice.tx } if lastTraffice.rx > maxTraffice.rx { maxTraffice.rx = lastTraffice.rx } } public func secondToString(second:Int) ->String { let sec = second % 60 let min = second % (60*60) / 60 let hour = second / (60*60) return String.init(format: "%02d:%02d:%02d", hour,min,sec) } public func map(j:JSON) { startDate = Date.init(timeIntervalSince1970: j["start"].doubleValue) as Date sessionStartTime = Date.init(timeIntervalSince1970: j["sessionStartTime"].doubleValue) reportTime = NSDate.init(timeIntervalSince1970: j["report_date"].doubleValue) as Date totalTraffice.mapObject(j: j["total"]) lastTraffice.mapObject(j: j["last"]) maxTraffice.mapObject(j: j["max"]) cellTraffice.mapObject(j:j["cell"]) wifiTraffice.mapObject(j: j["wifi"]) directTraffice.mapObject(j: j["direct"]) proxyTraffice.mapObject(j: j["proxy"]) // if let c = j["memory"].uInt64 { // memoryUsed = c // } // if let tcp = j["finishedCount"].int { // finishedCount = tcp // } // if let tcp = j["workingCount"].int { // workingCount = tcp // } } func resport() ->Data{ //reportTime = Date() //memoryUsed = reportMemoryUsed()//reportCurrentMemory() var status:[String:AnyObject] = [:] status["start"] = NSNumber.init(value: startDate.timeIntervalSince1970) status["sessionStartTime"] = NSNumber.init(value: sessionStartTime.timeIntervalSince1970) status["report_date"] = NSNumber.init(value: reportTime.timeIntervalSince1970) //status["runing"] = NSNumber.init(double:runing) status["total"] = totalTraffice.resp() as AnyObject? status["last"] = lastTraffice.resp() as AnyObject? status["max"] = maxTraffice.resp() as AnyObject? status["memory"] = NSNumber.init(value: memoryUsed) //memoryUsed) //let count = SFTCPConnectionManager.manager.connections.count status["finishedCount"] = NSNumber.init(value: finishedCount) // //status["workingCount"] = NSNumber.init(value: count) // status["cell"] = cellTraffice.resp() as AnyObject? status["wifi"] = wifiTraffice.resp() as AnyObject? status["direct"] = directTraffice.resp() as AnyObject? status["proxy"] = proxyTraffice.resp() as AnyObject? let j = JSON(status) //print("recentRequestData \(j)") var data:Data do { try data = j.rawData() }catch let error { //AxLogger.log("ruleResultData error \(error.localizedDescription)") //let x = error.localizedDescription //let err = "report error" data = error.localizedDescription.data(using: .utf8)!// NSData() } return data } public func memoryString() ->String { let f = Float(memoryUsed) if memoryUsed < 1024 { return "\(memoryUsed) Bytes" }else if memoryUsed >= 1024 && memoryUsed < 1024*1024 { return String(format: "%.2f KB", f/1024.0) } return String(format: "%.2f MB", f/1024.0/1024.0) } } class LogListTableViewController: SFTableViewController { var filePath:String = "" var fileList:[SFFILE] = [] var showSession:Bool = false var reportInfo:SFVPNStatisticsApp? override func viewDidLoad() { super.viewDidLoad() if filePath.isEmpty { self.title = "Sessions" }else { self.title = "Session Detail" showSession = true } findFiles() navigationItem.rightBarButtonItem = editButtonItem // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @IBAction func deleteAll(_ sender:AnyObject) { if let m = SFVPNManager.shared.manager , m.connection.status == .connected { for file in fileList.dropFirst() { let url = groupContainerURL().appendingPathComponent("Log/"+file.name) do { try fm.removeItem(at: url) }catch let error as NSError { alertMessageAction("delete \(url.path) failure: \(error.description)",complete: nil) return } } }else { for file in fileList { let url = groupContainerURL().appendingPathComponent("Log/"+file.name) do { try fm.removeItem(at: url) }catch let error as NSError { alertMessageAction("delete \(url.path) failure: \(error.description)",complete: nil) return } } } findFiles() } func findFiles(){ let q = DispatchQueue(label:"com.yarshure.sortlog") q.async(execute: { [weak self] () -> Void in self!.fileList.removeAll() //let urlContain = FileManager.default.containerURLForSecurityApplicationGroupIdentifier("group.com.yarshure.Surf") let url = groupContainerURL().appendingPathComponent("Log/" + self!.filePath) let dir = url.path //NSHomeDirectory().NS.stringByAppendingPathComponent("Documents/applog") if FileManager.default.fileExists(atPath:dir) { let files = try! FileManager.default.contentsOfDirectory(atPath: dir) var tmpArray:[SFFILE] = [] for file in files { let url = url.appendingPathComponent(file) let att = try! fm.attributesOfItem(atPath: url.path) let d = att[ FileAttributeKey.init("NSFileCreationDate")] as! NSDate let size = att[FileAttributeKey.init("NSFileSize")]! as! NSNumber let fn = SFFILE.init(n: file, d: d,size:size.int64Value) tmpArray.append(fn) } tmpArray.sort(by: { $0.date.compare($1.date as Date) == ComparisonResult.orderedDescending }) DispatchQueue.main.async(execute: { if let strongSelf = self { strongSelf.fileList.append(contentsOf: tmpArray) if strongSelf.showSession { strongSelf.loadReport() }else { strongSelf.tableView.reloadData() } } }) }else { } }) //fileList = try! FileManager.default.contentsOfDirectoryAtURL(url, includingPropertiesForKeys keys: [String]?, options mask: NSDirectoryEnumerationOptions) throws -> [NSURL] } func loadReport(){ let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/db.zip") let urlJson = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/session.json") if FileManager.default.fileExists(atPath: urlJson.path){ reportInfo = SFVPNStatisticsApp()//.init(name: self.filePath) do { let data = try Data.init(contentsOf: urlJson) let obj = try! JSON.init(data: data) reportInfo!.map(j: obj) tableView.reloadData() return }catch let e { alertMessageAction("\(e.localizedDescription)", complete: nil) } } if FileManager.default.fileExists(atPath: url.path){ let _ = RequestHelper.shared.openForApp(self.filePath) let resultsFin = RequestHelper.shared.fetchAll() reportInfo = SFVPNStatisticsApp()//.init(name: self.filePath) for req in resultsFin { reportInfo?.totalTraffice.addRx(x:Int(req.traffice.rx) ) reportInfo?.totalTraffice.addTx(x:Int(req.traffice.tx) ) if req.interfaceCell == 1 { reportInfo?.cellTraffice.addRx(x: Int(req.traffice.rx)) reportInfo?.cellTraffice.addTx(x: Int(req.traffice.tx)) }else { reportInfo?.wifiTraffice.addRx(x: Int(req.traffice.rx)) reportInfo?.wifiTraffice.addTx(x: Int(req.traffice.tx)) } if req.rule.policy == .Direct { reportInfo?.directTraffice.addRx(x: Int(req.traffice.rx)) reportInfo?.directTraffice.addTx(x: Int(req.traffice.tx)) }else { reportInfo?.proxyTraffice.addRx(x: Int(req.traffice.rx)) reportInfo?.proxyTraffice.addTx(x: Int(req.traffice.tx)) } if req.sTime.compare(reportInfo!.sessionStartTime) == .orderedAscending{ reportInfo!.sessionStartTime = req.sTime } if req.eTime.compare(reportInfo!.reportTime) == .orderedDescending { reportInfo!.reportTime = req.eTime } } let data = reportInfo!.resport() let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/session.json") do { try data.write(to:url ) } catch let e { alertMessageAction("\(e.localizedDescription)", complete: nil) } } tableView.reloadData() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if filePath.isEmpty { let dir = fileList[indexPath.row] print(dir) let vc = self.storyboard?.instantiateViewController(withIdentifier: "filelist") as! LogListTableViewController vc.filePath = dir.name self.navigationController?.pushViewController(vc, animated: true) }else { let cell = tableView.cellForRow(at: indexPath) if indexPath.row > fileList.count { self.performSegue(withIdentifier: "showFile", sender: cell) }else { let f = fileList[indexPath.row] if f.name == "db.zip" { self.performSegue(withIdentifier: "showDB", sender: cell) }else { self.performSegue(withIdentifier: "showFile", sender: cell) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections if filePath.isEmpty { if fileList.count == 0 { return 1 } return 2 }else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if section == 0 { if fileList.count == 0 { return 1 } return fileList.count }else { if showSession { if let _ = reportInfo{ return 6 }else { return 0 } }else { return 1 } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "logidentifier", for: indexPath as IndexPath) if fileList.count == 0 { cell.textLabel?.text = "No log files" cell.detailTextLabel?.text = "" }else { // Configure the cell... //bug if indexPath.row < fileList.count { let f = fileList[indexPath.row] cell.textLabel?.text = f.name if !filePath.isEmpty { cell.detailTextLabel?.text = f.desc }else { cell.detailTextLabel?.text = "" } } } cell.updateStandUI() return cell }else { if showSession { let cell = tableView.dequeueReusableCell(withIdentifier: "StatusCell", for: indexPath as IndexPath) as! StatusCell guard let r = self.reportInfo else { return cell } configCell(cell: cell,indexPath: indexPath, report: r) return cell }else { let cell = tableView.dequeueReusableCell(withIdentifier: "deleteAll", for: indexPath as IndexPath) return cell } } } func configCell(cell:StatusCell, indexPath:IndexPath,report:SFVPNStatisticsApp){ let flag = true let f = UIFont.init(name: "Ionicons", size: 20)! cell.downLabel.text = "\u{f35d}" cell.downLabel.font = f cell.upLabel.text = "\u{f366}" cell.upLabel.font = f cell.updateUI() switch indexPath.row { case 0: cell.catLabel.text = "\u{f3b3}" cell.downInfoLabel.isHidden = true //report.memoryString() cell.downLabel.isHidden = true cell.upLabel.isHidden = true cell.upInfoLabel.text = report.runing return case 1: cell.catLabel.text = "\u{f37c}" //cell.textLabel?.text = "Total: \(report.totalTraffice.reportTraffic())" cell.upInfoLabel.text = report.totalTraffice.toString(x: report.totalTraffice.tx,label: "",speed: false) cell.downInfoLabel.text = report.totalTraffice.toString(x: report.totalTraffice.rx,label: "",speed: false) case 2: cell.upInfoLabel.text = report.directTraffice.toString(x: report.directTraffice.tx,label: "",speed: false) cell.downInfoLabel.text = report.directTraffice.toString(x: report.directTraffice.rx,label: "",speed: false) cell.catLabel.text = "\u{f394}"//cell.textLabel?.text = "DIRECT: \(report.directTraffice.reportTraffic())" case 3: //cell.textLabel?.text = "PROXY: \(report.proxyTraffice.reportTraffic())" cell.catLabel.text = "\u{f4a8}" cell.upInfoLabel.text = report.proxyTraffice.toString(x: report.proxyTraffice.tx,label: "",speed: false) cell.downInfoLabel.text = report.proxyTraffice.toString(x: report.proxyTraffice.rx,label: "",speed: false) case 4: //cell.textLabel?.attributedText = report.wifi() cell.upInfoLabel.text = report.wifiTraffice.toString(x: report.wifiTraffice.tx,label: "",speed: false) cell.downInfoLabel.text = report.wifiTraffice.toString(x: report.wifiTraffice.rx,label: "",speed: false) cell.catLabel.text = "\u{f25c}" case 5: //cell.textLabel?.text = "CELL: \(report.cellTraffice.reportTraffic())" cell.upInfoLabel.text = report.cellTraffice.toString(x: report.cellTraffice.tx,label: "",speed: false) cell.downInfoLabel.text = report.cellTraffice.toString(x: report.cellTraffice.rx,label: "",speed: false) cell.catLabel.text = "\u{f274}" default: break } /* if flag { //print("TCP Connection: \(report.connectionCount) memory:\(report.memoryUsed) ") }else { cell.textLabel?.text = "Session Not Start" cell.catLabel.isHidden = true cell.downLabel.isHidden = true cell.downInfoLabel.isHidden = true cell.upLabel.isHidden = true cell.upInfoLabel.isHidden = true }*/ cell.downLabel.isHidden = false cell.upLabel.isHidden = false } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if indexPath.section == 0 && fileList.count == 0 { return nil } if indexPath.section == 1 { return nil } return indexPath } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row == 0 { guard let m = SFVPNManager.shared.manager else {return true} if m.connection.status == .connected { return false }else { if fileList.count == 0 { return false } return true } } return true } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if indexPath.item < fileList.count { return .delete } return .delete } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ let f = fileList[indexPath.row] let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/" + f.name) //saveProxys() do { try fm.removeItem(at: url) fileList.remove(at: indexPath.row) } catch _ { } tableView.reloadData() } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. if segue.identifier == "showFile"{ guard let addEditController = segue.destination as? LogFileViewController else{return} let cell = sender as? UITableViewCell guard let indexPath = tableView.indexPath(for: cell!) else {return } let f = fileList[indexPath.row] addEditController.navigationItem.title = f.name let url = groupContainerURL().appendingPathComponent("Log/" + self.filePath + "/" + f.name) addEditController.filePath = url // addEditController.delegate = self }else if segue.identifier == "showDB" { guard let vc = segue.destination as? HistoryViewController else{return} vc.session = self.filePath } } }
bsd-3-clause
e74c2775004f828e37ad8c1b6af16b44
37.084192
183
0.546898
4.710946
false
false
false
false
wowiwj/WDayDayCook
WDayDayCook/WDayDayCook/Controllers/Choose/ChooseViewController.swift
1
11413
// // ChooseViewController.swift // WDayDayCook // // Created by wangju on 16/7/24. // Copyright © 2016年 wangju. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import RealmSwift import SDCycleScrollView let cellIdentifier = "MyCollectionCell" let ThemeListTableViewCellID = "ThemeListTableViewCell" let RecipeDiscussListTableViewCellID = "RecipeDiscussListTableViewCell" final class ChooseViewController: UIViewController { @IBOutlet weak var tableView: UITableView!{ didSet{ tableView.backgroundColor = UIColor.white tableView.register(MyCollectionCell.self, forCellReuseIdentifier: cellIdentifier) tableView.register(ThemeListTableViewCell.self, forCellReuseIdentifier: ThemeListTableViewCellID) tableView.register(RecipeDiscussListTableViewCell.self, forCellReuseIdentifier: RecipeDiscussListTableViewCellID) tableView.separatorStyle = .none tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0) tableView.estimatedRowHeight = 250 } } fileprivate lazy var titleView :UIImageView = { let titleView = UIImageView() titleView.image = UIImage(named: "navi_logo~iphone") titleView.sizeToFit() return titleView }() fileprivate var realm: Realm! // 广告数据 fileprivate lazy var adData: Results<MainADItem> = { return getADItemInRealm(self.realm) }() // 每日新品数据 fileprivate var newFoodItems: Results<NewFood>?{ didSet{ tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic) } } /// 主题推荐 fileprivate var themeList: Results<FoodRecmmand>? /// 热门推荐 fileprivate var recipeList: Results<FoodRecmmand>? /// 话题推荐 fileprivate var recipeDiscussList: Results<FoodRecmmand>? // tabble头部 var cycleView: SDCycleScrollView? override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = titleView let searchButton = UIBarButtonItem(image: UIImage(named: "icon-search~iphone"), style: .plain, target: self, action: #selector(searchButtonClicked(_:))) navigationItem.rightBarButtonItem = searchButton realm = try! Realm() let placeholderImage = UIImage(named: "default_1~iphone")! let images = realm.objects(MainADItem.self).map { item -> String in return item.path } cycleView = SDCycleScrollView(frame: CGRect(origin: CGPoint.zero, size: placeholderImage.size), delegate: self, placeholderImage: placeholderImage) //cycleView!.imageURLStringsGroup = images tableView.tableHeaderView = cycleView tableView.addHeaderWithCallback { let group = DispatchGroup() let queue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default) queue.async(group: group) { self.loadADData() } queue.async(group: group) { self.loadNewFoodEachDay(0, pageSize: 10) } group.notify(queue: queue) { self.loadRecommandInfo() } } self.tableView.headerBeginRefreshing() // self.tableView.addEmptyDataSetView { (set) in // set.image = UIImage(named: "666") // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.navigationController?.navigationBar.hidden = false } // MARK: - LoadData /// 加载上方滚动广告 func loadADData(){ Alamofire.request(Router.chooseViewAdList(parameters: nil)).responseJSON { [unowned self] responses in if responses.result.isFailure { WDAlert.alertSorry(message: "网络异常", inViewController: self) // 加载失败,使用旧数据 return } let json = responses.result.value let result = JSON(json!) deleteAllADItem() addNewMainADItemInRealm(result["data"]) // 加载成功,使用新数据 self.adData = getADItemInRealm(self.realm) self.cycleView?.imageURLStringsGroup = self.realm.objects(MainADItem.self).map { item -> String in return item.path } } } // 加载每日新品 func loadNewFoodEachDay(_ currentPage:Int,pageSize:Int) { Alamofire.request(Router.newFoodEachDay(currentpage: currentPage, pageSize: pageSize)).responseJSON { [unowned self] response in if response.result.isFailure { WDAlert.alertSorry(message: "网络异常", inViewController: self) // 获取离线数据 self.newFoodItems = getNewFoodItemInRealm(self.realm) return } let value = response.result.value let result = JSON(value!) deleteAllObject(NewFood.self) addNewFoodItemInRealm(result["data"]) self.newFoodItems = getNewFoodItemInRealm(self.realm) } } /// 加载推荐信息数据 func loadRecommandInfo() { Alamofire.request(Router.recommendInfo(parameters: nil)).responseJSON {[unowned self] response in self.tableView.headerEndRefreshing() func getFoodRecmmand() { self.themeList = getThemeListInRealm(self.realm) self.recipeList = getRecipeListInRealm(self.realm) self.recipeDiscussList = getRecipeDiscussListInRealm(self.realm) self.tableView.reloadData() } if response.result.isFailure { print(response.request) print(response.result.error) WDAlert.alertSorry(message: "网络异常", inViewController: self) getFoodRecmmand() return } let value = response.result.value let result = JSON(value!) func updateFoodRecmmand() { // 删除之前存的旧数据 deleteAllObject(FoodRecmmand.self) // 添加新数据到数据库 addFoodRecmmandItemInRealm(result["themeList"]) addFoodRecmmandItemInRealm(result["recipeList"]) addFoodRecmmandItemInRealm(result["recipeDiscussList"]) } updateFoodRecmmand() getFoodRecmmand() } } // MARK: - 控制器跳转 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else{ return } if identifier == "showDetail" { let vc = segue.destination as! ShowDetailViewController let item = sender as! Int vc.id = item } } // MARK: - 动作监听 @objc fileprivate func searchButtonClicked(_ button:UIButton) { } } // MARK: - UITableViewDelegate,UITableViewDataSource extension ChooseViewController:UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if recipeDiscussList == nil { return 3 } return recipeDiscussList!.count > 0 ? 4 : 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch (indexPath as NSIndexPath).row { case CellStyle.themeList.rawValue: let cell = tableView.dequeueReusableCell(withIdentifier: ThemeListTableViewCellID)! as! ThemeListTableViewCell cell.delegate = self return cell case CellStyle.recipeDiscussList.rawValue: let cell = tableView.dequeueReusableCell(withIdentifier: RecipeDiscussListTableViewCellID)! return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)! as! MyCollectionCell cell.delegate = self return cell } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).row { case CellStyle.newFood.rawValue: let newFoodcell = cell as! MyCollectionCell newFoodcell.newFoodItems = newFoodItems case CellStyle.themeList.rawValue: let cell = cell as! ThemeListTableViewCell cell.themeList = themeList case CellStyle.recipeList.rawValue: let cell = cell as! MyCollectionCell cell.recipeList = recipeList default: let cell = cell as! RecipeDiscussListTableViewCell cell.recipeDiscussList = recipeDiscussList } } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { // let cell = cell as! MyCollectionCell // cell.collectionView.frame = CGRectZero } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch (indexPath as NSIndexPath).row { case CellStyle.themeList.rawValue: return CGFloat(themeList?.count ?? 0).autoAdjust() * WDConfig.themeListHeight + 30 case CellStyle.recipeDiscussList.rawValue: return CGFloat(200).autoAdjust() default: return CGFloat(280).autoAdjust() } } } extension ChooseViewController : SDCycleScrollViewDelegate { func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) { let item = adData[index] performSegue(withIdentifier: "showDetail", sender: Int(item.url)) } } extension ChooseViewController :MyCollectionCellDelegete,ThemeListTableViewCellDelagate { func didSeclectItem(_ item: Object) { if item is NewFood { performSegue(withIdentifier: "showDetail", sender: (item as! NewFood).id) } if item is FoodRecmmand{ performSegue(withIdentifier: "showDetail", sender: (item as! FoodRecmmand).recipe_id) } if item is FoodRecmmand { } } }
mit
f17babece346aa97cef52f4836a52d22
29.319783
160
0.582767
5.330157
false
false
false
false
Eonil/Editor
Editor4/WorkspaceWindowController.swift
1
3799
// // WorkspaceWindowController.swift // Editor4 // // Created by Hoon H. on 2016/04/20. // Copyright © 2016 Eonil. All rights reserved. // import Foundation import AppKit import EonilToolbox private struct LocalState { var workspaceID: WorkspaceID? } final class WorkspaceWindowController: NSWindowController, DriverAccessible, WorkspaceRenderable { private let columnSplitViewController = NSSplitViewController() private let navigatorViewController = NavigatorViewController() private let rowSplitViewController = NSSplitViewController() private let dummy1ViewController = WorkspaceRenderableViewController() private var installer = ViewInstaller() private var localState = LocalState() //////////////////////////////////////////////////////////////// /// Designated initializer. init() { let newWindow = WorkspaceWindow() newWindow.appearance = NSAppearance(named: NSAppearanceNameVibrantDark) newWindow.styleMask |= NSClosableWindowMask | NSResizableWindowMask | NSTitledWindowMask super.init(window: newWindow) // newWindow.display() // newWindow.makeKeyAndOrderFront(self) // let newWorkspaceViewController = WorkspaceViewController() // workspaceViewController = newWorkspaceViewController // contentViewController = newWorkspaceViewController shouldCloseDocument = false NotificationUtility.register(self, NSWindowWillCloseNotification, self.dynamicType.process) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationUtility.deregister(self) } //////////////////////////////////////////////////////////////// func render(state: UserInteractionState, workspace: (id: WorkspaceID, state: WorkspaceState)?) { renderLocalState() contentViewController?.renderRecursively(state, workspace: workspace) } private func renderLocalState() { installer.installIfNeeded { // assert(columnSplitViewController.view.autoresizesSubviews == false) // assert(rowSplitViewController.view.autoresizesSubviews == false) contentViewController = columnSplitViewController columnSplitViewController.view.autoresizesSubviews = false columnSplitViewController.splitViewItems = [ NSSplitViewItem(contentListWithViewController: navigatorViewController), NSSplitViewItem(viewController: rowSplitViewController), ] rowSplitViewController.view.autoresizesSubviews = false rowSplitViewController.splitViewItems = [ NSSplitViewItem(viewController: dummy1ViewController), ] } localState.workspaceID = localState.workspaceID } private func process(n: NSNotification) { switch n.name { case NSWindowWillCloseNotification: guard n.object === window else { return } guard let workspaceID = localState.workspaceID else { return } driver.operation.closeWorkspace(workspaceID) default: break } } } extension WorkspaceWindowController { override var shouldCloseDocument: Bool { willSet { assert(newValue == false) } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private final class WorkspaceWindow: NSWindow { override var canBecomeMainWindow: Bool { get { return true } } }
mit
cf87b2729e16e785f5ed93cfb6a62b25
28.44186
128
0.614534
6.155592
false
false
false
false
ryanspillsbury90/HaleMeditates
ios/Hale Meditates/CallToActionViewController.swift
1
1622
// // CallToActionViewController.swift // Hale Meditates // // Created by Ryan Pillsbury on 6/27/15. // Copyright (c) 2015 koait. All rights reserved. // import UIKit class CallToActionViewController: UIViewController { @IBOutlet weak var proportialConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad(); self.navigationItem.title = "Home"; // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: true); super.viewWillAppear(animated); } @IBAction func openGoPremiumWebPage() { let controller = UIUtil.getViewControllerFromStoryboard("WebViewController") as! WebViewController if let URL = NSURL(string: "http://www.wired.com") { controller.url = URL; controller.view.frame = self.navigationController!.view.frame; self.presentViewController(controller, animated: true, completion: nil); } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
b021911dceb0a982b429e6aa4ed1c7e3
30.803922
106
0.675709
4.945122
false
false
false
false
tjw/swift
test/Constraints/overload.swift
4
6073
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} func f0(_: Float) -> Float {} func f0(_: Int) -> Int {} func f1(_: Int) {} func identity<T>(_: T) -> T {} func f2<T>(_: T) -> T {} // FIXME: Fun things happen when we make this T, U! func f2<T>(_: T, _: T) -> (T, T) { } struct X {} var x : X var i : Int var f : Float _ = f0(i) _ = f0(1.0) _ = f0(1) f1(f0(1)) f1(identity(1)) f0(x) // expected-error{{cannot invoke 'f0' with an argument list of type '(X)'}} // expected-note @-1 {{overloads for 'f0' exist with these partially matching parameter lists: (Float), (Int)}} _ = f + 1 _ = f2(i) _ = f2((i, f)) class A { init() {} } class B : A { override init() { super.init() } } class C : B { override init() { super.init() } } func bar(_ b: B) -> Int {} // #1 func bar(_ a: A) -> Float {} // #2 var barResult = bar(C()) // selects #1, which is more specialized i = barResult // make sure we got #1 f = bar(C()) // selects #2 because of context // Overload resolution for constructors protocol P1 { } struct X1a : P1 { } struct X1b { init(x : X1a) { } init<T : P1>(x : T) { } } X1b(x: X1a()) // expected-warning{{unused}} // Overload resolution for subscript operators. class X2a { } class X2b : X2a { } class X2c : X2b { } struct X2d { subscript (index : X2a) -> Int { return 5 } subscript (index : X2b) -> Int { return 7 } func foo(_ x : X2c) -> Int { return self[x] } } // Invalid declarations // FIXME: Suppress the diagnostic for the call below, because the invalid // declaration would have matched. func f3(_ x: Intthingy) -> Int { } // expected-error{{use of undeclared type 'Intthingy'}} func f3(_ x: Float) -> Float { } f3(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} func f4(_ i: Wonka) { } // expected-error{{use of undeclared type 'Wonka'}} func f4(_ j: Wibble) { } // expected-error{{use of undeclared type 'Wibble'}} f4(5) func f1() { var c : Class // expected-error{{use of undeclared type 'Class'}} markUsed(c.x) // make sure error does not cascade here } // We don't provide return-type sensitivity unless there is context. func f5(_ i: Int) -> A { return A() } // expected-note{{candidate}} func f5(_ i: Int) -> B { return B() } // expected-note{{candidate}} f5(5) // expected-error{{ambiguous use of 'f5'}} struct HasX1aProperty { func write(_: X1a) {} func write(_: P1) {} var prop = X1a() func test() { write(prop) // no error, not ambiguous } } // rdar://problem/16554496 @available(*, unavailable) func availTest(_ x: Int) {} func availTest(_ x: Any) { markUsed("this one") } func doAvailTest(_ x: Int) { availTest(x) } // rdar://problem/20886179 func test20886179(_ handlers: [(Int) -> Void], buttonIndex: Int) { handlers[buttonIndex](buttonIndex) } // The problem here is that the call has a contextual result type incompatible // with *all* overload set candidates. This is not an ambiguity. func overloaded_identity(_ a : Int) -> Int {} func overloaded_identity(_ b : Float) -> Float {} func test_contextual_result_1() { return overloaded_identity() // expected-error {{cannot invoke 'overloaded_identity' with no arguments}} // expected-note @-1 {{overloads for 'overloaded_identity' exist with these partially matching parameter lists: (Int), (Float)}} } func test_contextual_result_2() { return overloaded_identity(1) // expected-error {{unexpected non-void return value in void function}} } // rdar://problem/24128153 struct X0 { init(_ i: Any.Type) { } init?(_ i: Any.Type, _ names: String...) { } } let x0 = X0(Int.self) let x0check: X0 = x0 // okay: chooses first initializer struct X1 { init?(_ i: Any.Type) { } init(_ i: Any.Type, _ names: String...) { } } let x1 = X1(Int.self) let x1check: X1 = x1 // expected-error{{value of optional type 'X1?' not unwrapped; did you mean to use '!' or '?'?}} struct X2 { init?(_ i: Any.Type) { } init(_ i: Any.Type, a: Int = 0) { } init(_ i: Any.Type, a: Int = 0, b: Int = 0) { } init(_ i: Any.Type, a: Int = 0, c: Int = 0) { } } let x2 = X2(Int.self) let x2check: X2 = x2 // expected-error{{value of optional type 'X2?' not unwrapped; did you mean to use '!' or '?'?}} // rdar://problem/28051973 struct R_28051973 { mutating func f(_ i: Int) {} @available(*, deprecated, message: "deprecated") func f(_ f: Float) {} } let r28051973: Int = 42 R_28051973().f(r28051973) // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}} // Fix for CSDiag vs CSSolver disagreement on what constitutes a // valid overload. func overloadedMethod(n: Int) {} // expected-note {{'overloadedMethod(n:)' declared here}} func overloadedMethod<T>() {} // expected-error@-1 {{generic parameter 'T' is not used in function signature}} overloadedMethod() // expected-error@-1 {{missing argument for parameter 'n' in call}} // Ensure we select the overload of '??' returning T? rather than T. func SR3817(_ d: [String : Any], _ s: String, _ t: String) -> Any { if let r = d[s] ?? d[t] { return r } else { return 0 } } // Overloading with mismatched labels. func f6<T>(foo: T) { } func f6<T: P1>(bar: T) { } struct X6 { init<T>(foo: T) { } init<T: P1>(bar: T) { } } func test_f6() { let _: (X1a) -> Void = f6 let _: (X1a) -> X6 = X6.init } func curry<LHS, RHS, R>(_ f: @escaping (LHS, RHS) -> R) -> (LHS) -> (RHS) -> R { return { lhs in { rhs in f(lhs, rhs) } } } // We need to have an alternative version of this to ensure that there's an overload disjunction created. func curry<F, S, T, R>(_ f: @escaping (F, S, T) -> R) -> (F) -> (S) -> (T) -> R { return { fst in { snd in { thd in f(fst, snd, thd) } } } } // Ensure that we consider these unambiguous let _ = curry(+)(1) let _ = [0].reduce(0, +) let _ = curry(+)("string vs. pointer") func autoclosure1<T>(_: T, _: @autoclosure () -> X) { } func autoclosure1<T>(_: [T], _: X) { } func test_autoclosure1(ia: [Int]) { autoclosure1(ia, X()) // okay: resolves to the second function }
apache-2.0
1b575998e1b949c28456c1970c127e3c
24.952991
132
0.618146
2.95811
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift
27
2165
// // Generate.swift // Rx // // Created by Krunoslav Zaher on 9/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class GenerateSink<S, O: ObserverType> : Sink<O> { typealias Parent = Generate<S, O.E> let parent: Parent var state: S init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent self.state = parent.initialState super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return parent.scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in do { if !isFirst { self.state = try self.parent.iterate(self.state) } if try self.parent.condition(self.state) { let result = try self.parent.resultSelector(self.state) self.observer?.on(.Next(result)) recurse(false) } else { self.observer?.on(.Completed) self.dispose() } } catch let error { self.observer?.on(.Error(error)) self.dispose() } } } } class Generate<S, E> : Producer<E> { let initialState: S let condition: S throws -> Bool let iterate: S throws -> S let resultSelector: S throws -> E let scheduler: ImmediateSchedulerType init(initialState: S, condition: S throws -> Bool, iterate: S throws -> S, resultSelector: S throws -> E, scheduler: ImmediateSchedulerType) { self.initialState = initialState self.condition = condition self.iterate = iterate self.resultSelector = resultSelector self.scheduler = scheduler super.init() } override func run<O : ObserverType where O.E == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
gpl-3.0
e51ade6b3a4895c6d73222eed85ff26d
29.492958
146
0.548983
4.623932
false
false
false
false
playstones/NEKit
src/Utils/Checksum.swift
1
1569
import Foundation open class Checksum { open static func computeChecksum(_ data: Data, from start: Int = 0, to end: Int? = nil, withPseudoHeaderChecksum initChecksum: UInt32 = 0) -> UInt16 { return toChecksum(computeChecksumUnfold(data, from: start, to: end, withPseudoHeaderChecksum: initChecksum)) } open static func validateChecksum(_ payload: Data, from start: Int = 0, to end: Int? = nil) -> Bool { let cs = computeChecksumUnfold(payload, from: start, to: end) return toChecksum(cs) == 0 } open static func computeChecksumUnfold(_ data: Data, from start: Int = 0, to end: Int? = nil, withPseudoHeaderChecksum initChecksum: UInt32 = 0) -> UInt32 { let scanner = BinaryDataScanner(data: data, littleEndian: true) scanner.skip(to: start) var result: UInt32 = initChecksum var end = end if end == nil { end = data.count } while scanner.position + 2 <= end! { let value = scanner.read16()! result += UInt32(value) } if scanner.position != end { // data is of odd size // Intel and ARM are both litten endian // so just add it let value = scanner.readByte()! result += UInt32(value) } return result } open static func toChecksum(_ checksum: UInt32) -> UInt16 { var result = checksum while (result) >> 16 != 0 { result = result >> 16 + result & 0xFFFF } return ~UInt16(result) } }
bsd-3-clause
d8a73f477fbf7383ac8ed0bb736ee7da
34.659091
160
0.585723
4.161804
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/viewcontrollers/setting/SettingViewController.swift
1
9443
// // SettingViewController.swift // Chance_wallet // // Created by Chance on 16/1/26. // Copyright © 2016年 Chance. All rights reserved. // import UIKit class SettingViewController: BaseTableViewController { /// 列表title var rowsTitle: [[String]] = [ [ "Export Public Key".localized(), "Export Private Key".localized(), "Export RedeemScript".localized(), ], [ "Export Wallet Passphrases".localized(), "Restore Wallet By Passphrases".localized(), ], [ "Security Setting".localized(), ], [ "Blockchain Nodes".localized(), ], [ "iCloud Auto Backup".localized(), ], [ "Reset Wallet".localized(), ] ] var currentAccount: CHBTCAcount? { let i = CHBTCWallet.sharedInstance.selectedAccountIndex if i != -1 { return CHBTCWallet.sharedInstance.getAccount(byIndex: i) } else { return nil } } override func viewDidLoad() { super.viewDidLoad() self.setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //CloudUtils.shared.query() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return self.rowsTitle.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if let account = self.currentAccount { if account.accountType == .multiSig { return self.rowsTitle[section].count } else { return self.rowsTitle[section].count - 1 } } else { return 0 } default: return self.rowsTitle[section].count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SettingCell.cellIdentifier) as! SettingCell cell.switchEnable.isHidden = true cell.accessoryType = .disclosureIndicator cell.labelTitle.text = self.rowsTitle[indexPath.section][indexPath.row] switch indexPath.section { case 4: //icloud同步开关 cell.accessoryType = .none cell.switchEnable.isHidden = false cell.switchEnable.isOn = CHWalletWrapper.enableICloud //设置是否登录icloud账号 if CloudUtils.shared.iCloud { cell.switchEnable.isEnabled = true } else { cell.switchEnable.isEnabled = false } //开关调用 cell.enableChange = { (pressCell, sender) -> Void in self.handleICloudBackupChange(sender: sender) } default: cell.switchEnable.isHidden = true cell.accessoryType = .disclosureIndicator } return cell } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 18 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == self.numberOfSections(in: self.tableView) - 1 { return 60 } else { return 0.01 } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let doBlock = { () -> Void in var title = "" if indexPath.section == 0 { var keyType = ExportKeyType.PublicKey if indexPath.row == 0 { keyType = ExportKeyType.PublicKey title = "Public Key".localized() } else if indexPath.row == 1 { keyType = ExportKeyType.PrivateKey title = "Private Key".localized() } else if indexPath.row == 2 { keyType = ExportKeyType.RedeemScript title = "RedeemScript".localized() } guard let vc = StoryBoard.setting.initView(type: ExportKeyViewController.self) else { return } vc.currentAccount = self.currentAccount! vc.keyType = keyType vc.navigationItem.title = title vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } else if indexPath.section == 1 { var restoreOperateType = RestoreOperateType.lookupPassphrase var title = "" if indexPath.row == 0 { restoreOperateType = .lookupPassphrase title = "Passphrase".localized() } else { restoreOperateType = .initiativeRestore title = "Restore wallet".localized() } guard let vc = StoryBoard.setting.initView(type: RestoreWalletViewController.self) else { return } vc.restoreOperateType = restoreOperateType vc.navigationItem.title = title vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } else if indexPath.section == 2 { if indexPath.row == 0 { guard let vc = StoryBoard.setting.initView(type: PasswordSettingViewController.self) else { return } vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } } else if indexPath.section == 3 { //进入设置云节点 if indexPath.row == 0 { guard let vc = StoryBoard.setting.initView(type: BlockchainNodeSettingViewController.self) else { return } vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } } else if indexPath.section == 4 { } else if indexPath.section == 5 { self.showResetWalletAlert() } } switch indexPath.section { case 0, 1, 2, 5: //需要密码 //需要提供指纹密码 CHWalletWrapper.unlock(vc: self, complete: { (flag, error) in if flag { doBlock() } else { if error != "" { SVProgressHUD.showError(withStatus: error) } } }) default: //默认不需要密码 doBlock() } } } // MARK: - 控制器方法 extension SettingViewController { /** 配置UI */ func setupUI() { self.navigationItem.title = "Setting".localized() } /// 切换是否使用icloud备份 /// /// - Parameter sender: @IBAction func handleICloudBackupChange(sender: UISwitch) { CHWalletWrapper.enableICloud = sender.isOn if sender.isOn { //开启后,马上进行同步 let db = RealmDBHelper.shared.acountDB RealmDBHelper.shared.iCloudSynchronize(db: db) } } /// 弹出重置钱包的警告 func showResetWalletAlert() { let actionSheet = UIAlertController(title: "Warning".localized(), message: "Please backup your passphrase before you do that.It's dangerous.".localized(), preferredStyle: UIAlertControllerStyle.actionSheet) actionSheet.addAction(UIAlertAction(title: "Reset".localized(), style: UIAlertActionStyle.default, handler: { (action) -> Void in //删除钱包所有资料 CHWalletWrapper.deleteAllWallets() //弹出欢迎界面,创新创建钱包 AppDelegate.sharedInstance().restoreWelcomeController() })) actionSheet.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel, handler: { (action) -> Void in })) self.present(actionSheet, animated: true, completion: nil) } }
mit
819437cfabe82aea88f644219d8d581f
31.314685
214
0.516988
5.701419
false
false
false
false
natecook1000/swift
test/SILGen/objc_factory_init.swift
3
6617
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import Foundation import ImportAsMember.Class // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive> func testInstanceTypeFactoryMethod(queen: Bee) { // CHECK: bb0([[QUEEN:%[0-9]+]] : @owned $Optional<Bee>, [[HIVE_META:%[0-9]+]] : @trivial $@thick Hive.Type): // CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: destroy_value [[QUEEN]] // CHECK-NEXT: return [[HIVE]] : $Optional<Hive> var hive1 = Hive(queen: queen) } extension Hive { // FIXME: This whole approach is wrong. This should be a factory initializer, // not a convenience initializer, which means it does not have an initializing // entry point at all. // CHECK-LABEL: sil hidden @$SSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive { // CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[OLD_HIVE:%.*]] : @owned $Hive): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self" // CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var Hive }, 0 // CHECK: store [[OLD_HIVE]] to [init] [[PB_BOX]] // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[BORROWED_SELF]] : $Hive // CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]] // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK: [[BORROWED_QUEEN:%.*]] = begin_borrow [[QUEEN]] // CHECK: [[COPIED_BORROWED_QUEEN:%.*]] = copy_value [[BORROWED_QUEEN]] // CHECK: [[OPT_COPIED_BORROWED_QUEEN:%.*]] = enum $Optional<Bee>, #Optional.some!enumelt.1, [[COPIED_BORROWED_QUEEN]] // CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: [[NEW_HIVE:%.*]] = apply [[FACTORY]]([[OPT_COPIED_BORROWED_QUEEN]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: destroy_value [[OPT_COPIED_BORROWED_QUEEN]] // CHECK: end_borrow [[BORROWED_QUEEN]] from [[QUEEN]] // CHECK: switch_enum [[NEW_HIVE]] : $Optional<Hive>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[NEW_HIVE:%.*]] : @owned $Hive): // CHECK: assign [[NEW_HIVE]] to [[PB_BOX]] // CHECK: } // end sil function '$SSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc' convenience init(otherQueen other: Bee) { self.init(queen: other) } // CHECK-LABEL: sil hidden @$SSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC : $@convention(method) (@owned Bee, @thick Hive.Type) -> (@owned Hive, @error Error) { // CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[METATYPE:%.*]] : @trivial $@thick Hive.Type): // CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]] // CHECK: [[HIVE:%.*]] = alloc_ref_dynamic [objc] [[OBJC_METATYPE]] // CHECK: try_apply {{.*}}([[QUEEN]], [[HIVE]]) : $@convention(method) (@owned Bee, @owned Hive) -> (@owned Hive, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[NORMAL_BB]]([[HIVE:%.*]] : @owned $Hive): // CHECK: return [[HIVE]] // // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: builtin "willThrow"([[ERROR]] : $Error) // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$SSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC' convenience init(otherFlakyQueen other: Bee) throws { try self.init(flakyQueen: other) } } extension SomeClass { // CHECK-LABEL: sil hidden @$SSo12IAMSomeClassC17objc_factory_initE6doubleABSd_tcfc : $@convention(method) (Double, @owned SomeClass) -> @owned SomeClass { // CHECK: bb0([[DOUBLE:%.*]] : @trivial $Double, // CHECK-NOT: value_metatype // CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // CHECK: apply [[FNREF]]([[DOUBLE]]) // CHECK: } // end sil function '$SSo12IAMSomeClassC17objc_factory_initE6doubleABSd_tcfc' convenience init(double: Double) { self.init(value: double) } } class SubHive : Hive { // CHECK-LABEL: sil hidden @$S17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive { // CHECK: bb0([[SUBHIVE:%.*]] : @owned $SubHive): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SubHive }, let, name "self" // CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var SubHive } // CHECK: [[PB_BOX:%.*]] = project_box [[MU]] : ${ var SubHive }, 0 // CHECK: store [[SUBHIVE]] to [init] [[PB_BOX]] // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[UPCAST_BORROWED_SELF:%.*]] = upcast [[BORROWED_SELF]] : $SubHive to $Hive // CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST_BORROWED_SELF:%.*]] // CHECK: end_borrow [[BORROWED_SELF]] from [[PB_BOX]] // CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]] // CHECK: [[QUEEN:%.*]] = unchecked_ref_cast {{.*}} : $Bee to $Optional<Bee> // CHECK: [[HIVE_INIT_FN:%.*]] = objc_method [[OBJC_METATYPE]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign // CHECK: apply [[HIVE_INIT_FN]]([[QUEEN]], [[OBJC_METATYPE]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: destroy_value [[QUEEN]] // CHECK: } // end sil function '$S17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc' convenience init(delegatesToInherited: ()) { self.init(queen: Bee()) } }
apache-2.0
f00c6ca4ba72724cc867ace219401cb2
65.17
265
0.631857
3.31347
false
false
false
false