repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
howardhsien/EasyTaipei-iOS
EasyTaipei/EasyTaipei/controller/MapViewController.swift
1
8272
// // MapViewController.swift // EasyTaipei // // Created by howard hsien on 2016/7/5. // Copyright © 2016年 AppWorks School Hsien. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController{ //MARK: outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var detailPanel: UIView! @IBOutlet weak var detailPanelTitleLabel: UILabel! @IBOutlet weak var detailPanelSubtitleLabel: UILabel! @IBOutlet weak var detailPanelSideLabel: UILabel! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet weak var mapNavigateButton: UIButton! @IBOutlet weak var markerImageView: UIImageView! //MARK: helpers var locationManager = CLLocationManager() var jsonParser = JSONParser.sharedInstance() var annotationAdded = false var dataType :DataType? //reuse images to save memory var toiletIcon : UIImage? = { if let image = UIImage(named: "toilet") { return image.imageWithRenderingMode(.AlwaysTemplate) } else{ return nil } }() var youbikeIcon : UIImage? = { if let image = UIImage(named: "bike") { return image.imageWithRenderingMode(.AlwaysTemplate) } else{ return nil } }() //MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() setupDetailPanel() setupStyle() setupMapAndLocationManager() setupMapRegion() setupActivityIndicator() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !annotationAdded{ guard let dataType = dataType else{ return } showInfoType(dataType: dataType) } } //MARK: Style Setting private func bringViewToFront(){ view.bringSubviewToFront(mapNavigateButton) view.bringSubviewToFront(activityIndicatorView) } private func setupActivityIndicator(){ activityIndicatorView.hidden = true activityIndicatorView.hidesWhenStopped = true } private func setupStyle(){ self.view.bringSubviewToFront(detailPanel) markerImageView.image = markerImageView.image?.imageWithRenderingMode(.AlwaysTemplate) markerImageView.tintColor = UIColor.esyOffWhiteColor() } private func setupDetailPanel(){ detailPanel.hidden = true } //MARK: Display Infomation func showInfoType(dataType type: DataType){ activityIndicatorView?.startAnimating() jsonParser.request?.cancel() jsonParser.getDataWithCompletionHandler(type, completion: {[unowned self] in self.dataType = type guard let _ = self.mapView else { return } self.addAnnotationOnMapview(dataType: type) self.activityIndicatorView?.stopAnimating() } ) } func reloadData(){ guard let dataType = self.dataType else { return } showInfoType(dataType: dataType) } } //MARK: MapView and LocationManager Method extension MapViewController: MKMapViewDelegate, CLLocationManagerDelegate { //MARK: locationManager func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { print("didChangeAuthorizationStatus") setupMapRegion() } func setupMapAndLocationManager(){ locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyBest mapView.delegate = self mapView.showsUserLocation = true mapNavigateButton.addTarget(self, action: #selector(setupMapRegion), forControlEvents: .TouchUpInside) } //MARK: Method func addAnnotationOnMapview(dataType type: DataType){ mapView.removeAnnotations(mapView.annotations) switch type { case .Toilet: if jsonParser.toilets.isEmpty { return } for toilet in jsonParser.toilets{ let annotation = CustomMKPointAnnotation() annotation.type = type annotation.toilet = toilet annotation.updateInfo() mapView.addAnnotation(annotation) } case .Youbike: if jsonParser.youbikes.isEmpty { return } for youbike in jsonParser.youbikes{ let annotation = CustomMKPointAnnotation() annotation.type = type annotation.youbike = youbike annotation.updateInfo() mapView.addAnnotation(annotation) } } self.annotationAdded = true } func setupMapRegion(){ let span = MKCoordinateSpanMake(0.006, 0.006) if let location = locationManager.location { let region = MKCoordinateRegion(center: location.coordinate , span: span) mapView.setRegion(region, animated: true) } else{ let location = mapView.userLocation let region = MKCoordinateRegion(center: location.coordinate , span: span) mapView.setRegion(region, animated: true) } } //MARK: MapView func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? CustomMKPointAnnotation else { return nil} var annotationView: CustomAnnotationView? let annotationViewDiameter:CGFloat = 35; switch annotation.type! { case .Toilet: let reuseIdentifier = " toiletAnnotationView" //handle reuse identifier to better manage the memory if let view = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier){ annotationView = view as? CustomAnnotationView } else { annotationView = CustomAnnotationView(frame:CGRectMake(0, 0, annotationViewDiameter, annotationViewDiameter),annotation: annotation, reuseIdentifier: reuseIdentifier) if let icon = toiletIcon{ annotationView?.setCustomImage(icon) } } case .Youbike: let reuseIdentifier = " youbikeAnnotationView" if let view = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier){ annotationView = view as? CustomAnnotationView } else { annotationView = CustomAnnotationView(frame:CGRectMake(0, 0, annotationViewDiameter, annotationViewDiameter),annotation: annotation, reuseIdentifier: reuseIdentifier) if let icon = youbikeIcon{ annotationView?.setCustomImage(icon) } } } annotationView?.canShowCallout = true return annotationView } func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { if let annotation = view.annotation as? CustomMKPointAnnotation { view.backgroundColor = UIColor.esyRobinsEggBlueColor() detailPanel.hidden = false let annotationLocation = CLLocation( latitude:annotation.coordinate.latitude, longitude: annotation.coordinate.longitude) if let userLocation = locationManager.location{ let distance = annotationLocation.distanceFromLocation(userLocation) let distanceInTime = distance / (3 / 3.6 * 60) //distance in time is not accurate now let roundDistanceInTime = ceil(distanceInTime) detailPanelSideLabel.text = String(format: "%0.0f min(s)", roundDistanceInTime) } detailPanelTitleLabel.text = annotation.title detailPanelSubtitleLabel.text = annotation.address } } func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView) { if view.annotation is MKUserLocation{ return } detailPanel.hidden = true view.backgroundColor = UIColor.whiteColor() } }
mit
logansease/SeaseAssist
Pod/Classes/String+EmojiCheck.swift
1
2784
// // String+emojiCheck.swift // SeaseAssist // // Created by lsease on 2/28/17. // Copyright © 2017 Logan Sease. All rights reserved. // import UIKit public extension UnicodeScalar { var isEmoji: Bool { switch value { case 0x3030, 0x00AE, 0x00A9, // Special Characters 0x1D000 ... 0x1F77F, // Emoticons 0x2100 ... 0x27BF, // Misc symbols and Dingbats 0xFE00 ... 0xFE0F, // Variation Selectors 0x1F900 ... 0x1F9FF: // Supplemental Symbols and Pictographs return true default: return false } } var isZeroWidthJoiner: Bool { return value == 8205 } } public extension String { var glyphCount: Int { let richText = NSAttributedString(string: self) let line = CTLineCreateWithAttributedString(richText) return CTLineGetGlyphCount(line) } var isSingleEmoji: Bool { return glyphCount == 1 && containsEmoji } var containsEmoji: Bool { return !unicodeScalars.filter { $0.isEmoji }.isEmpty } var containsOnlyEmoji: Bool { return unicodeScalars.first(where: { !$0.isEmoji && !$0.isZeroWidthJoiner }) == nil } // The next tricks are mostly to demonstrate how tricky it can be to determine emoji's // If anyone has suggestions how to improve this, please let me know var emojiString: String { return emojiScalars.map { String($0) }.reduce("", +) } var emojis: [String] { var scalars: [[UnicodeScalar]] = [] var currentScalarSet: [UnicodeScalar] = [] var previousScalar: UnicodeScalar? for scalar in emojiScalars { if let prev = previousScalar, !prev.isZeroWidthJoiner && !scalar.isZeroWidthJoiner { scalars.append(currentScalarSet) currentScalarSet = [] } currentScalarSet.append(scalar) previousScalar = scalar } scalars.append(currentScalarSet) return scalars.map { $0.map{ String($0) } .reduce("", +) } } fileprivate var emojiScalars: [UnicodeScalar] { var chars: [UnicodeScalar] = [] var previous: UnicodeScalar? for cur in unicodeScalars { if let previous = previous, previous.isZeroWidthJoiner && cur.isEmoji { chars.append(previous) chars.append(cur) } else if cur.isEmoji { chars.append(cur) } previous = cur } return chars } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09771-swift-typebase-getcanonicaltype.swift
11
232
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A { var d = f var f : b { } protocol b { typealias e : e
mit
MoralAlberto/SlackWebAPIKit
SlackWebAPIKit/Classes/Data/APIClient/Endpoints/UsersListEndpoint.swift
1
145
public class UsersListEndpoint: Endpoint { public var endpointType: EndpointType = .usersList public var parameters: [String: String]? }
mit
MisumiRize/HackerNews-iOS
HackerNewsUITests/HackerNewsUITests.swift
1
1256
// // HackerNewsUITests.swift // HackerNewsUITests // // Created by hoaxster on 2015/10/01. // Copyright © 2015年 Rize MISUMI. All rights reserved. // import XCTest class HackerNewsUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
22377832/swiftdemo
ViewControllerDemo/ViewControllerDemo/FirstViewController.swift
1
1505
// // FirstViewController.swift // ViewControllerDemo // // Created by adults on 2017/3/24. // Copyright © 2017年 adults. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("FirstViewController will appear") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("FirstViewController did appear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("FirstViewController will disappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("FirstViewController did disappear") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - 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
idomizrachi/Regen
regen/Utilities/Logger.swift
1
1484
// // Logger.swift // regen // // Created by Ido Mizrachi on 5/12/17. // import Foundation public class Logger { public enum Level: Int { case verbose = 0 case debug = 1 case info = 2 case warning = 3 case error = 4 case off = 5 } private static let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSS" return formatter }() public static var logLevel: Level = .error public static var color: Bool = true public static func verbose(_ text: String) { log(text, level: .verbose) } public static func debug(_ text: String) { log(color ? text.green : text, level: .debug) } public static func info(_ text: String) { log(text, level: .info) } public static func warning(_ text: String) { log(color ? text.yellow.bold : text, level: .warning) } public static func error(_ text: String) { log(color ? text.red.bold : text, level: .error) } private static func log(_ text: String, level: Level) { if shouldLog(level: level) == false { return } let date = formatter.string(from: Date()) print("\(date) \(text)") } private static func shouldLog(level: Level) -> Bool { return level.rawValue >= Logger.logLevel.rawValue } }
mit
jbrudvik/swift-playgrounds
constants.playground/section-1.swift
1
1108
// `var` defines variables, `let` defines constants // `let` constants must be initialized when defined // let causesAnError: Int // causes an error // Constants may not be assigned more than once let cannotBeAssignedTwice = 3 // cannotBeAssignedTwice = 3 // causes an error // `let` affects deeper than the variable reference itself // `let` arrays may not have their contents changed, nor their lengths changed. This is a change from early versions of Swift, where contents could be changed let a = [Int](0..<10) // a[3] = 12 // cannot change existing indexes a // a.append(3) // fails because append changes length // a.removeAll() // fails because removeAll changes length // `let` dictionaries may not have their contents changed. They are truly immutable. let d = [ "onlyKey": "onlyValue" ] d["onlyKey"] // Evaluates to wrapped optional type containing "onlyValue" d["missingKey"] // Evaluates to nil // bar["onlyKey"] = "differentValue" // fails because dictionary contents may not be changed // bar["missingKey"] = "valueNeverAdded" // fails because new dictionary contents may not be added
mit
bustoutsolutions/siesta
Source/Siesta/Request/NetworkRequest.swift
1
5481
// // NetworkRequest.swift // Siesta // // Created by Paul on 2015/12/15. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation internal final class NetworkRequestDelegate: RequestDelegate { // Basic metadata private let resource: Resource internal var config: Configuration { resource.configuration(for: underlyingRequest) } internal let requestDescription: String // Networking private let requestBuilder: () -> URLRequest // so repeated() can re-read config private let underlyingRequest: URLRequest internal var networking: RequestNetworking? // present only after start() // Progress private var progressComputation: RequestProgressComputation // MARK: Managing request init(resource: Resource, requestBuilder: @escaping () -> URLRequest) { self.resource = resource self.requestBuilder = requestBuilder underlyingRequest = requestBuilder() requestDescription = SiestaLog.Category.enabled.contains(.network) || SiestaLog.Category.enabled.contains(.networkDetails) ? debugStr([underlyingRequest.httpMethod, underlyingRequest.url]) : "NetworkRequest" progressComputation = RequestProgressComputation(isGet: underlyingRequest.httpMethod == "GET") } func startUnderlyingOperation(passingResponseTo completionHandler: RequestCompletionHandler) { let networking = resource.service.networkingProvider.startRequest(underlyingRequest) { res, data, err in DispatchQueue.main.async { self.responseReceived( underlyingResponse: res, body: data, error: err, completionHandler: completionHandler) } } self.networking = networking } func cancelUnderlyingOperation() { networking?.cancel() } func repeated() -> RequestDelegate { NetworkRequestDelegate(resource: resource, requestBuilder: requestBuilder) } // MARK: Progress func computeProgress() -> Double { if let networking = networking { progressComputation.update(from: networking.transferMetrics) } return progressComputation.fractionDone } var progressReportingInterval: TimeInterval { config.progressReportingInterval } // MARK: Response handling // Entry point for response handling. Triggered by RequestNetworking completion callback. private func responseReceived( underlyingResponse: HTTPURLResponse?, body: Data?, error: Error?, completionHandler: RequestCompletionHandler) { DispatchQueue.mainThreadPrecondition() SiestaLog.log(.network, ["Response: ", underlyingResponse?.statusCode ?? error, "←", requestDescription]) SiestaLog.log(.networkDetails, ["Raw response headers:", underlyingResponse?.allHeaderFields]) SiestaLog.log(.networkDetails, ["Raw response body:", body?.count ?? 0, "bytes"]) let responseInfo = interpretResponse(underlyingResponse, body, error) if completionHandler.willIgnore(responseInfo) { return } progressComputation.complete() transformResponse(responseInfo, then: completionHandler.broadcastResponse) } private func isError(httpStatusCode: Int?) -> Bool { guard let httpStatusCode = httpStatusCode else { return false } return httpStatusCode >= 400 } private func interpretResponse( _ underlyingResponse: HTTPURLResponse?, _ body: Data?, _ error: Error?) -> ResponseInfo { if isError(httpStatusCode: underlyingResponse?.statusCode) || error != nil { return ResponseInfo( response: .failure(RequestError(response: underlyingResponse, content: body, cause: error))) } else if underlyingResponse?.statusCode == 304 { if let entity = resource.latestData { return ResponseInfo(response: .success(entity), isNew: false) } else { return ResponseInfo( response: .failure(RequestError( userMessage: NSLocalizedString("No data available", comment: "userMessage"), cause: RequestError.Cause.NoLocalDataFor304()))) } } else { return ResponseInfo(response: .success(Entity<Any>(response: underlyingResponse, content: body ?? Data()))) } } private func transformResponse( _ rawInfo: ResponseInfo, then afterTransformation: @escaping (ResponseInfo) -> Void) { let processor = config.pipeline.makeProcessor(rawInfo.response, resource: resource) DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { let processedInfo = rawInfo.isNew ? ResponseInfo(response: processor(), isNew: true) : rawInfo DispatchQueue.main.async { afterTransformation(processedInfo) } } } }
mit
cburrows/swift-protobuf
FuzzTesting/Sources/FuzzTextFormat/main.swift
3
641
import Foundation import FuzzCommon @_cdecl("LLVMFuzzerTestOneInput") public func FuzzTextFormat(_ start: UnsafeRawPointer, _ count: Int) -> CInt { let bytes = UnsafeRawBufferPointer(start: start, count: count) guard let str = String(data: Data(bytes), encoding: .utf8) else { return 0 } var msg: Fuzz_Testing_Message? do { msg = try Fuzz_Testing_Message( textFormatString: str, extensions: Fuzz_Testing_FuzzTesting_Extensions) } catch { // Error parsing are to be expected since not all input will be well formed. } // Test serialization for completeness. let _ = msg?.textFormatString() return 0 }
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/26216-swift-parser-parsebraceitems.swift
1
421
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck {{}{{let:{let:{var b{c
apache-2.0
kripple/bti-watson
ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift
37
30653
// UploadTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class UploadFileInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndFile() { // Given let URLString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") // When let request = Alamofire.upload(.POST, URLString, file: imageURL) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndFile() { // Given let URLString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") // When let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], file: imageURL) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndData() { // Given let URLString = "https://httpbin.org/" // When let request = Alamofire.upload(.POST, URLString, data: NSData()) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndData() { // Given let URLString = "https://httpbin.org/" // When let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], data: NSData()) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadStreamInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndStream() { // Given let URLString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") let imageStream = NSInputStream(URL: imageURL)! // When let request = Alamofire.upload(.POST, URLString, stream: imageStream) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndStream() { // Given let URLString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") let imageStream = NSInputStream(URL: imageURL)! // When let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], stream: imageStream) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataTestCase: BaseTestCase { func testUploadDataRequest() { // Given let URLString = "https://httpbin.org/post" let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("Upload request should succeed: \(URLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var error: NSError? // When Alamofire.upload(.POST, URLString, data: data) .response { responseRequest, responseResponse, _, responseError in request = responseRequest response = responseResponse error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") } func testUploadDataRequestWithProgress() { // Given let URLString = "https://httpbin.org/post" let data: NSData = { var text = "" for _ in 1...3_000 { text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " } return text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! }() let expectation = expectationWithDescription("Bytes upload progress should be reported: \(URLString)") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var responseRequest: NSURLRequest? var responseResponse: NSHTTPURLResponse? var responseData: NSData? var responseError: ErrorType? // When let upload = Alamofire.upload(.POST, URLString, data: data) upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite) byteValues.append(bytes) let progress = ( completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount ) progressValues.append(progress) } upload.response { request, response, data, error in responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(responseRequest, "response request should not be nil") XCTAssertNotNil(responseResponse, "response response should not be nil") XCTAssertNotNil(responseData, "response data should not be nil") XCTAssertNil(responseError, "response error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } } // MARK: - class UploadMultipartFormDataTestCase: BaseTestCase { // MARK: Tests func testThatUploadingMultipartFormDataSetsContentTypeHeader() { // Given let URLString = "https://httpbin.org/post" let uploadData = "upload_data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var formData: MultipartFormData? var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingCompletion: { result in switch result { case .Success(let upload, _, _): upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") if let request = request, multipartFormData = formData, contentType = request.valueForHTTPHeaderField("Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() { // Given let URLString = "https://httpbin.org/post" let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingCompletion: { result in switch result { case .Success(let upload, _, _): upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") } func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) } func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) } func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() { // Given let URLString = "https://httpbin.org/post" let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: NSURL? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingCompletion: { result in switch result { case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _, _, _, _ in expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNil(streamFileURL, "stream file URL should be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } } func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() { // Given let URLString = "https://httpbin.org/post" let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var formData: MultipartFormData? var request: NSURLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingCompletion: { result in switch result { case let .Success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { responseRequest, _, _, _ in request = responseRequest expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } if let request = request, multipartFormData = formData, contentType = request.valueForHTTPHeaderField("Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() { // Given let URLString = "https://httpbin.org/post" let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: NSURL? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingMemoryThreshold: 0, encodingCompletion: { result in switch result { case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _, _, _, _ in expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNotNil(streamFileURL, "stream file URL should not be nil") if let streamingFromDisk = streamingFromDisk, streamFilePath = streamFileURL?.path { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") XCTAssertTrue( NSFileManager.defaultManager().fileExistsAtPath(streamFilePath), "stream file path should exist" ) } } func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() { // Given let URLString = "https://httpbin.org/post" let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var formData: MultipartFormData? var request: NSURLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingMemoryThreshold: 0, encodingCompletion: { result in switch result { case let .Success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { responseRequest, _, _, _ in request = responseRequest expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") } if let request = request, multipartFormData = formData, contentType = request.valueForHTTPHeaderField("Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { // Given let manager: Manager = { let identifier = "com.alamofire.uploadtests.\(NSUUID().UUIDString)" let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier) return Manager(configuration: configuration, serverTrustPolicyManager: nil) }() let URLString = "https://httpbin.org/post" let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let expectation = expectationWithDescription("multipart form data upload should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? var streamingFromDisk: Bool? // When manager.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingCompletion: { result in switch result { case let .Success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") } else { XCTFail("streaming from disk should not be nil") } } // MARK: Combined Test Execution private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk streamFromDisk: Bool) { // Given let URLString = "https://httpbin.org/post" let loremData1: NSData = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") } return loremValues.joinWithSeparator(" ").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! }() let loremData2: NSData = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.") } return loremValues.joinWithSeparator(" ").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! }() let expectation = expectationWithDescription("multipart form data upload should succeed") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.upload( .POST, URLString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: loremData1, name: "lorem1") multipartFormData.appendBodyPart(data: loremData2, name: "lorem2") }, encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000, encodingCompletion: { result in switch result { case .Success(let upload, _, _): upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in let bytes = ( bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite ) byteValues.append(bytes) let progress = ( completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount ) progressValues.append(progress) } upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .Failure: expectation.fulfill() } } ) waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } }
mit
zero2launch/z2l-ios-social-network
InstagramClone/Api.swift
1
482
// // Api.swift // InstagramClone // // Created by The Zero2Launch Team on 1/8/17. // Copyright © 2017 The Zero2Launch Team. All rights reserved. // import Foundation struct Api { static var User = UserApi() static var Post = PostApi() static var Comment = CommentApi() static var Post_Comment = Post_CommentApi() static var MyPosts = MyPostsApi() static var Follow = FollowApi() static var Feed = FeedApi() static var HashTag = HashTagApi() }
mit
SuPair/firefox-ios
Client/Application/QuickActions.swift
4
6582
/* 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 Storage import Shared import XCGLogger enum ShortcutType: String { case newTab = "NewTab" case newPrivateTab = "NewPrivateTab" case openLastBookmark = "OpenLastBookmark" case qrCode = "QRCode" init?(fullType: String) { guard let last = fullType.components(separatedBy: ".").last else { return nil } self.init(rawValue: last) } var type: String { return Bundle.main.bundleIdentifier! + ".\(self.rawValue)" } } protocol QuickActionHandlerDelegate { func handleShortCutItemType(_ type: ShortcutType, userData: [String: NSSecureCoding]?) } class QuickActions: NSObject { fileprivate let log = Logger.browserLogger static let QuickActionsVersion = "1.0" static let QuickActionsVersionKey = "dynamicQuickActionsVersion" static let TabURLKey = "url" static let TabTitleKey = "title" fileprivate let lastBookmarkTitle = NSLocalizedString("Open Last Bookmark", tableName: "3DTouchActions", comment: "String describing the action of opening the last added bookmark from the home screen Quick Actions via 3D Touch") fileprivate let _lastTabTitle = NSLocalizedString("Open Last Tab", tableName: "3DTouchActions", comment: "String describing the action of opening the last tab sent to Firefox from the home screen Quick Actions via 3D Touch") static var sharedInstance = QuickActions() var launchedShortcutItem: UIApplicationShortcutItem? // MARK: Administering Quick Actions func addDynamicApplicationShortcutItemOfType(_ type: ShortcutType, fromShareItem shareItem: ShareItem, toApplication application: UIApplication) { var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(type, withUserData: userData, toApplication: application) } @discardableResult func addDynamicApplicationShortcutItemOfType(_ type: ShortcutType, withUserData userData: [AnyHashable: Any] = [AnyHashable: Any](), toApplication application: UIApplication) -> Bool { // add the quick actions version so that it is always in the user info var userData: [AnyHashable: Any] = userData userData[QuickActions.QuickActionsVersionKey] = QuickActions.QuickActionsVersion var dynamicShortcutItems = application.shortcutItems ?? [UIApplicationShortcutItem]() switch type { case .openLastBookmark: let openLastBookmarkShortcut = UIMutableApplicationShortcutItem(type: ShortcutType.openLastBookmark.type, localizedTitle: lastBookmarkTitle, localizedSubtitle: userData[QuickActions.TabTitleKey] as? String, icon: UIApplicationShortcutIcon(templateImageName: "quick_action_last_bookmark"), userInfo: userData ) if let index = (dynamicShortcutItems.index { $0.type == ShortcutType.openLastBookmark.type }) { dynamicShortcutItems[index] = openLastBookmarkShortcut } else { dynamicShortcutItems.append(openLastBookmarkShortcut) } default: log.warning("Cannot add static shortcut item of type \(type)") return false } application.shortcutItems = dynamicShortcutItems return true } func removeDynamicApplicationShortcutItemOfType(_ type: ShortcutType, fromApplication application: UIApplication) { guard var dynamicShortcutItems = application.shortcutItems, let index = (dynamicShortcutItems.index { $0.type == type.type }) else { return } dynamicShortcutItems.remove(at: index) application.shortcutItems = dynamicShortcutItems } // MARK: Handling Quick Actions @discardableResult func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem, withBrowserViewController bvc: BrowserViewController ) -> Bool { // Verify that the provided `shortcutItem`'s `type` is one handled by the application. guard let shortCutType = ShortcutType(fullType: shortcutItem.type) else { return false } DispatchQueue.main.async { self.handleShortCutItemOfType(shortCutType, userData: shortcutItem.userInfo, browserViewController: bvc) } return true } fileprivate func handleShortCutItemOfType(_ type: ShortcutType, userData: [String: NSSecureCoding]?, browserViewController: BrowserViewController) { switch type { case .newTab: handleOpenNewTab(withBrowserViewController: browserViewController, isPrivate: false) case .newPrivateTab: handleOpenNewTab(withBrowserViewController: browserViewController, isPrivate: true) // even though we're removing OpenLastTab, it's possible that someone will use an existing last tab quick action to open the app // the first time after upgrading, so we should still handle it case .openLastBookmark: if let urlToOpen = (userData?[QuickActions.TabURLKey] as? String)?.asURL { handleOpenURL(withBrowserViewController: browserViewController, urlToOpen: urlToOpen) } case .qrCode: handleQRCode(with: browserViewController) } } fileprivate func handleOpenNewTab(withBrowserViewController bvc: BrowserViewController, isPrivate: Bool) { bvc.openBlankNewTab(focusLocationField: true, isPrivate: isPrivate) } fileprivate func handleOpenURL(withBrowserViewController bvc: BrowserViewController, urlToOpen: URL) { // open bookmark in a non-private browsing tab bvc.switchToPrivacyMode(isPrivate: false) // find out if bookmarked URL is currently open // if so, open to that tab, // otherwise, create a new tab with the bookmarked URL bvc.switchToTabForURLOrOpen(urlToOpen, isPrivileged: true) } fileprivate func handleQRCode(with vc: QRCodeViewControllerDelegate & UIViewController) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = vc let controller = UINavigationController(rootViewController: qrCodeViewController) vc.present(controller, animated: true, completion: nil) } }
mpl-2.0
ccrama/Slide-iOS
Slide for Reddit/SwipeForwardNavigationController.swift
1
12660
// // SwipeForwardNavigationController.swift // Slide for Reddit // // Created by Carlos Crane on 7/18/20. // Copyright © 2020 Haptic Apps. All rights reserved. // // Swift code based on Christopher Wendel https://github.com/CEWendel/SWNavigationController/blob/master/SWNavigationController/PodFiles/SWNavigationController.m // import UIKit typealias SWNavigationControllerPushCompletion = () -> Void class SwipeForwardNavigationController: UINavigationController { private var percentDrivenInteractiveTransition: UIPercentDrivenInteractiveTransition? public var interactivePushGestureRecognizer: UIScreenEdgePanGestureRecognizer? public var pushableViewControllers: [UIViewController] = [] /* View controllers we can push onto the navigation stack by pulling in from the right screen edge. */ // Extra state used to implement completion blocks on pushViewController: public var pushCompletion: SWNavigationControllerPushCompletion? private var pushedViewController: UIViewController? public var fullWidthBackGestureRecognizer = UIPanGestureRecognizer() var pushAnimatedTransitioningClass: SwipeForwardAnimatedTransitioning? override var prefersHomeIndicatorAutoHidden: Bool { return true } override var childForHomeIndicatorAutoHidden: UIViewController? { return nil } override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) { super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) setup() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } func setup() { pushableViewControllers = [UIViewController]() delegate = self pushAnimatedTransitioningClass = SwipeForwardAnimatedTransitioning() } override func viewDidLoad() { super.viewDidLoad() interactivePushGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleRightSwipe(_:))) interactivePushGestureRecognizer?.edges = UIRectEdge.right interactivePushGestureRecognizer?.delegate = self view.addGestureRecognizer(interactivePushGestureRecognizer!) // To ensure swipe-back is still recognized interactivePopGestureRecognizer?.delegate = self if let interactivePopGestureRecognizer = interactivePopGestureRecognizer, let targets = interactivePopGestureRecognizer.value(forKey: "targets") { fullWidthBackGestureRecognizer.setValue(targets, forKey: "targets") fullWidthBackGestureRecognizer.delegate = self fullWidthBackGestureRecognizer.require(toFail: interactivePushGestureRecognizer!) view.addGestureRecognizer(fullWidthBackGestureRecognizer) if #available(iOS 13.4, *) { fullWidthBackGestureRecognizer.allowedScrollTypesMask = .continuous } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.splitViewController?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if let first = pushableViewControllers.first as? SplitMainViewController { pushableViewControllers.removeAll() pushableViewControllers.append(first) } else { pushableViewControllers.removeAll() } } @objc func handleRightSwipe(_ swipeGestureRecognizer: UIScreenEdgePanGestureRecognizer?) { let view = self.view! let progress = abs(-(swipeGestureRecognizer?.translation(in: view).x ?? 0.0) / view.frame.size.width) // 1.0 When the pushable vc has been pulled into place // Start, update, or finish the interactive push transition switch swipeGestureRecognizer?.state { case .began: pushNextViewControllerFromRight(nil) case .changed: percentDrivenInteractiveTransition?.update(progress) case .ended: // Figure out if we should finish the transition or not handleEdgeSwipeEnded(withProgress: progress, velocity: swipeGestureRecognizer?.velocity(in: view).x ?? 0) case .failed: percentDrivenInteractiveTransition?.cancel() case .cancelled, .possible: fallthrough default: break } } @objc func handleRightSwipeFull(_ swipeGestureRecognizer: UIPanGestureRecognizer?) { let view = self.view! let progress = abs(-(swipeGestureRecognizer?.translation(in: view).x ?? 0.0) / view.frame.size.width) // 1.0 When the pushable vc has been pulled into place // Start, update, or finish the interactive push transition switch swipeGestureRecognizer?.state { case .began: pushNextViewControllerFromRight(nil) case .changed: percentDrivenInteractiveTransition?.update(progress) case .ended: // Figure out if we should finish the transition or not handleEdgeSwipeEnded(withProgress: progress, velocity: swipeGestureRecognizer?.velocity(in: view).x ?? 0) case .failed: percentDrivenInteractiveTransition?.cancel() case .cancelled, .possible: fallthrough default: break } } func handleEdgeSwipeEnded(withProgress progress: CGFloat, velocity: CGFloat) { // kSWGestureVelocityThreshold threshold indicates how hard the finger has to flick left to finish the push transition if velocity < 0 && (progress > 0.5 || velocity < -500) { percentDrivenInteractiveTransition?.finish() } else { percentDrivenInteractiveTransition?.cancel() } } } extension SwipeForwardNavigationController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { var shouldBegin = false if gestureRecognizer == interactivePushGestureRecognizer || gestureRecognizer == NavigationHomeViewController.edgeGesture { shouldBegin = pushableViewControllers.count > 0 && !((pushableViewControllers.last) == topViewController) } else { shouldBegin = viewControllers.count > 1 } return shouldBegin } } extension SwipeForwardNavigationController { override func pushViewController(_ viewController: UIViewController, animated: Bool) { pushableViewControllers.removeAll() super.pushViewController(viewController, animated: animated) } override func popViewController(animated: Bool) -> UIViewController? { // Dismiss the current view controllers keyboard (if it is displaying one), to avoid first responder problems when pushing back onto the stack topViewController?.view.endEditing(true) let poppedViewController = super.popViewController(animated: animated) if let poppedViewController = poppedViewController { pushableViewControllers.append(poppedViewController) } return poppedViewController } override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? { let poppedViewControllers = super.popToViewController(viewController, animated: animated) self.pushableViewControllers = poppedViewControllers?.backwards() ?? [] return poppedViewControllers ?? [] } override func popToRootViewController(animated: Bool) -> [UIViewController]? { let poppedViewControllers = super.popToRootViewController(animated: true) if let all = poppedViewControllers?.backwards() { pushableViewControllers = all } return poppedViewControllers } override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { super.setViewControllers(viewControllers, animated: animated) self.pushableViewControllers.removeAll() } func push(_ viewController: UIViewController?, animated: Bool, completion: @escaping SWNavigationControllerPushCompletion) { pushedViewController = viewController pushCompletion = completion if let viewController = viewController { super.pushViewController(viewController, animated: animated) } } override func collapseSecondaryViewController(_ secondaryViewController: UIViewController, for splitViewController: UISplitViewController) { if let secondaryAsNav = secondaryViewController as? UINavigationController, (UIDevice.current.userInterfaceIdiom == .phone) { viewControllers += secondaryAsNav.viewControllers } } func pushNextViewControllerFromRight(_ callback: (() -> Void)?) { let pushedViewController = pushableViewControllers.last if pushedViewController != nil && visibleViewController != nil && visibleViewController?.isBeingPresented == false && visibleViewController?.isBeingDismissed == false { push(pushedViewController, animated: UIApplication.shared.isSplitOrSlideOver ? false : true) { if !self.pushableViewControllers.isEmpty { self.pushableViewControllers.removeLast() callback?() } } } } } extension SwipeForwardNavigationController: UISplitViewControllerDelegate { func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? { if UIDevice.current.userInterfaceIdiom == .phone { var main: UIViewController? for viewController in viewControllers { if viewController is MainViewController { main = viewController } } for viewController in pushableViewControllers { if viewController is MainViewController { main = viewController } } if let main = main { return SwipeForwardNavigationController(rootViewController: main) } } return nil } } extension SwipeForwardNavigationController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .push && (((navigationController as? SwipeForwardNavigationController)?.interactivePushGestureRecognizer)?.state == .began || NavigationHomeViewController.edgeGesture?.state == .began) { return self.pushAnimatedTransitioningClass } return nil } func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { let navController = navigationController as? SwipeForwardNavigationController if navController?.interactivePushGestureRecognizer?.state == .began || NavigationHomeViewController.edgeGesture?.state == .began { navController?.percentDrivenInteractiveTransition = UIPercentDrivenInteractiveTransition() navController?.percentDrivenInteractiveTransition?.completionCurve = .easeOut } else { navController?.percentDrivenInteractiveTransition = nil } return navController?.percentDrivenInteractiveTransition } func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if pushedViewController != viewController { pushedViewController = nil pushCompletion = nil } } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { if (pushCompletion != nil) && pushedViewController == viewController { pushCompletion?() } pushCompletion = nil pushedViewController = nil } }
apache-2.0
ja-mes/experiments
iOS/Animations/Animations/AppDelegate.swift
1
6096
// // AppDelegate.swift // Animations // // Created by James Brown on 8/7/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.Animations" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Animations", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
ryet231ere/DouYuSwift
douyu/douyu/Classes/Home/Model/CycleModel.swift
1
765
// // CycleModel.swift // douyu // // Created by 练锦波 on 2017/2/16. // Copyright © 2017年 练锦波. All rights reserved. // import UIKit class CycleModel: NSObject { // 标题 var title : String = "" // 展示的图片地址 var pic_url : String = "" // 主播信息对应的字典 var room : [String : NSObject]? { didSet { guard let room = room else { return } anchor = ANchorModel(dict: room) } } // 主播信息对应的模型对象 var anchor : ANchorModel? init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
box/box-ios-sdk
Sources/Network/ArrayInputStream.swift
1
4676
// swiftlint:disable all /// Notes: /// The purpose of this class (ArrayInputStream) is to "merge" multiple InputStreams into a single InputStream. /// This merging can be implemented by sequentially reading from an array of input streams with an interface that is the same as InputStream. /// This is done here by creating a subclass of InputStream that takes in an array of streams and has a custom read method that reads sequentially from its array of InputStreams. // Copyright 2019 Soroush Khanlou // // 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 class ArrayInputStream: InputStream { private let inputStreams: [InputStream] private var currentIndex: Int private var _streamStatus: Stream.Status private var _streamError: Error? private var _delegate: StreamDelegate? init(inputStreams: [InputStream]) { self.inputStreams = inputStreams currentIndex = 0 _streamStatus = .notOpen _streamError = nil super.init(data: Data()) // required because `init()` is not marked as a designated initializer } // Methods in the InputStream class that must be implemented override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int { if _streamStatus == .closed { return 0 } var totalNumberOfBytesRead = 0 while totalNumberOfBytesRead < maxLength { if currentIndex == inputStreams.count { close() break } let currentInputStream = inputStreams[currentIndex] if currentInputStream.streamStatus != .open { currentInputStream.open() } if !currentInputStream.hasBytesAvailable { currentIndex += 1 continue } let remainingLength = maxLength - totalNumberOfBytesRead let numberOfBytesRead = currentInputStream.read(&buffer[totalNumberOfBytesRead], maxLength: remainingLength) if numberOfBytesRead == 0 { currentIndex += 1 continue } if numberOfBytesRead == -1 { _streamError = currentInputStream.streamError _streamStatus = .error return -1 } totalNumberOfBytesRead += numberOfBytesRead } return totalNumberOfBytesRead } override func getBuffer(_: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>, length _: UnsafeMutablePointer<Int>) -> Bool { return false } override var hasBytesAvailable: Bool { return true } // Methods and variables in the Stream class that must be implemented override func open() { guard _streamStatus == .open else { return } _streamStatus = .open } override func close() { _streamStatus = .closed for stream in inputStreams { stream.close() } } override func property(forKey _: Stream.PropertyKey) -> Any? { return nil } override func setProperty(_: Any?, forKey _: Stream.PropertyKey) -> Bool { return false } override var streamStatus: Stream.Status { return _streamStatus } override var streamError: Error? { return _streamError } override var delegate: StreamDelegate? { get { return _delegate } set { _delegate = newValue } } override func schedule(in _: RunLoop, forMode _: RunLoop.Mode) {} override func remove(from _: RunLoop, forMode _: RunLoop.Mode) {} }
apache-2.0
caopengxu/scw
scw/scw/AppDelegate.swift
1
2787
// // AppDelegate.swift // scw // // Created by cpx on 2017/6/19. // Copyright © 2017年 scw. All rights reserved. // import UIKit import QorumLogs @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 打印log设置 QorumLogs.enabled = true window = UIWindow() if UserDefaults.standard.bool(forKey: "JudgeSign") { let storyboard = UIStoryboard.init(name: "MainTabBar", bundle: nil) let main = storyboard.instantiateInitialViewController() window?.rootViewController = main } else { let storyboard = UIStoryboard.init(name: "SignController", bundle: nil) let main = storyboard.instantiateInitialViewController() window?.rootViewController = main } 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
linweiqiang/WQDouShi
WQDouShi/WQDouShi/ViewController.swift
1
500
// // ViewController.swift // WQDouShi // // Created by yoke2 on 2017/3/15. // Copyright © 2017年 yoke121. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
halo/biosphere
Biosphere/Controllers/Components/GitController.swift
1
1054
import Cocoa class GitController: NSViewController { public var satisfied: Bool { if FileManager.default.fileExists(atPath: Paths.gitExecutable) { Log.debug("\(Paths.gitExecutable) exists") return true } else { Log.debug("\(Paths.gitExecutable) not found") return false } } @IBAction func installCommandLineTools(sender: NSButton) { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select") task.arguments = ["--install"] let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.terminationHandler = { (process) in Log.debug("xcode-select exitet with status: \(process.terminationStatus)") let data = pipe.fileHandleForReading.readDataToEndOfFile() if let output = String(data: data, encoding: String.Encoding.utf8) { Log.debug(output) } } do { try task.run() } catch { Log.debug("Failed to execute xcode-select. Does the executable exist?") } } }
mit
eoger/firefox-ios
XCUITests/IntegrationTests.swift
2
4347
/* 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 XCTest private let testingURL = "example.com" private let userName = "iosmztest" private let userPassword = "test15mz" class IntegrationTests: BaseTestCase { let testWithDB = ["testFxASyncHistory", "testFxASyncBookmark"] // This DB contains 1 entry example.com let historyDB = "exampleURLHistoryBookmark.db" override func setUp() { // Test name looks like: "[Class testFunc]", parse out the function name let parts = name.replacingOccurrences(of: "]", with: "").split(separator: " ") let key = String(parts[1]) if testWithDB.contains(key) { // for the current test name, add the db fixture used launchArguments = [LaunchArguments.SkipIntro, LaunchArguments.StageServer, LaunchArguments.SkipWhatsNew, LaunchArguments.LoadDatabasePrefix + historyDB] } super.setUp() } func allowNotifications () { addUIInterruptionMonitor(withDescription: "notifications") { (alert) -> Bool in alert.buttons["Allow"].tap() return true } sleep(5) app.swipeDown() } private func signInFxAccounts() { navigator.goto(FxASigninScreen) waitforExistence(app.webViews.staticTexts["Sign in"], timeout: 10) userState.fxaUsername = ProcessInfo.processInfo.environment["FXA_EMAIL"]! userState.fxaPassword = ProcessInfo.processInfo.environment["FXA_PASSWORD"]! navigator.performAction(Action.FxATypeEmail) navigator.performAction(Action.FxATypePassword) navigator.performAction(Action.FxATapOnSignInButton) allowNotifications() } private func waitForInitialSyncComplete() { navigator.nowAt(BrowserTab) navigator.goto(SettingsScreen) waitforExistence(app.tables.staticTexts["Sync Now"], timeout: 10) } func testFxASyncHistory () { // History is generated using the DB so go directly to Sign in // Sign into Firefox Accounts navigator.goto(BrowserTabMenu) signInFxAccounts() // Wait for initial sync to complete waitForInitialSyncComplete() } func testFxASyncBookmark () { // Bookmark is added by the DB // Sign into Firefox Accounts signInFxAccounts() // Wait for initial sync to complete waitForInitialSyncComplete() } func testFxASyncTabs () { navigator.openURL(testingURL) waitUntilPageLoad() navigator.goto(BrowserTabMenu) signInFxAccounts() // Wait for initial sync to complete navigator.nowAt(BrowserTab) // This is only to check that the device's name changed navigator.goto(SettingsScreen) app.tables.cells.element(boundBy: 0).tap() waitforExistence(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"]) XCTAssertEqual(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"].value! as! String, "Fennec on iOS") // Sync again just to make sure to sync after new name is shown app.buttons["Settings"].tap() app.tables.cells.element(boundBy: 1).tap() waitforExistence(app.tables.staticTexts["Sync Now"], timeout: 15) } func testFxASyncLogins () { navigator.openURL("gmail.com") waitUntilPageLoad() // Log in in order to save it waitforExistence(app.webViews.textFields["Email or phone"]) app.webViews.textFields["Email or phone"].tap() app.webViews.textFields["Email or phone"].typeText(userName) app.webViews.buttons["Next"].tap() waitforExistence(app.webViews.secureTextFields["Password"]) app.webViews.secureTextFields["Password"].tap() app.webViews.secureTextFields["Password"].typeText(userPassword) app.webViews.buttons["Sign in"].tap() // Save the login waitforExistence(app.buttons["SaveLoginPrompt.saveLoginButton"]) app.buttons["SaveLoginPrompt.saveLoginButton"].tap() // Sign in with FxAccount signInFxAccounts() // Wait for initial sync to complete waitForInitialSyncComplete() } }
mpl-2.0
benlangmuir/swift
test/Concurrency/actor_isolation_swift6.swift
5
2590
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency -swift-version 6 // REQUIRES: concurrency // REQUIRES: asserts final class ImmutablePoint: Sendable { let x : Int = 0 let y : Int = 0 } actor SomeActor { } @globalActor struct SomeGlobalActor { static let shared = SomeActor() } /// ------------------------------------------------------------------ /// -- Value types do not need isolation on their stored properties -- protocol MainCounter { @MainActor var counter: Int { get set } @MainActor var ticker: Int { get set } } struct InferredFromConformance: MainCounter { var counter = 0 var ticker: Int { get { 1 } set {} } } @MainActor struct InferredFromContext { var point = ImmutablePoint() var polygon: [ImmutablePoint] { get { [] } } nonisolated let flag: Bool = false // expected-error {{'nonisolated' is redundant on struct's stored properties}}{{3-15=}} subscript(_ i: Int) -> Int { return i } static var stuff: [Int] = [] } func checkIsolationValueType(_ formance: InferredFromConformance, _ ext: InferredFromContext, _ anno: NoGlobalActorValueType) async { // these do not need an await, since it's a value type _ = ext.point _ = formance.counter _ = anno.point _ = anno.counter // make sure it's just a warning if someone was awaiting on it previously _ = await ext.point // expected-warning {{no 'async' operations occur within 'await' expression}} _ = await formance.counter // expected-warning {{no 'async' operations occur within 'await' expression}} _ = await anno.point // expected-warning {{no 'async' operations occur within 'await' expression}} _ = await anno.counter // expected-warning {{no 'async' operations occur within 'await' expression}} // these do need await, regardless of reference or value type _ = await (formance as any MainCounter).counter _ = await ext[1] _ = await formance.ticker _ = await ext.polygon _ = await InferredFromContext.stuff _ = await NoGlobalActorValueType.polygon } // check for instance members that do not need global-actor protection struct NoGlobalActorValueType { @SomeGlobalActor var point: ImmutablePoint // expected-error {{stored property 'point' within struct cannot have a global actor}} @MainActor let counter: Int // expected-error {{stored property 'counter' within struct cannot have a global actor}} @MainActor static var polygon: [ImmutablePoint] = [] } /// -----------------------------------------------------------------
apache-2.0
keefmoon/SwiftOpenCV
Pods/ImageCoordinateSpace/ImageCoordinateSpace/ContentAdjustment.swift
1
1376
// // ContentAdjustment.swift // ImageCoordinateSpace // // Created by Paul Zabelin on 2/14/16. // // import UIKit extension UIView { func contentAdjustment() -> ContentAdjustment { return ContentAdjustment(contentSize: self.intrinsicContentSize(), contentMode: self.contentMode) } } class ContentAdjustment { var contentSize : CGSize var contentMode : UIViewContentMode init(contentSize size: CGSize, contentMode mode: UIViewContentMode) { contentSize = size contentMode = mode } func transform(contentSize:CGSize, viewSize:CGSize) -> CGAffineTransform { if contentSize != viewSize { let transformer = ViewContentModeTransformer( viewSize: viewSize, contentSize: contentSize, contentMode: contentMode ) return transformer.contentToViewTransform() } else { return CGAffineTransformIdentity } } func contentTransformToSize(size: CGSize) -> CGAffineTransform { return transform(contentSize, viewSize: size) } func transformingToSpace(space: UICoordinateSpace) -> UICoordinateSpace { return TransformedCoordinateSpace( size: contentSize, transform: contentTransformToSize(space.bounds.size), destination: space ) } }
mit
antoninbiret/DataSourceKit
Example/Tests/DataSourceKit/SectionDataSourceSpec/SectionDataSourceSpec.swift
1
9552
// // SectionDataSourceSpec.swift // TimesheetTests // // Created by Antonin Biret on 24/05/2017. // Copyright © 2017 antoninbiret. All rights reserved. // import Quick import Nimble @testable import DataSourceKit class SectionDataSourceSpec: QuickSpec { override func spec() { var collectionDataSource = CollectionDataSource<SectionDataSource<Stub>>(sections: []) var sectionDataSource = SectionDataSource<Stub>(items: []) let makeChanges = { (changes: @escaping (() -> Void) ) -> ([CollectionChange]) in var collectionChanges: [CollectionChange] = [] waitUntil(timeout: 10) { done in collectionDataSource.changesNotification = { _collectionChanges in collectionChanges = _collectionChanges done() } collectionDataSource.performBatchUpdates({ changes() }) } return collectionChanges } beforeEach { let stubs = [Stub(stub:1), Stub(stub:2), Stub(stub:3)] sectionDataSource = SectionDataSource(items: stubs) collectionDataSource = CollectionDataSource(sections: [sectionDataSource]) } // MARK: - Adding describe("Adding") { it("an item should update the section") { let stub = Stub(stub: 4) let collectionChanges = makeChanges({ sectionDataSource.add(item: stub) }) expect(sectionDataSource.items.count).to(equal(4)) expect(sectionDataSource.items.index(of: stub)).to(equal(3)) let expectedChanges: [CollectionChange] = [ CollectionChange.insert(0, 3) ] expect(collectionChanges == expectedChanges).to(beTrue()) } it("items should update the section") { let stub1 = Stub(stub: 4) let stub2 = Stub(stub: 5) let collectionChanges = makeChanges({ sectionDataSource.add(items: [stub1, stub2]) }) expect(sectionDataSource.items.count).to(equal(5)) expect(sectionDataSource.items.index(of: stub1)).to(equal(3)) expect(sectionDataSource.items.index(of: stub2)).to(equal(4)) let expectedChanges: [CollectionChange] = [ CollectionChange.insert(0, 3), CollectionChange.insert(0, 4) ] expect(collectionChanges == expectedChanges).to(beTrue()) } describe("and removing") { it("items at differents indexes should update the section") { let stub = Stub(stub: 4) let collectionChanges = makeChanges({ sectionDataSource.add(item: stub) sectionDataSource.removeItem(at: 0) }) expect(sectionDataSource.items.count).to(equal(3)) expect(sectionDataSource.items.index(of: stub)).to(equal(2)) let expectedChanges: [CollectionChange] = [ CollectionChange.delete(0, 0), CollectionChange.insert(0, 2) ] expect(collectionChanges == expectedChanges).to(beTrue()) } } } // MARK: - Inserting describe("Inserting") { describe("An item") { let insertItemTest = { (item: Stub, index: Int) -> Void in let collectionChanges = makeChanges({ sectionDataSource.insert(item: item, at: index) }) expect(sectionDataSource.items.count).to(equal(4)) expect(sectionDataSource.items.index(of: item)).to(equal(index)) let expectedChanges: [CollectionChange] = [ CollectionChange.insert(0, index) ] expect(collectionChanges == expectedChanges).to(beTrue()) } it("at the begining of the section's items should update the section") { let stub = Stub(stub: 4) insertItemTest(stub, 0) } it("in the middle of the section's items should update the section") { let stub = Stub(stub: 22) insertItemTest(stub, 1) } it("at the end of the section's items should update the section") { let stub = Stub(stub: 4) insertItemTest(stub, 3) } } describe("Items") { let insertItemsTest = { (item1: Stub, item2: Stub, index: Int) -> Void in let collectionChanges = makeChanges({ sectionDataSource.insert(items: [item1, item2], from: index) }) let index1 = index let index2 = index+1 expect(sectionDataSource.items.count).to(equal(5)) expect(sectionDataSource.items.index(of: item1)).to(equal(index1)) expect(sectionDataSource.items.index(of: item2)).to(equal(index2)) let expectedChanges: [CollectionChange] = [ CollectionChange.insert(0, index1), CollectionChange.insert(0, index2) ] expect(collectionChanges == expectedChanges).to(beTrue()) } it("at the begining of the section's items should update the section") { let stub1 = Stub(stub: 4) let stub2 = Stub(stub: 5) insertItemsTest(stub1, stub2, 0) } it("in the middle of the section's items should update the section") { let stub1 = Stub(stub: 4) let stub2 = Stub(stub: 5) insertItemsTest(stub1, stub2, 1) } it("at the end of the section's items should update the section") { let stub1 = Stub(stub: 4) let stub2 = Stub(stub: 5) insertItemsTest(stub1, stub2, 3) } } } // MARK: - Removing describe("Removing") { describe("An item") { let removeItemTest = { (index: Int) -> Void in let item = sectionDataSource.items[index] let collectionChanges = makeChanges({ sectionDataSource.removeItem(at: index) }) expect(sectionDataSource.items.count).to(equal(2)) expect(sectionDataSource.items.index(of: item)).to(beNil()) let expectedChanges: [CollectionChange] = [ CollectionChange.delete(0, index) ] expect(collectionChanges == expectedChanges).to(beTrue()) } it("at the begining of the section's items should update the section") { removeItemTest(0) } it("in the middle of the section's items should update the section") { removeItemTest(1) } it("at the end of the section's items should update the section") { removeItemTest(2) } } // describe("Items") { // // let removeItemsTest = { (index1: Int, index2: Int) -> Void in // let item1 = sectionDataSource.items[index1] // let item2 = sectionDataSource.items[index2] // // let range: Range<Int> = index1..<(index2+1) // let collectionChanges = makeChanges({ // sectionDataSource.removeItems(in: range) // }) // // expect(sectionDataSource.items.count).to(equal(1)) // expect(sectionDataSource.items.index(of: item1)).to(beNil()) // expect(sectionDataSource.items.index(of: item2)).to(beNil()) // // let expectedChanges: [CollectionChange] = [ // CollectionChange.delete(0, index2), // CollectionChange.delete(0, index1) // ] // // expect(collectionChanges == expectedChanges).to(beTrue()) // } // // it("at the begining of the section's items should update the section") { // removeItemsTest(0, 1) // } // // it("in the end of the section's items should update the section") { // removeItemsTest(1, 2) // } // // } } // MARK: - Replacing describe("Replacing") { describe("An item") { let replacingItemTest = { (item: Stub, index: Int) -> Void in let oldItem = sectionDataSource.items[index] let collectionChanges = makeChanges({ sectionDataSource.replace(item: item, at: index) }) expect(sectionDataSource.items.count).to(equal(3)) expect(sectionDataSource.items.index(of: item)).to(equal(index)) expect(sectionDataSource.items.index(of: oldItem)).to(beNil()) let expectedChanges: [CollectionChange] = [ CollectionChange.delete(0, index), CollectionChange.insert(0, index), ] expect(collectionChanges == expectedChanges).to(beTrue()) } it("at the begining of the section's items should update the section") { let stub = Stub(stub: 11) replacingItemTest(stub, 0) } it("in the middle of the section's items should update the section") { let stub = Stub(stub: 22) replacingItemTest(stub, 1) } it("at the end of the section's items should update the section") { let stub = Stub(stub: 33) replacingItemTest(stub, 2) } } } } }
mit
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/Final Assembly/LandInTheEditorHelper.swift
1
2241
typealias HomepageEditorCompletion = () -> Void class LandInTheEditorHelper { /// Land in the editor, or continue as usual - Used to branch on the feature flag for landing in the editor from the site creation flow /// - Parameter blog: Blog (which was just created) for which to show the home page editor /// - Parameter navigationController: UINavigationController used to present the home page editor /// - Parameter completion: HomepageEditorCompletion callback to be invoked after the user finishes editing the home page, or immediately iwhen the feature flag is disabled static func landInTheEditorOrContinue(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) { // branch here for feature flag if FeatureFlag.landInTheEditor.enabled { landInTheEditor(for: blog, navigationController: navigationController, completion: completion) } else { completion() } } private static func landInTheEditor(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) { fetchAllPages(for: blog, success: { _ in DispatchQueue.main.async { if let homepage = blog.homepage { let editorViewController = EditPageViewController(homepage: homepage, completion: completion) navigationController.present(editorViewController, animated: false) WPAnalytics.track(.landingEditorShown) } } }, failure: { _ in NSLog("Fetching all pages failed after site creation!") }) } // This seems to be necessary before casting `AbstractPost` to `Page`. private static func fetchAllPages(for blog: Blog, success: @escaping PostServiceSyncSuccess, failure: @escaping PostServiceSyncFailure) { let options = PostServiceSyncOptions() options.number = 20 let context = ContextManager.sharedInstance().mainContext let postService = PostService(managedObjectContext: context) postService.syncPosts(ofType: .page, with: options, for: blog, success: success, failure: failure) } }
gpl-2.0
SuguKumar91/sampleApp
sampleViewCotroller/ViewController.swift
1
439
// // ViewController.swift // sampleViewCotroller // // Created by Mac09 on 5/8/17. // Copyright © 2017 Great Innovus Solutions. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
frootloops/swift
test/IRGen/class_resilience.swift
1
14835
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience %s | %FileCheck %s // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience -O %s // CHECK: %swift.type = type { [[INT:i32|i64]] } // CHECK: @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd = {{(protected )?}}global [[INT]] 0 // CHECK: @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd = {{(protected )?}}global [[INT]] 0 // CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd = {{(protected )?}}global [[INT]] 0 // CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd = {{(protected )?}}global [[INT]] 0 // CHECK: @_T016class_resilience14ResilientChildC5fields5Int32VvpWvd = {{(protected )?}}global [[INT]] {{8|16}} // CHECK: @_T016class_resilience21ResilientGenericChildC5fields5Int32VvpWvi = {{(protected )?}}global [[INT]] {{56|88}} // CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd = {{(protected )?}}constant [[INT]] {{8|16}} // CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|20}} // CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd = {{(protected )?}}constant [[INT]] {{8|16}} // CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|24}} import resilient_class import resilient_struct import resilient_enum // Concrete class with resilient stored property public class ClassWithResilientProperty { public let p: Point public let s: Size public let color: Int32 public init(p: Point, s: Size, color: Int32) { self.p = p self.s = s self.color = color } } // Concrete class with non-fixed size stored property public class ClassWithResilientlySizedProperty { public let r: Rectangle public let color: Int32 public init(r: Rectangle, color: Int32) { self.r = r self.color = color } } // Concrete class with resilient stored property that // is fixed-layout inside this resilience domain public struct MyResilientStruct { public let x: Int32 } public class ClassWithMyResilientProperty { public let r: MyResilientStruct public let color: Int32 public init(r: MyResilientStruct, color: Int32) { self.r = r self.color = color } } // Enums with indirect payloads are fixed-size public class ClassWithIndirectResilientEnum { public let s: FunnyShape public let color: Int32 public init(s: FunnyShape, color: Int32) { self.s = s self.color = color } } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientChild : ResilientOutsideParent { public let field: Int32 = 0 } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> { public let field: Int32 = 0 } // Superclass is resilient and has a resilient value type payload, // but everything is in one module public class MyResilientParent { public let s: MyResilientStruct = MyResilientStruct(x: 0) } public class MyResilientChild : MyResilientParent { public let field: Int32 = 0 } // ClassWithResilientProperty.color getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg(%T16class_resilience26ClassWithResilientPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientProperty metadata accessor // CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience26ClassWithResilientPropertyCMa() // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience26ClassWithResilientPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientProperty to i8*), i8* undef) // CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: ret %swift.type* [[RESULT]] // ClassWithResilientlySizedProperty.color getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientlySizedProperty metadata accessor // CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa() // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientlySizedProperty to i8*), i8* undef) // CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: ret %swift.type* [[RESULT]] // ClassWithIndirectResilientEnum.color getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2 // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ResilientChild.field getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience14ResilientChildC5fields5Int32Vvg(%T16class_resilience14ResilientChildC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience14ResilientChildC5fields5Int32VvpWvd // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ResilientGenericChild.field getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience21ResilientGenericChildC5fields5Int32Vvg(%T16class_resilience21ResilientGenericChildC* swiftself) // FIXME: we could eliminate the unnecessary isa load by lazily emitting // metadata sources in EmitPolymorphicParameters // CHECK: load %swift.type* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]] // CHECK-NEXT: [[INDIRECT_OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience21ResilientGenericChildC5fields5Int32VvpWvi // CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[INDIRECT_OFFSET]] // CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]* // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]] // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[RESULT]] // MyResilientChild.field getter // CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience16MyResilientChildC5fields5Int32Vvg(%T16class_resilience16MyResilientChildC* swiftself) // CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2 // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[RESULT]] // ClassWithResilientProperty metadata initialization function // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientProperty // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 4) // CHECK: [[SIZE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa() // CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 3, {{.*}}) // CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]* // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd // CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML release, // CHECK: ret void // ClassWithResilientlySizedProperty metadata initialization function // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientlySizedProperty // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 3) // CHECK: [[RECTANGLE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa() // CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 2, {{.*}}) // CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]* // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd // CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML release, // CHECK: ret void
apache-2.0
slavapestov/swift
validation-test/compiler_crashers/28155-swift-typechecker-validategenericfuncsignature.swift
3
324
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing // Crash type: memory error ("Invalid read of size 2") class A{func b->Self{{{}}class B<n{let a=self
apache-2.0
ioscreator/ioscreator
SwiftUIPreviewDevicesTutorial/SwiftUIPreviewDevicesTutorial/AppDelegate.swift
1
1445
// // AppDelegate.swift // SwiftUIPreviewDevicesTutorial // // Created by Arthur Knopper on 18/09/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
mit
themonki/onebusaway-iphone
OneBusAway/ui/MapTable/EmbeddedCollectionViewCell.swift
1
1308
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class EmbeddedCollectionViewCell: UICollectionViewCell { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let view = UICollectionView(frame: .zero, collectionViewLayout: layout) view.backgroundColor = .white view.alwaysBounceVertical = false view.alwaysBounceHorizontal = true self.contentView.addSubview(view) return view }() override func layoutSubviews() { super.layoutSubviews() collectionView.frame = contentView.frame } }
apache-2.0
joerocca/GitHawk
Classes/Bookmark v2/Bookmark.swift
1
1697
// // Bookmark.swift // Freetime // // Created by Hesham Salman on 11/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation struct Bookmark: Codable { let type: NotificationType let name: String let owner: String let number: Int let title: String let hasIssueEnabled: Bool let defaultBranch: String init(type: NotificationType, name: String, owner: String, number: Int = 0, title: String = "", hasIssueEnabled: Bool = false, defaultBranch: String = "master" ) { self.type = type self.name = name self.owner = owner self.number = number self.title = title self.hasIssueEnabled = hasIssueEnabled self.defaultBranch = defaultBranch } } extension Bookmark: Equatable { static func ==(lhs: Bookmark, rhs: Bookmark) -> Bool { return lhs.type == rhs.type && lhs.name == rhs.name && lhs.owner == rhs.owner && lhs.number == rhs.number && lhs.title == rhs.title && lhs.hasIssueEnabled == rhs.hasIssueEnabled && lhs.defaultBranch == rhs.defaultBranch } } extension Bookmark: Filterable { func match(query: String) -> Bool { let lowerQuery = query.lowercased() if type.rawValue.contains(lowerQuery) { return true } if String(number).contains(lowerQuery) { return true } if title.lowercased().contains(lowerQuery) { return true } if owner.lowercased().contains(lowerQuery) { return true } if name.lowercased().contains(lowerQuery) { return true } return false } }
mit
eridbardhaj/Weather
Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
1
11928
// // Operators.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // Copyright (c) 2014 hearst. All rights reserved. // /** * This file defines a new operator which is used to create a mapping between an object and a JSON key value. * There is an overloaded operator definition for each type of object that is supported in ObjectMapper. * This provides a way to add custom logic to handle specific types of objects */ infix operator <- {} // MARK:- Objects with Basic types /** * Object of Basic type */ public func <- <T>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.basicType(&left, object: right.value()) } else { ToJSON.basicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Optional object of basic type */ public func <- <T>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Implicitly unwrapped optional object of basic type */ public func <- <T>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Raw Representable types /** * Object of Raw Representable type */ public func <- <T: RawRepresentable>(inout left: T, right: Map) { left <- (right, EnumTransform()) } /** * Optional Object of Raw Representable type */ public func <- <T: RawRepresentable>(inout left: T?, right: Map) { left <- (right, EnumTransform()) } /** * Implicitly Unwrapped Optional Object of Raw Representable type */ public func <- <T: RawRepresentable>(inout left: T!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Arrays of Raw Representable type /** * Array of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [T], right: Map) { left <- (right, EnumTransform()) } /** * Array of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) { left <- (right, EnumTransform()) } /** * Array of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Dictionaries of Raw Representable type /** * Dictionary of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) { left <- (right, EnumTransform()) } /** * Dictionary of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) { left <- (right, EnumTransform()) } /** * Dictionary of Raw Representable object */ public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Transforms /** * Object of Basic type with Transform */ public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { var value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.basicType(&left, object: value) } else { var value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /** * Optional object of basic type with Transform */ public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { var value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { var value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /** * Implicitly unwrapped optional object of basic type with Transform */ public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { var value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { var value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /// Array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Implicitly unwrapped optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Implicitly unwrapped optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] { if let values = input as? [AnyObject] { return values.filterMap { value in return transform.transformFromJSON(value) } } else { return [] } } private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] { if let values = input as? [String: AnyObject] { return values.filterMap { value in return transform.transformFromJSON(value) } } else { return [:] } } private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? { return input?.filterMap { value in return transform.transformToJSON(value) } } private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? { return input?.filterMap { value in return transform.transformToJSON(value) } } // MARK:- Mappable Objects - <T: Mappable> /** * Object conforming to Mappable */ public func <- <T: Mappable>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.object(&left, object: right.currentValue) } else { ToJSON.object(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Optional Mappable objects */ public func <- <T: Mappable>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Implicitly unwrapped optional Mappable objects */ public func <- <T: Mappable>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable> /** * Dictionary of Mappable objects <String, T: Mappable> */ public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectDictionary(&left, object: right.currentValue) } else { ToJSON.objectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Optional Dictionary of Mappable object <String, T: Mappable> */ public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> */ public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Array of Mappable objects - Array<T: Mappable> /** * Array of Mappable objects */ public func <- <T: Mappable>(inout left: Array<T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectArray(&left, object: right.currentValue) } else { ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Optional array of Mappable objects */ public func <- <T: Mappable>(inout left: Array<T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /** * Implicitly unwrapped Optional array of Mappable objects */ public func <- <T: Mappable>(inout left: Array<T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } }
mit
overtake/TelegramSwift
Telegram-Mac/instantPageWebEmbedView.swift
1
4423
// // instantPageWebEmbedView.swift // Telegram // // Created by keepcoder on 10/08/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCore import TGUIKit import WebKit private final class InstantPageWebView : WKWebView { var enableScrolling: Bool = true override func scrollWheel(with event: NSEvent) { if enableScrolling { super.scrollWheel(with: event) } else { if event.scrollingDeltaX != 0 { super.scrollWheel(with: event) } else { super.enclosingScrollView?.scrollWheel(with: event) } } } } private class WeakInstantPageWebEmbedNodeMessageHandler: NSObject, WKScriptMessageHandler { private let f: (WKScriptMessage) -> () init(_ f: @escaping (WKScriptMessage) -> ()) { self.f = f super.init() } func userContentController(_ controller: WKUserContentController, didReceive scriptMessage: WKScriptMessage) { self.f(scriptMessage) } } final class InstantPageWebEmbedView: View, InstantPageView { let url: String? let html: String? private var webView: InstantPageWebView! let updateWebEmbedHeight: (CGFloat) -> Void init(frame: CGRect, url: String?, html: String?, enableScrolling: Bool, updateWebEmbedHeight: @escaping(CGFloat) -> Void) { self.url = url self.html = html self.updateWebEmbedHeight = updateWebEmbedHeight super.init() let js = "var TelegramWebviewProxyProto = function() {}; " + "TelegramWebviewProxyProto.prototype.postEvent = function(eventName, eventData) { " + "window.webkit.messageHandlers.performAction.postMessage({'eventName': eventName, 'eventData': eventData}); " + "}; " + "var TelegramWebviewProxy = new TelegramWebviewProxyProto();" let configuration = WKWebViewConfiguration() let userController = WKUserContentController() let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false) userController.addUserScript(userScript) userController.add(WeakInstantPageWebEmbedNodeMessageHandler { [weak self] message in if let strongSelf = self { strongSelf.handleScriptMessage(message) } }, name: "performAction") configuration.userContentController = userController let webView = InstantPageWebView(frame: CGRect(origin: CGPoint(), size: frame.size), configuration: configuration) if let html = html { webView.loadHTMLString(html, baseURL: nil) } else if let url = url, let parsedUrl = URL(string: url) { var request = URLRequest(url: parsedUrl) if let scheme = parsedUrl.scheme, let host = parsedUrl.host { let referrer = "\(scheme)://\(host)" request.setValue(referrer, forHTTPHeaderField: "Referer") } webView.load(request) } self.webView = webView webView.enableScrolling = enableScrolling addSubview(webView) } private func handleScriptMessage(_ message: WKScriptMessage) { guard let body = message.body as? [String: Any] else { return } guard let eventName = body["eventName"] as? String, let eventString = body["eventData"] as? String else { return } guard let eventData = eventString.data(using: .utf8) else { return } guard let dict = (try? JSONSerialization.jsonObject(with: eventData, options: [])) as? [String: Any] else { return } if eventName == "resize_frame", let height = dict["height"] as? Int { self.updateWebEmbedHeight(CGFloat(height)) } } deinit { } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override func layout() { super.layout() self.webView.frame = self.bounds } func updateIsVisible(_ isVisible: Bool) { } }
gpl-2.0
acalvomartinez/ironhack
Week 6/Day 3/MyPlayground.playground/Pages/Closures.xcplaygroundpage/Sources/Person.swift
1
474
import Foundation public class Coordinate { public var latitude: Float? public var longitude: Float? public init(latitude: Float, longitude: Float) { self.latitude = latitude self.longitude = longitude } } public class Person { public var name: String = "John Doe" public var address: String = "C/ María Martillo" public var homeCoordinate: Coordinate? public init(name: String) { self.name = name } }
mit
iadmir/Signal-iOS
Signal/src/Profiles/ProfileFetcherJob.swift
2
7439
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit @objc class ProfileFetcherJob: NSObject { let TAG = "[ProfileFetcherJob]" let networkManager: TSNetworkManager let storageManager: TSStorageManager // This property is only accessed on the main queue. static var fetchDateMap = [String: Date]() let ignoreThrottling: Bool public class func run(thread: TSThread, networkManager: TSNetworkManager) { ProfileFetcherJob(networkManager: networkManager).run(recipientIds: thread.recipientIdentifiers) } public class func run(recipientId: String, networkManager: TSNetworkManager, ignoreThrottling: Bool) { ProfileFetcherJob(networkManager: networkManager, ignoreThrottling:ignoreThrottling).run(recipientIds: [recipientId]) } init(networkManager: TSNetworkManager, ignoreThrottling: Bool = false) { self.networkManager = networkManager self.storageManager = TSStorageManager.shared() self.ignoreThrottling = ignoreThrottling } public func run(recipientIds: [String]) { AssertIsOnMainThread() DispatchQueue.main.async { for recipientId in recipientIds { self.updateProfile(recipientId: recipientId) } } } enum ProfileFetcherJobError: Error { case throttled(lastTimeInterval: TimeInterval), unknownNetworkError } public func updateProfile(recipientId: String, remainingRetries: Int = 3) { self.getProfile(recipientId: recipientId).then { profile in self.updateProfile(signalServiceProfile: profile) }.catch { error in switch error { case ProfileFetcherJobError.throttled(let lastTimeInterval): Logger.info("\(self.TAG) skipping updateProfile: \(recipientId), lastTimeInterval: \(lastTimeInterval)") case let error as SignalServiceProfile.ValidationError: Logger.warn("\(self.TAG) skipping updateProfile retry. Invalid profile for: \(recipientId) error: \(error)") default: if remainingRetries > 0 { self.updateProfile(recipientId: recipientId, remainingRetries: remainingRetries - 1) } else { Logger.error("\(self.TAG) in \(#function) failed to get profile with error: \(error)") } } }.retainUntilComplete() } public func getProfile(recipientId: String) -> Promise<SignalServiceProfile> { AssertIsOnMainThread() if !ignoreThrottling { if let lastDate = ProfileFetcherJob.fetchDateMap[recipientId] { let lastTimeInterval = fabs(lastDate.timeIntervalSinceNow) // Don't check a profile more often than every N minutes. // // Only throttle profile fetch in production builds in order to // facilitate debugging. let kGetProfileMaxFrequencySeconds = _isDebugAssertConfiguration() ? 0 : 60.0 * 5.0 guard lastTimeInterval > kGetProfileMaxFrequencySeconds else { return Promise(error: ProfileFetcherJobError.throttled(lastTimeInterval: lastTimeInterval)) } } } ProfileFetcherJob.fetchDateMap[recipientId] = Date() Logger.error("\(self.TAG) getProfile: \(recipientId)") let request = OWSGetProfileRequest(recipientId: recipientId) let (promise, fulfill, reject) = Promise<SignalServiceProfile>.pending() self.networkManager.makeRequest( request, success: { (_: URLSessionDataTask?, responseObject: Any?) -> Void in do { let profile = try SignalServiceProfile(recipientId: recipientId, rawResponse: responseObject) fulfill(profile) } catch { reject(error) } }, failure: { (_: URLSessionDataTask?, error: Error?) in if let error = error { reject(error) } reject(ProfileFetcherJobError.unknownNetworkError) }) return promise } private func updateProfile(signalServiceProfile: SignalServiceProfile) { verifyIdentityUpToDateAsync(recipientId: signalServiceProfile.recipientId, latestIdentityKey: signalServiceProfile.identityKey) OWSProfileManager.shared().updateProfile(forRecipientId: signalServiceProfile.recipientId, profileNameEncrypted: signalServiceProfile.profileNameEncrypted, avatarUrlPath: signalServiceProfile.avatarUrlPath) } private func verifyIdentityUpToDateAsync(recipientId: String, latestIdentityKey: Data) { OWSDispatch.sessionStoreQueue().async { if OWSIdentityManager.shared().saveRemoteIdentity(latestIdentityKey, recipientId: recipientId) { Logger.info("\(self.TAG) updated identity key with fetched profile for recipient: \(recipientId)") self.storageManager.archiveAllSessions(forContact: recipientId) } else { // no change in identity. } } } } struct SignalServiceProfile { let TAG = "[SignalServiceProfile]" enum ValidationError: Error { case invalid(description: String) case invalidIdentityKey(description: String) case invalidProfileName(description: String) } public let recipientId: String public let identityKey: Data public let profileNameEncrypted: Data? public let avatarUrlPath: String? init(recipientId: String, rawResponse: Any?) throws { self.recipientId = recipientId guard let responseDict = rawResponse as? [String: Any?] else { throw ValidationError.invalid(description: "\(TAG) unexpected type: \(String(describing: rawResponse))") } guard let identityKeyString = responseDict["identityKey"] as? String else { throw ValidationError.invalidIdentityKey(description: "\(TAG) missing identity key: \(String(describing: rawResponse))") } guard let identityKeyWithType = Data(base64Encoded: identityKeyString) else { throw ValidationError.invalidIdentityKey(description: "\(TAG) unable to parse identity key: \(identityKeyString)") } let kIdentityKeyLength = 33 guard identityKeyWithType.count == kIdentityKeyLength else { throw ValidationError.invalidIdentityKey(description: "\(TAG) malformed key \(identityKeyString) with decoded length: \(identityKeyWithType.count)") } if let profileNameString = responseDict["name"] as? String { guard let data = Data(base64Encoded: profileNameString) else { throw ValidationError.invalidProfileName(description: "\(TAG) unable to parse profile name: \(profileNameString)") } self.profileNameEncrypted = data } else { self.profileNameEncrypted = nil } self.avatarUrlPath = responseDict["avatar"] as? String // `removeKeyType` is an objc category method only on NSData, so temporarily cast. self.identityKey = (identityKeyWithType as NSData).removeKeyType() as Data } }
gpl-3.0
eurofurence/ef-app_ios
Packages/EurofurenceKit/Tests/EurofurenceWebAPITests/Remote Configuration/FirebaseRemoteConfigurationTests.swift
1
1498
@testable import EurofurenceWebAPI import Foundation import XCTest class FirebaseRemoteConfigurationTests: XCTestCase { func testTellsConfigurationToAcquireRemoteValuesDuringPreparation() async throws { let narrowedConfiguration = FakeNarrowedFirebaseConfiguration() let firebaseConfiguration = FirebaseRemoteConfiguration(firebaseConfiguration: narrowedConfiguration) XCTAssertFalse( narrowedConfiguration.toldToAcquireRemoteValues, "Should not acquire remote values until told to" ) await firebaseConfiguration.prepareConfiguration() XCTAssertTrue( narrowedConfiguration.toldToAcquireRemoteValues, "Should acquire remote values when told to" ) } func testAdaptsConventionDateAsEpochTime() async throws { let conventionStartDateRelativeToEpoch: TimeInterval = 1551371501 let expected = Date(timeIntervalSince1970: conventionStartDateRelativeToEpoch) let narrowedConfiguration = FakeNarrowedFirebaseConfiguration() narrowedConfiguration.stub(NSNumber(value: conventionStartDateRelativeToEpoch), forKey: "nextConStart") let firebaseConfiguration = FirebaseRemoteConfiguration(firebaseConfiguration: narrowedConfiguration) await firebaseConfiguration.prepareConfiguration() XCTAssertEqual(expected, firebaseConfiguration[RemoteConfigurationKeys.ConventionStartTime.self]) } }
mit
huangboju/Moots
UICollectionViewLayout/elongation-preview-master/ElongationPreview/Source/ElongationConfig.swift
2
3530
// // ElongationConfig.swift // ElongationPreview // // Created by Abdurahim Jauzee on 09/02/2017. // Copyright © 2017 Ramotion. All rights reserved. // import UIKit /// Whole module views configuration public struct ElongationConfig { /// Empty public initializer. public init() {} /// Shared instance. Override this property to apply changes. public static var shared = ElongationConfig() // MARK: Behaviour 🔧 /// :nodoc: public enum CellTouchAction { case collapseOnTopExpandOnBottom, collapseOnBottomExpandOnTop, collapseOnBoth, expandOnBoth, expandOnTop, expandOnBottom } /// What `elongationCell` should do on touch public var cellTouchAction = CellTouchAction.collapseOnTopExpandOnBottom /// :nodoc: public enum HeaderTouchAction { case collpaseOnBoth, collapseOnTop, collapseOnBottom, noAction } /// What `elongationHeader` should do on touch public var headerTouchAction = HeaderTouchAction.collapseOnTop /// Enable gestures on `ElongationCell` & `ElongationHeader`. /// These gestures will give ability to expand/dismiss the cell and detail view controller. /// Default value: `true` public var isSwipeGesturesEnabled = true /// Enable `UIPreviewIntearction` on `ElongationCell`. /// Default value: `true` public var forceTouchPreviewInteractionEnabled = true /// Enable `UILongPressGesture` on `ElongationCell`. /// This gesture will allow to `expand` `ElongationCell` on long tap. By default, this option will be used on devices without 3D Touch technology. /// Default value: `true` public var longPressGestureEnabled = true // MARK: Appearance 🎨 /// Actual height of `topView`. /// Default value: `200` public var topViewHeight: CGFloat = 200 /// `topView` scale value which will be used for making CGAffineTransform /// to `expanded` state /// Default value: `0.9` public var scaleViewScaleFactor: CGFloat = 0.9 /// Parallax effect factor. /// Default value: `nil` public var parallaxFactor: CGFloat? /// Should we enable parallax effect on ElongationCell (read-only). /// Will be `true` if `separator` not `nil` && greater than zero public var isParallaxEnabled: Bool { switch parallaxFactor { case .none: return false case let .some(value): return value > 0 } } /// Offset of `bottomView` against `topView` /// Default value: `20` public var bottomViewOffset: CGFloat = 20 /// `bottomView` height value /// Default value: `180` public var bottomViewHeight: CGFloat = 180 /// Height of custom separator line between cells in tableView /// Default value: `nil` public var separatorHeight: CGFloat? /// Color of custom separator /// Default value: `.white` public var separatorColor: UIColor = .white /// Should we create custom separator view (read-only). /// Will be `true` if `separator` not `nil` && greater than zero. public var customSeparatorEnabled: Bool { switch separatorHeight { case .none: return false case let .some(value): return value > 0 } } /// Duration of `detail` view controller presentation animation /// Default value: `0.3` public var detailPresentingDuration: TimeInterval = 0.3 /// Duration of `detail` view controller dismissing animation /// Default value: `0.4` public var detailDismissingDuration: TimeInterval = 0.4 }
mit
embryoconcepts/TIY-Assignments
00 -- This-is-Heavy/Counter (conversion errors)/Counter/ViewController.swift
1
4401
// // ViewController.swift // Swift-Counter // // Created by Ben Gohlke on 8/17/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // import UIKit class ViewController: UIViewController { // The following variables and constants are called properties; they hold values that can be accessed from any method in this class // This allows the app to set its current count when the app first loads. // The line below simply generates a random number and then makes sure it falls within the bounds 1-100. var currentCount: Int = Int(arc4random() % 100) // These are called IBOutlets and are a kind of property; they connect elements in the storyboard with the code so you can update the UI elements from code. @IBOutlet weak var countTextField: UITextField! @IBOutlet weak var slider: UISlider! @IBOutlet weak var stepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() // // 1. Once the currentCount variable is set, each of the UI elements on the screen need to be updated to match the currentCount. // There is a method below that performs these steps. All you need to do perform a method call in the line below. // updateViewsWithCurrentCount() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateViewsWithCurrentCount() { // Here we are updating the different subviews in our main view with the current count. // // 2. The textfield needs to always show the current count. Fill in the blank below to set the text value of the textfield. // countTextField.text = "\(currentCount)" // // 3. Here we are setting the value property of the UISlider in the view. This causes the slider to set its handle to the // appropriate position. Fill in the blank below. // slider.value = Float(currentCount) // // 4. We also need to update the value of the UIStepper. The user will not see any change to the stepper, but it needs to have a // current value nonetheless, so when + or - is tapped, it will know what value to increment. Fill in the blanks below. // stepper.value = Double(currentCount) } // MARK: - Gesture recognizers @IBAction func viewTapped(sender: UITapGestureRecognizer) { // This method is run whenever the user taps on the blank, white view (meaning they haven't tapped any of the controls on the // view). It hides the keyboard if the user has edited the count textfield, and also updates the currentCount variable. if countTextField.isFirstResponder() { countTextField.resignFirstResponder() // // 8. Hopefully you're seeing a pattern here. After we update the currentCount variable, what do we need to do next? Fill in // the blank below. // updateViewsWithCurrentCount() } } // MARK: - Action handlers @IBAction func sliderValueChanged(sender: UISlider) { // // 5. This method will run whenever the value of the slider is changed by the user. The "sender" object passed in as an argument // to this method represents the slider from the view. We need to take the value of the slider and use it to update the // value of our "currentCount" instance variable. Fill in the blank below. // currentCount = Int(sender.value) // // 6. Once we update the value of currentCount, we need to make sure all the UI elements on the screen are updated to keep // everything in sync. We have previously done this (look in viewDidLoad). Fill in the blank below. // updateViewsWithCurrentCount() } @IBAction func stepperValueChanged(sender: UIStepper) { // // 7. This method is run when the value of the stepper is changed by the user. If you've done steps 5 and 6 already, these steps // should look pretty familiar, hint, hint. ;) Fill in the blanks below. // currentCount = Int(sender.value) updateViewsWithCurrentCount() } }
cc0-1.0
huonw/swift
test/NameBinding/MutualDependency.swift
7
631
// RUN: %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -parse-as-library // RUN: %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs // RUN: %target-swift-frontend -typecheck %S/Inputs/MutualDependencyHelper.swift -enable-source-import -I %S // RUN: %target-swift-frontend -interpret -I %S/Inputs -enable-source-import %s -verify import MutualDependencyHelper public class MyClass { public var delegate : MyDelegate // expected-note {{'self.delegate' not initialized}} public init() {} // expected-error {{return from initializer without initializing all stored properties}} }
apache-2.0
ioriwellings/BluetoothKit
Source/BKPeripheralConfiguration.swift
13
1844
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // 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 CoreBluetooth /** A subclass of BKConfiguration for constructing configurations to use when starting BKPeripheral objects. */ public class BKPeripheralConfiguration: BKConfiguration { // MARK: Properties /// The local name to broadcast to remote centrals. public let localName: String? // MARK: Initialization public init(dataServiceUUID: NSUUID, dataServiceCharacteristicUUID: NSUUID, localName: String? = nil) { self.localName = localName super.init(dataServiceUUID: dataServiceUUID, dataServiceCharacteristicUUID: dataServiceCharacteristicUUID) } }
mit
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Chat/ChatCells/VoiceChatCell.swift
1
5684
// // VoiceChatCell.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/28. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class VoiceChatCell: BaseChatCell { //MARK: 属性 weak var delegate:VoiceChatCellDelegate? var viewModel:VoiceChatCellViewModel?{ didSet{ super.baseViewModel = viewModel backView.image = viewModel?.voicebackImage backView.highlightedImage = viewModel?.voicebackHightLightImage voiceTimeLabel.text = viewModel?.voiceTimeLabelText voiceTimeLabel.font = viewModel?.voiceTimeLabelFont guard let viewFrame = viewModel?.viewFrame else { return } layoutVoiceChatCell(viewFrame) } } private var isRecordigAnimation:Bool = false private var isPlayingAnimation:Bool = false private var backViewAlpha:CGFloat = 1.0 //MARK: 懒加载 lazy var voiceImage:VoiceView = { () -> VoiceView in let image = VoiceView(frame: CGRect.zero) image.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(voiceImageViewDidTap)) image.addGestureRecognizer(tap) return image }() lazy var voiceTimeLabel:UILabel = { () -> UILabel in let label = UILabel() label.textColor = UIColor.gray return label }() //MARK: 构造方法 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupVoiceChatCell() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 私有方法 private func setupVoiceChatCell() { addSubview(voiceImage) addSubview(voiceTimeLabel) } private func layoutVoiceChatCell(_ viewFrame:ViewFrame) { voiceImage.viewLocation = self.viewModel?.viewLocation if self.viewModel?.viewLocation == .right { voiceTimeLabel.snp.remakeConstraints({ (make) in make.centerY.equalTo(backView.snp.centerY) make.right.equalTo(voiceImage.snp.left).offset(-margin) }) voiceImage.snp.remakeConstraints({ (make) in make.right.equalTo(backView).offset(-margin*2.0) make.width.height.equalTo(20) }) backView.snp.remakeConstraints { (make) in make.left.equalTo(voiceTimeLabel).offset(-margin*2.0) make.bottom.equalTo(voiceImage).offset(margin*2.0) make.right.equalTo(avatarButton.snp.left).offset(-margin*0.5) make.top.equalTo(nameLabel.snp.bottom).offset(-margin*0.1) } } else { voiceTimeLabel.snp.remakeConstraints({ (make) in make.left.equalTo(voiceImage.snp.right).offset(margin) make.centerY.equalTo(backView.snp.centerY) }) voiceImage.snp.remakeConstraints({ (make) in make.left.equalTo(backView).offset(margin*2.0) make.width.height.equalTo(20) }) backView.snp.remakeConstraints { (make) in make.right.equalTo(voiceTimeLabel).offset(margin*2.0) make.bottom.equalTo(voiceImage).offset(margin*2.0) make.top.equalTo(nameLabel.snp.bottom).offset(-margin*0.1) make.left.equalTo(avatarButton.snp.right).offset(margin*0.5) } } if viewModel?.voiceStatus == .recording { voiceTimeLabel.isHidden = true voiceImage.isHidden = true startRecordingAnimation() } else{ voiceTimeLabel.isHidden = false voiceImage.isHidden = false stopRecordingAnimation() } if viewModel?.voiceStatus == .playing { voiceImage.startPlaying() } else { voiceImage.stopPlaying() } } private func startRecordingAnimation() { isRecordigAnimation = true backViewAlpha = 0.4 recordingAnimation() } private func stopRecordingAnimation() { isRecordigAnimation = false backViewAlpha = 1.0 backView.alpha = backViewAlpha } private func recordingAnimation() { UIView.animate(withDuration: 1.0, animations: { self.backView.alpha = self.backViewAlpha }) { (finished) in self.backViewAlpha = self.backViewAlpha > 0.9 ? 0.4:1.0 if finished && self.isRecordigAnimation { self.recordingAnimation() } else{ self.backView.alpha = 1.0 } } } private func voicePlayingAnimation() { if isPlayingAnimation { voiceImage.startPlaying() } else{ voiceImage.stopPlaying() } } //MARK: 内部响应 @objc private func voiceImageViewDidTap() { isPlayingAnimation = !isPlayingAnimation //: 播放 voicePlayingAnimation() delegate?.didTapVoiceChatCell(cell: self ,isStart: isPlayingAnimation) } } //MARK: 协议 protocol VoiceChatCellDelegate:NSObjectProtocol { func didTapVoiceChatCell(cell:VoiceChatCell, isStart:Bool) }
mit
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/utilities/LGAudioRecorder.swift
1
3991
// // LGAudioRecorder.swift // LGChatViewController // // Created by jamy on 10/13/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import AVFoundation protocol LGAudioRecorderDelegate { func audioRecorderUpdateMetra(metra: Float) } let soundPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! let audioSettings: [String: AnyObject] = [AVLinearPCMIsFloatKey: NSNumber(bool: false), AVLinearPCMIsBigEndianKey: NSNumber(bool: false), AVLinearPCMBitDepthKey: NSNumber(int: 16), AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatLinearPCM), AVNumberOfChannelsKey: NSNumber(int: 1), AVSampleRateKey: NSNumber(int: 16000), AVEncoderAudioQualityKey: NSNumber(integer: AVAudioQuality.Medium.rawValue)] class LGAudioRecorder: NSObject, AVAudioRecorderDelegate { var audioData: NSData! var operationQueue: NSOperationQueue! var recorder: AVAudioRecorder! var startTime: Double! var endTimer: Double! var timeInterval: NSNumber! var delegate: LGAudioRecorderDelegate? convenience init(fileName: String) { self.init() let filePath = NSURL(fileURLWithPath: (soundPath as NSString).stringByAppendingPathComponent(fileName)) recorder = try! AVAudioRecorder(URL: filePath, settings: audioSettings) recorder.delegate = self recorder.meteringEnabled = true } override init() { operationQueue = NSOperationQueue() super.init() } func startRecord() { startTime = NSDate().timeIntervalSince1970 performSelector("readyStartRecord", withObject: self, afterDelay: 0.5) } func readyStartRecord() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryRecord) } catch { NSLog("setCategory fail") return } do { try audioSession.setActive(true) } catch { NSLog("setActive fail") return } recorder.record() let operation = NSBlockOperation() operation.addExecutionBlock(updateMeters) operationQueue.addOperation(operation) } func stopRecord() { endTimer = NSDate().timeIntervalSince1970 timeInterval = nil if (endTimer - startTime) < 0.5 { NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "readyStartRecord", object: self) } else { timeInterval = NSNumber(int: NSNumber(double: recorder.currentTime).intValue) if timeInterval.intValue < 1 { performSelector("readyStopRecord", withObject: self, afterDelay: 0.4) } else { readyStopRecord() } } operationQueue.cancelAllOperations() } func readyStopRecord() { recorder.stop() let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(false, withOptions: .NotifyOthersOnDeactivation) } catch { // no-op } audioData = NSData(contentsOfURL: recorder.url) } func updateMeters() { repeat { recorder.updateMeters() timeInterval = NSNumber(float: NSNumber(double: recorder.currentTime).floatValue) let averagePower = recorder.averagePowerForChannel(0) // let pearPower = recorder.peakPowerForChannel(0) // NSLog("%@ %f %f", timeInterval, averagePower, pearPower) delegate?.audioRecorderUpdateMetra(averagePower) NSThread.sleepForTimeInterval(0.2) } while(recorder.recording) } // MARK: audio delegate func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) { NSLog("%@", (error?.localizedDescription)!) } }
mit
happyeverydayzhh/WWDC
WWDC/VideosViewController.swift
1
13898
// // ViewController.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import ViewUtils class VideosViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var scrollView: NSScrollView! @IBOutlet weak var tableView: NSTableView! var splitManager: SplitManager? var indexOfLastSelectedRow = -1 let savedSearchTerm = Preferences.SharedPreferences().searchTerm var finishedInitialSetup = false var restoredSelection = false var loadedStoryboard = false lazy var headerController: VideosHeaderViewController! = VideosHeaderViewController.loadDefaultController() override func awakeFromNib() { super.awakeFromNib() if splitManager == nil && loadedStoryboard { if let splitViewController = parentViewController as? NSSplitViewController { splitManager = SplitManager(splitView: splitViewController.splitView) // this caused a crash when running on 10.11... // splitViewController.splitView.delegate = self.splitManager } } loadedStoryboard = true } override func awakeAfterUsingCoder(aDecoder: NSCoder) -> AnyObject? { return super.awakeAfterUsingCoder(aDecoder) } override func viewDidLoad() { super.viewDidLoad() setupSearching() setupScrollView() tableView.gridColor = Theme.WWDCTheme.separatorColor loadSessions(refresh: false, quiet: false) let nc = NSNotificationCenter.defaultCenter() nc.addObserverForName(SessionProgressDidChangeNotification, object: nil, queue: nil) { _ in self.reloadTablePreservingSelection() } nc.addObserverForName(SessionFavoriteStatusDidChangeNotification, object: nil, queue: nil) { _ in self.reloadTablePreservingSelection() } nc.addObserverForName(VideoStoreNotificationDownloadStarted, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.reloadTablePreservingSelection() } nc.addObserverForName(VideoStoreNotificationDownloadFinished, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.reloadTablePreservingSelection() } nc.addObserverForName(VideoStoreDownloadedFilesChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.reloadTablePreservingSelection() } nc.addObserverForName(AutomaticRefreshPreferenceChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in self.setupAutomaticSessionRefresh() } } override func viewDidAppear() { super.viewDidAppear() if finishedInitialSetup { return } GRLoadingView.showInWindow(self.view.window!) finishedInitialSetup = true } func setupScrollView() { let insetHeight = NSHeight(headerController.view.frame) scrollView.automaticallyAdjustsContentInsets = false scrollView.contentInsets = NSEdgeInsets(top: insetHeight, left: 0, bottom: 0, right: 0) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateScrollInsets:", name: LiveEventBannerVisibilityChangedNotification, object: nil) setupViewHeader(insetHeight) } func updateScrollInsets(note: NSNotification?) { if let bannerController = LiveEventBannerViewController.DefaultController { scrollView.contentInsets = NSEdgeInsets(top: scrollView.contentInsets.top, left: 0, bottom: bannerController.barHeight, right: 0) } } func setupViewHeader(insetHeight: CGFloat) { if let superview = scrollView.superview { superview.addSubview(headerController.view) headerController.view.frame = CGRectMake(0, NSHeight(superview.frame)-insetHeight, NSWidth(superview.frame), insetHeight) headerController.view.autoresizingMask = [NSAutoresizingMaskOptions.ViewWidthSizable, NSAutoresizingMaskOptions.ViewMinYMargin] headerController.performSearch = search } // show search term from previous launch in search bar headerController.searchBar.stringValue = savedSearchTerm } var sessions: [Session]! { didSet { if sessions != nil { // run transcript indexing service if needed TranscriptStore.SharedStore.runIndexerIfNeeded(sessions) headerController.enable() // restore search from previous launch if savedSearchTerm != "" { search(savedSearchTerm) indexOfLastSelectedRow = Preferences.SharedPreferences().selectedSession } searchController.sessions = sessions } if savedSearchTerm == "" { reloadTablePreservingSelection() } } } // MARK: Session loading func loadSessions(refresh refresh: Bool, quiet: Bool) { if !quiet { if let window = view.window { GRLoadingView.showInWindow(window) } } let completionHandler: DataStore.fetchSessionsCompletionHandler = { success, sessions in dispatch_async(dispatch_get_main_queue()) { self.sessions = sessions self.splitManager?.restoreDividerPosition() self.splitManager?.startSavingDividerPosition() if !quiet { GRLoadingView.dismissAllAfterDelay(0.3) } self.setupAutomaticSessionRefresh() } } DataStore.SharedStore.fetchSessions(completionHandler, disableCache: refresh) } @IBAction func refresh(sender: AnyObject?) { loadSessions(refresh: true, quiet: false) } var sessionListRefreshTimer: NSTimer? func setupAutomaticSessionRefresh() { if Preferences.SharedPreferences().automaticRefreshEnabled { if sessionListRefreshTimer == nil { sessionListRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(Preferences.SharedPreferences().automaticRefreshInterval, target: self, selector: "sessionListRefreshFromTimer", userInfo: nil, repeats: true) } } else { sessionListRefreshTimer?.invalidate() sessionListRefreshTimer = nil } } func sessionListRefreshFromTimer() { loadSessions(refresh: true, quiet: true) } // MARK: TableView func reloadTablePreservingSelection() { tableView.reloadData() if !restoredSelection { indexOfLastSelectedRow = Preferences.SharedPreferences().selectedSession restoredSelection = true } if indexOfLastSelectedRow > -1 { tableView.selectRowIndexes(NSIndexSet(index: indexOfLastSelectedRow), byExtendingSelection: false) } } func numberOfRowsInTableView(tableView: NSTableView) -> Int { if let count = displayedSessions?.count { return count } else { return 0 } } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeViewWithIdentifier("video", owner: tableView) as! VideoTableCellView if row > displayedSessions.count { return cell } cell.session = displayedSessions[row] return cell } func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 40.0 } func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { return tableView.makeViewWithIdentifier("row", owner: tableView) as? NSTableRowView } // MARK: Table Menu @IBAction func markAsWatchedMenuAction(sender: NSMenuItem) { // if there is only one row selected, change the status of the clicked row instead of using the selection if tableView.selectedRowIndexes.count < 2 { var session = displayedSessions[tableView.clickedRow] session.progress = 100 } else { doMassiveSessionPropertyUpdate(.Progress(100)) } } @IBAction func markAsUnwatchedMenuAction(sender: NSMenuItem) { // if there is only one row selected, change the status of the clicked row instead of using the selection if tableView.selectedRowIndexes.count < 2 { var session = displayedSessions[tableView.clickedRow] session.progress = 0 } else { doMassiveSessionPropertyUpdate(.Progress(0)) } } @IBAction func addToFavoritesMenuAction(sender: NSMenuItem) { // if there is only one row selected, change the status of the clicked row instead of using the selection if tableView.selectedRowIndexes.count < 2 { var session = displayedSessions[tableView.clickedRow] session.favorite = true } else { doMassiveSessionPropertyUpdate(.Favorite(true)) } } @IBAction func removeFromFavoritesMenuAction(sender: NSMenuItem) { // if there is only one row selected, change the status of the clicked row instead of using the selection if tableView.selectedRowIndexes.count < 2 { var session = displayedSessions[tableView.clickedRow] session.favorite = false } else { doMassiveSessionPropertyUpdate(.Favorite(false)) } } private let userInitiatedQ = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0) private enum MassiveUpdateProperty { case Progress(Double) case Favorite(Bool) } // changes the property of all selected sessions on a background queue private func doMassiveSessionPropertyUpdate(property: MassiveUpdateProperty) { dispatch_async(userInitiatedQ) { self.tableView.selectedRowIndexes.enumerateIndexesUsingBlock { idx, _ in let session = self.displayedSessions[idx] switch property { case .Progress(let progress): session.setProgressWithoutSendingNotification(progress) case .Favorite(let favorite): session.setFavoriteWithoutSendingNotification(favorite) } } dispatch_async(dispatch_get_main_queue()) { self.reloadTablePreservingSelection() } } } @IBAction func copyURL(sender: NSMenuItem) { var stringToCopy:String? if tableView.selectedRowIndexes.count < 2 && tableView.clickedRow >= 0 { let session = displayedSessions[tableView.clickedRow] stringToCopy = session.shareURL } else { stringToCopy = "" for idx in tableView.selectedRowIndexes { let session = self.displayedSessions[idx] stringToCopy? += session.shareURL if tableView.selectedRowIndexes.lastIndex != idx { stringToCopy? += "\n" } } } if let string = stringToCopy { let pb = NSPasteboard.generalPasteboard() pb.clearContents() pb.writeObjects([string]) } } @IBAction func copy(sender: NSMenuItem) { copyURL(sender) } // MARK: Navigation var detailsViewController: VideoDetailsViewController? { get { if let splitViewController = parentViewController as? NSSplitViewController { return splitViewController.childViewControllers[1] as? VideoDetailsViewController } else { return nil } } } func tableViewSelectionDidChange(notification: NSNotification) { if let detailsVC = detailsViewController { detailsVC.selectedCount = tableView.selectedRowIndexes.count } if tableView.selectedRow >= 0 { Preferences.SharedPreferences().selectedSession = tableView.selectedRow indexOfLastSelectedRow = tableView.selectedRow let session = displayedSessions[tableView.selectedRow] if let detailsVC = detailsViewController { detailsVC.session = session } } else { if let detailsVC = detailsViewController { detailsVC.session = nil } } } // MARK: Search var searchController = SearchController() private func setupSearching() { searchController.searchDidFinishCallback = { dispatch_async(dispatch_get_main_queue()) { self.reloadTablePreservingSelection() } } } var currentSearchTerm: String? { didSet { if currentSearchTerm != nil { Preferences.SharedPreferences().searchTerm = currentSearchTerm! } else { Preferences.SharedPreferences().searchTerm = "" } } } func search(term: String) { currentSearchTerm = term searchController.searchFor(currentSearchTerm) } var displayedSessions: [Session]! { get { return searchController.displayedSessions } } }
bsd-2-clause
avito-tech/Marshroute
Example/NavigationDemo/VIPER/Categories/Router/CategoriesRouterIpad.swift
1
1100
import UIKit import Marshroute final class CategoriesRouterIpad: BaseDemoRouter, CategoriesRouter { // MARK: - CategoriesRouter func showSubcategories(categoryId: CategoryId) { pushViewControllerDerivedFrom { routerSeed -> UIViewController in let subcategoriesAssembly = assemblyFactory.subcategoriesAssembly() let viewController = subcategoriesAssembly.ipadModule( categoryId: categoryId, routerSeed: routerSeed ) return viewController } } func showSearchResults(categoryId: CategoryId) { pushViewControllerDerivedFrom { routerSeed -> UIViewController in let searchResultsAssembly = assemblyFactory.searchResultsAssembly() let viewController = searchResultsAssembly.ipadModule( categoryId: categoryId, routerSeed: routerSeed ) return viewController } } func returnToCategories() { focusOnCurrentModule() } }
mit
sgtsquiggs/WordSearch
WordSearch/CharacterGridViewDelegate.swift
1
422
// // CharacterGridViewDelegate.swift // WordSearch // // Created by Matthew Crenshaw on 11/13/15. // Copyright © 2015 Matthew Crenshaw. All rights reserved. // import UIKit // This can't be represented in objc because Highlight is a struct maybe. Can't make this IB-friendly. protocol CharacterGridViewDelegate { func shouldHighlight(highlight: Highlight) -> Bool func didHighlight(highlight: Highlight) }
mit
gank0326/meituan_ipad
Tuan/Kingfisher/String+MD5.swift
8
8376
// // String+MD5.swift // WebImageDemo // // Created by Wei Wang on 15/4/6. // Copyright (c) 2015年 Wei Wang. All rights reserved. // // This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift // which is a modified version of CryptoSwift: // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset of CryptoSwift as a (temporary?) alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation extension String { func kf_MD5() -> String { if let data = self.dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(data) let MD5Data = MD5Calculator.calculate() let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) var MD5String = "" for c in resultEnumerator { MD5String += String(format: "%02x", c) } return MD5String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) var v = value var valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value var bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T),totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { self.appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } class HashBase { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len:Int = 64) -> NSMutableData { var tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.length; var counter = 0; while msgLength % len != (len - 8) { counter++ msgLength++ } var bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8))) tmpMessage.appendBytes(bufZeros, length: counter) return tmpMessage } } func rotateLeft(v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } class MD5 : HashBase { /** specifies the per-round shift amounts */ private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391] private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> NSData { var tmpMessage = prepare() // hash values var hh = h // Step 2. Append Length a 64-bit representation of lengthInBits var lengthInBits = (message.length * 8) var lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage.appendBytes(reverse(lengthBytes)); // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes))) let bytes = tmpMessage.bytes; // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0) let range = NSRange(location:0, length: M.count * sizeof(UInt32)) chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range) // Initialize hash value for this chunk: var A:UInt32 = hh[0] var B:UInt32 = hh[1] var C:UInt32 = hh[2] var D:UInt32 = hh[3] var dTemp:UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F:UInt32 = 0 switch (j) { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), s[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var buf: NSMutableData = NSMutableData(); hh.map({ (item) -> () in var i:UInt32 = item.littleEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData; } }
mit
KanChen2015/DRCRegistrationKit
DRCRegistrationKit/DRCRegistrationKit/DRRSignUpViewModel.swift
1
4480
// // DRRSignUpViewModel.swift // DRCRegistrationKit // // Created by Kan Chen on 6/8/16. // Copyright © 2016 drchrono. All rights reserved. // import Foundation internal let kDRRSignupFullNameKey = "name" internal let kDRRSignupFirstNameKey = "firstName" internal let kDRRSignupLastNameKey = "lastName" internal let kDRRSignupEmailKey = "email" internal let kDRRSignupPhoneKey = "office_phone" internal let kDRRSignupSessionKey = "signup_session" //step 2 internal let kDRRSignupStateKey = "state" internal let kDRRSignupSpecialtyKey = "specialty" internal let kDRRSignupJobTitleKey = "job_title" //step 3 internal let kDRRSignupUsernameKey = "username" internal let kDRRSignupPasswordKey = "password" internal let kDRRSignupPasswordConfirmKey = "password_confirm" internal let kDRRSignupTermsConfirmedKey = "terms_of_service_agreement" //#define kDRCSignupBillingKey @"billing" //#define kDRCSignupProvidersKey @"providers" //#define kDRCSignupTermsKey @"" //#define kPracticeSizeDisplays @[@"Just Me", @"2 to 5", @"6 to 10", @"10+"] //#define kBillingTypeDisplays @[@"Insurance", @"Cash-based"] final class DRRSignUpViewModel { typealias signupStepComplete = (success: Bool, errorMsg: String?) -> Void var delegate: DRCRegistrationNetworkingDelegate? = DelegateProvider.shared.networkingDelegate var stateChoices: [String] = [] var jobTitleChoices: [String] = [] var specialtyChoices: [String] = [] private var signupSession: String = "" var registeredUsername: String = "" var registeredPassword: String = "" func signupStep1WithInfo(info: [String: AnyObject], complete: signupStepComplete) { delegate?.attemptSignupStep1RequestWithInfo(info, complete: { (json, error) in if let error = error { complete(success: false, errorMsg: error.localizedDescription) return } if let success = json["success"] as? Bool where success { self.signupSession = json[kDRRSignupSessionKey] as? String ?? "" self.stateChoices = json["state_choices"] as? [String] ?? [] self.jobTitleChoices = json["job_title_choices"] as? [String] ?? [] self.specialtyChoices = json["specialty_choices"] as? [String] ?? [] complete(success: true, errorMsg: nil) } else { complete(success: false, errorMsg: json["errors"] as? String) } }) } func signupStep2WithInfo(info: [String: AnyObject], complete: signupStepComplete) { var finalInfo = info finalInfo[kDRRSignupSessionKey] = signupSession delegate?.attemptSignupStep2RequestWithInfo(finalInfo, complete: { (json, error) in if let error = error { complete(success: false, errorMsg: error.localizedDescription) return } if let success = json["success"] as? Bool where success { complete(success: true, errorMsg: nil) } else { complete(success: false, errorMsg: json["errors"] as? String) } }) } func signupStep3WithInfo(info: [String: AnyObject], complete: signupStepComplete) { var finalInfo = info finalInfo[kDRRSignupSessionKey] = signupSession //TODO: does this is required by our backend? finalInfo[kDRRSignupTermsConfirmedKey] = true delegate?.attemptSignupStep3RequestWithInfo(finalInfo, complete: { (json, error) in if let error = error { complete(success: false, errorMsg: error.localizedDescription) return } if let success = json["success"] as? Bool where success { guard let registeredUsername = json["username"] as? String, registeredPassword = json["password"] as? String where !registeredUsername.isEmpty && !registeredPassword.isEmpty else { complete(success: false, errorMsg: "An unknown error happened, please try again later") return } self.registeredUsername = registeredUsername self.registeredPassword = registeredPassword //TODO: PIN Manager complete(success: true, errorMsg: nil) } else { complete(success: false, errorMsg: json["errors"] as? String) } }) } }
mit
brentdax/swift
test/Constraints/metatypes.swift
16
935
// RUN: %target-typecheck-verify-swift class A {} class B : A {} let test0 : A.Type = A.self let test1 : A.Type = B.self let test2 : B.Type = A.self // expected-error {{cannot convert value of type 'A.Type' to specified type 'B.Type'}} let test3 : AnyClass = A.self let test4 : AnyClass = B.self struct S {} let test5 : S.Type = S.self let test6 : AnyClass = S.self // expected-error {{cannot convert value of type 'S.Type' to specified type 'AnyClass' (aka 'AnyObject.Type')}} func acceptMeta<T>(_ meta: T.Type) { } acceptMeta(A) // expected-error {{expected member name or constructor call after type name}} // expected-note@-1 {{add arguments after the type to construct a value of the type}} // expected-note@-2 {{use '.self' to reference the type object}} acceptMeta((A) -> Void) // expected-error {{expected member name or constructor call after type name}} // expected-note@-1 {{use '.self' to reference the type object}}
apache-2.0
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift
15
3526
// // RxCollectionViewReactiveArrayDataSource.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif // objc monkey business class _RxCollectionViewReactiveArrayDataSource : NSObject , UICollectionViewDataSource { @objc(numberOfSectionsInCollectionView:) func numberOfSections(in: UICollectionView) -> Int { return 1 } func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView(collectionView, numberOfItemsInSection: section) } fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return _collectionView(collectionView, cellForItemAt: indexPath) } } class RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S: Sequence> : RxCollectionViewReactiveArrayDataSource<S.Iterator.Element> , RxCollectionViewDataSourceType { typealias Element = S override init(cellFactory: @escaping CellFactory) { super.init(cellFactory: cellFactory) } func collectionView(_ collectionView: UICollectionView, observedEvent: Event<S>) { Binder(self) { collectionViewDataSource, sectionModels in let sections = Array(sectionModels) collectionViewDataSource.collectionView(collectionView, observedElements: sections) }.on(observedEvent) } } // Please take a look at `DelegateProxyType.swift` class RxCollectionViewReactiveArrayDataSource<Element> : _RxCollectionViewReactiveArrayDataSource , SectionedViewDataSourceType { typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell var itemModels: [Element]? = nil func modelAtIndex(_ index: Int) -> Element? { return itemModels?[index] } func model(at indexPath: IndexPath) throws -> Any { precondition(indexPath.section == 0) guard let item = itemModels?[indexPath.item] else { throw RxCocoaError.itemsNotYetBound(object: self) } return item } var cellFactory: CellFactory init(cellFactory: @escaping CellFactory) { self.cellFactory = cellFactory } // data source override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemModels?.count ?? 0 } override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) } // reactive func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) { self.itemModels = observedElements collectionView.reloadData() // workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index collectionView.collectionViewLayout.invalidateLayout() } } #endif
mit
alvaromb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Feed/News/NewsViewController.swift
1
5773
// // ViewController.swift // Twitter_test // // Created by Marin Todorov on 6/18/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import Social import Accounts import SQLite import XLPagerTabStrip class NewsViewController: TweetListViewController { let newsCtr = NewsController() let userCtr = UserController() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) observeNotification(kTabItemSelectedNotification, selector: "didTapTabItem:") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) observeNotification(kTabItemSelectedNotification, selector: nil) } func didTapTabItem(notification: NSNotification) { if let index = notification.userInfo?["object"] as? Int where index == EventBlankTabIndex.Feed.rawValue { mainQueue({ if self.tweets.count > 0 { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) } }) } } // MARK: table view methods override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell let row = indexPath.row let tweet = self.tweets[indexPath.row] let usersTable = database[UserConfig.tableName] let user = usersTable.filter(User.idColumn == tweet[Chat.idUser]).first cell.message.text = tweet[News.news] cell.timeLabel.text = NSDate(timeIntervalSince1970: Double(tweet[News.created])).relativeTimeToString() cell.message.selectedRange = NSRange(location: 0, length: 0) if let attachmentUrlString = tweet[News.imageUrl], let attachmentUrl = NSURL(string: attachmentUrlString) { cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 5.0, completion: {result in cell.attachmentImage.image = result }) }) cell.didTapAttachment = { PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view) } cell.attachmentHeight.constant = 148.0 } if let user = user { cell.nameLabel.text = user[User.name] if let imageUrlString = user[User.photoUrl], let imageUrl = NSURL(string: imageUrlString) { cell.userImage.hnk_setImageFromURL(imageUrl, placeholder: UIImage(named: "feed-item"), format: nil, failure: nil, success: {image in image.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5.0, completion: {result in cell.userImage.image = result }) }) } } cell.didTapURL = {tappedUrl in if tappedUrl.absoluteString!.hasPrefix("http") { let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = tappedUrl self.navigationController!.pushViewController(webVC, animated: true) } else { UIApplication.sharedApplication().openURL(tappedUrl) } } return cell } // MARK: load/fetch data override func loadTweets() { //fetch latest tweets from db let latestText = tweets.first?[News.news] tweets = self.newsCtr.allNews() lastRefresh = NSDate().timeIntervalSince1970 if latestText == tweets.first?[News.news] { //latest tweet is the same, bail return; } //reload table mainQueue { self.tableView.reloadData() if self.tweets.count == 0 { self.tableView.addSubview(MessageView(text: "No tweets found at this time, try again later")) } else { MessageView.removeViewFrom(self.tableView) } } } override func fetchTweets() { twitter.authorize({success in MessageView.removeViewFrom(self.tableView) if success { self.twitter.getTimeLineForUsername(Event.event[Event.twitterAdmin]!, completion: {tweetList, user in if let user = user where tweetList.count > 0 { self.userCtr.persistUsers([user]) self.newsCtr.persistNews(tweetList) self.loadTweets() } }) } else { delay(seconds: 0.5, { self.tableView.addSubview( //show a message + button to settings MessageView(text: "You don't have Twitter accounts set up. Open Settings app, select Twitter and connect an account. \n\nThen pull this view down to refresh the feed." //TODO: add the special iOS9 settings links later // ,buttonTitle: "Open Settings App", // buttonTap: { // UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) // } )) }) } mainQueue { self.refreshView.endRefreshing() } }) } }
mit
blockchain/My-Wallet-V3-iOS
Modules/RemoteNotifications/Sources/RemoteNotificationsKit/DIKit.swift
1
1743
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import NetworkKit import UIKit extension DependencyContainer { // MARK: - RemoteNotificationsKit Module public static var remoteNotificationsKit = module { factory { RemoteNotificationAuthorizer( application: UIApplication.shared, analyticsRecorder: DIKit.resolve(), userNotificationCenter: UNUserNotificationCenter.current() ) as RemoteNotificationAuthorizing } factory { RemoteNotificationNetworkService( pushNotificationsUrl: BlockchainAPI.shared.pushNotificationsUrl, networkAdapter: DIKit.resolve() ) as RemoteNotificationNetworkServicing } factory { RemoteNotificationService( authorizer: DIKit.resolve(), notificationRelay: DIKit.resolve(), backgroundReceiver: DIKit.resolve(), externalService: DIKit.resolve(), networkService: DIKit.resolve(), sharedKeyRepository: DIKit.resolve(), guidRepository: DIKit.resolve() ) as RemoteNotificationService } factory { () -> RemoteNotificationServicing in let service: RemoteNotificationService = DIKit.resolve() return service as RemoteNotificationServicing } single { () -> RemoteNotificationServiceContaining in let service: RemoteNotificationService = DIKit.resolve() return RemoteNotificationServiceContainer( service: service ) as RemoteNotificationServiceContaining } } }
lgpl-3.0
prolificinteractive/simcoe
Simcoe/mParticle/MPProduct+Simcoe.swift
1
1806
// // MPProduct+Simcoe.swift // Simcoe // // Created by Michael Campbell on 10/25/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import mParticle_Apple_SDK extension MPProduct { /// A convenience initializer. /// /// - Parameter product: A SimcoeProductConvertible instance. internal convenience init(product: SimcoeProductConvertible) { let simcoeProduct = product.toSimcoeProduct() self.init(name: simcoeProduct.productName, // INTENTIONAL: In MPProduct: SKU of a product. This is the product id sku: simcoeProduct.productId, quantity: NSNumber(value: simcoeProduct.quantity), price: NSNumber(value: simcoeProduct.price ?? 0)) guard let properties = simcoeProduct.properties else { return } if let brand = properties[MPProductKeys.brand.rawValue] as? String { self.brand = brand } if let category = properties[MPProductKeys.category.rawValue] as? String { self.category = category } if let couponCode = properties[MPProductKeys.couponCode.rawValue] as? String { self.couponCode = couponCode } if let sku = properties[MPProductKeys.sku.rawValue] as? String { // INTENTIONAL: In MPProduct: The variant of the product self.variant = sku } if let position = properties[MPProductKeys.position.rawValue] as? UInt { self.position = position } let remaining = MPProductKeys.remaining(properties: properties) for (key, value) in remaining { if let value = value as? String { self[key] = value } } } }
mit
gouyz/GYZBaking
baking/Classes/Home/View/GYZHomeCell.swift
1
9238
// // GYZHomeCell.swift // baking // // Created by gouyz on 2017/3/24. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit protocol HomeCellDelegate : NSObjectProtocol { func didSelectIndex(index : Int) } class GYZHomeCell: UITableViewCell { var delegate: HomeCellDelegate? /// 填充数据 var dataModel : GYZHomeModel?{ didSet{ if let model = dataModel { //设置数据 for item in model.img! { if item.id == "1" { hotLab.text = item.title hotdesLab.text = item.sub_title hotImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_hot_default"), options: nil, progressBlock: nil, completionHandler: nil) }else if item.id == "2" { newLab.text = item.title newDesLab.text = item.sub_title topImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_home_default"), options: nil, progressBlock: nil, completionHandler: nil) }else if item.id == "3" { goodLab.text = item.title goodDesLab.text = item.sub_title bottomImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_home_default"), options: nil, progressBlock: nil, completionHandler: nil) } } } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ contentView.addSubview(leftView) leftView.addSubview(hotLab) leftView.addSubview(hotTagImgView) leftView.addSubview(hotdesLab) leftView.addSubview(hotImgView) contentView.addSubview(lineView1) contentView.addSubview(rightTopView) rightTopView.addSubview(newLab) rightTopView.addSubview(newDesLab) rightTopView.addSubview(topImgView) contentView.addSubview(lineView2) contentView.addSubview(rightBottomView) rightBottomView.addSubview(goodLab) rightBottomView.addSubview(goodDesLab) rightBottomView.addSubview(bottomImgView) leftView.snp.makeConstraints { (make) in make.top.bottom.left.equalTo(contentView) make.width.equalTo(rightTopView) make.right.equalTo(lineView1.snp.left) } hotLab.snp.makeConstraints { (make) in make.top.equalTo(leftView).offset(kMargin) make.left.equalTo(leftView).offset(kMargin) make.size.equalTo(CGSize.init(width: 70, height: 20)) } hotTagImgView.snp.makeConstraints { (make) in make.top.equalTo(hotLab) make.left.equalTo(hotLab.snp.right) make.size.equalTo(CGSize.init(width: 28, height: 15)) } hotdesLab.snp.makeConstraints { (make) in make.left.equalTo(hotLab) make.right.equalTo(leftView).offset(-kMargin) make.top.equalTo(hotLab.snp.bottom) make.height.equalTo(20) } hotImgView.snp.makeConstraints { (make) in make.left.right.equalTo(hotdesLab) make.top.equalTo(hotdesLab.snp.bottom).offset(5) make.bottom.equalTo(leftView).offset(-5) } lineView1.snp.makeConstraints { (make) in make.top.bottom.equalTo(contentView) make.left.equalTo(leftView.snp.right) make.width.equalTo(klineWidth) } rightTopView.snp.makeConstraints { (make) in make.top.right.equalTo(contentView) make.left.equalTo(lineView1.snp.right) make.bottom.equalTo(lineView2.snp.top) make.height.equalTo(rightBottomView) make.width.equalTo(leftView) } newLab.snp.makeConstraints { (make) in make.left.equalTo(rightTopView).offset(kMargin) make.top.equalTo(rightTopView).offset(15) make.right.equalTo(topImgView.snp.left).offset(-5) make.height.equalTo(20) } newDesLab.snp.makeConstraints { (make) in make.left.right.equalTo(newLab) make.top.equalTo(newLab.snp.bottom) make.height.equalTo(20) } topImgView.snp.makeConstraints { (make) in make.right.equalTo(rightTopView).offset(-kMargin) make.centerY.equalTo(rightTopView) make.size.equalTo(CGSize.init(width: 50, height: 50)) } lineView2.snp.makeConstraints { (make) in make.left.right.equalTo(rightTopView) make.top.equalTo(rightTopView.snp.bottom) make.height.equalTo(klineWidth) } rightBottomView.snp.makeConstraints { (make) in make.bottom.right.equalTo(contentView) make.left.equalTo(rightTopView) make.top.equalTo(lineView2.snp.bottom) make.height.equalTo(rightTopView) } goodLab.snp.makeConstraints { (make) in make.left.equalTo(rightBottomView).offset(kMargin) make.top.equalTo(rightBottomView).offset(15) make.right.equalTo(bottomImgView.snp.left).offset(-5) make.height.equalTo(20) } goodDesLab.snp.makeConstraints { (make) in make.left.right.equalTo(goodLab) make.top.equalTo(goodLab.snp.bottom) make.height.equalTo(20) } bottomImgView.snp.makeConstraints { (make) in make.right.equalTo(rightBottomView).offset(-kMargin) make.centerY.equalTo(rightBottomView) make.size.equalTo(CGSize.init(width: 50, height: 50)) } } fileprivate lazy var leftView: UIView = { let view = UIView() view.tag = 101 view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : ))) return view }() fileprivate lazy var rightTopView: UIView = { let view = UIView() view.tag = 102 view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : ))) return view }() fileprivate lazy var rightBottomView: UIView = { let view = UIView() view.tag = 103 view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : ))) return view }() ///热门标题 lazy var hotLab: UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor return lab }() ///热门hot图片标志 lazy var hotTagImgView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_hot_tag")) ///热门描述 lazy var hotdesLab: UILabel = { let lab = UILabel() lab.font = k12Font lab.textColor = kRedFontColor return lab }() ///热门hot图片 lazy var hotImgView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_hot_default")) fileprivate lazy var lineView1 : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() ///新店推荐标题 lazy var newLab: UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor return lab }() ///新店推荐图片 lazy var topImgView: UIImageView = { let imgView = UIImageView.init(image: UIImage.init(named: "icon_home_business")) imgView.cornerRadius = 25 return imgView }() ///新店推荐描述 lazy var newDesLab: UILabel = { let lab = UILabel() lab.font = k12Font lab.textColor = kGaryFontColor return lab }() fileprivate lazy var lineView2 : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() ///每日好店标题 lazy var goodLab: UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor return lab }() ///每日好店图片 lazy var bottomImgView: UIImageView = { let imgView = UIImageView.init(image: UIImage.init(named: "icon_home_business")) imgView.cornerRadius = 25 return imgView }() ///新店推荐描述 lazy var goodDesLab: UILabel = { let lab = UILabel() lab.font = k12Font lab.textColor = kGaryFontColor return lab }() ///点击事件 func menuViewClick(sender : UITapGestureRecognizer){ let tag = sender.view?.tag delegate?.didSelectIndex(index: tag! - 100) } }
mit
merlos/iOS-Open-GPX-Tracker
OpenGpxTracker/GPXTileServer.swift
1
4694
// // GPXTileServer.swift // OpenGpxTracker // // Created by merlos on 25/01/15. // // Shared file: this file is also included in the OpenGpxTracker-Watch Extension target. import Foundation /// /// Configuration for supported tile servers. /// /// Maps displayed in the application are sets of small square images caled tiles. There are different servers that /// provide these tiles. /// /// A tile server is defined by an internal id (for instance .openStreetMap), a name string for displaying /// on the interface and a URL template. /// enum GPXTileServer: Int { /// Apple tile server case apple /// Apple satellite tile server case appleSatellite /// Open Street Map tile server case openStreetMap //case AnotherMap /// CartoDB tile server case cartoDB /// CartoDB tile server (2x tiles) case cartoDBRetina /// OpenTopoMap tile server case openTopoMap ///String that describes the selected tile server. var name: String { switch self { case .apple: return "Apple Mapkit (no offline cache)" case .appleSatellite: return "Apple Satellite (no offline cache)" case .openStreetMap: return "Open Street Map" case .cartoDB: return "Carto DB" case .cartoDBRetina: return "Carto DB (Retina resolution)" case .openTopoMap: return "OpenTopoMap" } } /// URL template of current tile server (it is of the form http://{s}.map.tile.server/{z}/{x}/{y}.png var templateUrl: String { switch self { case .apple: return "" case .appleSatellite: return "" case .openStreetMap: return "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" case .cartoDB: return "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png" case .cartoDBRetina: return "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png" case .openTopoMap: return "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png" } } /// In the `templateUrl` the {s} means subdomain, typically the subdomains available are a,b and c /// Check the subdomains available for your server. /// /// Set an empty array (`[]`) in case you don't use `{s}` in your `templateUrl`. /// /// Subdomains is useful to distribute the tile request download among the diferent servers /// and displaying them faster as result. var subdomains: [String] { switch self { case .apple: return [] case .appleSatellite: return [] case .openStreetMap: return ["a", "b", "c"] case .cartoDB, .cartoDBRetina: return ["a", "b", "c"] case .openTopoMap: return ["a", "b", "c"] // case .AnotherMap: return ["a","b"] } } /// Maximum zoom level the tile server supports /// Tile servers provide files till a certain level of zoom that ranges from 0 to maximumZ. /// If map zooms more than the limit level, tiles won't be requested. /// /// Typically the value is around 19,20 or 21. /// /// Use negative to avoid setting a limit. /// /// - see https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers /// var maximumZ: Int { switch self { case .apple: return -1 case .appleSatellite: return -1 case .openStreetMap: return 19 case .cartoDB, .cartoDBRetina: return 21 case .openTopoMap: return 17 // case .AnotherMap: return 10 } } /// /// Minimum zoom supported by the tile server /// /// This limits the tiles requested based on current zoom level. /// No tiles will be requested for zooms levels lower that this. /// /// Needs to be 0 or larger. /// var minimumZ: Int { switch self { case .apple: return 0 case .appleSatellite: return 0 case .openStreetMap: return 0 case .cartoDB, .cartoDBRetina: return 0 case .openTopoMap: return 0 // case .AnotherMap: return ["a","b"] } } /// tile size of the third-party tile. /// /// 1x tiles are 256x256 /// 2x/retina tiles are 512x512 var tileSize: Int { switch self { case .cartoDBRetina: return 512 default: return 256 } } var needForceDarkMode: Bool { return self == .appleSatellite } /// Returns the number of tile servers currently defined static var count: Int { return GPXTileServer.openTopoMap.rawValue + 1} }
gpl-3.0
tjw/swift
test/Frontend/emit-plus-one-normal-arguments.swift
4
240
// RUN: %target-swift-frontend -disable-guaranteed-normal-arguments -module-name Swift -emit-silgen %s class Klass {} // CHECK-LABEL: sil hidden @$S4main3fooyyAA5KlassCF : $@convention(thin) (@owned Klass) -> () { func foo(_ k: Klass) {}
apache-2.0
huangboju/QMUI.swift
QMUI.swift/Demo/Modules/Common/Utils/UIImage+Effects.swift
1
8516
// // UIImage+Effects.swift // QMUI.swift // // Created by qd-hxt on 2018/4/13. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit import Accelerate extension UIImage { func applyLightEffect() -> UIImage? { return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } func applyExtraLightEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } func applyDarkEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.cgImage == nil { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.cgImage == nil { print("*** error: maskImage must be backed by a CGImage: \(String(describing: maskImage))") return nil } let __FLT_EPSILON__ = CGFloat(Float.ulpOfOne) let screenScale = UIScreen.main.scale let imageRect = CGRect(origin: CGPoint.zero, size: size) var effectImage = self let hasBlur = blurRadius > __FLT_EPSILON__ let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = UInt(context.width) let height = UInt(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() effectInContext?.scaleBy(x: 1.0, y: -1.0) effectInContext?.translateBy(x: 0, y: -size.height) effectInContext?.draw(self.cgImage!, in: imageRect) var effectInBuffer = createEffectBuffer(effectInContext!) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext!) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale let tmp = inputRadius * 3.0 * CGFloat(sqrt(2 * Double.pi)) / 4 + 0.5 var radius = UInt32(floor(tmp)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](repeating: 0, count: matrixSize) for i: Int in 0 ..< matrixSize { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1.0, y: -1.0) outputContext?.translateBy(x: 0, y: -size.height) // Draw base image. outputContext?.draw(self.cgImage!, in: imageRect) // Draw effect image. if hasBlur { outputContext?.saveGState() if let image = maskImage { outputContext?.clip(to: imageRect, mask: image.cgImage!); } outputContext?.draw(effectImage.cgImage!, in: imageRect) outputContext?.restoreGState() } // Add in color tint. if let color = tintColor { outputContext?.saveGState() outputContext?.setFillColor(color.cgColor) outputContext?.fill(imageRect) outputContext?.restoreGState() } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
mit
KellenYangs/KLSwiftTest_05_05
SlideMenu/12-SlideMenuTests/_2_SlideMenuTests.swift
1
992
// // _2_SlideMenuTests.swift // 12-SlideMenuTests // // Created by bcmac3 on 16/7/27. // Copyright © 2016年 KellenYangs. All rights reserved. // import XCTest @testable import _2_SlideMenu class _2_SlideMenuTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
AdAdaptive/adadaptive-ios-pod
AdAdaptive/Classes/AdAdaptiveDeviceData.swift
1
18944
// // AdAdaptiveDeviceData.swift // AdAdaptiveFramework // /************************************************************************************************************************** * * SystemicsCode Nordic AB * **************************************************************************************************************************/ import Foundation import CoreLocation import AdSupport import CoreTelephony import SystemConfiguration import UIKit class AdAdaptiveDeviceData { // device[geo] fileprivate var lat: CLLocationDegrees! // Latitude from -90.0 to +90.0, where negative is south. fileprivate var lon: CLLocationDegrees! // Longitude from -180.0 to +180.0, where negative is west. fileprivate var ttype: Int = 1 // Source of location data; recommended when passing lat/lon // 1 = GPS/Location Services // 2 = IP Address // 3 = User provided (e.g., registration data) // 4 = Cell-ID Location Service (e.g Combain) - not standard(added for skylab) // 5 = Indoor positioning system - not standard(added for skylab) fileprivate var country: String? = nil // Country code using ISO-3166-1-alpha-3. fileprivate var region: String? = nil // Region code using ISO-3166-2; 2-letter state code if USA fileprivate var city: String? = nil // City Name fileprivate var zip: String? = nil // Zip or postal code fileprivate var street: String? = nil // Street name fileprivate var streetno: String? = nil // Sub Adress or street number: eg. 94-102 // device fileprivate var lmt: Int = 0 // Limit Ad Tracking” signal commercially endorsed (e.g., iOS, Android), where // 0 = tracking is unrestricted, 1 = tracking must be limited per commercial guidelines. fileprivate var idfa: String? = nil // Unique device identifier Advertiser ID fileprivate var devicetype: Int? = nil // Device type (e.g. 1=Mobile/Tablet, 2=Personal computer, 3=Connected TV, 4=Phone, 5=Tablet, 6=Connected Device, 7=Set Top Box fileprivate let make: String = "Apple" // Device make fileprivate var model: String? = nil // Device model (e.g., “iPhone”) fileprivate var os: String? = "iPhone OS" // Device operating system (e.g., “iOS”) fileprivate var osv: String? = nil // Device operating system version (e.g., “9.3.2”). fileprivate var hwv: String? = nil // Hardware version of the device (e.g., “5S” for iPhone 5S, "qcom" for Android). fileprivate var h: CGFloat = 0.0 // Physical height of the screen in pixels fileprivate var w: CGFloat = 0.0 // Physical width of the screen in pixels. fileprivate var ppi: CGFloat? = nil // Screen size as pixels per linear inch. fileprivate var pxratio: CGFloat? = nil // The ratio of physical pixels to device independent pixels. For all devices that do not have Retina Displays this will return a 1.0f, // while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f. fileprivate var language: String? = nil // Display Language ISO-639-1-alpha-2 fileprivate var carrier: String? = nil // Carrier or ISP (e.g., “VERIZON”) fileprivate var connectiontype: Int = 0 // Network connection type: //0=Unknown; 1=Ethernet; 2=WIFI; 3=Cellular Network – Unknown Generation; 4=Cellular Network – 2G; 5=Cellular Network – 3G; 6=Cellular Network – 4G fileprivate var publisher_id: String? = nil fileprivate var app_id: String? = nil // micello // Mocello Indoor Map related data fileprivate var level_id: Int? = nil // The Micello map level id // user // user data is stored persistently using the NSUserDaults fileprivate let userData = UserDefaults.standard fileprivate let DEFAULT_TIMER: UInt64 = 10 // 10 sec default time for timed ad delivery //***********************************************************************************************************************************/ // Init functions //***********************************************************************************************************************************/ init(){ let screenBounds: CGRect = UIScreen.main.bounds h = screenBounds.height w = screenBounds.width let pxratio: CGFloat = UIScreen.main.scale ppi = pxratio * 160 // country = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String // print("Country = \(country)") // Check if Advertising Tracking is Enabled if ASIdentifierManager.shared().isAdvertisingTrackingEnabled { idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString lmt = 0 //debugPrint("IDFA = \(idfa)") } else { lmt = 1 idfa = nil } model = UIDevice.current.model if (model == "iPad") { devicetype = 5 } if (model == "iPhone"){ devicetype = 4 } os = UIDevice.current.systemName osv = UIDevice.current.systemVersion hwv = getDeviceHardwareVersion() language = Locale.preferredLanguages[0] carrier = CTTelephonyNetworkInfo().subscriberCellularProvider?.carrierName if (!isConnectedToNetwork()){ debugPrint("AdADaptive Info: Not Connected to the Network") } } //***********************************************************************************************************************************/ // User Data Set functions //***********************************************************************************************************************************/ func setUserDataYob(_ yob: Int){ // Year of birth as a 4-digit integer userData.set(yob, forKey: "yob") userData.synchronize() } func setUserDataGender(_ gender: String){ // Gender, where “M” = male, “F” = female, “O” = known to be other userData.setValue(gender, forKey: "gender") userData.synchronize() } func setADTimer(_ time: UInt64){ // Wrap the UInt64 in an NSNumber as store the NSNumber in NSUserDefaults // NSNumber.init(unsignedLongLong: time) userData.set(NSNumber(value: time as UInt64), forKey: "adtimer") userData.synchronize() } func getADTimer() -> UInt64{ if userData.object(forKey: "adtimer") != nil { let time_sec: NSNumber! = userData.value(forKey: "adtimer") as! NSNumber //cast the returned value to an UInt64 guard let return_time = time_sec else { return DEFAULT_TIMER // deafualt 60.0 sec } return return_time.uint64Value } else{ return DEFAULT_TIMER // default 60.0 sec } } func setIndoorMapLevelID(_ level_id: Int){ self.level_id = level_id } func setPublisherID(publisherID: String){ self.publisher_id = publisherID } func setAppID(appID: String){ self.app_id = appID } //***********************************************************************************************************************************/ // Utility functions //***********************************************************************************************************************************/ fileprivate func getDeviceHardwareVersion() -> String { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } }//String return modelName } //----------------------------------------------------------------------------------------------------------------------------------// fileprivate func isConnectedToNetwork() -> Bool { // Network connection type: 0=Unknown; 1=Ethernet; 2=WIFI; 3=Cellular Network – Unknown Generation; 4=Cellular Network – 2G; 5=Cellular Network – 3G; 6=Cellular Network – 4G var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) let isNetworkReachable = (isReachable && !needsConnection) if (isNetworkReachable) { if (flags.contains(SCNetworkReachabilityFlags.isWWAN)) { let carrierType = CTTelephonyNetworkInfo().currentRadioAccessTechnology switch carrierType{ case CTRadioAccessTechnologyGPRS?,CTRadioAccessTechnologyEdge?,CTRadioAccessTechnologyCDMA1x?: debugPrint("AdADaptive Info: Connection Type: = 2G") connectiontype = 4 case CTRadioAccessTechnologyWCDMA?,CTRadioAccessTechnologyHSDPA?,CTRadioAccessTechnologyHSUPA?,CTRadioAccessTechnologyCDMAEVDORev0?,CTRadioAccessTechnologyCDMAEVDORevA?,CTRadioAccessTechnologyCDMAEVDORevB?,CTRadioAccessTechnologyeHRPD?: debugPrint("AdADaptive Info: Connection Type: = 3G") connectiontype = 5 case CTRadioAccessTechnologyLTE?: debugPrint("AdADaptive Info: Connection Type: = 4G") connectiontype = 6 default: debugPrint("AdADaptive Info: Connection Type: = Unknown Generation") connectiontype = 3 }//switch } else { debugPrint("AdADaptive Info: Connection Type: WIFI") connectiontype = 2 } }//if return isNetworkReachable }//connectedToNetwork() //***********************************************************************************************************************************/ // Get functions //***********************************************************************************************************************************/ func getDeviceParameters(_ location: CLLocation, completion:@escaping (_ result: [String: AnyObject])->Void){ var device_parameters: [String: AnyObject] = [:] lat = location.coordinate.latitude lon = location.coordinate.longitude //finding the user adress by using reverse geocodding let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in var placemark:CLPlacemark! if error == nil && placemarks!.count > 0 { placemark = placemarks![0] as CLPlacemark self.streetno = placemark.subThoroughfare self.street = placemark.thoroughfare self.zip = placemark.postalCode self.city = placemark.locality self.region = placemark.administrativeArea self.country = placemark.country } //if device_parameters = self.getDeviceParametersFormat() completion(device_parameters) }) // geocoder.reverseGeocodeLocation } //----------------------------------------------------------------------------------------------------------------------------------// func getDeviceParameters(completion:@escaping (_ result: [String: AnyObject])->Void){ var device_parameters: [String: AnyObject] = [:] device_parameters = self.getDeviceParametersFormat() completion(device_parameters) } //----------------------------------------------------------------------------------------------------------------------------------// func getDeviceWidth()->CGFloat{ return w } //----------------------------------------------------------------------------------------------------------------------------------// // format the device parametrs that it can be passed as parameter to an Alamofire call func getDeviceParametersFormat()->[String: AnyObject]{ var parameters: [String: AnyObject] = [:] if self.publisher_id != nil { parameters["publisher[pid]"] = self.publisher_id as AnyObject? } if self.app_id != nil { parameters["publisher[appid]"] = self.app_id as AnyObject? } if self.lat != nil { parameters["device[geo][lat]"] = self.lat as AnyObject? } if self.lon != nil { parameters["device[geo][lon]"] = self.lon as AnyObject? } if self.country != nil { parameters["device[geo][country]"] = self.country as AnyObject? } if self.region != nil { parameters["device[geo][region]"] = self.region as AnyObject? } if self.city != nil { parameters["device[geo][city]"] = self.city as AnyObject? } if self.zip != nil { parameters["device[geo][zip]"] = self.zip as AnyObject? } if self.streetno != nil { parameters["device[geo][streetno]"] = self.streetno as AnyObject? } if self.street != nil { parameters["device[geo][street]"] = self.street as AnyObject? } parameters["device[lmt]"] = self.lmt as AnyObject? if lmt == 0 { if self.idfa != nil { parameters["device[idfa]"] = self.idfa as AnyObject? } } if self.model != nil { parameters["device[model]"] = self.model as AnyObject? } if self.os != nil { parameters["device[os]"] = self.os as AnyObject? } if self.osv != nil { parameters["device[osv]"] = self.osv as AnyObject? } if self.hwv != nil { parameters["device[hwv]"] = self.hwv as AnyObject? } parameters["device[h]"] = self.h as AnyObject? parameters["device[w]"] = self.w as AnyObject? if self.ppi != nil { parameters["device[ppi]"] = self.ppi as AnyObject? } if self.pxratio != nil { parameters["device[pxratio]"] = self.pxratio as AnyObject? } if self.language != nil { parameters["device[language]"] = self.language as AnyObject? } if self.carrier != nil { parameters["device[carrier]"] = self.carrier as AnyObject? } parameters["device[connectiontype]"] = self.connectiontype as AnyObject? if userData.object(forKey: "yob") != nil { parameters["user[yob]"] = userData.integer(forKey: "yob") as AnyObject? } if userData.object(forKey: "gender") != nil { parameters["user[gender]"] = userData.string(forKey: "gender") as AnyObject? } if self.level_id != nil { parameters["micello[level_id]"] = self.level_id as AnyObject? level_id = nil } return parameters } }
mit
danielsaidi/iExtra
iExtraTests/Operations/SerialCollectionItemOperationTests.swift
1
2360
// // SerialCollectionItemOperationTests.swift // iExtra // // Created by Daniel Saidi on 2019-01-26. // Copyright © 2019 Daniel Saidi. All rights reserved. // import Quick import Nimble import iExtra class SerialCollectionItemOperationTests: QuickSpec { override func spec() { var obj: TestClass! beforeEach { obj = TestClass() } describe("when performing operation") { it("completes once for empty sequence") { var counter = 0 obj.perform(onCollection: []) { _ in counter += 1 } expect(counter).to(equal(1)) } it("completes once for non-empty sequence") { var counter = 0 obj.perform(onCollection: [1, 2, 3, 4, 5]) { _ in counter += 1 } expect(counter).to(equal(1)) } it("performs operation on each item") { obj.perform(onCollection: [1, 2, 3, 4, 5]) { _ in } expect(obj.result).to(equal([2, 4, 6, 8, 10])) } it("performs operation sequentially and is affected by halt") { obj.performCompletion = false obj.perform(onCollection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _ in } expect(obj.result).to(equal([2])) } it("completes with resulting errors") { let error = NSError(domain: "foo", code: 1, userInfo: nil ) obj.error = error var errors = [Error?]() obj.perform(onCollection: [1, 2, 3, 4, 5]) { res in errors = res } expect(errors.count).to(equal(2)) expect(errors[0]).to(be(error)) expect(errors[1]).to(be(error)) } } } } private class TestClass: SerialCollectionItemOperation { typealias OperationItemType = Int var error: Error? var performCompletion = true private(set) var result = [Int]() private var addon = 1 func perform(onItem item: Int, completion: @escaping ItemCompletion) { result.append(item + addon) addon += 1 guard performCompletion else { return } completion(item % 2 == 0 ? error : nil) } }
mit
hooman/swift
stdlib/public/core/StringUTF16View.swift
3
22451
//===--- StringUTF16.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-16 code units. /// /// You can access a string's view of UTF-16 code units by using its `utf16` /// property. A string's UTF-16 view encodes the string's Unicode scalar /// values as 16-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf16 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 55357 /// // 56464 /// /// Unicode scalar values that make up a string's contents can be up to 21 /// bits long. The longer scalar values may need two `UInt16` values for /// storage. Those "pairs" of code units are called *surrogate pairs*. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf16 { /// print(v) /// } /// // 55357 /// // 56464 /// /// To convert a `String.UTF16View` instance back into a string, use the /// `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.utf16.firstIndex(where: { $0 >= 128 }) { /// let asciiPrefix = String(favemoji.utf16[..<i])! /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " /// /// UTF16View Elements Match NSString Characters /// ============================================ /// /// The UTF-16 code units of a string's `utf16` view match the elements /// accessed through indexed `NSString` APIs. /// /// print(flowers.utf16.count) /// // Prints "10" /// /// let nsflowers = flowers as NSString /// print(nsflowers.length) /// // Prints "10" /// /// Unlike `NSString`, however, `String.UTF16View` does not use integer /// indices. If you need to access a specific position in a UTF-16 view, use /// Swift's index manipulation methods. The following example accesses the /// fourth code unit in both the `flowers` and `nsflowers` strings: /// /// print(nsflowers.character(at: 3)) /// // Prints "119" /// /// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3) /// print(flowers.utf16[i]) /// // Prints "119" /// /// Although the Swift overlay updates many Objective-C methods to return /// native Swift indices and index ranges, some still return instances of /// `NSRange`. To convert an `NSRange` instance to a range of /// `String.Index`, use the `Range(_:in:)` initializer, which takes an /// `NSRange` and a string as arguments. /// /// let snowy = "❄️ Let it snow! ☃️" /// let nsrange = NSRange(location: 3, length: 12) /// if let range = Range(nsrange, in: snowy) { /// print(snowy[range]) /// } /// // Prints "Let it snow!" @frozen public struct UTF16View: Sendable { @usableFromInline internal var _guts: _StringGuts @inlinable internal init(_ guts: _StringGuts) { self._guts = guts _invariantCheck() } } } extension String.UTF16View { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant( startIndex.transcodedOffset == 0 && endIndex.transcodedOffset == 0) } #endif // INTERNAL_CHECKS_ENABLED } extension String.UTF16View: BidirectionalCollection { public typealias Index = String.Index /// The position of the first code unit if the `String` is /// nonempty; identical to `endIndex` otherwise. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty UTF-16 view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } @inlinable @inline(__always) public func index(after idx: Index) -> Index { if _slowPath(_guts.isForeign) { return _foreignIndex(after: idx) } if _guts.isASCII { return idx.nextEncoded } // For a BMP scalar (1-3 UTF-8 code units), advance past it. For a non-BMP // scalar, use a transcoded offset first. // TODO: If transcoded is 1, can we just skip ahead 4? let idx = _utf16AlignNativeIndex(idx) let len = _guts.fastUTF8ScalarLength(startingAt: idx._encodedOffset) if len == 4 && idx.transcodedOffset == 0 { return idx.nextTranscoded } return idx.strippingTranscoding.encoded(offsetBy: len)._scalarAligned } @inlinable @inline(__always) public func index(before idx: Index) -> Index { precondition(!idx.isZeroPosition) if _slowPath(_guts.isForeign) { return _foreignIndex(before: idx) } if _guts.isASCII { return idx.priorEncoded } if idx.transcodedOffset != 0 { _internalInvariant(idx.transcodedOffset == 1) return idx.strippingTranscoding } let idx = _utf16AlignNativeIndex(idx) let len = _guts.fastUTF8ScalarLength(endingAt: idx._encodedOffset) if len == 4 { // 2 UTF-16 code units comprise this scalar; advance to the beginning and // start mid-scalar transcoding return idx.encoded(offsetBy: -len).nextTranscoded } // Single UTF-16 code unit _internalInvariant((1...3) ~= len) return idx.encoded(offsetBy: -len)._scalarAligned } public func index(_ i: Index, offsetBy n: Int) -> Index { if _slowPath(_guts.isForeign) { return _foreignIndex(i, offsetBy: n) } let lowerOffset = _nativeGetOffset(for: i) let result = _nativeGetIndex(for: lowerOffset + n) return result } public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { if _slowPath(_guts.isForeign) { return _foreignIndex(i, offsetBy: n, limitedBy: limit) } let iOffset = _nativeGetOffset(for: i) let limitOffset = _nativeGetOffset(for: limit) // If distance < 0, limit has no effect if it is greater than i. if _slowPath(n < 0 && limit <= i && limitOffset > iOffset + n) { return nil } // If distance > 0, limit has no effect if it is less than i. if _slowPath(n >= 0 && limit >= i && limitOffset < iOffset + n) { return nil } let result = _nativeGetIndex(for: iOffset + n) return result } public func distance(from start: Index, to end: Index) -> Int { if _slowPath(_guts.isForeign) { return _foreignDistance(from: start, to: end) } let lower = _nativeGetOffset(for: start) let upper = _nativeGetOffset(for: end) return upper &- lower } @inlinable public var count: Int { if _slowPath(_guts.isForeign) { return _foreignCount() } return _nativeGetOffset(for: endIndex) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-16 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf16.startIndex /// print("First character's UTF-16 code unit: \(greeting.utf16[i])") /// // Prints "First character's UTF-16 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` must be /// less than the view's end index. @inlinable @inline(__always) public subscript(idx: Index) -> UTF16.CodeUnit { String(_guts)._boundsCheck(idx) if _fastPath(_guts.isFastUTF8) { let scalar = _guts.fastUTF8Scalar( startingAt: _guts.scalarAlign(idx)._encodedOffset) return scalar.utf16[idx.transcodedOffset] } return _foreignSubscript(position: idx) } } extension String.UTF16View { @frozen public struct Iterator: IteratorProtocol, Sendable { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int // If non-nil, return this value for `next()` (and set it to nil). // // This is set when visiting a non-BMP scalar: the leading surrogate is // returned, this field is set with the value of the trailing surrogate, and // `_position` is advanced to the start of the next scalar. @usableFromInline internal var _nextIsTrailingSurrogate: UInt16? = nil @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable public mutating func next() -> UInt16? { if _slowPath(_nextIsTrailingSurrogate != nil) { let trailing = self._nextIsTrailingSurrogate._unsafelyUnwrappedUnchecked self._nextIsTrailingSurrogate = nil return trailing } guard _fastPath(_position < _end) else { return nil } let (scalar, len) = _guts.errorCorrectedScalar(startingAt: _position) _position &+= len if _slowPath(scalar.value > UInt16.max) { self._nextIsTrailingSurrogate = scalar.utf16[1] return scalar.utf16[0] } return UInt16(truncatingIfNeeded: scalar.value) } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } } extension String.UTF16View: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UTF16View: CustomDebugStringConvertible { public var debugDescription: String { return "StringUTF16(\(self.description.debugDescription))" } } extension String { /// A UTF-16 encoding of `self`. @inlinable public var utf16: UTF16View { @inline(__always) get { return UTF16View(_guts) } @inline(__always) set { self = String(newValue._guts) } } /// Creates a string corresponding to the given sequence of UTF-16 code units. @inlinable @inline(__always) @available(swift, introduced: 4.0) public init(_ utf16: UTF16View) { self.init(utf16._guts) } } // Index conversions extension String.UTF16View.Index { /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified string position. /// /// If the index passed as `sourcePosition` represents either the start of a /// Unicode scalar value or the position of a UTF-16 trailing surrogate, /// then the initializer succeeds. If `sourcePosition` does not have an /// exact corresponding position in `target`, then the result is `nil`. For /// example, an attempt to convert the position of a UTF-8 continuation byte /// results in `nil`. /// /// The following example finds the position of a space in a string and then /// converts that position to an index in the string's `utf16` view. /// /// let cafe = "Café 🍵" /// /// let stringIndex = cafe.firstIndex(of: "é")! /// let utf16Index = String.Index(stringIndex, within: cafe.utf16)! /// /// print(String(cafe.utf16[...utf16Index])!) /// // Prints "Café" /// /// - Parameters: /// - sourcePosition: A position in at least one of the views of the string /// shared by `target`. /// - target: The `UTF16View` in which to find the new position. public init?( _ idx: String.Index, within target: String.UTF16View ) { if _slowPath(target._guts.isForeign) { guard idx._foreignIsWithin(target) else { return nil } } else { guard target._guts.isOnUnicodeScalarBoundary(idx) else { return nil } } self = idx } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// This index must be a valid index of `String(unicodeScalars).utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method to find the same /// position in the string's `unicodeScalars` view. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.firstIndex(of: 32)! /// let j = i.samePosition(in: cafe.unicodeScalars)! /// print(String(cafe.unicodeScalars[..<j])) /// // Prints "Café" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// This index must be a valid index of at least one view of the string /// shared by `unicodeScalars`. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `unicodeScalars`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-16 trailing surrogate /// returns `nil`. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } } // Reflection extension String.UTF16View: CustomReflectable { /// Returns a mirror that reflects the UTF-16 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } // Slicing extension String.UTF16View { public typealias SubSequence = Substring.UTF16View public subscript(r: Range<Index>) -> Substring.UTF16View { return Substring.UTF16View(self, _bounds: r) } } // Foreign string support extension String.UTF16View { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) return i.strippingTranscoding.nextEncoded } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) return i.strippingTranscoding.priorEncoded } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignSubscript(position i: Index) -> UTF16.CodeUnit { _internalInvariant(_guts.isForeign) return _guts.foreignErrorCorrectedUTF16CodeUnit(at: i.strippingTranscoding) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignDistance(from start: Index, to end: Index) -> Int { _internalInvariant(_guts.isForeign) // Ignore transcoded offsets, i.e. scalar align if-and-only-if from a // transcoded view return end._encodedOffset - start._encodedOffset } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { _internalInvariant(_guts.isForeign) let l = limit._encodedOffset - i._encodedOffset if n > 0 ? l >= 0 && l < n : l <= 0 && n < l { return nil } return i.strippingTranscoding.encoded(offsetBy: n) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index { _internalInvariant(_guts.isForeign) return i.strippingTranscoding.encoded(offsetBy: n) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignCount() -> Int { _internalInvariant(_guts.isForeign) return endIndex._encodedOffset - startIndex._encodedOffset } // Align a native UTF-8 index to a valid UTF-16 position. If there is a // transcoded offset already, this is already a valid UTF-16 position // (referring to the second surrogate) and returns `idx`. Otherwise, this will // scalar-align the index. This is needed because we may be passed a // non-scalar-aligned index from the UTF8View. @_alwaysEmitIntoClient // Swift 5.1 @inline(__always) internal func _utf16AlignNativeIndex(_ idx: String.Index) -> String.Index { _internalInvariant(!_guts.isForeign) guard idx.transcodedOffset == 0 else { return idx } return _guts.scalarAlign(idx) } } extension String.Index { @usableFromInline @inline(never) // opaque slow-path @_effects(releasenone) internal func _foreignIsWithin(_ target: String.UTF16View) -> Bool { _internalInvariant(target._guts.isForeign) // If we're transcoding, we're a UTF-8 view index, not UTF-16. return self.transcodedOffset == 0 } } // Breadcrumb-aware acceleration extension _StringGuts { @inline(__always) fileprivate func _useBreadcrumbs(forEncodedOffset offset: Int) -> Bool { return hasBreadcrumbs && offset >= _StringBreadcrumbs.breadcrumbStride } } extension String.UTF16View { @usableFromInline @_effects(releasenone) internal func _nativeGetOffset(for idx: Index) -> Int { // Trivial and common: start if idx == startIndex { return 0 } if _guts.isASCII { _internalInvariant(idx.transcodedOffset == 0) return idx._encodedOffset } let idx = _utf16AlignNativeIndex(idx) guard _guts._useBreadcrumbs(forEncodedOffset: idx._encodedOffset) else { // TODO: Generic _distance is still very slow. We should be able to // skip over ASCII substrings quickly return _distance(from: startIndex, to: idx) } // Simple and common: endIndex aka `length`. let breadcrumbsPtr = _guts.getBreadcrumbsPtr() if idx == endIndex { return breadcrumbsPtr.pointee.utf16Length } // Otherwise, find the nearest lower-bound breadcrumb and count from there let (crumb, crumbOffset) = breadcrumbsPtr.pointee.getBreadcrumb( forIndex: idx) return crumbOffset + _distance(from: crumb, to: idx) } @usableFromInline @_effects(releasenone) internal func _nativeGetIndex(for offset: Int) -> Index { // Trivial and common: start if offset == 0 { return startIndex } if _guts.isASCII { return Index(_encodedOffset: offset) } guard _guts._useBreadcrumbs(forEncodedOffset: offset) else { return _index(startIndex, offsetBy: offset) } // Simple and common: endIndex aka `length`. let breadcrumbsPtr = _guts.getBreadcrumbsPtr() if offset == breadcrumbsPtr.pointee.utf16Length { return endIndex } // Otherwise, find the nearest lower-bound breadcrumb and advance that let (crumb, remaining) = breadcrumbsPtr.pointee.getBreadcrumb( forOffset: offset) if remaining == 0 { return crumb } return _guts.withFastUTF8 { utf8 in var readIdx = crumb._encodedOffset let readEnd = utf8.count _internalInvariant(readIdx < readEnd) var utf16I = 0 let utf16End: Int = remaining // Adjust for sub-scalar initial transcoding: If we're starting the scan // at a trailing surrogate, then we set our starting count to be -1 so as // offset counting the leading surrogate. if crumb.transcodedOffset != 0 { utf16I = -1 } while true { let len = _utf8ScalarLength(utf8[_unchecked: readIdx]) let utf16Len = len == 4 ? 2 : 1 utf16I &+= utf16Len if utf16I >= utf16End { // Uncommon: final sub-scalar transcoded offset if _slowPath(utf16I > utf16End) { _internalInvariant(utf16Len == 2) return Index(encodedOffset: readIdx, transcodedOffset: 1) } return Index(_encodedOffset: readIdx &+ len)._scalarAligned } readIdx &+= len } } } // Copy (i.e. transcode to UTF-16) our contents into a buffer. `alignedRange` // means that the indices are part of the UTF16View.indices -- they are either // scalar-aligned or transcoded (e.g. derived from the UTF-16 view). They do // not need to go through an alignment check. internal func _nativeCopy( into buffer: UnsafeMutableBufferPointer<UInt16>, alignedRange range: Range<String.Index> ) { _internalInvariant(_guts.isFastUTF8) _internalInvariant( range.lowerBound == _utf16AlignNativeIndex(range.lowerBound)) _internalInvariant( range.upperBound == _utf16AlignNativeIndex(range.upperBound)) if _slowPath(range.isEmpty) { return } let isASCII = _guts.isASCII return _guts.withFastUTF8 { utf8 in var writeIdx = 0 let writeEnd = buffer.count var readIdx = range.lowerBound._encodedOffset let readEnd = range.upperBound._encodedOffset if isASCII { _internalInvariant(range.lowerBound.transcodedOffset == 0) _internalInvariant(range.upperBound.transcodedOffset == 0) while readIdx < readEnd { _internalInvariant(utf8[readIdx] < 0x80) buffer[_unchecked: writeIdx] = UInt16( truncatingIfNeeded: utf8[_unchecked: readIdx]) readIdx &+= 1 writeIdx &+= 1 } return } // Handle mid-transcoded-scalar initial index if _slowPath(range.lowerBound.transcodedOffset != 0) { _internalInvariant(range.lowerBound.transcodedOffset == 1) let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx) buffer[writeIdx] = scalar.utf16[1] readIdx &+= len writeIdx &+= 1 } // Transcode middle while readIdx < readEnd { let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx) buffer[writeIdx] = scalar.utf16[0] readIdx &+= len writeIdx &+= 1 if _slowPath(scalar.utf16.count == 2) { buffer[writeIdx] = scalar.utf16[1] writeIdx &+= 1 } } // Handle mid-transcoded-scalar final index if _slowPath(range.upperBound.transcodedOffset == 1) { _internalInvariant(writeIdx < writeEnd) let (scalar, _) = _decodeScalar(utf8, startingAt: readIdx) _internalInvariant(scalar.utf16.count == 2) buffer[writeIdx] = scalar.utf16[0] writeIdx &+= 1 } _internalInvariant(writeIdx <= writeEnd) } } }
apache-2.0
lorentey/swift
test/Sema/clang_types_in_ast.swift
3
2173
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -DNOCRASH1 // RUN: %target-swift-frontend %s -typecheck -DNOCRASH1 -use-clang-function-types // RUN: %target-swift-frontend %s -typecheck -DNOCRASH2 -sdk %clang-importer-sdk // RUN: %target-swift-frontend %s -typecheck -DNOCRASH2 -sdk %clang-importer-sdk -use-clang-function-types // RUN: %target-swift-frontend %s -DAUXMODULE -module-name Foo -emit-module -o %t // rdar://problem/57644243 : We shouldn't crash if -use-clang-function-types is not enabled. // RUN: %target-swift-frontend %s -typecheck -DNOCRASH3 -I %t // FIXME: [clang-function-type-serialization] This should stop crashing once we // start serializing clang function types. // RUN: not --crash %target-swift-frontend %s -typecheck -DCRASH -I %t -use-clang-function-types #if NOCRASH1 public func my_signal() -> Optional<@convention(c) (Int32) -> Void> { let s : Optional<@convention(c) (Int32) -> Void> = .none; var s2 : Optional<@convention(c) (Int32) -> Void> = s; return s2; } #endif #if NOCRASH2 import ctypes func f() { _ = getFunctionPointer() as (@convention(c) (CInt) -> CInt)? } #endif #if AUXMODULE public var DUMMY_SIGNAL1 : Optional<@convention(c) (Int32) -> ()> = .none public var DUMMY_SIGNAL2 : Optional<@convention(c) (Int32) -> Void> = .none #endif #if NOCRASH3 import Foo public func my_signal1() -> Optional<@convention(c) (Int32) -> ()> { return Foo.DUMMY_SIGNAL1 } public func my_signal2() -> Optional<@convention(c) (Int32) -> Void> { return Foo.DUMMY_SIGNAL1 } public func my_signal3() -> Optional<@convention(c) (Int32) -> ()> { return Foo.DUMMY_SIGNAL2 } public func my_signal4() -> Optional<@convention(c) (Int32) -> Void> { return Foo.DUMMY_SIGNAL2 } #endif #if CRASH import Foo public func my_signal1() -> Optional<@convention(c) (Int32) -> ()> { return Foo.DUMMY_SIGNAL1 } public func my_signal2() -> Optional<@convention(c) (Int32) -> Void> { return Foo.DUMMY_SIGNAL1 } public func my_signal3() -> Optional<@convention(c) (Int32) -> ()> { return Foo.DUMMY_SIGNAL2 } public func my_signal4() -> Optional<@convention(c) (Int32) -> Void> { return Foo.DUMMY_SIGNAL2 } #endif
apache-2.0
ihak/iHAKTableRefresh
iHAKTableRefresh/AppDelegate.swift
1
2172
// // AppDelegate.swift // iHAKTableRefresh // // Created by Hassan Ahmed on 10/18/16. // Copyright © 2016 Hassan Ahmed. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
powerytg/Accented
Accented/UI/Common/Components/Menu/MenuSeparator.swift
1
286
// // MenuSeparator.swift // Accented // // Menu separator // // Created by Tiangong You on 8/27/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class MenuSeparator: MenuItem { init() { super.init(action: .None, text: "Separator") } }
mit
phimage/AboutWindow
Sources/AboutWindowController.swift
1
8583
// // AboutWindowController.swift // AboutWindow /* The MIT License (MIT) Copyright (c) 2015-2016 Perceval Faramaz Copyright (c) 2016 Eric Marchand (phimage) 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 open class AboutWindowController : NSWindowController { open var appName: String? open var appVersion: String? open var appCopyright: NSAttributedString? /** The string to hold the credits if we're showing them in same window. */ open var appCredits: NSAttributedString? open var appEULA: NSAttributedString? open var appURL: URL? open var appStoreURL: URL? open var logClosure: (String) -> Void = { message in print(message) } open var font: NSFont = NSFont(name: "HelveticaNeue", size: 11.0)! /** Select a background color (defaults to white). */ open var backgroundColor: NSColor = NSColor.white /** Select the title (app name & version) color (defaults to black). */ open var titleColor: NSColor = NSColor.black /** Select the text (Acknowledgments & EULA) color (defaults to light grey). */ open var textColor: NSColor = (floor(NSAppKitVersionNumber) <= Double(NSAppKitVersionNumber10_9)) ? NSColor.lightGray : NSColor.tertiaryLabelColor open var windowShouldHaveShadow: Bool = true open var windowState: Int = 0 open var amountToIncreaseHeight:CGFloat = 100 /** The info view. */ @IBOutlet var infoView: NSView! /** The main text view. */ @IBOutlet var textField: NSTextView! /** The app version's text view. */ @IBOutlet var versionField: NSTextField! /** The button that opens the app's website. */ @IBOutlet var visitWebsiteButton: NSButton! /** The button that opens the EULA. */ @IBOutlet var EULAButton: NSButton! /** The button that opens the credits. */ @IBOutlet var creditsButton: NSButton! /** The button that opens the appstore's website. */ @IBOutlet var ratingButton: NSButton! @IBOutlet var EULAConstraint: NSLayoutConstraint! @IBOutlet var creditsConstraint: NSLayoutConstraint! @IBOutlet var ratingConstraint: NSLayoutConstraint! // MARK: override override open var windowNibName : String! { return "PFAboutWindow" } override open func windowDidLoad() { super.windowDidLoad() assert (self.window != nil) self.window?.backgroundColor = backgroundColor self.window?.hasShadow = self.windowShouldHaveShadow self.windowState = 0 self.infoView.wantsLayer = true self.infoView.layer?.cornerRadius = 10.0 self.infoView.layer?.backgroundColor = NSColor.white.cgColor (self.visitWebsiteButton.cell as? NSButtonCell)?.highlightsBy = NSCellStyleMask() if self.appName == nil { self.appName = valueFromInfoDict("CFBundleName") } if self.appVersion == nil { let version = valueFromInfoDict("CFBundleVersion") let shortVersion = valueFromInfoDict("CFBundleShortVersionString") self.appVersion = String(format: NSLocalizedString("Version %@ (Build %@)", comment:"Version %@ (Build %@), displayed in the about window"), shortVersion, version) } versionField.stringValue = self.appVersion ?? "" versionField.textColor = self.titleColor if self.appCopyright == nil { let attribs: [String:AnyObject] = [NSForegroundColorAttributeName: textColor, NSFontAttributeName: font] self.appCopyright = NSAttributedString(string: valueFromInfoDict("NSHumanReadableCopyright"), attributes:attribs) } if let copyright = self.appCopyright { self.textField.textStorage?.setAttributedString(copyright) self.textField.textColor = self.textColor } self.creditsButton.title = NSLocalizedString("Credits", comment: "Caption of the 'Credits' button in the about window") if self.appCredits == nil { if let creditsRTF = Bundle.main.url(forResource: "Credits", withExtension: "rtf"), let str = try? NSAttributedString(url: creditsRTF, options: [:], documentAttributes : nil) { self.appCredits = str } else { hideButton(self.creditsButton, self.creditsConstraint) logClosure("Credits not found in bundle. Hiding Credits Button.") } } self.EULAButton.title = NSLocalizedString("License Agreement", comment: "Caption of the 'License Agreement' button in the about window") if self.appEULA == nil { if let eulaRTF = Bundle.main.url(forResource: "EULA", withExtension: "rtf"), let str = try? NSAttributedString(url: eulaRTF, options: [:], documentAttributes: nil) { self.appEULA = str } else { hideButton(self.EULAButton, self.EULAConstraint) logClosure("EULA not found in bundle. Hiding EULA Button.") } } self.ratingButton.title = NSLocalizedString("★Rate on the app store", comment: "Caption of the 'Rate on the app store'") if appStoreURL == nil { hideButton(self.ratingButton, self.ratingConstraint) } } open func windowShouldClose(_ sender: AnyObject) -> Bool { self.showCopyright(sender) return true } // MARK: IBAction @IBAction open func visitWebsite(_ sender: AnyObject) { if let URL = appURL { NSWorkspace.shared().open(URL) } } @IBAction open func visitAppStore(_ sender: AnyObject) { if let URL = appStoreURL { NSWorkspace.shared().open(URL) } } @IBAction open func showCredits(_ sender: AnyObject) { changeWindowState(1, amountToIncreaseHeight) self.textField.textStorage?.setAttributedString(self.appCredits ?? NSAttributedString()) self.textField.textColor = self.textColor } @IBAction open func showEULA(_ sender: AnyObject) { changeWindowState(1, amountToIncreaseHeight) self.textField.textStorage?.setAttributedString(self.appEULA ?? NSAttributedString()) self.textField.textColor = self.textColor } @IBAction open func showCopyright(_ sender: AnyObject) { changeWindowState(0, -amountToIncreaseHeight) self.textField.textStorage?.setAttributedString(self.appCopyright ?? NSAttributedString()) self.textField.textColor = self.textColor } // MARK: Private fileprivate func valueFromInfoDict(_ string: String) -> String { let dictionary = Bundle.main.infoDictionary! return dictionary[string] as! String } fileprivate func changeWindowState(_ state: Int,_ amountToIncreaseHeight: CGFloat) { if let window = self.window , self.windowState != state { var oldFrame = window.frame oldFrame.size.height += amountToIncreaseHeight oldFrame.origin.y -= amountToIncreaseHeight window.setFrame(oldFrame, display: true, animate: true) self.windowState = state } } fileprivate func hideButton(_ button: NSButton,_ constraint: NSLayoutConstraint) { button.isHidden = true button.setFrameSize(NSSize(width: 0, height: self.creditsButton.frame.height)) button.title = "" button.isBordered = false constraint.constant = 0 print("\(button.frame)") } }
mit
mmllr/CleanTweeter
CleanTweeter/UseCases/NewPost/Interactor/NewPostInteractorInput.swift
1
184
import Foundation protocol NewPostInteractorInput { func postContent(_ content: String, forUser: String, publicationDate: Date) func requestAvatarForUserName(_ userName: String) }
mit
zehrer/SOGraphDB
Tests/SOGraphDBTests/SOGraphDBTests.swift
1
435
import XCTest @testable import SOGraphDB class SOGraphDBTests: XCTestCase { /** func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. //XCTAssertEqual(SOGraphDB().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] */ }
mit
SwiftStudies/OysterKit
Sources/STLR/Generators/Swift/String+Swift.swift
1
1526
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation extension String { var asSwiftString : String { return debugDescription } }
bsd-2-clause
polok/UICheckbox.Swift
Example/UICheckbox/AppDelegate.swift
1
2178
// // AppDelegate.swift // UICheckbox // // Created by marcin.polak on 07/04/2016. // Copyright (c) 2016 marcin.polak. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
mit
jdommes/inquire
Sources/TextField.swift
1
3522
// // TextField.swift // Inquire // // Created by Wesley Cope on 1/13/16. // Copyright © 2016 Wess Cope. All rights reserved. // import Foundation import UIKit /// UITextField with name, validators, and errors for usage with Form. open class TextField : UITextField, Field { /// Form containing field. open var form:Form? /// Previous Field in form open var previousField: Field? /// Next field open var nextField:Field? /// Block called when the field isn't valid. open var onError:FieldErrorHandler? /// Name of field, default to property name in form. open var name:String = "" /// Title of field, usually the same as Placeholder open var title:String = "" /// meta data for field open var meta:[String:Any] = [:] /// Input toolbar fileprivate lazy var toolbar:UIToolbar = { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44) let _toolbar = UIToolbar(frame: frame) return _toolbar }() /// Items for field toolbar. open var toolbarItems:[FieldToolbarButtonItem]? { didSet { inputAccessoryView = nil if let items = toolbarItems , items.count > 0 { toolbar.items = items inputAccessoryView = toolbar } } } /// Validators used against value of field. open var validators:[ValidationRule] = [] /// Field errors. open var errors:[(ValidationType, String)] = [] /// Field's value. open var value:String? { get { return self.text } set { self.text = String(describing: newValue) } } open var setupBlock:((TextField) -> Void)? = nil public convenience init(placeholder:String?) { self.init(validators:[], setup:nil) self.placeholder = placeholder } public convenience init(placeholder:String?, setup:((TextField) -> Void)?) { self.init(validators:[], setup:setup) self.placeholder = placeholder } public convenience init(placeholder:String?, validators:[ValidationRule]?) { self.init(validators:validators ?? [], setup:nil) self.placeholder = placeholder } public convenience init(placeholder:String?, validators:[ValidationRule]?, setup:((TextField) -> Void)?) { self.init(validators:validators ?? [], setup:setup) self.placeholder = placeholder } public convenience init() { self.init(validators:[], setup:nil) } public convenience init(setup:((TextField) -> Void)?) { self.init(validators:[], setup:setup) } public convenience init(validators:[ValidationRule] = []) { self.init(validators:validators, setup:nil) } public required init(validators:[ValidationRule] = [], setup:((TextField) -> Void)?) { super.init(frame: .zero) self.validators = validators self.setupBlock = setup } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func move(_ to:Field) { resignFirstResponder() if let field = to as? TextField { field.becomeFirstResponder() } if let field = to as? TextView { field.becomeFirstResponder() } } }
mit
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift
6
1674
// // Range.swift // Rx // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RangeProducer<E: SignedInteger> : Producer<E> { fileprivate let _start: E fileprivate let _count: E fileprivate let _scheduler: ImmediateSchedulerType init(start: E, count: E, scheduler: ImmediateSchedulerType) { if count < 0 { rxFatalError("count can't be negative") } if start &+ (count - 1) < start { rxFatalError("overflow of count") } _start = start _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = RangeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } class RangeSink<O: ObserverType> : Sink<O> where O.E: SignedInteger { typealias Parent = RangeProducer<O.E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in if i < self._parent._count { self.forwardOn(.next(self._parent._start + i)) recurse(i + 1) } else { self.forwardOn(.completed) self.dispose() } } } }
mit
shahmishal/swift
test/Driver/options-repl.swift
4
2188
// RUN: not %swift -repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -sdk "" -repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -sdk "" -lldb-repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -sdk "" -deprecated-integrated-repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s // REPL_NO_FILES: REPL mode requires no input files // RUN: %empty-directory(%t) // RUN: mkdir -p %t/usr/bin // RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/usr/bin/swift) // RUN: %t/usr/bin/swift -sdk "" -deprecated-integrated-repl -### | %FileCheck -check-prefix=INTEGRATED %s // INTEGRATED: swift{{c?(\.EXE)?"?}} -frontend -repl // INTEGRATED: -module-name REPL // RUN: %swift_driver -sdk "" -lldb-repl -### | %FileCheck -check-prefix=LLDB %s // RUN: %swift_driver -sdk "" -lldb-repl -D A -DB -D C -DD -L /path/to/libraries -L /path/to/more/libraries -F /path/to/frameworks -lsomelib -framework SomeFramework -sdk / -I "this folder" -module-name Test -target %target-triple -### | %FileCheck -check-prefix=LLDB-OPTS %s // LLDB: lldb{{(\.exe)?"?}} {{"?}}--repl= // LLDB-NOT: -module-name // LLDB-NOT: -target // LLDB-OPTS: lldb{{(\.exe)?"?}} "--repl= // LLDB-OPTS-DAG: -target {{[^ ]+}} // LLDB-OPTS-DAG: -D A -D B -D C -D D // LLDB-OPTS-DAG: -sdk / // LLDB-OPTS-DAG: -L /path/to/libraries // LLDB-OPTS-DAG: -L /path/to/more/libraries // LLDB-OPTS-DAG: -F /path/to/frameworks // LLDB-OPTS-DAG: -lsomelib // LLDB-OPTS-DAG: -framework SomeFramework // LLDB-OPTS-DAG: -I \"this folder\" // LLDB-OPTS: " // Test LLDB detection, first in a clean environment, then in one that looks // like the Xcode installation environment. We use hard links to make sure // the Swift driver really thinks it's been moved. // RUN: %t/usr/bin/swift -sdk "" -repl -### | %FileCheck -check-prefix=INTEGRATED %s // RUN: %t/usr/bin/swift -sdk "" -### | %FileCheck -check-prefix=INTEGRATED %s // RUN: touch %t/usr/bin/lldb // RUN: chmod +x %t/usr/bin/lldb // RUN: %t/usr/bin/swift -sdk "" -repl -### | %FileCheck -check-prefix=LLDB %s // RUN: %t/usr/bin/swift -sdk "" -### | %FileCheck -check-prefix=LLDB %s
apache-2.0
3lvis/Notification
Pod/App/AppDelegate.swift
1
482
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) // Override point for customization after application launch. self.window!.makeKeyAndVisible() return true } }
mit
pawel-sp/AppFlowController
AppFlowController/AppFlowController.swift
1
24184
// // AppFlowController.swift // AppFlowController // // Created by Paweł Sporysz on 22.09.2016. // Copyright (c) 2017 Paweł Sporysz // https://github.com/pawel-sp/AppFlowController // // 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 open class AppFlowController { // MARK: - Properties public static let shared = AppFlowController() public var rootNavigationController: UINavigationController? private(set) var rootPathStep: PathStep? let tracker: Tracker // MARK: - Init init(trackerClass: Tracker.Type) { tracker = trackerClass.init() } public convenience init() { self.init(trackerClass: Tracker.self) } // MARK: - Setup /** You need to use that method before you gonna start use AppFlowController to present pages. - Parameter window: Current app's window. - Parameter rootNavigationController: AppFlowController requires that root navigation controller is kind of UINavigationController. */ public func prepare(for window: UIWindow, rootNavigationController: UINavigationController = UINavigationController()) { self.rootNavigationController = rootNavigationController window.rootViewController = rootNavigationController } public func register(pathComponent: FlowPathComponent) throws { try register(pathComponents: [pathComponent]) } public func register(pathComponents: [FlowPathComponent]) throws { if let lastPathComponent = pathComponents.last, !lastPathComponent.supportVariants, rootPathStep?.search(pathComponent: lastPathComponent) != nil { throw AFCError.pathAlreadyRegistered(identifier: lastPathComponent.identifier) } var previousStep: PathStep? for var element in pathComponents { if let found = rootPathStep?.search(pathComponent: element) { previousStep = found continue } else { if let previous = previousStep { if element.supportVariants { element.variantName = previous.pathComponent.identifier } if element.forwardTransition == nil || element.backwardTransition == nil { throw AFCError.missingPathStepTransition(identifier: element.identifier) } previousStep = previous.add(pathComponent: element) } else { rootPathStep = PathStep(pathComponent: element) previousStep = rootPathStep } } } } /** Before presenting any page you need to register it using path components. - Parameter pathComponents: Sequences of pages which represent all possible paths inside the app. The best way to register pages is to use => and =>> operators which assign transitions directly to pages. - Throws: AFCError.missingPathStepTransition if forward or backward transition of any page is nil AFCError.pathAlreadyRegistered if that page was registered before (all pages need to have unique name). If you want to use the same page few times in different places it's necessary to set supportVariants property to true. */ public func register(pathComponents: [[FlowPathComponent]]) throws { for subPathComponents in pathComponents { try register(pathComponents: subPathComponents) } } // MARK: - Navigation /** Display view controller configured inside the path. - Parameter pathComponent: Page to present. - Parameter variant: If page supports variants you need to pass the correct variant (previous page). Default = nil. - Parameter parameters: For every page you can set single string value as it's parameter. It works also for pages with variants. Default = nil. - Parameter animated: Determines if presenting page should be animated or not. Default = true. - Parameter skipDismissTransitions: Use that property to skip all dismiss transitions. Use that with conscience since it can break whole view's stack (it's helpfull for example when app has side menu). - Parameter skipPages: Pages to skip. - Throws: AFCError.missingConfiguration if prepare(UIWindow, UINavigationController) wasn't invoked before. AFCError.showingSkippedPage if page was previously skipped (for example when you're trying go back to page which before was skipped and it's not present inside the navigation controller). AFCError.missingVariant if page's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter. AFCError.variantNotSupported if page's property supportVariants == false you cannot pass variant property, because there is only one variant of that page. AFCError.unregisteredPathIdentifier page need to be registered before showing it. */ open func show( _ pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil, parameters: [TransitionParameter]? = nil, animated: Bool = true, skipDismissTransitions: Bool = false, skipPathComponents: [FlowPathComponent]? = nil) throws { guard let rootNavigationController = rootNavigationController else { throw AFCError.missingConfiguration } let foundStep = try pathStep(from: pathComponent, variant: variant) let newPathComponents = rootPathStep?.allParentPathComponents(from: foundStep) ?? [] let currentStep = visibleStep let currentPathComponents = currentStep == nil ? [] : (rootPathStep?.allParentPathComponents(from: currentStep!) ?? []) let keysToClearSkip = newPathComponents.filter({ !currentPathComponents.contains($0) }).map({ $0.identifier }) if let currentStep = currentStep { let distance = PathStep.distanceBetween(step: currentStep, and: foundStep) let dismissCounter = distance.up let _ = distance.down let dismissRange: Range<Int> = dismissCounter == 0 ? 0..<0 : (currentPathComponents.count - dismissCounter) ..< currentPathComponents.count let displayRange: Range<Int> = 0 ..< newPathComponents.count try verify(pathComponents: currentPathComponents, distance: distance) dismiss(pathComponents: currentPathComponents, fromIndexRange: dismissRange, animated: animated, skipTransition: skipDismissTransitions) { self.register(parameters: parameters, for: newPathComponents, skippedPathComponents: skipPathComponents) self.tracker.disableSkip(for: keysToClearSkip) self.display(pathComponents: newPathComponents, fromIndexRange: displayRange, animated: animated, skipPathComponents: skipPathComponents, completion: nil) } } else { rootNavigationController.viewControllers.removeAll() tracker.reset() register(parameters: parameters, for: newPathComponents, skippedPathComponents: skipPathComponents) tracker.disableSkip(for: keysToClearSkip) display(pathComponents: newPathComponents, fromIndexRange: 0..<newPathComponents.count, animated: animated, skipPathComponents: skipPathComponents, completion: nil) } } /** Displays previous page. - Parameter animated: Determines if presenting page should be animated or not. Default = true. */ public func goBack(animated: Bool = true) { guard let visible = visibleStep else { return } guard let pathComponent = visible.firstParentPathComponent(where: { tracker.viewController(for: $0.identifier) != nil }) else { return } guard let viewController = tracker.viewController(for: pathComponent.identifier) else { return } visible.pathComponent.backwardTransition?.performBackwardTransition(animated: animated){}(viewController) } /** Pops navigation controller to specified path. It always current view controller's navigation controller. If page isn't not present in current navigation controller nothing would happen. - Parameter pathComponent: Path component to pop. - Parameter animated: Determines if transition should be animated or not. */ public func pop(to pathComponent: FlowPathComponent, animated: Bool = true) throws { guard let rootNavigationController = rootNavigationController else { throw AFCError.missingConfiguration } guard let foundStep = rootPathStep?.search(pathComponent: pathComponent) else { throw AFCError.unregisteredPathIdentifier(identifier: pathComponent.identifier) } guard let targetViewController = tracker.viewController(for: foundStep.pathComponent.identifier) else { throw AFCError.popToSkippedPath(identifier: foundStep.pathComponent.identifier) } rootNavigationController.visible.navigationController?.popToViewController(targetViewController, animated: animated) } /** If you presented view controller without AppFlowController you need to update current path. Use that method inside the viewDidLoad method of presented view controller to make sure that whole step tree still works. - Parameter viewController: Presented view controller. - Parameter name: Name of path associated with that view controller. That page need to be registered. - Throws: AFCError.unregisteredPathIdentifier if page wasn't registered before. */ public func updateCurrentPath(with viewController: UIViewController, for name:String) throws { if let _ = rootPathStep?.search(identifier: name) { self.tracker.register(viewController: viewController, for: name) } else { throw AFCError.unregisteredPathIdentifier(identifier: name) } } /** Returns string representation of whole path to specified page, for example home/start/login. - Parameter pathComponent: Path component to receive all path steps. - Parameter variant: Variant of that page (previous path component). Use it only if page supports variants. - Throws: AFCError.missingVariant if page's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter. AFCError.variantNotSupported if page's property supportVariants == false you cannot pass variant property, because there is only one variant of that page. AFCError.unregisteredPathIdentifier page need to be registered before showing it. */ open func pathComponents(for pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> String { let foundStep = try pathStep(from: pathComponent, variant: variant) let pathComponents = rootPathStep?.allParentPathComponents(from: foundStep) ?? [] let pathComponentStrings = pathComponents.map{ $0.identifier } return pathComponentStrings.joined(separator: "/") } /** Returns string representation of whole path to current path, for example home/start/login. */ open var currentPathDescription: String? { if let visibleStep = visibleStep { let items = rootPathStep?.allParentPathComponents(from: visibleStep) ?? [] let itemStrings = items.map{ $0.identifier } return itemStrings.joined(separator: "/") } else { return nil } } /** Returns currenlty visible path. */ open var currentPathComponent: FlowPathComponent? { return visibleStep?.pathComponent } /** Returns parameter for currently visible path. It's nil if path was presented without any parametes. */ open var currentPathParameter: String? { if let currentPathID = currentPathComponent?.identifier { return tracker.parameter(for: currentPathID) } else { return nil } } /** Returns parameter for specified path. It's nil if page was presented without any parametes. - Parameter pathComponent: Path component to retrieve parameter. - Parameter variant: Variant of that path (previous path). Use it only if page supports variants. - Throws: AFCError.missingVariant if pathe's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter. AFCError.variantNotSupported if path's property supportVariants == false you cannot pass variant property, because there is only one variant of that page. AFCError.unregisteredPathIdentifier page need to be registered before showing it. */ open func parameter(for pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> String? { let step = try pathStep(from: pathComponent, variant: variant) return tracker.parameter(for: step.pathComponent.identifier) } /** Reset root navigation controller and view's tracker. It removes all view controllers including those presented modally. */ open func reset(completion: (()->())? = nil) { rootNavigationController?.dismissAllPresentedViewControllers() { self.rootNavigationController?.viewControllers.removeAll() self.tracker.reset() completion?() } } // MARK: - Helpers private var visibleStep: PathStep? { guard let currentViewController = rootNavigationController?.visibleNavigationController.visible else { return nil } guard let key = tracker.key(for: currentViewController) else { return nil } return rootPathStep?.search(identifier: key) } private func viewControllers(from pathComponents: [FlowPathComponent], skipPathComponents: [FlowPathComponent]? = nil) -> [UIViewController] { var viewControllers: [UIViewController] = [] for pathComponent in pathComponents { if pathComponent.forwardTransition?.shouldPreloadViewController() == true, let viewController = tracker.viewController(for: pathComponent.identifier) { viewControllers.append(viewController) continue } if skipPathComponents?.contains(where: { $0.identifier == pathComponent.identifier }) == true { tracker.register(viewController: nil, for: pathComponent.identifier, skipped: true) continue } let viewController = pathComponent.viewControllerInit() tracker.register(viewController: viewController, for: pathComponent.identifier) if let step = rootPathStep?.search(pathComponent: pathComponent) { let preload = step.children.filter({ $0.pathComponent.forwardTransition?.shouldPreloadViewController() == true }) for item in preload { if let childViewController = self.viewControllers(from: [item.pathComponent], skipPathComponents: skipPathComponents).first { item.pathComponent.forwardTransition?.preloadViewController(childViewController, from: viewController) } } } viewControllers.append(pathComponent.forwardTransition?.configureViewController(from: viewController) ?? viewController) } return viewControllers } private func register(parameters: [TransitionParameter]?, for pathComponents: [FlowPathComponent], skippedPathComponents: [FlowPathComponent]?) { if let parameters = parameters { for parameter in parameters { if pathComponents.filter({ $0.identifier == parameter.identifier }).count == 0 { continue } if (skippedPathComponents?.filter({ $0.identifier == parameter.identifier }).count ?? 0) > 0 { continue } self.tracker.register(parameter: parameter.value, for: parameter.identifier) } } } private func display(pathComponents: [FlowPathComponent], fromIndexRange indexRange: Range<Int>, animated: Bool, skipPathComponents: [FlowPathComponent]? = nil, completion: (() -> ())?) { let index = indexRange.lowerBound let item = pathComponents[index] let identifier = item.identifier guard let navigationController = rootNavigationController?.visible.navigationController ?? rootNavigationController else { completion?() return } func displayNextItem(range: Range<Int>, animated: Bool, offset: Int = 0) { let newRange:Range<Int> = (range.lowerBound + 1 + offset) ..< range.upperBound if newRange.count == 0 { completion?() } else { self.display( pathComponents: pathComponents, fromIndexRange: newRange, animated: animated, skipPathComponents: skipPathComponents, completion: completion ) } } let viewControllerExists = tracker.viewController(for: item.identifier) != nil let pathSkipped = tracker.isItemSkipped(at: item.identifier) let itemIsPreloaded = item.forwardTransition?.shouldPreloadViewController() == true if navigationController.viewControllers.count == 0 { let pathComponentsToPush = [item] + pathComponents[1..<pathComponents.count].prefix(while: { $0.forwardTransition is PushPopFlowTransition }) let viewControllersToPush = self.viewControllers(from: pathComponentsToPush, skipPathComponents: skipPathComponents) let skippedPathComponents = pathComponentsToPush.count - viewControllersToPush.count navigationController.setViewControllers(viewControllersToPush, animated: false) { displayNextItem(range: indexRange, animated: false, offset: max(0, viewControllersToPush.count - 1 + skippedPathComponents)) } } else if (!viewControllerExists || itemIsPreloaded) && !pathSkipped { let viewControllers = self.viewControllers(from: [item], skipPathComponents: skipPathComponents) if let viewController = viewControllers.first { item.forwardTransition?.performForwardTransition(animated: animated){ displayNextItem(range: indexRange, animated: animated) }(navigationController, viewController) } else { displayNextItem(range: indexRange, animated: animated) } } else { displayNextItem(range: indexRange, animated: animated) } } private func dismiss(pathComponents: [FlowPathComponent], fromIndexRange indexRange: Range<Int>, animated: Bool, skipTransition: Bool = false, viewControllerForSkippedPath: UIViewController? = nil, completion:(() -> ())?) { if indexRange.count == 0 { completion?() } else { let index = indexRange.upperBound - 1 let item = pathComponents[index] let parentPathComponent = rootPathStep?.search(pathComponent: item)?.parent?.pathComponent let skipParentPathComponent = parentPathComponent == nil ? false : tracker.isItemSkipped(at: parentPathComponent!.identifier) let skippedPathComponent = tracker.isItemSkipped(at: item.identifier) let viewController = tracker.viewController(for: item.identifier) func dismissNext(viewControllerForSkippedPath: UIViewController? = nil) { self.dismiss( pathComponents: pathComponents, fromIndexRange: indexRange.lowerBound..<indexRange.upperBound - 1, animated: animated, skipTransition: skipTransition, viewControllerForSkippedPath: viewControllerForSkippedPath, completion: completion ) } func dismiss(useTransition: Bool, viewController: UIViewController) { if useTransition { item.backwardTransition?.performBackwardTransition(animated: animated){ dismissNext() }(viewController) } else { dismissNext() } } if skipParentPathComponent { dismissNext(viewControllerForSkippedPath: viewController ?? viewControllerForSkippedPath) } else if let viewController = viewControllerForSkippedPath, skippedPathComponent { dismiss(useTransition: !skipTransition, viewController: viewController) } else if let viewController = viewController, !skippedPathComponent { dismiss(useTransition: !skipTransition, viewController: viewController) } else { completion?() } } } private func pathStep(from pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> PathStep { var pathComponent = pathComponent if pathComponent.supportVariants && variant == nil { throw AFCError.missingVariant(identifier: pathComponent.identifier) } if !pathComponent.supportVariants && variant != nil { throw AFCError.variantNotSupported(identifier: pathComponent.identifier) } if pathComponent.supportVariants && variant != nil { pathComponent.variantName = variant?.identifier } guard let foundStep = rootPathStep?.search(pathComponent: pathComponent) else { throw AFCError.unregisteredPathIdentifier(identifier: pathComponent.identifier) } return foundStep } private func verify(pathComponents: [FlowPathComponent], distance: (up: Int, down: Int)) throws { if distance.up > 0 { let lastIndexToDismiss = pathComponents.count - 1 - distance.up if lastIndexToDismiss >= 0 && lastIndexToDismiss < pathComponents.count - 1 { let item = pathComponents[lastIndexToDismiss] if tracker.isItemSkipped(at: item.identifier) { throw AFCError.showingSkippedPath(identifier: item.identifier) } } } } }
mit
X140Yu/Lemon
Lemon/Library/GitHub API/User.swift
1
2492
import Foundation import ObjectMapper enum UserType { case User case Organization } extension UserType { init(typeString: String) { if typeString == "Organization" { self = .Organization // } else if typeString == "User" { // self = .User } else { self = .User } } } class User: Mappable { var avatarUrl : String? var bio : String? var blog : String? var company : String? var createdAt : String? var email : String? var eventsUrl : String? var followers : Int = 0 var followersUrl : String? var following : Int = 0 var followingUrl : String? var gistsUrl : String? var gravatarId : String? var hireable : Bool? var htmlUrl : String? var id : Int? var location : String? var login : String? var name : String? var organizationsUrl : String? var publicGists : Int = 0 var publicRepos : Int = 0 var receivedEventsUrl : String? var reposUrl : String? var siteAdmin : Bool? var starredUrl : String? var subscriptionsUrl : String? var type : UserType = .User var updatedAt : String? var url : String? public init(){} public required init?(map: Map) {} public func mapping(map: Map) { avatarUrl <- map["avatar_url"] bio <- map["bio"] blog <- map["blog"] company <- map["company"] createdAt <- map["created_at"] email <- map["email"] eventsUrl <- map["events_url"] followers <- map["followers"] followersUrl <- map["followers_url"] following <- map["following"] followingUrl <- map["following_url"] gistsUrl <- map["gists_url"] gravatarId <- map["gravatar_id"] hireable <- map["hireable"] htmlUrl <- map["html_url"] id <- map["id"] location <- map["location"] login <- map["login"] name <- map["name"] organizationsUrl <- map["organizations_url"] publicGists <- map["public_gists"] publicRepos <- map["public_repos"] receivedEventsUrl <- map["received_events_url"] reposUrl <- map["repos_url"] siteAdmin <- map["site_admin"] starredUrl <- map["starred_url"] subscriptionsUrl <- map["subscriptions_url"] if let typeString = map["type"].currentValue as? String { type = UserType(typeString: typeString) } // type <- map["type"] updatedAt <- map["updated_at"] url <- map["url"] } } extension User: CustomStringConvertible { var description: String { return "User: `\(login ?? "")` `\(bio ?? "")` `\(blog ?? "")` `\(company ?? "")`" } }
gpl-3.0
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/action/MD2NewObjectAction.swift
1
1172
// // MD2NewObjectAction.swift // md2-ios-library // // Created by Christoph Rieger on 05.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /// Action to create an empty object within a content provider. class MD2NewObjectAction: MD2Action { /// Unique action identifier. let actionSignature: String /// The content provider to change. let contentProvider: MD2ContentProvider /** Default initializer. :param: actionSignature The action identifier. :param: contentProvider The content provider to change. */ init(actionSignature: String, contentProvider: MD2ContentProvider) { self.actionSignature = actionSignature self.contentProvider = contentProvider } /// Execute the action commands: Create a new object in the content provider. func execute() { contentProvider.setContent() } /** Compare two action objects. :param: anotherAction The action to compare with. */ func equals(anotherAction: MD2Action) -> Bool { return actionSignature == anotherAction.actionSignature } }
apache-2.0
Alienson/Bc
source-code/Parketovanie/ParquetElkoObratene.swift
1
2043
// // ParquetElkoObratene.swift // Parketovanie // // Created by Adam Turna on 19.4.2016. // Copyright © 2016 Adam Turna. All rights reserved. // import Foundation import SpriteKit class ParquetElkoObratene: Parquet { init(parent: SKSpriteNode, position: CGPoint){ super.init(imageNamed: "7-elko-obratene", position: position) let abstractCell = Cell() let height = abstractCell.frame.height // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*2), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*3), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX+height, y: self.frame.maxY-height*3), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: height), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: 0), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: -height), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: -height/2, y: -height), parent: parent)) //let cell1 = Cell(row: 1, collumn: 1, isEmpty: true, parent: parent) for cell in self.arrayOfCells { //parent.addChild(cell) self.addChild(cell) cell.anchorPoint = CGPoint(x: 0.5, y: 0.5) cell.alpha = CGFloat(1) cell.barPosition = cell.position } super.alpha = CGFloat(0.5) //self.arrayOfCells = [[Cell(position: CGPoint(self.frame.),parent: parent), nil],[Cell(parent: parent), nil],[Cell(parent: parent), Cell(parent: parent)]] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
zetasq/Aztec
Aztec-macOSTests/Aztec_macOSTests.swift
1
1007
// // Aztec_macOSTests.swift // Aztec-macOSTests // // Created by Zhu Shengqi on 15/04/2017. // Copyright © 2017 Zhu Shengqi. All rights reserved. // import XCTest @testable import Aztec class Aztec_macOSTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. print(printPath()) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
CrossWaterBridge/Attributed
Attributed/Parse.swift
1
3315
// // Copyright (c) 2015 Hilton Campbell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension NSAttributedString { public static func attributedStringFromMarkup(_ markup: String, withModifier modifier: @escaping Modifier) -> NSAttributedString? { if let data = "<xml>\(markup)</xml>".data(using: .utf8) { let parser = XMLParser(data: data) let parserDelegate = ParserDelegate(modifier: modifier) parser.delegate = parserDelegate parser.parse() return parserDelegate.result } else { return nil } } } private class ParserDelegate: NSObject, XMLParserDelegate { let result = NSMutableAttributedString() let modifier: Modifier var lastIndex = 0 var stack = [MarkupElement]() init(modifier: @escaping Modifier) { self.modifier = modifier } @objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { let range = NSMakeRange(lastIndex, result.length - lastIndex) let startElement = MarkupElement(name: elementName, attributes: attributeDict) modify(in: range, startElement: startElement, endElement: nil) lastIndex = result.length stack.append(startElement) } @objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let range = NSMakeRange(lastIndex, result.length - lastIndex) let endElement = stack.last modify(in: range, startElement: nil, endElement: endElement) lastIndex = result.length stack.removeLast() } @objc func parser(_ parser: XMLParser, foundCharacters string: String) { result.append(NSAttributedString(string: string)) } func modify(in range: NSRange, startElement: MarkupElement?, endElement: MarkupElement?) { if !stack.isEmpty { let state = State(mutableAttributedString: result, range: range, stack: Array(stack[1..<stack.count]), startElement: startElement, endElement: endElement) modifier(state) } } }
mit
wburhan2/TicTacToe
tictactoe/TTTImageView.swift
1
594
// // TTTImageView.swift // tictactoe // // Created by Wilson Burhan on 10/17/14. // Copyright (c) 2014 Wilson Burhan. All rights reserved. // import UIKit class TTTImageView: UIImageView { var player:String? var activated:Bool = false func setPlayer(_player:String){ self.player = _player; if activated == false{ if _player == "X" { self.image = UIImage(named: "X") } else{ self.image = UIImage(named: "O") } activated = true } } }
apache-2.0
fgengine/quickly
Quickly/Text/IQText.swift
1
932
// // Quickly // public protocol IQText : class { var string: String { get } var font: UIFont? { get } var color: UIColor? { get } var attributed: NSAttributedString? { get } func size() -> CGSize func size(width: CGFloat) -> CGSize func size(height: CGFloat) -> CGSize func size(size: CGSize) -> CGSize } extension IQText { public func size() -> CGSize { return self.size(size: CGSize( width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude )) } public func size(width: CGFloat) -> CGSize { return self.size(size: CGSize( width: width, height: CGFloat.greatestFiniteMagnitude )) } public func size(height: CGFloat) -> CGSize { return self.size(size: CGSize( width: CGFloat.greatestFiniteMagnitude, height: height )) } }
mit
fgengine/quickly
Quickly/ViewControllers/Dialog/Background/QDialogBlurBackgroundView.swift
1
1839
// // Quickly // public final class QDialogBlurBackgroundView : QBlurView, IQDialogContainerBackgroundView { public weak var containerViewController: IQDialogContainerViewController? public required init() { super.init(blur: Const.hiddenBlur) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func setup() { super.setup() self.blur = Const.hiddenBlur self.isHidden = true } public func present(viewController: IQDialogViewController, isFirst: Bool, animated: Bool) { if isFirst == true { self.isHidden = false if animated == true { UIView.animate(withDuration: Const.duration, delay: 0, options: [ .beginFromCurrentState ], animations: { self.blur = Const.visibleBlur }) } else { self.blur = Const.visibleBlur } } } public func dismiss(viewController: IQDialogViewController, isLast: Bool, animated: Bool) { if isLast == true { if animated == true { UIView.animate(withDuration: Const.duration, delay: 0, options: [ .beginFromCurrentState ], animations: { self.blur = Const.hiddenBlur }, completion: { (_) in self.isHidden = true }) } else { self.blur = Const.hiddenBlur self.isHidden = true } } } } // MARK: Private private extension QDialogBlurBackgroundView { struct Const { static let duration: TimeInterval = 0.25 static let hiddenBlur: UIBlurEffect? = nil static let visibleBlur: UIBlurEffect? = UIBlurEffect(style: .dark) } }
mit
epodkorytov/OCTextInput
OCTextInput/Classes/OCTextView.swift
1
2577
import UIKit final internal class OCTextView: UITextView { weak var textInputDelegate: TextInputDelegate? override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { delegate = self } override func resignFirstResponder() -> Bool { return super.resignFirstResponder() } } extension OCTextView: TextInput { var currentText: String? { get { return text } set { self.text = newValue } } var textAttributes: [NSAttributedString.Key: Any] { get { return typingAttributes } set { self.typingAttributes = textAttributes } } var currentSelectedTextRange: UITextRange? { get { return self.selectedTextRange } set { self.selectedTextRange = newValue } } public var currentBeginningOfDocument: UITextPosition? { return self.beginningOfDocument } func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) { returnKeyType = newReturnKeyType } func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? { return position(from: from, offset: offset) } } extension OCTextView: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { textInputDelegate?.textInputDidBeginEditing(textInput: self) } func textViewDidEndEditing(_ textView: UITextView) { textInputDelegate?.textInputDidEndEditing(textInput: self) } func textViewDidChange(_ textView: UITextView) { textInputDelegate?.textInputDidChange(textInput: self) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true } return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: text) ?? true } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true } }
mit
CodaFi/swift-compiler-crashes
fixed/04504-swift-typebase-getcanonicaltype.swift
11
212
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T,g{class a{class B<fd{class B<T>:a
mit
uber/RIBs
ios/RIBsTests/Workflow/WorkflowTests.swift
1
6851
// // Copyright (c) 2017. Uber Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import RxSwift @testable import RIBs final class WorkerflowTests: XCTestCase { func test_nestedStepsDoNotRepeat() { var outerStep1RunCount = 0 var outerStep2RunCount = 0 var outerStep3RunCount = 0 var innerStep1RunCount = 0 var innerStep2RunCount = 0 var innerStep3RunCount = 0 let emptyObservable = Observable.just(((), ())) let workflow = Workflow<String>() _ = workflow .onStep { (mock) -> Observable<((), ())> in outerStep1RunCount += 1 return emptyObservable } .onStep { (_, _) -> Observable<((), ())> in outerStep2RunCount += 1 return emptyObservable } .onStep { (_, _) -> Observable<((), ())> in outerStep3RunCount += 1 let innerStep: Step<String, (), ()>? = emptyObservable.fork(workflow) innerStep? .onStep({ (_, _) -> Observable<((), ())> in innerStep1RunCount += 1 return emptyObservable }) .onStep({ (_, _) -> Observable<((), ())> in innerStep2RunCount += 1 return emptyObservable }) .onStep({ (_, _) -> Observable<((), ())> in innerStep3RunCount += 1 return emptyObservable }) .commit() return emptyObservable } .commit() .subscribe("Test Actionable Item") XCTAssertEqual(outerStep1RunCount, 1, "Outer step 1 should not have been run more than once") XCTAssertEqual(outerStep2RunCount, 1, "Outer step 2 should not have been run more than once") XCTAssertEqual(outerStep3RunCount, 1, "Outer step 3 should not have been run more than once") XCTAssertEqual(innerStep1RunCount, 1, "Inner step 1 should not have been run more than once") XCTAssertEqual(innerStep2RunCount, 1, "Inner step 2 should not have been run more than once") XCTAssertEqual(innerStep3RunCount, 1, "Inner step 3 should not have been run more than once") } func test_workflowReceivesError() { let workflow = TestWorkflow() let emptyObservable = Observable.just(((), ())) _ = workflow .onStep { _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return Observable.error(WorkflowTestError.error) } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .commit() .subscribe(()) XCTAssertEqual(0, workflow.completeCallCount) XCTAssertEqual(0, workflow.forkCallCount) XCTAssertEqual(1, workflow.errorCallCount) } func test_workflowDidComplete() { let workflow = TestWorkflow() let emptyObservable = Observable.just(((), ())) _ = workflow .onStep { _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .commit() .subscribe(()) XCTAssertEqual(1, workflow.completeCallCount) XCTAssertEqual(0, workflow.forkCallCount) XCTAssertEqual(0, workflow.errorCallCount) } func test_workflowDidFork() { let workflow = TestWorkflow() let emptyObservable = Observable.just(((), ())) _ = workflow .onStep { _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .onStep { _, _ -> Observable<((), ())> in let forkedStep: Step<(), (), ()>? = emptyObservable.fork(workflow) forkedStep? .onStep { _, _ -> Observable<((), ())> in return emptyObservable } .commit() return emptyObservable } .commit() .subscribe(()) XCTAssertEqual(1, workflow.completeCallCount) XCTAssertEqual(1, workflow.forkCallCount) XCTAssertEqual(0, workflow.errorCallCount) } func test_fork_verifySingleInvocationAtRoot() { let workflow = TestWorkflow() var rootCallCount = 0 let emptyObservable = Observable.just(((), ())) let rootStep = workflow .onStep { _ -> Observable<((), ())> in rootCallCount += 1 return emptyObservable } let firstFork: Step<(), (), ()>? = rootStep.asObservable().fork(workflow) _ = firstFork? .onStep { (_, _) -> Observable<((), ())> in return Observable.just(((), ())) } .commit() let secondFork: Step<(), (), ()>? = rootStep.asObservable().fork(workflow) _ = secondFork? .onStep { (_, _) -> Observable<((), ())> in return Observable.just(((), ())) } .commit() XCTAssertEqual(0, rootCallCount) _ = workflow.subscribe(()) XCTAssertEqual(1, rootCallCount) } } private enum WorkflowTestError: Error { case error } private class TestWorkflow: Workflow<()> { var completeCallCount = 0 var errorCallCount = 0 var forkCallCount = 0 override func didComplete() { completeCallCount += 1 } override func didFork() { forkCallCount += 1 } override func didReceiveError(_ error: Error) { errorCallCount += 1 } }
apache-2.0
Arcovv/CleanArchitectureRxSwift
CoreDataPlatform/Entities/CDCompany+Ext.swift
2
1068
// // CDCompany+Ext.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation import CoreData import Domain import QueryKit import RxSwift extension CDCompany { static var bs: Attribute<String> { return Attribute("bs")} static var catchPhrase: Attribute<String> { return Attribute("catchPhrase")} static var name: Attribute<String> { return Attribute("name")} } extension CDCompany: DomainConvertibleType { func asDomain() -> Company { return Company(bs: bs!, catchPhrase: catchPhrase!, name: name!) } } extension CDCompany: Persistable { static var entityName: String { return "CDCompany" } } extension Company: CoreDataRepresentable { internal var uid: String { return "" } typealias CoreDataType = CDCompany func update(entity: CDCompany) { entity.bs = bs entity.name = name entity.catchPhrase = catchPhrase } }
mit
64characters/Telephone
UseCases/NormalizedLowercasedStringTests.swift
1
1900
// // NormalizedLowercasedStringTests.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // @testable import UseCases import XCTest final class NormalizedLowercasedStringTests: XCTestCase { func testValueIsOrigin() { let sut = NormalizedLowercasedString("foobar") XCTAssertEqual(sut.value, "foobar") } func testValueIsLowercasedOrigin() { let sut = NormalizedLowercasedString("StringWithCapitalLetters") XCTAssertEqual(sut.value, "stringwithcapitalletters") } func testValueEqualsToDecomposedOriginWhenOriginIsPrecomposed() { let sut = NormalizedLowercasedString(precomposed) XCTAssertEqual(sut.value, decomposed) } func testValueEqualsToPrecomposedOriginWhenOriginIsDecomposed() { let sut = NormalizedLowercasedString(decomposed) XCTAssertEqual(sut.value, precomposed) } func testValueEqualsToPrecomposedWhenOriginIsPrecomposed() { let sut = NormalizedLowercasedString(precomposed) XCTAssertEqual(sut.value, precomposed) } func testValueEqualsToDecomposedWhenOriginIsDecomposed() { let sut = NormalizedLowercasedString(decomposed) XCTAssertEqual(sut.value, decomposed) } } private let precomposed = "\u{E9}" // é private let decomposed = "\u{65}\u{301}" // e followed by ´
gpl-3.0
square/wire
wire-library/wire-runtime-swift/src/main/swift/wellknowntypes/Timestamp.swift
1
4407
// Code generated by Wire protocol buffer compiler, do not edit. // Source: google.protobuf.Timestamp in google/protobuf/timestamp.proto import Foundation /** * A Timestamp represents a point in time independent of any time zone * or calendar, represented as seconds and fractions of seconds at * nanosecond resolution in UTC Epoch time. It is encoded using the * Proleptic Gregorian Calendar which extends the Gregorian calendar * backwards to year one. It is encoded assuming all minutes are 60 * seconds long, i.e. leap seconds are "smeared" so that no leap second * table is needed for interpretation. Range is from * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. * By restricting to that range, we ensure that we can convert to * and from RFC 3339 date strings. * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). * * Example 1: Compute Timestamp from POSIX `time()`. * * Timestamp timestamp; * timestamp.set_seconds(time(NULL)); * timestamp.set_nanos(0); * * Example 2: Compute Timestamp from POSIX `gettimeofday()`. * * struct timeval tv; * gettimeofday(&tv, NULL); * * Timestamp timestamp; * timestamp.set_seconds(tv.tv_sec); * timestamp.set_nanos(tv.tv_usec * 1000); * * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. * * FILETIME ft; * GetSystemTimeAsFileTime(&ft); * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; * * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. * Timestamp timestamp; * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); * * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. * * long millis = System.currentTimeMillis(); * * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) * .setNanos((int) ((millis % 1000) * 1000000)).build(); * * * Example 5: Compute Timestamp from current time in Python. * * now = time.time() * seconds = int(now) * nanos = int((now - seconds) * 10**9) * timestamp = Timestamp(seconds=seconds, nanos=nanos) */ public struct Timestamp { /** * Represents seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. */ @JSONString public var seconds: Int64 /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. */ public var nanos: Int32 public var unknownFields: Data = .init() public init(seconds: Int64, nanos: Int32) { self.seconds = seconds self.nanos = nanos } } #if !WIRE_REMOVE_EQUATABLE extension Timestamp : Equatable { } #endif #if !WIRE_REMOVE_HASHABLE extension Timestamp : Hashable { } #endif extension Timestamp : ProtoMessage { public static func protoMessageTypeURL() -> String { return "type.googleapis.com/google.protobuf.Timestamp" } } extension Timestamp : Proto3Codable { public init(from reader: ProtoReader) throws { var seconds: Int64? = nil var nanos: Int32? = nil let token = try reader.beginMessage() while let tag = try reader.nextTag(token: token) { switch tag { case 1: seconds = try reader.decode(Int64.self) case 2: nanos = try reader.decode(Int32.self) default: try reader.readUnknownField(tag: tag) } } self.unknownFields = try reader.endMessage(token: token) self.seconds = try Timestamp.checkIfMissing(seconds, "seconds") self.nanos = try Timestamp.checkIfMissing(nanos, "nanos") } public func encode(to writer: ProtoWriter) throws { try writer.encode(tag: 1, value: self.seconds) try writer.encode(tag: 2, value: self.nanos) try writer.writeUnknownFields(unknownFields) } } #if !WIRE_REMOVE_CODABLE extension Timestamp : Codable { public enum CodingKeys : String, CodingKey { case seconds case nanos } } #endif
apache-2.0
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/Settings/AdBlockerSettingsTableViewController.swift
2
3497
// // AdBlockerSettingsTableViewController.swift // Client // // Created by Mahmoud Adam on 7/20/16. // Copyright © 2016 Mozilla. All rights reserved. // import UIKit class AdBlockerSettingsTableViewController: SubSettingsTableViewController { private let toggleTitles = [ NSLocalizedString("Block Ads", tableName: "Cliqz", comment: "[Settings -> Block Ads] Block Ads"), NSLocalizedString("Fair Mode", tableName: "Cliqz", comment: "[Settings -> Block Ads] Fair Mode") ] private let sectionFooters = [ NSLocalizedString("Block Ads footer", tableName: "Cliqz", comment: "[Settings -> Block Ads] Block Ads footer"), NSLocalizedString("Fair Mode footer", tableName: "Cliqz", comment: "[Settings -> Block Ads] Fair Mode footer") ] private lazy var toggles: [Bool] = { return [SettingsPrefs.shared.getAdBlockerPref(), SettingsPrefs.shared.getFairBlockingPref()] }() override func getSectionFooter(section: Int) -> String { guard section < sectionFooters.count else { return "" } return sectionFooters[section] } override func getViewName() -> String { return "block_ads" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = getUITableViewCell() cell.textLabel?.text = toggleTitles[indexPath.section] let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggles[indexPath.section] control.accessibilityLabel = "AdBlock Switch" cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.section if self.toggles[0] == false && indexPath.section == 1 { cell.isUserInteractionEnabled = false cell.textLabel?.textColor = UIColor.gray control.isEnabled = false } else { cell.isUserInteractionEnabled = true cell.textLabel?.textColor = UIColor.black control.isEnabled = true } return cell } override func numberOfSections(in tableView: UITableView) -> Int { if self.toggles[0] { return 2 } return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 1 { return 0 } return super.tableView(tableView, heightForHeaderInSection: section) } @objc func switchValueChanged(_ toggle: UISwitch) { self.toggles[toggle.tag] = toggle.isOn saveToggles() self.tableView.reloadData() // log telemetry signal let target = toggle.tag == 0 ? "enable" : "fair_blocking" let state = toggle.isOn == true ? "off" : "on" // we log old value let valueChangedSignal = TelemetryLogEventType.Settings("block_ads", "click", target, state, nil) TelemetryLogger.sharedInstance.logEvent(valueChangedSignal) } private func saveToggles() { SettingsPrefs.shared.updateAdBlockerPref(self.toggles[0]) SettingsPrefs.shared.updateFairBlockingPref(self.toggles[1]) } }
mpl-2.0
kconner/KMCGeigerCounter
ExampleApplication/AppDelegate.swift
1
502
// // AppDelegate.swift // ExampleApplication // // Created by Kevin Conner on 9/1/18. // Copyright © 2018 Kevin Conner. All rights reserved. // import UIKit @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { KMCGeigerCounter.shared().isEnabled = true return true } }
mit
apple/swift-numerics
Sources/ComplexModule/Complex+StringConvertible.swift
1
788
//===--- Complex+StringConvertible.swift ----------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // // Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// extension Complex: CustomStringConvertible { public var description: String { guard isFinite else { return "inf" } return "(\(x), \(y))" } } extension Complex: CustomDebugStringConvertible { public var debugDescription: String { "Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))" } }
apache-2.0
wjk930726/weibo
weiBo/weiBo/iPhone/Modules/Compose/EmotionKeyboard/WBEmotionTool.swift
1
2581
// // WBEmotionTool.swift // weiBo // // Created by 王靖凯 on 2016/12/6. // Copyright © 2016年 王靖凯. All rights reserved. // import UIKit class WBEmotionTool: NSObject { static let shared = WBEmotionTool() private var bundlePath: String { return Bundle.main.path(forResource: "Emoticons", ofType: "bundle")! } /// 默认表情的地址 private var defaultPath: String { return bundlePath + "/Contents/Resources/default/info.plist" } /// emoji表情的地址 private var emojiPath: String { return bundlePath + "/Contents/Resources/emoji/info.plist" } /// emoji表情的地址 private var lxhPath: String { return bundlePath + "/Contents/Resources/lxh/info.plist" } /// 根据path解析出表情的model func parseEmotionModel(path: String) -> [WBEmotionModel] { var array = [WBEmotionModel]() if let dictArray = NSArray(contentsOfFile: path) { for dict in dictArray { guard let dictionary = dict as? [String: Any] else { continue } let model = WBEmotionModel(dict: dictionary) if model.type == 0 { let folderPath = (path as NSString).deletingLastPathComponent model.fullPath = "\(folderPath)/\(model.png!)" } array.append(model) } } return array } /// 将表情model根据cell来分组 func devideEmotions(emotions: [WBEmotionModel]) -> [[WBEmotionModel]] { var resultArray = [[WBEmotionModel]]() let pageNum = (emotions.count - 1) / 20 + 1 for i in 0 ..< pageNum { if i + 1 == pageNum { let range = NSRange(location: i * 20, length: emotions.count - i * 20) resultArray.append((emotions as NSArray).subarray(with: range) as! [WBEmotionModel]) } else { let range = NSRange(location: i * 20, length: 20) resultArray.append((emotions as NSArray).subarray(with: range) as! [WBEmotionModel]) } } return resultArray } func emotionsDataSource() -> [[[WBEmotionModel]]] { return [ devideEmotions(emotions: parseEmotionModel(path: defaultPath)), devideEmotions(emotions: parseEmotionModel(path: defaultPath)), devideEmotions(emotions: parseEmotionModel(path: emojiPath)), devideEmotions(emotions: parseEmotionModel(path: lxhPath)), ] } }
mit
piwik/piwik-sdk-ios
MatomoTracker/Event.swift
1
5431
import Foundation import CoreGraphics /// Represents an event of any kind. /// /// - Todo: /// - Add Action info /// - Add Content Tracking info /// /// # Key Mapping: /// Most properties represent a key defined at: [Tracking HTTP API](https://developer.piwik.org/api-reference/tracking-api). Keys that are not supported for now are: /// /// - idsite, rec, rand, apiv, res, cookie, /// - All Plugins: fla, java, dir, qt, realp, pdf, wma, gears, ag public struct Event: Codable { public let uuid: UUID let siteId: String let visitor: Visitor let session: Session /// This flag defines if this event is a so called cutom action. /// api-key: ca /// More info: https://github.com/matomo-org/matomo-sdk-ios/issues/354 /// and https://github.com/matomo-org/matomo-sdk-ios/issues/363 let isCustomAction: Bool /// The Date and Time the event occurred. /// api-key: h, m, s let date: Date /// The full URL for the current action. /// api-key: url let url: URL? /// api-key: action_name let actionName: [String] /// The language of the device. /// Should be in the format of the Accept-Language HTTP header field. /// api-key: lang let language: String /// Should be set to true for the first event of a session. /// api-key: new_visit let isNewSession: Bool /// Currently only used for Campaigns /// api-key: urlref let referer: URL? var screenResolution: CGSize = Device.makeCurrentDevice().screenSize /// api-key: _cvar let customVariables: [CustomVariable] /// Event tracking /// https://piwik.org/docs/event-tracking/ let eventCategory: String? let eventAction: String? let eventName: String? let eventValue: Float? /// Campaign tracking /// https://matomo.org/docs/tracking-campaigns/ let campaignName: String? let campaignKeyword: String? /// Search tracking /// api-keys: search, search_cat, search_count let searchQuery: String? let searchCategory: String? let searchResultsCount: Int? let dimensions: [CustomDimension] let customTrackingParameters: [String:String] /// Content tracking /// https://matomo.org/docs/content-tracking/ let contentName: String? let contentPiece: String? let contentTarget: String? let contentInteraction: String? /// Goal tracking /// https://matomo.org/docs/tracking-goals-web-analytics/ let goalId: Int? let revenue: Float? /// Ecommerce Order tracking /// https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required let orderId: String? let orderItems: [OrderItem] let orderRevenue: Float? let orderSubTotal: Float? let orderTax: Float? let orderShippingCost: Float? let orderDiscount: Float? let orderLastDate: Date? } extension Event { public init(tracker: MatomoTracker, action: [String], url: URL? = nil, referer: URL? = nil, eventCategory: String? = nil, eventAction: String? = nil, eventName: String? = nil, eventValue: Float? = nil, customTrackingParameters: [String:String] = [:], searchQuery: String? = nil, searchCategory: String? = nil, searchResultsCount: Int? = nil, dimensions: [CustomDimension] = [], variables: [CustomVariable] = [], contentName: String? = nil, contentInteraction: String? = nil, contentPiece: String? = nil, contentTarget: String? = nil, goalId: Int? = nil, revenue: Float? = nil, orderId: String? = nil, orderItems: [OrderItem] = [], orderRevenue: Float? = nil, orderSubTotal: Float? = nil, orderTax: Float? = nil, orderShippingCost: Float? = nil, orderDiscount: Float? = nil, orderLastDate: Date? = nil, isCustomAction: Bool) { self.siteId = tracker.siteId self.uuid = UUID() self.visitor = tracker.visitor self.session = tracker.session self.date = Date() self.url = url ?? tracker.contentBase?.appendingPathComponent(action.joined(separator: "/")) self.actionName = action self.language = Locale.httpAcceptLanguage self.isNewSession = tracker.nextEventStartsANewSession self.referer = referer self.eventCategory = eventCategory self.eventAction = eventAction self.eventName = eventName self.eventValue = eventValue self.searchQuery = searchQuery self.searchCategory = searchCategory self.searchResultsCount = searchResultsCount self.dimensions = tracker.dimensions + dimensions self.campaignName = tracker.campaignName self.campaignKeyword = tracker.campaignKeyword self.customTrackingParameters = customTrackingParameters self.customVariables = tracker.customVariables + variables self.contentName = contentName self.contentPiece = contentPiece self.contentTarget = contentTarget self.contentInteraction = contentInteraction self.goalId = goalId self.revenue = revenue self.orderId = orderId self.orderItems = orderItems self.orderRevenue = orderRevenue self.orderSubTotal = orderSubTotal self.orderTax = orderTax self.orderShippingCost = orderShippingCost self.orderDiscount = orderDiscount self.orderLastDate = orderLastDate self.isCustomAction = isCustomAction } }
mit
MrPudin/Skeem
IOS/Prevoir/SKMSetting.swift
1
1075
// // SKMSetting.swift // Skeem // // Created by Zhu Zhan Yan on 29/10/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit public enum SKMSetting:String { //UI Settings case ui_shake = "pvr_set_ui_shake" /* NSNumber<Bool> - Whether shake to refresh is enabled*/ } public class SKMConfig:NSObject { //Data var cfg:[String:NSCoding] //Init /* * init(cfg:[String:NSCoding] * [Argument] * [String:NSCoding] - Inital Configuration data */ init(cfg:[String:NSCoding]) { self.cfg = cfg } //Data Methods /* * public func retrieveSetting(set:SKMSetting) -> NSCoding * - Retrieve value for setting specfied by set * */ public func retrieveSetting(set:SKMSetting) -> NSCoding { return self.cfg[set.rawValue]! } /* * public func commitSetting(set:SKMSetting,val:NSCoding) * - Save value for setting specifed by set */ public func commitSetting(set:SKMSetting,val:NSCoding) { self.cfg[set.rawValue] = val } }
mit
FirebaseExtended/crashlytics-migration-ios
Firebase/iOSApp/AppDelegate.swift
1
3152
// Copyright 2019 Google LLC // // 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 // // https://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. // // AppDelegate.swift // sample1 // // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //Firebase Initialization Statement FirebaseApp.configure() //Set tab bar controller font and font size let appearance = UITabBarItem.appearance() let attributes = [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 20)] appearance.setTitleTextAttributes(attributes as [NSAttributedString.Key : Any], for: .normal) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
einsteinx2/iSub
Carthage/Checkouts/Nuke/Tests/PerformanceTests.swift
1
4020
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Nuke import XCTest class ManagerPerformanceTests: XCTestCase { func testDefaultManager() { let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { Nuke.loadImage(with: url, into: view) } } } func testWithoutMemoryCache() { let loader = Loader(loader: DataLoader(), decoder: DataDecoder(), cache: nil) let manager = Manager(loader: Deduplicator(loader: loader)) let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { manager.loadImage(with: url, into: view) } } } func testWithoutDeduplicator() { let loader = Loader(loader: DataLoader(), decoder: DataDecoder(), cache: nil) let manager = Manager(loader: loader) let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { manager.loadImage(with: url, into: view) } } } } class CachePerformanceTests: XCTestCase { func testCacheWrite() { let cache = Cache() let image = Image() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(500))")! } measure { for url in urls { let request = Request(url: url) cache[request] = image } } } func testCacheHit() { let cache = Cache() for i in 0..<200 { cache[Request(url: URL(string: "http://test.com/\(i))")!)] = Image() } var hits = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } measure { for url in urls { let request = Request(url: url) if cache[request] != nil { hits += 1 } } } print("hits: \(hits)") } func testCacheMiss() { let cache = Cache() var misses = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } measure { for url in urls { let request = Request(url: url) if cache[request] == nil { misses += 1 } } } print("misses: \(misses)") } } class DeduplicatorPerformanceTests: XCTestCase { func testDeduplicatorHits() { let deduplicator = Deduplicator(loader: MockImageLoader()) let request = Request(url: URL(string: "http://test.com/\(arc4random())")!) measure { let cts = CancellationTokenSource() for _ in (0..<10_000) { _ = deduplicator.loadImage(with: request, token:cts.token) } } } func testDeduplicatorMisses() { let deduplicator = Deduplicator(loader: MockImageLoader()) let requests = (0..<10_000) .map { _ in return URL(string: "http://test.com/\(arc4random())")! } .map { return Request(url: $0) } measure { let cts = CancellationTokenSource() for request in requests { _ = deduplicator.loadImage(with: request, token:cts.token) } } } } class MockImageLoader: Loading { func loadImage(with request: Request, token: CancellationToken?) -> Promise<Image> { return Promise() { fulfill, reject in return } } }
gpl-3.0
rodrigoruiz/SwiftUtilities
SwiftUtilities/Lite/NewStructures/Result.swift
1
4389
// // Result.swift // SwiftUtilities // // Created by Rodrigo Ruiz on 4/25/17. // Copyright © 2017 Rodrigo Ruiz. All rights reserved. // public enum Result<S, F> { case success(S) case failure(F) public func getSuccess() -> S? { if case let .success(s) = self { return s } return nil } public func getFailure() -> F? { if case let .failure(f) = self { return f } return nil } public func isSuccess() -> Bool { if case .success(_) = self { return true } return false } public func isFailure() -> Bool { return !isSuccess() } public func flatMap<S2>(_ transform: (S) -> Result<S2, F>) -> Result<S2, F> { switch self { case let .success(s): return transform(s) case let .failure(f): return .failure(f) } } public func map<S2>(_ transform: (S) -> S2) -> Result<S2, F> { return flatMap({ .success(transform($0)) }) } public func flatMapFailure<F2>(_ transform: (F) -> Result<S, F2>) -> Result<S, F2> { switch self { case let .success(s): return .success(s) case let .failure(f): return transform(f) } } public func mapFailure<F2>(_ transform: @escaping (F) -> F2) -> Result<S, F2> { return flatMapFailure({ .failure(transform($0)) }) } public func mapToValue<V>(_ successTransform: (S) -> V, _ failureTransform: (F) -> V) -> V { switch self { case let .success(s): return successTransform(s) case let .failure(f): return failureTransform(f) } } public func mapToVoid() -> Result<Void, F> { return map({ _ in }) } public func mapFailureToVoid() -> Result<S, Void> { return mapFailure({ _ in }) } } public func getSuccess<S, F>(_ result: Result<S, F>) -> S? { return result.getSuccess() } public func getFailure<S, F>(_ result: Result<S, F>) -> F? { return result.getFailure() } public func isSuccess<S, F>(_ result: Result<S, F>) -> Bool { return result.isSuccess() } public func isFailure<S, F>(_ result: Result<S, F>) -> Bool { return result.isFailure() } public func flatMap<S, F, S2>(_ transform: @escaping (S) -> Result<S2, F>) -> (Result<S, F>) -> Result<S2, F> { return { $0.flatMap(transform) } } public func map<S, F, S2>(_ transform: @escaping (S) -> S2) -> (Result<S, F>) -> Result<S2, F> { return { $0.map(transform) } } func flatMapFailure<S, F, F2>(_ transform: @escaping (F) -> Result<S, F2>) -> (Result<S, F>) -> Result<S, F2> { return { $0.flatMapFailure(transform) } } public func mapFailure<S, F, F2>(_ transform: @escaping (F) -> F2) -> (Result<S, F>) -> Result<S, F2> { return { $0.mapFailure(transform) } } public func mapToValue<S, F, V>( _ successTransform: @escaping (S) -> V, _ failureTransform: @escaping (F) -> V ) -> (Result<S, F>) -> V { return { $0.mapToValue(successTransform, failureTransform) } } public func mapToVoid<S, F>(_ result: Result<S, F>) -> Result<Void, F> { return result.mapToVoid() } public func mapFailureToVoid<S, F>(_ result: Result<S, F>) -> Result<S, Void> { return result.mapFailureToVoid() } public func reduceResults<S, F, S2>(_ initialResultValue: S2, _ nextPartialResultValue: @escaping (S2, S) -> S2) -> ([Result<S, F>]) -> Result<S2, F> { return { results in return results.reduce(Result<S2, F>.success(initialResultValue), { result, next in switch (result, next) { case let (.success(r), .success(n)): return .success(nextPartialResultValue(r, n)) case let (.failure(error), _): return .failure(error) case let (_, .failure(error)): return .failure(error) default: fatalError() } }) } } public func == <S: Equatable, F: Equatable>(lhs: Result<S, F>, rhs: Result<S, F>) -> Bool { switch (lhs, rhs) { case let (.success(left), .success(right)): return left == right case let (.failure(left), .failure(right)): return left == right default: return false } }
mit
graphcool-examples/react-apollo-auth0-example
quickstart-with-apollo/Instagram/Carthage/Checkouts/apollo-ios/Tests/LinuxMain.swift
1
251
import XCTest @testable import ApolloTests XCTMain([ testCase(GraphQLMapDecodingTests.allTests), testCase(GraphQLMapEncodingTests.allTests), testCase(ParseQueryResultDataTests.allTests), testCase(StarWarsServerTests.allTests), ])
mit
dice-media-group/evoagent_ios
EVO AgentUITests/EVO_AgentUITests.swift
1
1255
// // EVO_AgentUITests.swift // EVO AgentUITests // // Created by Captain Proton on 3/8/17. // Copyright © 2017 dicemediagroup. All rights reserved. // import XCTest class EVO_AgentUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
cenzuen/swiftAddressBook
swiftTest-10 AddressBook/ViewController.swift
1
4733
// // ViewController.swift // swiftTest-10 AddressBook // // Created by joey0824 on 2017/5/24. // Copyright © 2017年 JC. All rights reserved. // import UIKit import LKDBHelper class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView:UITableView? lazy var dataArr : [contactDBModel]? = { () -> [contactDBModel]? in guard let result = contactDBModel.search(withWhere: nil, orderBy: nil, offset: 0, count: 0) else{ return nil } return result as? [contactDBModel] }() var helper:LKDBHelper? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "联系人列表" self.helper = contactDBModel.getUsingLKDBHelper() setupTableView() setupNaviItem() print(NSHomeDirectory()) } //MARK: - tableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard (dataArr?.count) != nil else { return 0 } return (dataArr?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId") } guard let data = dataArr?[indexPath.row] else { return cell! } cell?.textLabel?.text = data.name cell?.detailTextLabel?.text = data.phoneNum return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC:detailViewController = detailViewController() detailVC.contact = (dataArr?[indexPath.row])! detailVC.saveContact = { (contact:contactDBModel) in contact.updateToDB() self.dataArr?[indexPath.row] = contact self.tableView?.reloadData() } self.navigationController?.pushViewController(detailVC, animated: true) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delAction = UITableViewRowAction(style: .destructive, title: "删除") { (rowAction, indexPath) in self.dataArr?[indexPath.row].deleteToDB() self.dataArr?.remove(at: indexPath.row) self.tableView?.reloadData() } return [delAction] } //tabelView func setupTableView() { tableView = UITableView(frame: view.bounds, style: .plain) tableView?.center = view.center tableView?.delegate = self tableView?.dataSource = self view.addSubview(tableView!) } //NaviItem func setupNaviItem() { let rightItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(touchupAdd)) self.navigationItem.rightBarButtonItem = rightItem } func touchupAdd() { let detailVC = detailViewController() detailVC.contact = contactDBModel.init() detailVC.saveContact = { (contact:contactDBModel) in contactDBModel.insert(toDB: contact) self.dataArr?.append(contact) self.tableView?.reloadData() } self.navigationController?.pushViewController(detailVC, animated: true) } //批量生成虚拟数据 private func loadData(competion:@escaping (_ list:[contactDBModel])->()) { DispatchQueue.global().async { print("正在努力jiaz") var arrayM = [contactDBModel]() for i in 0..<20 { var contact = contactDBModel.init(name: "客户\(i)", phoneNum: "1860"+String(format: "%06d", arc4random_uniform(100000)))//contactModel.init(name: "客户\(i)", phoneNum: "1860"+String(format: "%06d", arc4random_uniform(100000))) arrayM.append(contact) } DispatchQueue.main.async(execute: { competion(arrayM) }) } } }
apache-2.0