repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
applivery/applivery-ios-sdk
refs/heads/master
AppliveryBehaviorTests/Specs/ForceUpdateSpecs.swift
mit
1
// // ForceUpdateSpecs.swift // AppliverySDK // // Created by Alejandro Jiménez Agudo on 11/4/17. // Copyright © 2017 Applivery S.L. All rights reserved. // import Quick import Nimble import OHHTTPStubs @testable import Applivery class ForceUpdateSpecs: QuickSpec { var updatePresenter: UpdatePresenter! var config: GlobalConfig! var updateViewMock: UpdateViewMock! var appMock: AppMock! var userDefaultsMock: UserDefaultsMock! override func spec() { describe("force update") { beforeEach { self.config = GlobalConfig() GlobalConfig.shared = self.config self.updateViewMock = UpdateViewMock() self.appMock = AppMock() self.userDefaultsMock = UserDefaultsMock() self.updatePresenter = UpdatePresenter( updateInteractor: UpdateInteractor( output: nil, configData: ConfigDataManager( appInfo: self.appMock, configPersister: ConfigPersister( userDefaults: self.userDefaultsMock ), configService: ConfigService() ), downloadData: DownloadDataManager(), app: self.appMock, loginInteractor: LoginInteractor( app: self.appMock, loginDataManager: LoginDataManager( loginService: LoginService() ), globalConfig: self.config, sessionPersister: SessionPersister( userDefaults: self.userDefaultsMock ) ), globalConfig: self.config ), view: self.updateViewMock ) self.updatePresenter.updateInteractor.output = self.updatePresenter } afterEach { self.config = nil self.updatePresenter.updateInteractor.output = nil self.updateViewMock = nil self.appMock = nil self.userDefaultsMock = nil self.updatePresenter = nil HTTPStubs.removeAllStubs() } describe("view did load") { beforeEach { self.appMock.stubVersion = "1" self.config.textLiterals.forceUpdateMessage = "test force update message" self.updatePresenter.viewDidLoad() } it("should show update message") { expect(self.updateViewMock.spyShowUpdateMessage.called).to(beTrue()) expect(self.updateViewMock.spyShowUpdateMessage.message).to(equal("test force update message")) } } context("user did tap download") { beforeEach { self.appMock.stubVersion = "1" self.userDefaultsMock.stubDictionary = UserDefaultFakes.storedConfig(lastBuildID: "LAST_BUILD_ID_TEST") } it("should show loading") { self.updatePresenter.userDidTapDownload() expect(self.updateViewMock.spyShowLoadingCalled).to(beTrue()) } it("should request a download token") { var url: String? StubResponse.testRequest { url = $0 } self.updatePresenter.userDidTapDownload() expect(url).toEventually(equal("/v1/build/LAST_BUILD_ID_TEST/downloadToken")) } context("and service returns a valid token") { beforeEach { self.appMock.stubOpenUrlResult = true StubResponse.mockResponse(for: "/v1/build/LAST_BUILD_ID_TEST/downloadToken", with: "request_token_ok.json") self.updatePresenter.userDidTapDownload() } it("should open download url") { expect(self.appMock.spyOpenUrl.called).toEventually(beTrue()) expect(self.appMock.spyOpenUrl.url).toEventually(equal("itms-services://?action=download-manifest&url=\(GlobalConfig.HostDownload)/v1/download/test_token/manifest.plist")) } it("should hide loading") { expect(self.updateViewMock.spyStopLoadingCalled).toEventually(beTrue()) } } context("but service returns ko") { beforeEach { self.appMock.stubOpenUrlResult = true StubResponse.mockResponse(for: "/v1/build/LAST_BUILD_ID_TEST/downloadToken", with: "ko.json") self.updatePresenter.userDidTapDownload() } it("should hide loading") { expect(self.updateViewMock.spyStopLoadingCalled).toEventually(beTrue()) } it("should show error alert") { expect(self.updateViewMock.spyShowErrorMessage.called).toEventually(beTrue()) expect(self.updateViewMock.spyShowErrorMessage.message).toEventually(equal("Unexpected error")) } } context("but service returns limit exceeded") { beforeEach { self.appMock.stubOpenUrlResult = true StubResponse.mockResponse(for: "/v1/build/LAST_BUILD_ID_TEST/downloadToken", with: "error_5003.json") self.updatePresenter.userDidTapDownload() } it("should hide loading") { expect(self.updateViewMock.spyStopLoadingCalled).toEventually(beTrue()) } it("should show error alert") { expect(self.updateViewMock.spyShowErrorMessage.called).toEventually(beTrue()) expect(self.updateViewMock.spyShowErrorMessage.message).toEventually(equal(kLocaleErrorDownloadLimitMonth.replacingOccurrences(of: "%s", with: "3000"))) } } } context("when download needs auth") { var matchedDownloadURL = false var downloadHeaders: [String: String]? beforeEach { matchedDownloadURL = false downloadHeaders = nil StubResponse.testRequest(with: "ko.json", url: "/v1/build/LAST_BUILD_ID_TEST/downloadToken", matching: { _, _, headers in matchedDownloadURL = true downloadHeaders = headers }) self.appMock.stubVersion = "1" self.userDefaultsMock.stubDictionary = UserDefaultFakes.storedConfig( lastBuildID: "LAST_BUILD_ID_TEST", forceAuth: true ) self.updatePresenter.userDidTapDownload() } it("should show login alert") { expect(self.appMock.spyLoginView.called).toEventually(beTrue()) expect(self.appMock.spyLoginView.message).toEventually(equal(literal(.loginMessage))) } context("when login is cancelled") { beforeEach { self.appMock.spyLoginCancelClosure?() } it("should stop loading") { expect(self.updateViewMock.spyStopLoadingCalled).toEventually(beTrue()) } } context("when login is KO") { var matchedLoginURL = false var loginBody: JSON? beforeEach { loginBody = nil let email = "[email protected]" let password = "TEST_PASSWORD" matchedLoginURL = false StubResponse.testRequest(url: "/v1/auth/login") { _, json, _ in matchedLoginURL = true loginBody = json } self.appMock.spyLoginClosure?(email, password) } it("should request user token") { expect(matchedLoginURL).toEventually(beTrue()) expect(loginBody?["provider"]?.toString()).toEventually(equal("traditional")) expect(loginBody?["payload.user"]?.toString()).toEventually(equal("[email protected]")) expect(loginBody?["payload.password"]?.toString()).toEventually(equal("TEST_PASSWORD")) } it("should ask for login again") { expect(self.appMock.spyLoginView.called).toEventually(beTrue()) expect(self.appMock.spyLoginView.message).toEventually(equal(literal(.loginInvalidCredentials))) } } context("when login is OK") { var matchedLoginURL = false var loginBody: JSON? beforeEach { loginBody = nil let email = "[email protected]" let password = "TEST_PASSWORD" matchedLoginURL = false StubResponse.testRequest(with: "login_success.json", url: "/v1/auth/login") { _, json, _ in matchedLoginURL = true loginBody = json } self.appMock.spyLoginClosure?(email, password) } it("should request user token") { expect(matchedLoginURL).toEventually(beTrue()) expect(loginBody?["provider"]?.toString()).toEventually(equal("traditional")) expect(loginBody?["payload.user"]?.toString()).toEventually(equal("[email protected]")) expect(loginBody?["payload.password"]?.toString()).toEventually(equal("TEST_PASSWORD")) } it("should request an authenticated download token") { expect(matchedDownloadURL).toEventually(beTrue()) expect(downloadHeaders?["x-sdk-auth-token"]).toEventually(equal("test_user_token")) } } } context("when ota needs auth but was previously logged in") { var matchedDownloadURL = false var downloadHeaders: [String: String]? beforeEach { matchedDownloadURL = false downloadHeaders = nil StubResponse.testRequest(with: "ko.json", url: "/v1/build/LAST_BUILD_ID_TEST/downloadToken", matching: { _, _, headers in matchedDownloadURL = true downloadHeaders = headers }) self.userDefaultsMock.stubDictionary = UserDefaultFakes.storedConfig( lastBuildID: "LAST_BUILD_ID_TEST", forceAuth: true, accessToken: AccessToken(token: "TEST_TOKEN") ) self.appMock.stubVersion = "1" self.updatePresenter.userDidTapDownload() } it("should not show login alert") { expect(self.appMock.spyLoginView.called).toNotEventually(beTrue()) } it("should request an authenticated download token") { expect(matchedDownloadURL).toEventually(beTrue()) expect(downloadHeaders?["x-sdk-auth-token"]).toEventually(equal("TEST_TOKEN")) } } } } }
b737a335352f9fae0b9c733512c5628b
34.750988
177
0.682698
false
true
false
false
audrl1010/EasyMakePhotoPicker
refs/heads/master
EasyMakePhotoPicker/Classes/PhotosViewConfigure.swift
mit
1
// // PhotosViewConfigure.swift // PhotoPicker // // Created by myung gi son on 2017. 6. 25.. // Copyright © 2017년 grutech. All rights reserved. // import UIKit import Photos import PhotosUI import UIKit public protocol PhotosViewConfigure { var fetchOptions: PHFetchOptions { get } var allowsMultipleSelection: Bool { get } var allowsCameraSelection: Bool { get } // .video, .livePhoto var allowsPlayTypes: [AssetType] { get } var messageWhenMaxCountSelectedPhotosIsExceeded: String { get } var maxCountSelectedPhotos: Int { get } // get item image from PHCachingImageManager // based on the UICollectionViewFlowLayout`s itemSize, // therefore must set well itemSize in UICollectionViewFlowLayout. var layout: UICollectionViewFlowLayout { get } var photoCellTypeConverter: PhotoCellTypeConverter { get } var livePhotoCellTypeConverter: LivePhotoCellTypeConverter { get } var videoCellTypeConverter: VideoCellTypeConverter { get } var cameraCellTypeConverter: CameraCellTypeConverter { get } } public protocol CellTypeConverter { associatedtype Cellable var cellIdentifier: String { get } var cellClass: AnyClass { get } } public struct PhotoCellTypeConverter: CellTypeConverter { public typealias Cellable = PhotoCellable public var cellIdentifier: String public var cellClass: AnyClass public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable { cellIdentifier = NSStringFromClass(type) cellClass = type } } public struct LivePhotoCellTypeConverter: CellTypeConverter { public typealias Cellable = LivePhotoCellable public var cellIdentifier: String public var cellClass: AnyClass public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable { cellIdentifier = NSStringFromClass(type) cellClass = type } } public struct VideoCellTypeConverter: CellTypeConverter { public typealias Cellable = VideoCellable public var cellIdentifier: String public var cellClass: AnyClass public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable { cellIdentifier = NSStringFromClass(type) cellClass = type } } public struct CameraCellTypeConverter: CellTypeConverter { public typealias Cellable = CameraCellable public var cellIdentifier: String public var cellClass: AnyClass public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable { cellIdentifier = NSStringFromClass(type) cellClass = type } } public protocol CameraCellable: class { } public protocol PhotoCellable: class { var viewModel: PhotoCellViewModel? { get set } } public protocol LivePhotoCellable: PhotoCellable { } public protocol VideoCellable: PhotoCellable { }
6d9d5e55f5cf635a1b2caebcf5f092f5
22.444444
72
0.753555
false
false
false
false
jhurliman/NeuralSwift
refs/heads/master
NeuralSwift/NeuralSwift/DataLoader/BinaryDataScanner.swift
mit
1
// // BinaryDataScanner.swift // Murphy // // Created by Dave Peck on 7/20/14. // Copyright (c) 2014 Dave Peck. All rights reserved. // import Foundation protocol BinaryReadable { var littleEndian: Self { get } var bigEndian: Self { get } } extension UInt8: BinaryReadable { var littleEndian: UInt8 { return self } var bigEndian: UInt8 { return self } } extension UInt16: BinaryReadable {} extension UInt32: BinaryReadable {} extension UInt64: BinaryReadable {} class BinaryDataScanner { let data: NSData let littleEndian: Bool let encoding: NSStringEncoding var current: UnsafePointer<Void> var remaining: Int init(data: NSData, littleEndian: Bool, encoding: NSStringEncoding) { self.data = data self.littleEndian = littleEndian self.encoding = encoding self.current = self.data.bytes self.remaining = self.data.length } func read<T: BinaryReadable>() -> T? { if remaining < sizeof(T) { return nil } let tCurrent = UnsafePointer<T>(current) let v = tCurrent.memory current = UnsafePointer<Void>(tCurrent.successor()) remaining -= sizeof(T) return littleEndian ? v.littleEndian : v.bigEndian } /* convenience read funcs */ func readByte() -> UInt8? { return read() } func read16() -> UInt16? { return read() } func read32() -> UInt32? { return read() } func read64() -> UInt64? { return read() } func readNullTerminatedString() -> String? { var string:String? = nil var tCurrent = UnsafePointer<UInt8>(current) var count: Int = 0 // scan while (remaining > 0 && tCurrent.memory != 0) { remaining -= 1 count += 1 tCurrent = tCurrent.successor() } // create string if available if (remaining > 0 && tCurrent.memory == 0) { if let nsString = NSString(bytes: current, length: count, encoding: encoding) { string = nsString as String current = UnsafePointer<()>(tCurrent.successor()) remaining -= 1 } } return string } func readData(length: Int) -> NSData? { if length > remaining { return nil } remaining -= length return NSData(bytes: current, length: length) } }
2c33866babe828c277e5e41e2aecf321
23.495146
91
0.564407
false
false
false
false
bangslosan/ImagePickerSheetController
refs/heads/master
ImagePickerSheetController/ImagePickerSheetController/PreviewSupplementaryView.swift
mit
6
// // PreviewSupplementaryView.swift // ImagePickerSheet // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class PreviewSupplementaryView : UICollectionReusableView { private let button: UIButton = { let button = UIButton() button.tintColor = .whiteColor() button.userInteractionEnabled = false button.setImage(PreviewSupplementaryView.checkmarkImage, forState: .Normal) button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, forState: .Selected) return button }() var buttonInset = UIEdgeInsetsZero var selected: Bool = false { didSet { button.selected = selected reloadButtonBackgroundColor() } } class var checkmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } class var selectedCheckmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initialize() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { addSubview(button) } // MARK: - Other Methods override func prepareForReuse() { super.prepareForReuse() selected = false } override func tintColorDidChange() { super.tintColorDidChange() reloadButtonBackgroundColor() } private func reloadButtonBackgroundColor() { button.backgroundColor = (selected) ? tintColor : nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() button.sizeToFit() button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom) button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0 } }
c8580f8b5d2cf474e05f2cb53a46e9af
27.021739
135
0.641195
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/IDE/print_clang_bool_bridging.swift
apache-2.0
9
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -print-module -source-filename %s -module-to-print=BoolBridgingTests -function-definitions=false -print-regular-comments -skip-unavailable -F %S/Inputs/mock-sdk > %t.txt // RUN: diff -u <(tail +9 %s) %t.txt // REQUIRES: objc_interop // EXPECTED OUTPUT STARTS BELOW THIS LINE. @_exported import Foundation // stdbool.h uses #define, so this test does as well. func testCBool(_: Bool) -> Bool func testObjCBool(_: Bool) -> Bool func testDarwinBoolean(_: Bool) -> Bool typealias CBoolTypedef = Bool typealias ObjCBoolTypedef = ObjCBool typealias DarwinBooleanTypedef = DarwinBoolean func testCBoolTypedef(_: CBoolTypedef) -> CBoolTypedef func testObjCBoolTypedef(_: Bool) -> Bool func testDarwinBooleanTypedef(_: Bool) -> Bool func testCBoolPointer(_: UnsafeMutablePointer<Bool>) -> UnsafePointer<Bool> func testObjCBoolPointer(_: UnsafeMutablePointer<ObjCBool>) -> UnsafePointer<ObjCBool> func testDarwinBooleanPointer(_: UnsafeMutablePointer<DarwinBoolean>) -> UnsafePointer<DarwinBoolean> typealias CBoolFn = @convention(c) (Bool) -> Bool typealias ObjCBoolFn = @convention(c) (ObjCBool) -> ObjCBool typealias DarwinBooleanFn = @convention(c) (DarwinBoolean) -> DarwinBoolean typealias CBoolBlock = (Bool) -> Bool typealias ObjCBoolBlock = (Bool) -> Bool typealias DarwinBooleanBlock = (Bool) -> Bool func testCBoolFnToBlock(_: @escaping @convention(c) (Bool) -> Bool) -> (Bool) -> Bool func testObjCBoolFnToBlock(_: @escaping @convention(c) (ObjCBool) -> ObjCBool) -> (Bool) -> Bool func testDarwinBooleanFnToBlock(_: @escaping @convention(c) (DarwinBoolean) -> DarwinBoolean) -> (Bool) -> Bool func testCBoolFnToBlockTypedef(_: @escaping CBoolFn) -> CBoolBlock func testObjCBoolFnToBlockTypedef(_: @escaping ObjCBoolFn) -> ObjCBoolBlock func testDarwinBooleanFnToBlockTypedef(_: @escaping DarwinBooleanFn) -> DarwinBooleanBlock typealias CBoolFnToBlockType = (CBoolFn) -> CBoolBlock typealias ObjCBoolFnToBlockType = (ObjCBoolFn) -> ObjCBoolBlock typealias DarwinBooleanFnToBlockType = (DarwinBooleanFn) -> DarwinBooleanBlock var globalObjCBoolFnToBlockFP: @convention(c) (ObjCBoolFn) -> @convention(block) (ObjCBool) -> ObjCBool var globalObjCBoolFnToBlockFPP: UnsafeMutablePointer<@convention(c) (ObjCBoolFn) -> @convention(block) (ObjCBool) -> ObjCBool>? var globalObjCBoolFnToBlockBP: @convention(block) (ObjCBoolFn) -> @convention(block) (ObjCBool) -> ObjCBool var globalCBoolFn: CBoolFn var globalObjCBoolFn: ObjCBoolFn var globalDarwinBooleanFn: DarwinBooleanFn var globalCBoolBlock: @convention(block) (Bool) -> Bool var globalObjCBoolBlock: @convention(block) (ObjCBool) -> ObjCBool var globalDarwinBooleanBlock: @convention(block) (DarwinBoolean) -> DarwinBoolean class Test : NSObject { var propCBool: Bool var propObjCBool: Bool var propDarwinBoolean: Bool func testCBool(_ b: Bool) -> Bool func testObjCBool(_ b: Bool) -> Bool func testDarwinBoolean(_ b: Bool) -> Bool var propCBoolBlock: (Bool) -> Bool var propObjCBoolBlock: (Bool) -> Bool var propDarwinBooleanBlock: (Bool) -> Bool func testCBoolFn(toBlock fp: @escaping @convention(c) (Bool) -> Bool) -> (Bool) -> Bool func testObjCBoolFn(toBlock fp: @escaping @convention(c) (ObjCBool) -> ObjCBool) -> (Bool) -> Bool func testDarwinBooleanFn(toBlock fp: @escaping @convention(c) (DarwinBoolean) -> DarwinBoolean) -> (Bool) -> Bool func produceCBoolBlockTypedef(_ outBlock: AutoreleasingUnsafeMutablePointer<(@convention(block) (Bool) -> Bool)?>) func produceObjCBoolBlockTypedef(_ outBlock: AutoreleasingUnsafeMutablePointer<(@convention(block) (ObjCBool) -> ObjCBool)?>) func produceDarwinBooleanBlockTypedef(_ outBlock: AutoreleasingUnsafeMutablePointer<(@convention(block) (DarwinBoolean) -> DarwinBoolean)?>) init() }
8c798e1bec23a6af4e2a3fe6eae42605
44.975904
200
0.759958
false
true
false
false
CUITCHE/code-obfuscation
refs/heads/master
obfuse-code/obfuse-code/FileAnalysis.swift
mit
1
// // FileAnalysis.swift // CodeObfuscation // // Created by hejunqiu on 2017/8/15. // Copyright © 2017年 CHE. All rights reserved. // import Foundation fileprivate extension String { static let __scanTagString__ = "CO_CONFUSION_" static let __method__ = "METHOD" static let __property__ = "PROPERTY" } class FileAnalysis { enum FileAnalysisError: Error { case codeExistsError(code: Int) case generic(code: Int, message: String) } fileprivate let filepaths: [String] let cohFilepath: String fileprivate(set) var clazzs = [String: Clazz]() fileprivate(set) var protocols = [String: Protocol]() fileprivate var outStream: FileOutStream init(filepaths: [String], written targetpath: String) { self.filepaths = filepaths self.cohFilepath = targetpath if let obj = FileOutStream.init(filepath: targetpath) { self.outStream = obj } else { exit(-1) } } func start() { outStream.read() for filepath in self.filepaths { do { let filecontent = try String.init(contentsOfFile: filepath) if self.outStream.worth(parsing: filecontent, filename: (filepath as NSString).lastPathComponent) { try self._analysisClass(with: filecontent) } } catch { print(error) continue } } } func write() { guard self.outStream.needGenerateObfuscationCode else { return } self.outStream.begin() for (_, value) in self.clazzs { var dict = [String: String]() dict[value.categoryname ?? value.classname] = value.fakename ?? "" for prop in value.properties { dict[prop.name] = prop.fakename ?? "" } for method in value.methods { for sel in method.selectors { dict[sel.name] = sel.fakename ?? "" } } self.outStream.write(obfuscation: dict) } self.outStream.end() } } fileprivate extension FileAnalysis { func _analysisClass(with classString: String) throws { var scanner = Scanner.init(string: classString) scanner.charactersToBeSkipped = .whitespacesAndNewlines var scannedRanges = [NSRange]() var scannedRange = NSMakeRange(0, 0) while scanner.scanUpTo("@interface", into: nil) { scannedRange.location = scanner.scanLocation if scanner.scanUpTo("CO_CONFUSION_CLASS", into: nil) == false { continue } scanner.scanString("CO_CONFUSION_CLASS", into: nil) var className: NSString? = nil if scanner.scanUpTo(":", into: &className) { // 类首次声明 scanner.scanString(":", into: nil) var superName: NSString? = nil guard scanner.scanUpToCharacters(from: .whitespacesAndNewlines, into: &superName) else { throw FileAnalysisError.codeExistsError(code: 1) } let classname = className!.trimmingCharacters(in: .whitespacesAndNewlines) let clazz = Clazz.init(classname: classname, supername: superName as String?) var classDeclaredString: NSString? = nil if scanner.scanUpTo("@end", into: &classDeclaredString) { try self._analysisFile(with: classDeclaredString! as String, into: clazz, methodFlag: ";") self.clazzs[classname] = clazz registerClassRelationship(classname: classname, super: clazz.supername!, clazz: clazz); scanner.scanString("@end", into: nil) scannedRange.length = scanner.scanLocation - scannedRange.location scannedRanges.append(scannedRange) } else { throw FileAnalysisError.codeExistsError(code: -13) } } } let restString = NSMutableString.init(string: classString) for range in scannedRanges { restString.replaceCharacters(in: range, with: "") } scanner = Scanner.init(string: restString as String) // 扫描类别和扩展 while scanner.scanUpTo("@interface", into: nil) && scanner.isAtEnd == false { scanner.charactersToBeSkipped = .whitespacesAndNewlines scanner.scanString("@interface", into: nil) var className: NSString? = nil if scanner.scanUpTo("(", into: &className) { if scanner.scanUpTo("CO_CONFUSION_CATEGORY", into: nil) == false { continue } scanner.scanString("CO_CONFUSION_CATEGORY", into: nil) let classname = className!.trimmingCharacters(in: .whitespacesAndNewlines) var category: NSString? = nil var clazz: Clazz? = nil if scanner.scanUpTo(")", into: &category) { if category!.length == 0 { // 这是扩展。扩展必须从已有的分析的字典里取;否则报错 clazz = self.clazzs[classname] if clazz == nil { print("category(\(classname)): no such class.") exit(-1) } } else { // 这是类别。类别可以自建分析内容 let identifier = "\(classname) (\(category!))" clazz = self.clazzs[identifier] if clazz == nil { clazz = Clazz.init(classname: classname, supername: nil) clazz?.categoryname = category as String? self.clazzs[identifier] = clazz! } } } if let clazz = clazz { var fileString: NSString? = nil if scanner.scanUpTo("@end", into: &fileString) { try self._analysisFile(with: fileString! as String, into: clazz, methodFlag: ";") scanner.scanString("@end", into: nil) } else { throw FileAnalysisError.codeExistsError(code: -12) } } } scanner.charactersToBeSkipped = nil } // protocol 分析 scanner = Scanner.init(string: restString as String) scanner.charactersToBeSkipped = .whitespacesAndNewlines let protocolScannedFlag = CharacterSet.init(charactersIn: "<") while scanner.scanUpTo("@protocol", into: nil) { if scanner.scanUpTo("CO_CONFUSION_PROTOCOL", into: nil) == false { continue } scanner.scanString("CO_CONFUSION_PROTOCOL", into: nil) scannedRange.location = scanner.scanLocation var protocolName: NSString? = nil if scanner.scanUpToCharacters(from: protocolScannedFlag, into: &protocolName) { scanner.scanCharacters(from: protocolScannedFlag, into: nil) let protocolname = protocolName!.trimmingCharacters(in: .whitespacesAndNewlines) guard self.protocols[protocolname] == nil else { throw FileAnalysisError.codeExistsError(code: -10) } let proto = Protocol.init(name: protocolname) var protocolString: NSString? = nil if scanner.scanUpTo("@end", into: &protocolString) { try self._analysisProtocol(with: protocolString! as String, into: proto) self.protocols[protocolname] = proto scanner.scanString("@end", into: nil) } else { throw FileAnalysisError.codeExistsError(code: -11) } } } // implementation 分析 scanner = Scanner.init(string: classString) let implementationFlag = CharacterSet.init(charactersIn: "-+@(\n \t") while scanner.scanUpTo("@implementation", into: nil) && scanner.isAtEnd == false { scanner.scanString("@implementation", into: nil) var className: NSString? = nil if scanner.scanUpToCharacters(from: implementationFlag, into: &className) == false { continue } var category: String? = nil var categoryRange = NSMakeRange(NSNotFound, 0) let cs = classString as NSString for idx in scanner.scanLocation..<cs.length { let ch = classString.characters[classString.characters.index(classString.startIndex, offsetBy: idx)] if ch == (" ") || ch == ("\n") || ch == ("\t") { continue } if ch == ("(") { categoryRange.location = idx + 1 } else if ch == (")") { categoryRange.length = idx - categoryRange.location category = cs.substring(with: categoryRange).trimmingCharacters(in: .whitespacesAndNewlines) break } else { if categoryRange.location == NSNotFound { break } } } var clazz: Clazz? = nil if let category = category { if category.characters.count == 0 { clazz = self.clazzs[className! as String] } else { let identifier = "\(className! as String) (\(category))" clazz = self.clazzs[identifier] } } else { clazz = self.clazzs[className! as String] } guard clazz != nil else { throw FileAnalysisError.codeExistsError(code: -1) } var classDeclaredString: NSString? = nil if scanner.scanUpTo("@end", into: &classDeclaredString) { try self._analysisFile(with: classDeclaredString! as String, into: clazz!, methodFlag: "{") } else { throw FileAnalysisError.codeExistsError(code: -14) } } } /* 该方法传入的是整个文件(.h, .m, .mm)的内容 * 属性混淆实例:@property (nonatomic, strong) NSString * CO_CONFUSION_PROPERTY prop1; * 方法混淆实例: * CO_CONFUSION_METHOD * - (void)makeFoo:(NSString *)foo1 arg2:(NSInteger)arg2; */ func _analysisFile(with fileString: String, into clazz: Clazz, methodFlag: String) throws { let scanner = Scanner.init(string: fileString) var string: NSString? = nil let methodPropertyScannedTag = CharacterSet.init(charactersIn: "+-").union(.whitespacesAndNewlines) while scanner.scanUpTo(.__scanTagString__, into: &string) && scanner.isAtEnd == false { scanner.scanString(.__scanTagString__, into: nil) // 扫描property或者method string = nil scanner.scanUpToCharacters(from: methodPropertyScannedTag, into: &string) if string!.isEqual(to: .__property__) { var property: NSString? = nil if scanner.scanUpTo(";", into: &property) { let range = property!.range(of: " ") if range.location != NSNotFound { if range.location == 0 { throw FileAnalysisError.generic(code: -77, message: "scanning property occurs error: \(property!)") } else { property = property?.substring(to: range.location - 1) as NSString? } } clazz.add(property: Property.init(name: property! as String, location: NSMakeRange(scanner.scanLocation - property!.length, property!.length))) } } else if string!.isEqual(to: .__method__) { var method: NSString? = nil if scanner.scanUpTo(methodFlag, into: &method) && scanner.isAtEnd == false { clazz.add(method: Function.init(name: method! as String, location: NSMakeRange(scanner.scanLocation - method!.length, method!.length))) try self._analysisFunction(with: method!.trimmingCharacters(in: .whitespacesAndNewlines), into: clazz.methods.last!) } } } } // example: - (void)makeFoo:(NSString *)foo1 arg2:(NSInteger)arg2 :(NSString *)arg3 func _analysisFunction(with methodString: String, into method: Function) throws { let scanner = Scanner.init(string: methodString) // 找到第一个selector var selector: NSString? = nil scanner.scanUpTo(")", into: nil) scanner.scanLocation += 1 scanner.charactersToBeSkipped = .whitespacesAndNewlines scanner.scanUpTo(":", into: &selector) guard selector != nil else { throw FileAnalysisError.codeExistsError(code: -2) } scanner.charactersToBeSkipped = nil method.add(selector: SelectorPart.init(name: selector! as String, location: NSMakeRange(scanner.scanLocation - selector!.length, selector!.length))) // 找余下的selector while scanner.scanUpTo(")", into: nil) && scanner.isAtEnd == false { scanner.scanString(")", into: nil) scanner.charactersToBeSkipped = .whitespacesAndNewlines scanner.scanUpToCharacters(from: .whitespacesAndNewlines, into: nil) if scanner.scanUpTo(":", into: &selector) && scanner.isAtEnd == false { method.add(selector: SelectorPart.init(name: selector! as String, location: NSMakeRange(scanner.scanLocation - selector!.length, selector!.length))) } scanner.charactersToBeSkipped = nil } } func _analysisProtocol(with protocolString: String, into proto: Protocol) throws { let scanner = Scanner.init(string: protocolString) var string: NSString? = nil let methodPropertyScannedTag = CharacterSet.init(charactersIn: "+-").union(.whitespacesAndNewlines) while scanner.scanUpTo(.__scanTagString__, into: &string) && scanner.isAtEnd == false { scanner.scanString(.__scanTagString__, into: nil) // 扫描property或者method string = nil scanner.scanUpToCharacters(from: methodPropertyScannedTag, into: &string) if string!.isEqual(to: .__property__) { var property: NSString? = nil if scanner.scanUpTo(";", into: &property) { let range = property!.range(of: " ") if range.location != NSNotFound { if range.location == 0 { throw FileAnalysisError.generic(code: -77, message: "scanning property occurs error: \(property!) in protocol(\(proto.name))") } else { property = property?.substring(to: range.location - 1) as NSString? } } proto.add(property: Property.init(name: property! as String, location: NSMakeRange(scanner.scanLocation - property!.length, property!.length))) } } else if string!.isEqual(to: .__method__) { var method: NSString? = nil if scanner.scanUpTo(";", into: &method) && scanner.isAtEnd == false { proto.add(method: Function.init(name: method! as String, location: NSMakeRange(scanner.scanLocation - method!.length, method!.length))) try self._analysisFunction(with: method!.trimmingCharacters(in: .whitespacesAndNewlines), into: proto.methods.last!) } } } } }
56bd5fa457db778ea33fb0b0c4f97f59
46.226866
164
0.552873
false
false
false
false
psharanda/Jetpack
refs/heads/master
Sources/Observable+Binding.swift
mit
1
// // Created by Pavel Sharanda on 10/5/19. // Copyright © 2019 Jetpack. All rights reserved. // import Foundation extension ObserveValueProtocol { public func bind<T: UpdateValueProtocol>(to bindable: T) -> Disposable where T.UpdateValueType == ValueType { return subscribe { result in bindable.update(result) } } public func bind<T: UpdateValueProtocol>(to bindable: T) -> Disposable where T.UpdateValueType == ValueType? { return subscribe { result in bindable.update(result) } } public func bind<T: MutateValueProtocol>(to bindable: T, reduce: @escaping (inout T.MutateValueType, ValueType) -> Void ) -> Disposable { return subscribe { result in bindable.mutate { reduce(&$0, result) } } } public func bind<T: MutateValueProtocol>(to bindable: T, keyPath: WritableKeyPath<T.MutateValueType, ValueType>) -> Disposable { return bind(to: bindable) { $0[keyPath: keyPath] = $1 } } }
eccf0583f2fc5a62cf0553223b85bdd1
28.324324
141
0.606452
false
false
false
false
welbesw/BigcommerceApi
refs/heads/master
Example/BigcommerceApi/OrderStatusesViewController.swift
mit
1
// // OrderStatusesViewController.swift // BigcommerceApi // // Created by William Welbes on 8/11/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import UIKit import BigcommerceApi class OrderStatusesViewController: UITableViewController { var orderStatuses:[BigcommerceOrderStatus] = [] override func viewDidLoad() { super.viewDidLoad() //Load the order statuses from the API BigcommerceApi.sharedInstance.getOrderStatuses { (orderStatuses, error) -> () in if(error == nil) { DispatchQueue.main.async { self.orderStatuses = orderStatuses self.tableView.reloadData() } } else { let alertController = UIAlertController(title: "Error", message: "Error loading statuses: \(error!.localizedDescription)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapDoneButton(_ sender: AnyObject?) { DefaultsManager.sharedInstance.orderStatusIdFilter = nil self.dismiss(animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return self.orderStatuses.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "orderStatusCell", for: indexPath) // Configure the cell... let orderStatus = self.orderStatuses[indexPath.row] cell.textLabel!.text = "\(orderStatus.id) - " + orderStatus.name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //Use the selected row as the status filter tableView.deselectRow(at: indexPath, animated: true) let orderStatus = self.orderStatuses[indexPath.row] DefaultsManager.sharedInstance.orderStatusIdFilter = orderStatus.id self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
a918df40971c9f115d5a1a9ba43029be
32.641304
162
0.644911
false
false
false
false
MegaManX32/CD
refs/heads/master
CD/CD/View Controllers/SignupViewController.swift
mit
1
// // SignupViewController.swift // CustomDeal // // Created by Vladislav Simovic on 6/21/16. // Copyright © 2016 Vladislav Simovic. All rights reserved. // import UIKit import MBProgressHUD class SignupViewController: UIViewController { // MARK: - Properties @IBOutlet weak var firstNameTextField: IntroTextField! @IBOutlet weak var lastNameTextField: IntroTextField! @IBOutlet weak var emailTextField: IntroTextField! @IBOutlet weak var passwordTextField: IntroTextField! @IBOutlet weak var confirmPasswordTextField: IntroTextField! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // prepare text fields self.prepareTextFields() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - View Preparation func prepareTextFields() { self.firstNameTextField.placeholder = NSLocalizedString("First Name", comment: "First Name") self.lastNameTextField.placeholder = NSLocalizedString("Last Name", comment: "Last Name") self.emailTextField.placeholder = NSLocalizedString("Email Address", comment: "Email Address") self.passwordTextField.placeholder = NSLocalizedString("Password", comment: "Password") self.confirmPasswordTextField.placeholder = NSLocalizedString("Confirm Password", comment: "Confirm Password") } // MARK: - User Actions @IBAction func signupAction() { // try to create new User MBProgressHUD.showAdded(to: self.view, animated: true) let context = CoreDataManager.sharedInstance.createScratchpadContext(onMainThread: false) context.perform { [unowned self] in // create new user and populate it with data let newUser = User(context: context) newUser.firstName = self.firstNameTextField.text newUser.lastName = self.lastNameTextField.text newUser.email = self.emailTextField.text newUser.password = self.passwordTextField.text // create of or update user NetworkManager.sharedInstance.createOrUpdate(user: newUser, context: context, success: { [unowned self] (userID) in let controller = self.storyboard?.instantiateViewController(withIdentifier: "SignupFinishedViewController") as! SignupFinishedViewController controller.userID = userID self.show(controller, sender: self) MBProgressHUD.hide(for: self.view, animated: true) }, failure: { [unowned self] (errorMessage) in print(errorMessage) MBProgressHUD.hide(for: self.view, animated: true) }) } } @IBAction func backAction() { _ = self.navigationController?.popViewController(animated: true) } }
f81f2a4ea558a87fc89501e2ea4d5744
36.848101
156
0.660201
false
false
false
false
squall09s/VegOresto
refs/heads/master
VegoResto/Constantes.swift
gpl-3.0
1
// // Constantes.swift // VegoResto // // Created by Laurent Nicolas on 01/04/2016. // Copyright © 2016 Nicolas Laurent. All rights reserved. // import UIKit import Alamofire import Keys /// Device check /// Device check struct Device { static let WIDTH = UIScreen.main.bounds.size.width static let HEIGHT = UIScreen.main.bounds.size.height private static let maxLength = max(WIDTH, HEIGHT) private static let minLength = min(WIDTH, HEIGHT) static let IS_IPHONE_4 = ( Double( UIScreen.main.bounds.height) == Double(480.0) ) static let IS_IPHONE_5 = ( Double( UIScreen.main.bounds.height) == Double(568.0) ) static let IS_IPHONE_6 = ( Double( UIScreen.main.bounds.height) == Double(667.0) ) static let IS_IPHONE_6_PLUS = ( Double( UIScreen.main .bounds.height) == Double(736.0) ) static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && maxLength == 1024.0 static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && maxLength == 1366.0 static let IS_TV = UIDevice.current.userInterfaceIdiom == .tv } struct Debug { /** Methode permettant de réaliser des Logs uniquement en Debug via l'instruction Debug.log("mon log") :param: le message :returns: void */ static func log(object: Any) { if _isDebugAssertConfiguration() { Swift.print("DEBUG", object) } } } let COLOR_ORANGE: UIColor = UIColor(hexString: "F79F21") let COLOR_BLEU: UIColor = UIColor(hexString: "37A8DA") let COLOR_VERT: UIColor = UIColor(hexString: "70B211") let COLOR_VIOLET: UIColor = UIColor(hexString: "D252B9") let COLOR_GRIS_BACKGROUND: UIColor = UIColor(hexString: "EDEDED") let COLOR_GRIS_FONCÉ: UIColor = UIColor(hexString: "898989") let KEY_LAST_SYNCHRO = "DateLastShynchro" let INTERVAL_REFRESH_DATA: Int = 60*60 // byWeek = 24*60*60*7 struct APIConfig { static var apiBaseUrl: URL { return URL(string: VegoRestoKeys().apiBaseUrl)! } static var apiClientId: String { return VegoRestoKeys().apiClientId } static var apiClientSecret: String { return VegoRestoKeys().apiClientSecret } static var apiClientIss: String { return "\(apiBaseUrl.scheme!)://\(apiBaseUrl.host!)" } static var apiBasicAuthLogin: String { return VegoRestoKeys().apiBasicAuthLogin } static var apiBasicAuthPassword: String { return VegoRestoKeys().apiBasicAuthPassword } static func defaultHTTPHeaders() -> [String:String] { let authHeader = Request.authorizationHeader(user: apiBasicAuthLogin, password: apiBasicAuthPassword)! var headers = SessionManager.defaultHTTPHeaders headers[authHeader.key] = authHeader.value return headers } }
e0b0405dc692a48f467a930612ab5373
29.064516
110
0.677754
false
false
false
false
maximedegreve/Walllpaper
refs/heads/master
Sources/App/Controllers/LoginController.swift
mit
1
// // LoginController.swift // Walllpaper // // Created by Maxime De Greve on 19/02/2017. // // import Vapor import HTTP import Turnstile import Auth final class LoginController { func addRoutes(to drop: Droplet) { drop.get("admin/login", handler: loginAdmin) drop.get("api/login-callback", handler: callback) drop.get("api/login-mobile", handler: loginMobile) } func callback(_ request: Request) throws -> ResponseRepresentable { guard let code = request.data["code"]?.string else { throw Abort.badRequest } guard let accessToken = try Dribbble.getToken(code: code) else { throw Abort.badRequest } let token = DribbbleAccessToken(string: accessToken) if try request.session().data["isAdmin"]?.bool == true{ try request.auth.login(token) return Response(redirect: "/admin") } guard let user = try User.authenticate(credentials: token) as? User else { throw Abort.badRequest } return Response(redirect: "/api/me?token=\(user.accessToken)") } func loginAdmin(_ request: Request) throws -> ResponseRepresentable { try request.session().data["isAdmin"] = true return Response(redirect: Dribbble.loginLink()) } func loginMobile(_ request: Request) throws -> ResponseRepresentable { return Response(redirect: Dribbble.loginLink()) } }
5249adff94dce2e1e149f2da56597766
26.070175
82
0.601426
false
false
false
false
Jnosh/swift
refs/heads/master
test/SILGen/availability_query.swift
apache-2.0
14
// RUN: %target-swift-frontend -emit-sil %s -target x86_64-apple-macosx10.50 -verify // RUN: %target-swift-frontend -emit-silgen %s -target x86_64-apple-macosx10.50 | %FileCheck %s // REQUIRES: OS=macosx // CHECK-LABEL: sil{{.+}}@main{{.*}} { // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8 // CHECK: [[FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10.53.8, iOS 7.1, *) { } // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: cond_br [[TRUE]] // Since we are compiling for an unmentioned platform (OS X), we check against the minimum // deployment target, which is 10.50 if #available(iOS 7.1, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10.52, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(macOS 10.52, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10, *) { } // CHECK: } func doThing() {} func testUnreachableVersionAvailable(condition: Bool) { if #available(OSX 10.0, *) { doThing() // no-warning return } else { doThing() // FIXME-warning {{will never be executed}} } if true { doThing() // no-warning } if false { // expected-note {{condition always evaluates to false}} doThing() // expected-warning {{will never be executed}} } } func testUnreachablePlatformAvailable(condition: Bool) { if #available(iOS 7.1, *) { doThing() // no-warning return } else { doThing() // no-warning } if true { doThing() // no-warning } if false { // expected-note {{condition always evaluates to false}} doThing() // expected-warning {{will never be executed}} } } func testUnreachablePlatformAvailableGuard() { guard #available(iOS 7.1, *) else { doThing() // no-warning return } doThing() // no-warning }
5132ab3d67d9e93a40669d265ab5f6b5
38.692308
170
0.64175
false
false
false
false
saraheolson/TechEmpathy-iOS
refs/heads/master
TechEmpathy/TechEmpathy/Controllers/LIFXManager.swift
apache-2.0
1
// // LIFXManager.swift // TechEmpathy // // Created by Sarah Olson on 4/21/17. // Copyright © 2017 SarahEOlson. All rights reserved. // import Foundation class LIFXManager { static let sharedInstance: LIFXManager = LIFXManager() private init() { if let lifxPrompted = UserDefaults.standard.value(forKey: self.LIFX_PromptedKey) as? String { if lifxPrompted == LIFX_PromptedValue { self.hasBeenPromptedForLifx = true } } } private let LIFX_APIKey = "com.saraheolson.techempathy.LIFXToken" private let LIFX_PromptedKey = "com.saraheolson.techempathy.LIFXPrompted" private let LIFX_PromptedValue = "prompted" public private(set) var hasLamp = false public var hasBeenPromptedForLifx = false public func askUserForLampToken() -> UIAlertController { let alert = UIAlertController(title: "LIFX Light", message: "Do you want to integrate our app with a LIFX light?", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "LIFX API Token" } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self, weak alert] (_) in guard let strongSelf = self, let strongAlert = alert else { return } strongSelf.hasBeenPromptedForLifx = true UserDefaults.standard.setValue(strongSelf.LIFX_PromptedValue, forKey: strongSelf.LIFX_PromptedKey) if let text = strongAlert.textFields![0].text { UserDefaults.standard.setValue(text, forKey: strongSelf.LIFX_APIKey) strongSelf.hasLamp = true } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) return alert } public func updateAllLights(color: String, completion: @escaping (Bool) -> ()) { guard let lifxToken = UserDefaults.standard.value(forKey: self.LIFX_APIKey) as? String else { return } let loginString = String(format: "%@:%@", lifxToken, "") let loginData = loginString.data(using: String.Encoding.utf8)! let base64LoginString = loginData.base64EncodedString() // create the request let url = URL(string: "https://api.lifx.com/v1/lights/all/state")! var request = URLRequest(url: url) request.httpMethod = "PUT" let parameters = [ "power": "on", "color": color, ] do { if let data = try JSONSerialization.data(withJSONObject: parameters, options:JSONSerialization.WritingOptions(rawValue: 0)) as NSData? { request.httpBody = data as Data request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length") } } catch { print("Error creating parameters for LIFX API call.") completion(false) } let config = URLSessionConfiguration.default let authString = "Basic \(base64LoginString)" config.httpAdditionalHeaders = ["Authorization" : authString] let session = URLSession(configuration: config) session.dataTask(with: request) { ( data, response, error) in if error != nil { print("Error occurred: \(String(describing: error))") completion(false) } do { if let data = data, let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let results = json["results"] as? [[String: Any]], let status = results[0]["status"] as? String { if status == "ok" { print("Lit up.") completion(true) } } } catch { print("Error deserializing JSON: \(error)") completion(false) } }.resume() } }
ba952252bc8ec3a62da1e8905b0522e9
36.474138
144
0.551875
false
false
false
false
Derek316x/iOS8-day-by-day
refs/heads/master
01-swift-intro/SwiftIntro.playground/Contents.swift
apache-2.0
21
// Playground - noun: a place where people can play import Cocoa /******************* MUTABILITY ******************/ struct MyStruct { let t: Int var u: String } var struct1 = MyStruct(t: 15, u: "Hello") //struct1.t = 13 // Error: t is an immutable property struct1.u = "GoodBye" struct1 = MyStruct(t: 10, u: "You") let struct2 = MyStruct(t: 12, u: "World") //struct2.u = "Planet" // Error: struct2 is immutable //struct2 = MyStruct(t: 10, u: "Defeat") // Error: struct2 is an immutable ref class MyClass { let t: Int var u: String init(t: Int, u: String) { self.t = t self.u = u } } var class1 = MyClass(t: 15, u: "Hello") //class1.t = 13 // Error: t is an immutable property class1.u = "GoodBye" class1 = MyClass(t: 10, u: "You") let class2 = MyClass(t: 12, u: "World") class2.u = "Planet" // No error //class2 = MyClass(t: 11, u: "Geoid") Error: class2 is an immutable reference var array1 = [1,2,3,4] array1.append(5) array1[0] = 27 array1 array1 = [3,2] let array2 = [4,3,2,1] //array2.append(0) // Error: array2 is immutable //array2[2] = 36 // Error: array2 is immutable //array2 = [5,6] // Error: cannot reassign an immutable reference /******************* AnyObject ******************/ let myString: AnyObject = "hello" myString.cornerRadius // Returns nil func someFunc(parameter: AnyObject!) { if let castedParameter = parameter as? NSString { // Do something } } func someOtherFunc(parameter: AnyObject!) { let castedParameter = parameter as! NSString // Do something } func someArrayFunc(parameter: [AnyObject]!) { let newArray = parameter as! [NSString] // Do something } /******************* Protocols ******************/ protocol MyProtocol { func myProtocolMethod() -> Bool } //if let class1AsMyProtocol = class1 as? MyProtocol { // We're in //} // Error: need MyProtocol to be @objc @objc protocol MyNewProtocol { func myProtocolMethod() -> Bool } if let class1AsMyNewProtocol = class1 as? MyNewProtocol { // We're in } /******************* Enums ******************/ enum MyEnum { case FirstType case IntType (Int) case StringType (String) case TupleType (Int, String) func prettyFormat() -> String { switch self { case .FirstType: return "No params" case .IntType(let value): return "One param: \(value)" case .StringType(let value): return "One param: \(value)" case .TupleType(let v1, let v2): return "Some params: \(v1), \(v2)" default: return "Nothing to see here" } } } var enum1 = MyEnum.FirstType enum1.prettyFormat() enum1 = .TupleType(12, "Hello") enum1.prettyFormat()
d490adb96a1400bfdddf79359e1141a2
19.143939
78
0.615269
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Package.swift
mit
1
// swift-tools-version:5.5 import PackageDescription import class Foundation.ProcessInfo // get environment variables let environment = ProcessInfo.processInfo.environment let dynamicLibrary = environment["SWIFT_BUILD_DYNAMIC_LIBRARY"] != nil let generateCode = environment["SWIFTPM_ENABLE_PLUGINS"] != nil let buildDocs = environment["BUILDING_FOR_DOCUMENTATION_GENERATION"] != nil // force building as dynamic library let libraryType: PackageDescription.Product.Library.LibraryType? = dynamicLibrary ? .dynamic : nil var package = Package( name: "Bluetooth", platforms: [ .macOS(.v10_15), .iOS(.v13), .watchOS(.v6), .tvOS(.v13), ], products: [ .library( name: "Bluetooth", type: libraryType, targets: ["Bluetooth"] ), .library( name: "BluetoothGAP", type: libraryType, targets: ["BluetoothGAP"] ), .library( name: "BluetoothGATT", type: libraryType, targets: ["BluetoothGATT"] ), .library( name: "BluetoothHCI", type: libraryType, targets: ["BluetoothHCI"] ) ], targets: [ .target( name: "Bluetooth" ), .target( name: "BluetoothGAP", dependencies: [ "Bluetooth" ] ), .target( name: "BluetoothGATT", dependencies: [ "Bluetooth", ] ), .target( name: "BluetoothHCI", dependencies: [ "Bluetooth", "BluetoothGAP" ] ), .testTarget( name: "BluetoothTests", dependencies: [ "Bluetooth", .target( name: "BluetoothGAP", condition: .when(platforms: [.macOS, .linux, .macCatalyst, .windows]) ), .target( name: "BluetoothGATT", condition: .when(platforms: [.macOS, .linux, .macCatalyst, .windows]) ), .target( name: "BluetoothHCI", condition: .when(platforms: [.macOS, .linux, .macCatalyst, .windows]) ) ] ) ] ) // SwiftPM command plugins are only supported by Swift version 5.6 and later. #if swift(>=5.6) if buildDocs { package.dependencies += [ .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"), ] } if generateCode { for (index, _) in package.targets.enumerated() { package.targets[index].swiftSettings = [ .define("SWIFTPM_ENABLE_PLUGINS") ] } package.targets += [ .executableTarget( name: "GenerateBluetooth", dependencies: [] ), .plugin( name: "GenerateBluetoothDefinitions", capability: .buildTool(), dependencies: [ "GenerateBluetooth" ] ) ] package.targets[0].plugins = [ "GenerateBluetoothDefinitions" ] package.targets[4].plugins = [ "GenerateBluetoothDefinitions" ] } #endif
85478e19f53ad4667ada73dd49c18fc4
26.446281
98
0.501957
false
false
false
false
amnuaym/TiAppBuilder
refs/heads/master
Day6/MyShoppingListDB/MyShoppingListDB/ShoppingListViewController.swift
gpl-3.0
1
// // ShoppingListViewController.swift // MyShoppingListDB // // Created by DrKeng on 9/16/2560 BE. // Copyright © 2560 ANT. All rights reserved. // import UIKit import CoreData class ShoppingListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { //ตัวแปรสำหรับเก็บข้อมูล List ของ ShoppingItems var myShoppingItemsList : [AnyObject]? = [] //Add Variables for Item Category store var myItemCategoriesList : [AnyObject]? = [] @IBOutlet weak var mySegmentedControl: UISegmentedControl! @IBOutlet weak var myTableView: UITableView! //MARK: Customized SegmentedControl Methods func customizedSegmentedControlTab(){ //Delete All Segments mySegmentedControl.removeAllSegments() //Add first segment and some more mySegmentedControl.insertSegment(withTitle: "All", at: 0, animated: false) for myIndex in 0..<myItemCategoriesList!.count{ let myItemCategory = myItemCategoriesList![myIndex] let myItemName = myItemCategory.value(forKey: "CategoryName") as! String mySegmentedControl.insertSegment(withTitle: myItemName, at: myIndex + 1, animated: false) } } func displayShoppingItemsByItemCategory (categoryNumber : Int){ // Create AppDelegate Object to enable PersistentContainer(Core Data) Access let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem") if categoryNumber != 0 { let myItemCategory = myItemCategoriesList![categoryNumber - 1] as! NSManagedObject //Specifiy Data Query let myPredicate = NSPredicate(format: "itemCategory = %@", myItemCategory) myFetchRequest.predicate = myPredicate } do{ myShoppingItemsList = try myContext.fetch(myFetchRequest) }catch let error as NSError{ print(error.description) } self.myTableView.reloadData() } @IBAction func selectSegmentMethod() { let mySelection = mySegmentedControl.selectedSegmentIndex self.displayShoppingItemsByItemCategory(categoryNumber: mySelection) } override func viewDidLoad() { super.viewDidLoad() self.title = "My Shopping List" myTableView.delegate = self myTableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { //สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem") //Add Fetch data by Category let myCategodyFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCategory") do{ myShoppingItemsList = try myContext.fetch(myFetchRequest) //Read Iteam Category from Database myItemCategoriesList = try myContext.fetch(myCategodyFetchRequest) }catch let error as NSError{ print(error.description) } self.myTableView.reloadData() self.customizedSegmentedControlTab() mySegmentedControl.selectedSegmentIndex = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myShoppingItemsList!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // Configure the cell... let myShoppingItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject let myItemName = myShoppingItem.value(forKey: "itemName") as! String let myItemNumber = myShoppingItem.value(forKey: "itemNumber") as! Int let myItemPrice = myShoppingItem.value(forKey: "itemPrice") as! Float let myItemStatus = myShoppingItem.value(forKey: "itemStatus") as! Int //เช็ค Status เพื่อเปลี่ยนสีของ Font if myItemStatus == 0 { cell.textLabel?.textColor = UIColor.orange cell.detailTextLabel?.textColor = UIColor.orange } else{ cell.textLabel?.textColor = UIColor.black cell.detailTextLabel?.textColor = UIColor.black } cell.textLabel?.text = myItemName cell.detailTextLabel?.text = "จำนวน \(myItemNumber) | ราคาต่อหน่วย \(myItemPrice) บาท" return cell } //สร้างปุ่ม (Action) ในแต่ละ Row และกำหนดฟังก์ชันการทำงาน func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .default, title: "Delete") { (action:UITableViewRowAction, indexPath:IndexPath) in print("delete at:\(indexPath)") //Log ดูที่ Console self.deleteRowFromTableView(tableView, indexPath: indexPath) } delete.backgroundColor = UIColor.red let done = UITableViewRowAction(style: .default, title: "Done") { (action:UITableViewRowAction, indexPath:IndexPath) in print("done at:\(indexPath)") self.updateItemInTableView(tableView, indexPath: indexPath) } done.backgroundColor = UIColor.orange // let button1 = UITableViewRowAction(style: .default, title: "button1") { (action:UITableViewRowAction, indexPath:IndexPath) in // } // // let button2 = UITableViewRowAction(style: .default, title: "button2") { (action:UITableViewRowAction, indexPath:IndexPath) in // } // let button3 = UITableViewRowAction(style: .default, title: "button3") { (action:UITableViewRowAction, indexPath:IndexPath) in // } // // let button4 = UITableViewRowAction(style: .default, title: "button4") { (action:UITableViewRowAction, indexPath:IndexPath) in // } // return [delete, done, button1, button2, button3, button4] return [delete, done] } //ฟังก์ชันที่ถูกเรียกเมื่อกดปุ่ม Delete func deleteRowFromTableView (_ tableView: UITableView, indexPath: IndexPath){ //สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext //ลบข้อมูลออกจาก NSManagedObject myContext.delete(myShoppingItemsList![indexPath.row] as! NSManagedObject) //ลบข้อมูลออกจาก Datasource Array myShoppingItemsList!.remove(at: indexPath.row) // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) //บันทึกการลบข้อมูล do{ try myContext.save() print("ลบข้อมูลแล้ว!") }catch let error as NSError{ print(error.description + " : ไม่สามารถบันทึกการลบข้อมูลได้") } } func updateItemInTableView(_ tableView: UITableView, indexPath: IndexPath){ let selectedItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject //สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer let myAppDelegate = UIApplication.shared.delegate as! AppDelegate let myContext = myAppDelegate.persistentContainer.viewContext selectedItem.setValue(0, forKey: "itemStatus") //บันทึกลงฐานข้อมูล do{ try myContext.save() print("บันทึกข้อมูลแล้ว!") }catch let error as NSError{ print(error.description + " : ไม่สามารถบันทึกข้อมูลได้") } //Refresh ข้อมูลใน TableView let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem") do{ myShoppingItemsList = try myContext.fetch(myFetchRequest) }catch let error as NSError{ print(error.description) } tableView.reloadData() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "UpdateSegue"{ let indexPath = self.myTableView.indexPathForSelectedRow! let selectedItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject let myAddItemViewController = segue.destination as! AddItemViewController myAddItemViewController.myShoppingItem = selectedItem } } }
f7cadc4019225a1e2d634b154401c275
37.713693
135
0.648017
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/SILGen/retaining_globals.swift
apache-2.0
2
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/globals.h -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop // This test makes sure loading from globals properly retains/releases loads from globals. // NSString was the only real problem, as the compiler treats NSString globals specially. // The rest of these are just hedges against future changes. // From header: // globalString: __strong NSString* // globalObject: __strong NSObject* // globalID: __strong id // globalArray: __strong NSArray* // globalConstArray: __strong NSArray *const func main() { Globals.sharedInstance() // Initialize globals (dispatch_once) // CHECK: global_addr @globalConstArray : $*Optional<NSArray> // CHECK: global_addr @globalArray : $*Optional<NSArray> // CHECK: global_addr @globalId : $*Optional<AnyObject> // CHECK: global_addr @globalObject : $*Optional<NSObject> // CHECK: global_addr @globalString : $*NSString // CHECK: [[globalString:%.*]] = load [copy] {{%.*}} : $*NSString // CHECK: [[bridgeStringFunc:%.*]] = function_ref @{{.*}} : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: [[wrappedString:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[globalString]] : $NSString // CHECK: [[stringMetaType:%.*]] = metatype $@thin String.Type // CHECK: [[bridgedString:%.*]] = apply [[bridgeStringFunc]]([[wrappedString]], [[stringMetaType]]) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String let string = globalString // Problematic case, wasn't being retained // CHECK: [[load_1:%.*]] = load [copy] {{%.*}} : $*Optional<NSObject> let object = globalObject // CHECK: [[load_2:%.*]] = load [copy] {{%.*}} : $*Optional<AnyObject> let id = globalId // CHECK: [[load_3:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let arr = globalArray // CHECK: [[load_4:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let constArr = globalConstArray // Make sure there's no more copies // CHECK-NOT: load [copy] print(string as Any) print(object as Any) print(id as Any) print(arr as Any) print(constArr as Any) // CHECK: [[PRINT_FUN:%.*]] = function_ref @_TFs5printFTGSaP{{.*}} : $@convention(thin) (@owned Array<Any>, @owned String, @owned String) -> () // CHECK: apply [[PRINT_FUN]]({{.*}}) // CHECK: destroy_value [[load_4]] // CHECK: destroy_value [[load_3]] // CHECK: destroy_value [[load_2]] // CHECK: destroy_value [[load_1]] // CHECK: destroy_value [[bridgedString]] // Make sure there's no more destroys // CHECK-NOT: destroy_value // CHECK: } // end sil function '_TF17retaining_globals4mainFT_T_' } main() main() // Used to crash here, due to use-after-free. main() main() main() main()
8b26b61acfe06419799410df9c236530
37.162162
188
0.651912
false
false
false
false
norwoood/swiftBook
refs/heads/master
函数式swift/Enum.playground/Contents.swift
mit
1
import UIKit //: 高效利用类型来排除程序缺陷 //: ### 枚举 //: 类型 // swift中的枚举与整数或者其他类型没有关系,swift中的枚举值创建了新的类型 enum Encoding { case ascii case nextstep case japaneseEUC case utf8 } extension Encoding { var nsStringEncoding: String.Encoding { switch self { case .ascii: return String.Encoding.ascii case .nextstep: return String.Encoding.nextstep case .japaneseEUC: return String.Encoding.japaneseEUC case .utf8: return String.Encoding.utf8 } } init?(_ encoding: String.Encoding) { switch encoding { case String.Encoding.ascii: self = .ascii case String.Encoding.nextstep: self = .nextstep case String.Encoding.japaneseEUC: self = .japaneseEUC case String.Encoding.utf8: self = .utf8 default: return nil } } var localName: String { return String.localizedName(of: nsStringEncoding) } } enum LookUpError: Error { case capitalNotFound case populationNotFound } enum PopulatiobREsult { //关联值 case success(Int) case error(LookUpError) } /* func populationOfCapital(country: String) -> PopulationResult { guard let capital = capitals[country] else { return .error(.capitalNotFound) } guard let population = cities[capital] else { return .error(.populationNotFound) } return .success(population) }*/ /* /**/ /**/ */ //添加泛型 enum Result<T>{ case success(T) case error(Error) } //swift的错误处理 //swift使用throws指明哪些地方会抛出错误,使用try 可以保证错误得到处理 //必须借助函数的返回类型来触发,当我们构建一个参数会失败的情况,使用throws的方式会变得复杂 //换用result或者编码起来就没有那个复杂,就是采用返回枚举类型,关联值关联结果 /* func populationOfCapital(country: String)throws -> Int { guard let capital = capitals[country] else { return LookUpError.capitalNotFound } guard let population = cities[capital] else { return LookUpError.populationNotFound } return population }*/ //数据类型中的代数学 //
50c9cad8169f24cd7f8d72fcf7db4672
15.338346
63
0.59457
false
false
false
false
PseudoSudoLP/Bane
refs/heads/master
Carthage/Checkouts/Moya/Moya+ReactiveCocoa.swift
mit
1
// // Moya+ReactiveCocoa.swift // Moya // // Created by Ash Furrow on 2014-08-22. // Copyright (c) 2014 Ash Furrow. All rights reserved. // import Foundation import ReactiveCocoa /// Subclass of MoyaProvider that returns RACSignal instances when requests are made. Much better than using completion closures. public class ReactiveMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, RACSignal>() /// Initializes a reactive provider. override public init(endpointsClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping(), endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution(), stubResponses: Bool = false, stubBehavior: MoyaStubbedBehavior = MoyaProvider.DefaultStubBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) { super.init(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver, stubResponses: stubResponses, networkActivityClosure: networkActivityClosure) } /// Designated request-making method. public func request(token: T) -> RACSignal { let endpoint = self.endpoint(token) // weak self just for best practices – RACSignal will take care of any retain cycles anyway, // and we're connecting immediately (below), so self in the block will always be non-nil return RACSignal.defer { [weak self] () -> RACSignal! in if let existingSignal = self?.inflightRequests[endpoint] { return existingSignal } let signal = RACSignal.createSignal { (subscriber) -> RACDisposable! in let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in if let error = error { if let statusCode = statusCode { subscriber.sendError(NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo)) } else { subscriber.sendError(error) } } else { if let data = data { subscriber.sendNext(MoyaResponse(statusCode: statusCode!, data: data, response: response)) } subscriber.sendCompleted() } } return RACDisposable { () -> Void in if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } }.publish().autoconnect() if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = signal objc_sync_exit(weakSelf) } return signal } } }
9fbe5f26d1325c5c3671a8db782780ce
44.929577
349
0.586017
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/BlogServiceDeduplicationTests.swift
gpl-2.0
1
import CoreData import XCTest @testable import WordPress class BlogServiceDeduplicationTests: XCTestCase { var contextManager: TestContextManager! var blogService: BlogService! var context: NSManagedObjectContext { return contextManager.mainContext } override func setUp() { super.setUp() contextManager = TestContextManager() blogService = BlogService(managedObjectContext: contextManager.mainContext) } override func tearDown() { super.tearDown() ContextManager.overrideSharedInstance(nil) contextManager.mainContext.reset() contextManager = nil blogService = nil } func testDeduplicationDoesNothingWhenNoDuplicates() { let account = createAccount() let blog1 = createBlog(id: 1, url: "blog1.example.com", account: account) let blog2 = createBlog(id: 2, url: "blog2.example.com", account: account) createDraft(title: "Post 1 in Blog 2", blog: blog2, id: 1) createDraft(title: "Draft 2 in Blog 2", blog: blog2) let blog3 = createBlog(id: 3, url: "blog3.example.com", account: account) XCTAssertEqual(account.blogs.count, 3) XCTAssertEqual(blog1.posts?.count, 0) XCTAssertEqual(blog2.posts?.count, 2) XCTAssertEqual(blog3.posts?.count, 0) deduplicateAndSave(account) XCTAssertEqual(account.blogs.count, 3) XCTAssertEqual(blog1.posts?.count, 0) XCTAssertEqual(blog2.posts?.count, 2) XCTAssertEqual(blog3.posts?.count, 0) } func testDeduplicationRemovesDuplicateBlogsWithoutDrafts() { let account = createAccount() createBlog(id: 1, url: "blog1.example.com", account: account) createBlog(id: 2, url: "blog2.example.com", account: account) createBlog(id: 2, url: "blog2.example.com", account: account) XCTAssertEqual(account.blogs.count, 3) deduplicateAndSave(account) XCTAssertEqual(account.blogs.count, 2) } func testDeduplicationPrefersCandidateWithLocalDrafts() { let account = createAccount() let blog1 = createBlog(id: 1, url: "blog1.example.com", account: account) let blog2a = createBlog(id: 2, url: "blog2.example.com", account: account) createDraft(title: "Post 1 in Blog 2", blog: blog2a, id: 1) createDraft(title: "Draft 2 in Blog 2", blog: blog2a) let blog2b = createBlog(id: 2, url: "blog2.example.com", account: account) let blog3a = createBlog(id: 3, url: "blog3.example.com", account: account) let blog3b = createBlog(id: 3, url: "blog3.example.com", account: account) createDraft(title: "Post 1 in Blog 3", blog: blog3b, id: 1) createDraft(title: "Draft 2 in Blog 3", blog: blog3b) XCTAssertEqual(account.blogs.count, 5) XCTAssertEqual(blog1.posts?.count, 0) XCTAssertEqual(blog2a.posts?.count, 2) XCTAssertEqual(blog2b.posts?.count, 0) XCTAssertEqual(blog3a.posts?.count, 0) XCTAssertEqual(blog3b.posts?.count, 2) deduplicateAndSave(account) XCTAssertEqual(account.blogs.count, 3) XCTAssertEqual(account.blogs, Set(arrayLiteral: blog1, blog2a, blog3b)) XCTAssertFalse(isDeleted(blog1)) XCTAssertFalse(isDeleted(blog2a)) XCTAssertTrue(isDeleted(blog2b)) XCTAssertTrue(isDeleted(blog3a)) XCTAssertFalse(isDeleted(blog3b)) XCTAssertEqual(blog1.posts?.count, 0) XCTAssertEqual(blog2a.posts?.count, 2) XCTAssertEqual(blog3b.posts?.count, 2) } func testDeduplicationMigratesLocalDrafts() { let account = createAccount() let blog1 = createBlog(id: 1, url: "blog1.example.com", account: account) let blog2a = createBlog(id: 2, url: "blog2.example.com", account: account) createDraft(title: "Post 1 in Blog 2", blog: blog2a, id: 1) createDraft(title: "Draft 2 in Blog 2", blog: blog2a) let blog2b = createBlog(id: 2, url: "blog2.example.com", account: account) createDraft(title: "Post 1 in Blog 2", blog: blog2b, id: 1) createDraft(title: "Post 3 in Blog 2", blog: blog2b, id: 3) createDraft(title: "Draft 4 in Blog 2", blog: blog2b) XCTAssertEqual(account.blogs.count, 3) XCTAssertEqual(blog1.posts?.count, 0) XCTAssertEqual(blog2a.posts?.count, 2) XCTAssertEqual(blog2b.posts?.count, 3) deduplicateAndSave(account) XCTAssertEqual(account.blogs.count, 2) XCTAssertFalse(isDeleted(blog1)) // We don't care which one is deleted, but one of them should be XCTAssertTrue(isDeleted(blog2a) != isDeleted(blog2b), "Exactly one copy of Blog 2 should have been deleted") XCTAssertEqual(blog1.posts?.count, 0) guard let blog2Final = account.blogs.first(where: { $0.dotComID == 2 }) else { return XCTFail("There should be one blog with ID = 2") } XCTAssertTrue(findPost(title: "Post 1 in Blog 2", in: blog2Final)) XCTAssertTrue(findPost(title: "Draft 2 in Blog 2", in: blog2Final)) XCTAssertTrue(findPost(title: "Draft 4 in Blog 2", in: blog2Final)) } } private extension BlogServiceDeduplicationTests { func deduplicateAndSave(_ account: WPAccount) { blogService.deduplicateBlogs(for: account) contextManager.saveContextAndWait(context) } func isDeleted(_ object: NSManagedObject) -> Bool { return object.isDeleted || object.managedObjectContext == nil } func findPost(title: String, in blog: Blog) -> Bool { return blog.posts?.contains(where: { (post) in post.postTitle?.contains(title) ?? false }) ?? false } @discardableResult func createAccount() -> WPAccount { let accountService = AccountService(managedObjectContext: context) return accountService.createOrUpdateAccount(withUsername: "twoface", authToken: "twotoken") } @discardableResult func createBlog(id: Int, url: String, account: WPAccount) -> Blog { let blog = NSEntityDescription.insertNewObject(forEntityName: "Blog", into: context) as! Blog blog.dotComID = id as NSNumber blog.url = url blog.xmlrpc = url blog.account = account return blog } @discardableResult func createDraft(title: String, blog: Blog, id: Int? = nil) -> AbstractPost { let post = NSEntityDescription.insertNewObject(forEntityName: "Post", into: context) as! Post post.postTitle = title post.blog = blog post.postID = id.map({ $0 as NSNumber }) return post } }
da82894465d139146831bfca5336a7fd
36.954545
116
0.657784
false
true
false
false
YevhenHerasymenko/SwiftGroup1
refs/heads/master
TableView/TableView/ViewController.swift
apache-2.0
1
// // ViewController.swift // TableView // // Created by Wild Deer on 26.07.16. // Copyright © 2016 spalah. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! { didSet { tableView.delegate = self tableView.dataSource = self tableView.registerNib(ContactPreviewCell.nib, forCellReuseIdentifier: ContactPreviewCell.reuseIdentifier) tableView.tableFooterView = UIView() } } var objects: [String] = ["String 0", "String1"] { didSet { guard oldValue != objects else { return } tableView.reloadData() } } 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. } } extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: ContactPreviewCell cell = tableView.dequeueReusableCellWithIdentifier(ContactPreviewCell.reuseIdentifier, forIndexPath: indexPath) as! ContactPreviewCell cell.contactNameLabel.text = objects[indexPath.row] return cell } @IBAction func newItemButtonTapped(sender: UIBarButtonItem) { var string = "" for i in 0..<objects.count { string.appendContentsOf("String \(objects.count)") if i != objects.count - 1 { string.appendContentsOf("\n") } } objects.append(string) } } extension ViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // objects.removeAtIndex(indexPath.row) tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let labelInsets = UIEdgeInsets(top: 8, left: 8, bottom: 9, right: 8) let widthLimit = tableView.frame.width - labelInsets.left - labelInsets.right let size = CGSize(width: widthLimit, height: CGFloat.max) let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(17)] let text = objects[indexPath.row] let rect = text.boundingRectWithSize(size, options: [.UsesFontLeading, .UsesLineFragmentOrigin], attributes: attributes, context: nil) return ceil(rect.height) + labelInsets.top + labelInsets.bottom } // func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // let height = CGFloat(indexPath.row + 2) * 20 // return height // } }
14699a9ad5593c819d26abc9547d890e
34.885057
142
0.650224
false
false
false
false
kanumuri9593/YVLegendView
refs/heads/master
Example/YVLegendView/ViewController.swift
mit
1
// // ViewController.swift // YVLegendView // // Created by kanumuri9593 on 07/28/2017. // Copyright (c) 2017 kanumuri9593. All rights reserved. // import UIKit import YVLegendView import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! let MultipleLegendFeed:[LegendObject] = [ LegendObject(name: "Traffic Camera", info: [ infoObject(img: #imageLiteral(resourceName: "map_camera_on"), title: "Camera - On"), infoObject(img: #imageLiteral(resourceName: "map_camera_off"), title: "Camera - On") ]), LegendObject(name: "Roadway Weather", info: [ infoObject(img: #imageLiteral(resourceName: "icon_weather_dry"), title: "Dry"), infoObject(img: #imageLiteral(resourceName: "icon_weather_wet"), title: "Wet"), infoObject(img: #imageLiteral(resourceName: "icon_weather_ice_watch"), title: "Ice Watch"), infoObject(img: #imageLiteral(resourceName: "map_weather_sun"), title: "Sun"), infoObject(img: #imageLiteral(resourceName: "icon_weather_unknown"), title: "Unkonwon") ]), LegendObject(name: "Water Level", info: [ infoObject(img: #imageLiteral(resourceName: "flooding"), title: "Flooding Occuring"), infoObject(img: #imageLiteral(resourceName: "flooding-nodata"), title: "No Dota Available") ]) ] override func viewDidLoad() { super.viewDidLoad() AddLegendView(LegendInfoFeed:MultipleLegendFeed) } internal func AddLegendView(LegendInfoFeed:[LegendObject]){ let legendView = YVLegendView() legendView.removeFromSuperview() legendView.LegendFeed = LegendInfoFeed legendView.frame = CGRect(x:UIScreen.main.bounds.width - 20.5 , y: 70, width: 219, height:300) legendView.OpenLegend = { (legendView) in UIView.animate(withDuration: 1.0, animations: { legendView.frame = CGRect(x:UIScreen.main.bounds.width - 216 , y: 70, width: 219, height:300) }) } legendView.CloseLegend = { (legendView) in UIView.animate(withDuration: 1.0, animations: { legendView.frame = CGRect(x:UIScreen.main.bounds.width - 20.5 , y: 70, width: 219, height:300) }) } view.addSubview(legendView) } }
44770eeed7e7ff1731b2128378d08774
39.440678
110
0.630763
false
false
false
false
Jnosh/swift
refs/heads/master
test/Constraints/diagnostics.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: @escaping (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, i) // expected-error{{extra argument in call}} // Position mismatch f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}} return (c: 0, i: g()) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}} return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '(Int, Double) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error{{unexpected non-void return value in void function}} } precedencegroup Starry { associativity: left higherThan: MultiplicationPrecedence } infix operator **** : Starry func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ : Starry func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> // FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to // make sure that it doesn't crash. func rdar20142523() { myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral func rdar21080030() { var s = "Hello" if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}} // expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{'Int' is not convertible to 'Bool'}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{'Int' is not convertible to 'Bool'}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-warning @-1 {{comparing non-optional value of type 'Int' to nil always returns true}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} _ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Protocol' is not convertible to 'AnyObject'}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{use of undeclared type 'Nail'}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer closure type in the current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // rdar://19804707 - trailing closures for contextual member references. knownOps = .BinaryOperator(){$1 - $0} knownOps = .BinaryOperator{$1 - $0} _ = knownOps } func f7(_ a: Int) -> (_ b: Int) -> Int { return { b in a+b } } _ = f7(1)(1) f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}} let f8 = f7(2) _ = f8(1) f8(10) // expected-warning {{result of call is unused, but produces 'Int'}} f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}} class CurriedClass { func method1() {} func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } } func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}} } let c = CurriedClass() _ = c.method1 c.method1(1) // expected-error {{argument passed to call that takes no arguments}} _ = c.method2(1) _ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1)(2) c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}} c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}} c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method1(c)() _ = CurriedClass.method1(c) CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}} CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}} _ = CurriedClass.method2(c) _ = CurriedClass.method2(c)(32) _ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}} CurriedClass.method3(c)(32, b: 1) _ = CurriedClass.method3(c) _ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }} _ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}} _ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}} CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}} extension CurriedClass { func f() { method3(1, b: 2) method3() // expected-error {{missing argument for parameter #1 in call}} method3(42) // expected-error {{missing argument for parameter 'b' in call}} method3(self) // expected-error {{missing argument for parameter 'b' in call}} } } extension CurriedClass { func m1(_ a : Int, b : Int) {} func m2(_ a : Int) {} } // <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} // <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}} // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} static func overload(b : Int) -> Color {} static func frob(_ a : Int, b : inout Int) -> Color {} } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}} let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}} let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}} someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}} //expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } func test(_ a : B) { B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, nil) //expected-error {{missing argument label 'a:' in call}} a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions; operands here have types '_' and '([Int]) -> Bool'}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to nil always returns true}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) _ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String where T.Iterator.Element == String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}} // expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'CountableClosedRange<Int>' to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')}} _ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 _ = a + b // expected-warning {{deprecated}} a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}} b } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } postfix operator +++ postfix func +++ <T>(_: inout T) -> T { fatalError() } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} _ = bytes[i+++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}} } // SR-1594: Wrong error description when using === on non-class types class SR1594 { func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) { _ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}} _ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}} _ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}} _ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}} } } func nilComparison(i: Int, o: AnyObject) { _ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}} _ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}} _ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}} _ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}} // FIXME(integers): uncomment these tests once the < is no longer ambiguous // _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} _ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}} _ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}} } func secondArgumentNotLabeled(a: Int, _ b: Int) { } secondArgumentNotLabeled(10, 20) // expected-error@-1 {{missing argument label 'a' in call}} // <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion func testImplConversion(a : Float?) -> Bool {} func testImplConversion(a : Int?) -> Bool { let someInt = 42 let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}} } // <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands class Foo23752537 { var title: String? var message: String? } extension Foo23752537 { func isEquivalent(other: Foo23752537) { // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" // expected-error @+1 {{unexpected non-void return value in void function}} return (self.title != other.title && self.message != other.message) } } // <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" func rdar27391581(_ a : Int, b : Int) -> Int { return a == b && b != 0 // expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read<T : BinaryInteger>() -> T? { var buffer : T let n = withUnsafePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtractInPlace(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}} } // <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context func rdar24202058(a : Int) { return a <= 480 // expected-error {{unexpected non-void return value in void function}} } // SR-1752: Warning about unused result with ternary operator struct SR1752 { func foo() {} } let sr1752: SR1752? true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void // <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try' struct rdar27891805 { init(contentsOf: String, encoding: String) throws {} init(contentsOf: String, usedEncoding: inout String) throws {} init<T>(_ t: T) {} } try rdar27891805(contentsOfURL: nil, usedEncoding: nil) // expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}} // expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}} // Make sure RawRepresentable fix-its don't crash in the presence of type variables class NSCache<K, V> { func object(forKey: K) -> V? {} } class CacheValue { func value(x: Int) -> Int {} // expected-note {{found this candidate}} func value(y: String) -> String {} // expected-note {{found this candidate}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}} } // SR-2242: poor diagnostic when argument label is omitted func r27212391(x: Int, _ y: Int) { let _: Int = x + y } func r27212391(a: Int, x: Int, _ y: Int) { let _: Int = a + x + y } r27212391(3, 5) // expected-error {{missing argument label 'x' in call}} r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}} r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}} r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}} r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}} r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}} r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} // SR-1255 func foo1255_1() { return true || false // expected-error {{unexpected non-void return value in void function}} } func foo1255_2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // SR-2505: "Call arguments did not match up" assertion // Here we're simulating the busted Swift 3 behavior -- see // test/Constraints/diagnostics_swift4.swift for the correct // behavior. func sr_2505(_ a: Any) {} // expected-note {{}} sr_2505() // expected-error {{missing argument for parameter #1 in call}} sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4 sr_2505(1, 2) // expected-error {{extra argument in call}} sr_2505(a: 1, 2) // expected-error {{extra argument in call}} struct C_2505 { init(_ arg: Any) { } } protocol P_2505 { } extension C_2505 { init<T>(from: [T]) where T: P_2505 { } } class C2_2505: P_2505 { } // FIXME: emit a warning saying this becomes an error in Swift 4 let c_2505 = C_2505(arg: [C2_2505()]) // Diagnostic message for initialization with binary operations as right side let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}} let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}} let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} // SR-2208 struct Foo2208 { func bar(value: UInt) {} } func test2208() { let foo = Foo2208() let a: Int = 1 let b: Int = 2 let result = a / b foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: UInt(result)) // Ok } // SR-2164: Erroneous diagnostic when unable to infer generic type struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}} init(a: A) {} init(b: B) {} init(c: Int) {} init(_ d: A) {} init(e: A?) {} } struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}} init(_ a: [A]) {} } struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}} init(a: [A: Double]) {} } SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} let _ = SR_2164<Int, Bool>(a: 0) // Ok let _ = SR_2164<Int, Bool>(b: true) // Ok SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} // <rdar://problem/29850459> Swift compiler misreports type error in ternary expression let r29850459_flag = true let r29850459_a: Int = 0 let r29850459_b: Int = 1 func r29850459() -> Bool { return false } let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} // Ambiguous overload inside a trailing closure func ambiguousCall() -> Int {} // expected-note {{found this candidate}} func ambiguousCall() -> Float {} // expected-note {{found this candidate}} func takesClosure(fn: () -> ()) {} takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}} // SR-4692: Useless diagnostics calling non-static method class SR_4692_a { private static func foo(x: Int, y: Bool) { self.bar(x: x) // expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}} } private func bar(x: Int) { } } class SR_4692_b { static func a() { self.f(x: 3, y: true) // expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}} } private func f(a: Int, b: Bool, c: String) { self.f(x: a, y: b) } private func f(x: Int, y: Bool) { } } // rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful struct R32101765 { let prop32101765 = 0 } let _: KeyPath<R32101765, Float> = \.prop32101765 // expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765 // expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}}
a420e0010ceeca31cbdcf066a8599ace
44.64898
210
0.672427
false
false
false
false
rsrose21/cluelist
refs/heads/master
ClueList/ClueList/timeago.swift
mit
1
// // timeago.swift // https://gist.github.com/jacks205/4a77fb1703632eb9ae79 // // import Foundation func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String { let calendar = NSCalendar.currentCalendar() let now = NSDate() let earliest = now.earlierDate(date) let latest = (earliest == now) ? date : now let components:NSDateComponents = calendar.components([NSCalendarUnit.Minute , NSCalendarUnit.Hour , NSCalendarUnit.Day , NSCalendarUnit.WeekOfYear , NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Second], fromDate: earliest, toDate: latest, options: NSCalendarOptions()) //Format date for display: http://www.brianjcoleman.com/tutorial-nsdate-in-swift/ let formatter = NSDateFormatter(); formatter.dateFormat = "MMM dd 'at' h:mm a" // example: "Jan 01 at 12:00 PM" if (components.weekOfYear >= 1){ return formatter.stringFromDate(date) } else if (components.day >= 2) { return "\(components.day) days ago" } else if (components.day >= 1){ if (numericDates){ return "1 day ago" } else { return "Yesterday" } } else if (components.hour >= 2) { return "\(components.hour) hours ago" } else if (components.hour >= 1){ if (numericDates){ return "1 hour ago" } else { return "An hour ago" } } else if (components.minute >= 2) { return "\(components.minute) minutes ago" } else if (components.minute >= 1){ if (numericDates){ return "1 minute ago" } else { return "A minute ago" } } else if (components.second >= 3) { return "\(components.second) seconds ago" } else { return "Just now" } }
b2e4db48d709b1f476b5431b10af905a
34.039216
288
0.610862
false
false
false
false
makelove/Developing-iOS-8-Apps-with-Swift
refs/heads/master
Autolayout Localized/Autolayout/ViewController.swift
apache-2.0
5
// // ViewController.swift // Autolayout // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class ViewController: UIViewController { // after the demo, appropriate things were private-ized. // including outlets and actions. @IBOutlet private weak var loginField: UITextField! @IBOutlet private weak var passwordField: UITextField! @IBOutlet private weak var passwordLabel: UILabel! @IBOutlet private weak var companyLabel: UILabel! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var imageView: UIImageView! @IBOutlet weak var lastLoginLabel: UILabel! // our Model, the logged in user var loggedInUser: User? { didSet { updateUI() } } // sets whether the password field is secure or not var secure: Bool = false { didSet { updateUI() } } // update the user-interface // by transferring information from the Model to our View // and setting up security in the password fields // // NOTE: After the demo, this method was protected against // crashing if it is called before our outlets are set. // This is nice to do since setting our Model calls this // and our Model might get set while we are being prepared. // It was easy too. Just added ? after outlets. // private func updateUI() { passwordField?.secureTextEntry = secure let password = NSLocalizedString("Password", comment: "Prompt for the user's password when it is not secure (i.e. plain text)") let securedPassword = NSLocalizedString("Secured Password", comment: "Prompt for an obscured (not plain text) password") passwordLabel?.text = secure ? securedPassword : password nameLabel?.text = loggedInUser?.name companyLabel?.text = loggedInUser?.company image = loggedInUser?.image if let lastLogin = loggedInUser?.lastLogin { let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle let time = dateFormatter.stringFromDate(lastLogin) let numberFormatter = NSNumberFormatter() numberFormatter.maximumFractionDigits = 1 let daysAgo = numberFormatter.stringFromNumber(-lastLogin.timeIntervalSinceNow/(60*60*24))! let lastLoginFormatString = NSLocalizedString("Last Login %@ days ago at %@", comment: "Reports the number of days ago and time that the user last logged in") lastLoginLabel.text = String.localizedStringWithFormat(lastLoginFormatString, daysAgo, time) } else { lastLoginLabel.text = "" } } // once we're loaded (outlets set, etc.), update the UI override func viewDidLoad() { super.viewDidLoad() updateUI() } private struct AlertStrings { struct LoginError { static let Title = NSLocalizedString("Login Error", comment: "Title of alert when user types in an incorrect user name or password") static let Message = NSLocalizedString("Invalid user name or password", comment: "Message in an alert when the user types in an incorrect user name or password") static let DismissButton = NSLocalizedString("Try Again", comment: "The only button available in an alert presented when the user types incorrect user name or password") } } // log in (set our Model) @IBAction private func login() { loggedInUser = User.login(loginField.text ?? "", password: passwordField.text ?? "") if loggedInUser == nil { let alert = UIAlertController(title: AlertStrings.LoginError.Title, message: AlertStrings.LoginError.Message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: AlertStrings.LoginError.DismissButton, style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } // toggle whether passwords are secure or not @IBAction private func toggleSecurity() { secure = !secure } // a convenience property // so that we can easily intervene // when an image is set in our imageView // whenever the image is set in our imageView // we add a constraint that the imageView // must maintain the aspect ratio of its image private var image: UIImage? { get { return imageView?.image } set { imageView?.image = newValue if let constrainedView = imageView { if let newImage = newValue { aspectRatioConstraint = NSLayoutConstraint( item: constrainedView, attribute: .Width, relatedBy: .Equal, toItem: constrainedView, attribute: .Height, multiplier: newImage.aspectRatio, constant: 0) } else { aspectRatioConstraint = nil } } } } // the imageView aspect ratio constraint // when it is set here, // we'll remove any existing aspect ratio constraint // and then add the new one to our view private var aspectRatioConstraint: NSLayoutConstraint? { willSet { if let existingConstraint = aspectRatioConstraint { view.removeConstraint(existingConstraint) } } didSet { if let newConstraint = aspectRatioConstraint { view.addConstraint(newConstraint) } } } } // User is our Model, // so it can't itself have anything UI-related // but we can add a UI-specific property // just for us to use // because we are the Controller // note this extension is private private extension User { var image: UIImage? { if let image = UIImage(named: login) { return image } else { return UIImage(named: "unknown_user") } } } // wouldn't it be convenient // to have an aspectRatio property in UIImage? // yes, it would, so let's add one! // why is this not already in UIImage? // probably because the semantic of returning zero // if the height is zero is not perfect // (nil might be better, but annoying) extension UIImage { var aspectRatio: CGFloat { return size.height != 0 ? size.width / size.height : 0 } }
cfef0eb3e9ccd452338a0d46af707ca5
37.067797
167
0.629267
false
false
false
false
mattiasjahnke/GameOfLife
refs/heads/master
GameOfLife/GameOfLifeMatrix.swift
mit
2
// // GameOfLife.swift // GameOfLife // // Created by Mattias Jähnke on 2015-07-27. // Copyright © 2015 nearedge. All rights reserved. // import Foundation protocol GameOfLifeMatrix: Equatable { var width: Int { get } var height: Int { get } var activeCells: Set<Point> { get } var isEmpty: Bool { get } init(width: Int, height: Int, active: Set<Point>) subscript(point: Point) -> Bool { get set } } struct Point: Hashable, Equatable { let x: Int, y: Int init(x: Int = 0, y: Int = 0) { self.x = x self.y = y } var hashValue: Int { return "\(x.hashValue)\(y.hashValue)".hashValue } } func ==(lhs: Point, rhs: Point) -> Bool { return lhs.hashValue == rhs.hashValue } extension GameOfLifeMatrix { func contains(_ point: Point) -> Bool { return point.x >= 0 && point.y >= 0 && point.x <= width - 1 && point.y <= height - 1 } subscript(x: Int, y: Int) -> Bool { get { return self[Point(x: x, y: y)] } set { self[Point(x: x, y: y)] = newValue } } } extension GameOfLifeMatrix { func incrementedGeneration() -> Self { var next = Self.init(width: width, height: height, active: []) var processed = Set<Point>() for cell in activeCells { next[cell] = fate(cell) // Determine the fate for the the "inactive" neighbours for inactive in cell.adjecentPoints.filter({ self.contains($0) && !self[$0] }) { guard !processed.contains(inactive) else { continue } next[inactive] = fate(inactive) processed.insert(inactive) } } return next } fileprivate func fate(_ point: Point) -> Bool { let activeNeighbours = point.adjecentPoints.filter { self.contains($0) && self[$0] }.count switch activeNeighbours { case 3 where self[point] == false: // Dead cell comes alive return true case 2..<4 where self[point] == true: // Lives on return true default: // Under- or over-population, dies return false } } } // Move private extension Point { var adjecentPoints: Set<Point> { return [left, leftUp, up, rightUp, right, rightDown, down, leftDown] } var left: Point { return Point(x: x - 1, y: y) } var leftUp: Point { return Point(x: x - 1, y: y - 1) } var up: Point { return Point(x: x, y: y - 1) } var rightUp: Point { return Point(x: x + 1, y: y - 1) } var right: Point { return Point(x: x + 1, y: y) } var rightDown: Point { return Point(x: x + 1, y: y + 1) } var down: Point { return Point(x: x, y: y + 1) } var leftDown: Point { return Point(x: x - 1, y: y + 1) } }
320c7e76cbdfc21e632888c26b86fa28
29.72043
98
0.546377
false
false
false
false
RyanMacG/poppins
refs/heads/master
Poppins/ViewControllers/CascadeViewController.swift
mit
3
import CoreData import Cascade import Gifu import Result import Runes class CascadeViewController: UICollectionViewController { var controller: CascadeController? let popupViewManager = PopupViewManager() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.setBackgroundImage(UIImage(named: "NavigationBarBackground"), forBarMetrics: .Default) navigationItem.titleView = UIImage(named: "PoppinsTitle").map { UIImageView(image: $0) } let layout = collectionView?.collectionViewLayout as? CascadeLayout layout?.delegate = self collectionView?.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("sync"), name: UIApplicationDidBecomeActiveNotification, object: .None) sync() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchImages() if controller?.viewModel.shouldShowEmptyState ?? true { showEmptyState() } } @objc func sync() { controller?.syncWithTHECLOUD() if controller?.hasPasteboardImage ?? false { let alert = controller?.viewModel.alertControllerForImportingPasteboardImage(presentImportView) alert.map { self.presentViewController($0, animated: true, completion: .None) } } } private func fetchImages() { controller?.fetchImages() controller?.registerForChanges { inserted, updated, deleted in self.hideEmptyState() _ = self.collectionView?.performBatchUpdates({ self.collectionView?.insertItemsAtIndexPaths(inserted) self.collectionView?.reloadItemsAtIndexPaths(updated) self.collectionView?.deleteItemsAtIndexPaths(deleted) }, completion: .None) } } private func showEmptyState() { let emptyStateViewController = EmptyStateViewController.create() emptyStateViewController.moveToParent(self) { self.collectionView?.backgroundView = $0 } } private func hideEmptyState() { let emptyStateViewController = childViewControllers.last as? EmptyStateViewController emptyStateViewController?.removeFromParent { self.collectionView?.backgroundView = .None } } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return controller?.viewModel.numberOfImages ?? 0 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PoppinsCell", forIndexPath: indexPath) as! PoppinsCell cell.controller = controller?.cellControllerForIndexPath(indexPath) return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return controller?.viewModel.imageSizeForIndexPath(indexPath) ?? CGSize(width: 1, height: 1) } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let gifItemSource = controller?.viewModel.gifItemSourceForIndexPath(indexPath) if let source = gifItemSource { let activityVC = UIActivityViewController(activityItems: [source], applicationActivities: [FacebookMessengerActivity()]) presentViewController(activityVC, animated: true, completion: .None) } } @IBAction func hold(gesture: UILongPressGestureRecognizer) { if gesture.state == .Began { let point = gesture.locationInView(collectionView) let indexPath = collectionView?.indexPathForItemAtPoint(point) let frame = (indexPath >>- { self.collectionView?.layoutAttributesForItemAtIndexPath($0) })?.frame let realFrame = frame >>- { self.collectionView?.convertRect($0, toView: self.navigationController?.view) } let path = indexPath >>- { self.controller?.viewModel.imagePathForIndexPath($0) } let size = indexPath >>- { self.controller?.viewModel.imageSizeForIndexPath($0) } let previewViewController = popupViewManager.previewViewController <^> realFrame <*> path <*> size previewViewController.map { self.presentViewController($0, animated: true, completion: .None) } } else if gesture.state == .Ended { dismissViewControllerAnimated(true, completion: popupViewManager.recyclePreview) } } private func presentImportView() { let importViewController = popupViewManager.importViewController <^> controller?.importController() importViewController?.importViewDidDismiss = popupViewManager.recycleImport importViewController.map { self.presentViewController($0, animated: true, completion: .None) } } } extension CascadeViewController: CascadeLayoutDelegate { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: CascadeLayout, numberOfColumnsInSectionAtIndexPath indexPath: NSIndexPath) -> Int { return 2 } }
0e516b4dac4433e662494a9fb6569188
44.403361
170
0.713307
false
false
false
false
acort3255/Emby.ApiClient.Swift
refs/heads/master
Emby.ApiClient/apiinteraction/BaseApiClient.swift
mit
1
// // BaseApiClient.swift // Emby.ApiClient // // Created by Vedran Ozir on 03/11/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.apiinteraction; // //import mediabrowser.apiinteraction.device.IDevice; //import mediabrowser.apiinteraction.http.HttpHeaders; //import mediabrowser.model.apiclient.ApiHelpers; //import mediabrowser.model.extensions.*; //import mediabrowser.model.drawing.*; //import mediabrowser.model.dto.*; //import mediabrowser.model.entities.*; //import mediabrowser.model.livetv.*; //import mediabrowser.model.logging.*; //import mediabrowser.model.querying.*; //import mediabrowser.model.serialization.*; // //import java.text.DateFormat; //import java.text.SimpleDateFormat; //import java.util.Date; //import java.util.TimeZone; /** Provides api methods that are usable on all platforms */ //public abstract class BaseApiClient implements IDisposable public class BaseApiClient// implements IDisposable { // //C# TO JAVA CONVERTER TODO TASK: Events are not available in Java: // // public event EventHandler ServerLocationChanged; // private void OnServerLocationChanged() // { // //if (ServerLocationChanged != null) // //{ // //ServerLocationChanged(this, EventArgs.Empty); // //} // } // private var logger: ILogger private var jsonSerializer: IJsonSerializer private var clientName: String? private var device: DeviceProtocol? private var privateApplicationVersion: String? private var privateServerAddress: String private var privateAccessToken: String? private var privateImageQuality: Int? private var privateCurrentUserId: String? let httpHeaders = HttpHeaders() internal init(logger: ILogger, jsonSerializer: IJsonSerializer, serverAddress: String, clientName: String, device: DeviceProtocol, applicationVersion: String) { self.logger = logger self.jsonSerializer = jsonSerializer self.clientName = clientName self.device = device self.privateApplicationVersion = applicationVersion self.privateServerAddress = serverAddress } internal init(logger: ILogger, jsonSerializer: IJsonSerializer, serverAddress: String, accessToken: String) { self.logger = logger self.jsonSerializer = jsonSerializer self.privateServerAddress = serverAddress self.privateAccessToken = accessToken } public final func setJsonSerializer(value: IJsonSerializer) { self.jsonSerializer = value } public final func getJsonSerializer() -> IJsonSerializer? { return jsonSerializer } public final func setClientName(value: String) { self.clientName = value } public final func getClientName() -> String? { return clientName } public final func setApplicationVersion(value: String) { self.privateApplicationVersion = value } public final func getApplicationVersion() -> String? { return privateApplicationVersion } public final func setServerAddress(value: String) { self.privateServerAddress = value } public final func getServerAddress() -> String { return privateServerAddress } public final func setAccessToken(value: String?) { self.privateAccessToken = value } public final func getAccessToken() -> String? { return privateAccessToken } public final func getDevice() -> DeviceProtocol? { return device } public final func getDeviceName() -> String? { return getDevice()?.deviceName } public final func getDeviceId() -> String? { return getDevice()?.deviceId } public final func setImageQuality(value: Int) { self.privateImageQuality = value } public final func getImageQuality() -> Int? { return privateImageQuality } public final func setCurrentUserId(value: String?) { self.privateCurrentUserId = value } public final func getCurrentUserId() -> String? { return privateCurrentUserId } public final func getApiUrl() -> String { return getServerAddress() + "/emby" } internal final func getAuthorizationScheme() -> String { return "MediaBrowser" } public final func changeServerLocation(address: String) { setServerAddress(value: address) setAuthenticationInfo(accessToken: nil, userId: nil) } public func setAuthenticationInfo(accessToken: String?, userId: String?) { setCurrentUserId(value: userId) setAccessToken(value: accessToken) resetHttpHeaders() } public func setAuthenticationInfo(accessToken: String?) { setCurrentUserId(value: nil) setAccessToken(value: accessToken) resetHttpHeaders() } public func clearAuthenticationInfo() { setCurrentUserId(value: nil) setAccessToken(value: nil) resetHttpHeaders() } internal func resetHttpHeaders() { httpHeaders.setAccessToken(token: getAccessToken()) if let authValue = getAuthorizationParameter() { setAuthorizationHttpRequestHeader(scheme: getAuthorizationScheme(), parameter: authValue) } else { clearHttpRequestHeader(name: "Authorization") setAuthorizationHttpRequestHeader(scheme: nil, parameter: nil) } } internal func setAuthorizationHttpRequestHeader(scheme: String?, parameter: String?) { httpHeaders.authorizationScheme = scheme httpHeaders.authorizationParameter = parameter } private func clearHttpRequestHeader(name: String) { httpHeaders[name] = nil } internal func getAuthorizationParameter() -> String? { if let clientName = getClientName(), let deviceId = getDeviceId(), let deviceName = getDeviceName() { var header = "Client=\"\(clientName)\", DeviceId=\"\(deviceId)\", Device=\"\(deviceName)\", Version=\"\(getApplicationVersion() ?? "1.0")\"" if let currentUserId = getCurrentUserId() { header += ", UserId=\"\(currentUserId)\"" } return header } else { return nil } } internal final func getSlugName(name: String?) -> String { return ApiHelpers.getSlugName(name: name) } // // /** // Changes the server location. // // @param address The address. // */ // public final void ChangeServerLocation(String address) // { // setServerAddress(address); // // SetAuthenticationInfo(null, null); // // OnServerLocationChanged(); // } // public final func getApiUrl(handler: String?) -> String { return getApiUrl(handler: handler, queryString: nil) } internal final func getApiUrl(handler: String?, queryString: QueryStringDictionary?) -> String { let base = getApiUrl() + "/" + handler! return queryString != nil ? queryString!.getUrl(prefix: base) : base } public final func getSubtitleUrl(options: SubtitleDownloadOptions) -> String { let partialUrl: String = "Videos/\(options.itemId)/\(options.mediaSourceId)/Subtitles/\(options.streamIndex)/Stream.\(options.format)" return getApiUrl(handler: partialUrl) } internal final func getItemListUrl(query: ItemQuery) -> String { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("ParentId", value: query.parentId) dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("Limit", value: query.limit) dict.add("SortBy", value: query.sortBy) dict.addIfNotNil("SortOrder", value: query.sortOrder?.rawValue) dict.add("SeriesStatues", value: query.seriesStatus?.map({$0.rawValue})) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.add("Filters", value: query.filters?.map({$0.rawValue})) dict.add("ImageTypes", value: query.imageTypes?.map({$0.rawValue})) dict.addIfNotNil("Is3d", value: query.is3d) dict.add("AirDays", value: query.airDays) dict.add("VideoTypes", value: query.videoTypes?.map({$0.rawValue})) dict.addIfNotNilOrEmpty("MinOfficialRating", value: query.minOfficialRating) dict.addIfNotNilOrEmpty("MaxOfficialRating", value: query.maxOfficialRating) dict.addIfNotNil("recursive", value: query.recursive) dict.addIfNotNil("MinIndexNumber", value: query.minIndexNumber) dict.add("MediaTypes", value: query.mediaTypes) dict.addIfNotNil("Genres", value: query.genres?.joined(separator: "|")) dict.add("Ids", value: query.ids) dict.addIfNotNil("StudioIds", value: query.studioIds?.joined(separator: "|")) dict.add("ExcludeItemTypes", value: query.excludeItemTypes) dict.add("IncludeItemTypes", value: query.includeItemTypes) dict.add("ArtistIds", value: query.artistIds) dict.addIfNotNil("IsPlayed", value: query.isPlayed) dict.addIfNotNil("IsInBoxSet", value: query.isInBoxSet) dict.add("PersonIds", value: query.personIds) dict.add("PersonTypes", value: query.personTypes) dict.add("Years", value: query.years) dict.addIfNotNil("ParentIndexNumber", value: query.parentIndexNumber) dict.addIfNotNil("IsHD", value: query.isHd) dict.addIfNotNil("HasParentalRating", value: query.hasParentRating) dict.addIfNotNilOrEmpty("SearchTerm", value: query.searchTerm) dict.addIfNotNil("MinCriticRating", value: query.minCriticRating) dict.addIfNotNil("MinCommunityRating", value: query.minCommunityRating) dict.addIfNotNil("MinPlayers", value: query.minPlayers) dict.addIfNotNil("MaxPlayers", value: query.maxPlayers) dict.addIfNotNilOrEmpty("NameStartsWithOrGreater", value: query.nameStartsWithOrGreater) dict.addIfNotNilOrEmpty("NameStartsWith", value: query.nameStartsWith) dict.addIfNotNilOrEmpty("NameLessThan", value: query.nameLessThan) dict.addIfNotNilOrEmpty("AlbumArtistStartsWithOrGreater", value: query.albumArtistStartsWithOrGreater) dict.addIfNotNil("LocationTypes", value: query.locationTypes.map({String(describing: $0)})) dict.addIfNotNil("ExcludeLocationTypes", value: query.excludeLocationTypes.map({String(describing: $0)})) dict.addIfNotNil("IsMissing", value: query.isMissing) dict.addIfNotNil("IsUnaired", value: query.isUnaired) dict.addIfNotNil("IsVirtualUnaired", value: query.isVirtualUnaired) dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("EnableTotalRecordCount", value: query.enableTotalRecordCount) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) dict.addIfNotNil("AiredDuringSeason", value: query.airedDuringSeasion) return getApiUrl(handler: "Users/\(query.userId!)/Items", queryString: dict) } internal final func getNextUpUrl(query: NextUpQuery) -> String { let dict = QueryStringDictionary() dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("UserId", value: query.userId); dict.addIfNotNilOrEmpty("SeriesId", value: query.seriesId); dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) return getApiUrl(handler: "Shows/NextUp", queryString: dict) } internal final func getSimilarItemListUrl(query: SimilarItemsQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) return getApiUrl(handler: "\(type!)/\(query.id!)/Similar", queryString: dict) } internal final func getInstantMixUrl(query: SimilarItemsQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) return getApiUrl(handler: "\(type!)/\(query.id!)/InstantMix", queryString: dict) } internal final func getItemByNameListUrl(query: ItemsByNameQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("ParentId", value: query.parentId) dict.addIfNotNil("UserId", value: query.userId); dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("Limit", value: query.limit) dict.add("SortBy", value: query.sortBy) dict.addIfNotNil("sortOrder", value: query.sortOrder?.rawValue) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("IsPlayed", value: query.isPlayed) dict.add("Filters", value: query.filters?.map({$0.rawValue})) dict.add("ImageTypes", value: query.imageTypes?.map({$0.rawValue})) dict.addIfNotNil("recursive", value: query.recursive) dict.add("MediaTypes", value: query.mediaTypes) dict.add("ExcludeItemTypes", value: query.excludeItemTypes) dict.add("IncludeItemTypes", value: query.includeItemTypes) dict.addIfNotNilOrEmpty("NameStartsWithOrGreater", value: query.nameStartsWithOrGreater) dict.addIfNotNilOrEmpty("NameStartsWith", value: query.nameStartsWith) dict.addIfNotNilOrEmpty("NameLessThan", value: query.nameLessThan) dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) return getApiUrl(handler: type, queryString: dict) } private func getImageUrl(baseUrl: String, options: ImageOptions, queryParams: QueryStringDictionary) -> String { queryParams.addIfNotNil("Width", value: options.width) queryParams.addIfNotNil("Height", value: options.height) queryParams.addIfNotNil("MaxWidth", value: options.maxWidth) queryParams.addIfNotNil("MaxHeight", value: options.maxHeight) if let quality = options.quality ?? getImageQuality() { queryParams.addIfNotNil("Quality", value: quality) } queryParams.addIfNotNilOrEmpty("Tag", value: options.tag) queryParams.addIfNotNil("CropWhitespace", value: options.cropWhiteSpace) queryParams.addIfNotNil("EnableImageEnhancers", value: options.enableImageEnhancers) queryParams.addIfNotNil("Format", value: options.imageFormat?.rawValue) queryParams.addIfNotNil("AddPlayedIndicator", value: options.addPlayedIndicator) queryParams.addIfNotNil("UnPlayedCount", value: options.unplayedCount); queryParams.addIfNotNil("PercentPlayed", value: options.percentPlayed); queryParams.addIfNotNilOrEmpty("BackgroundColor", value: options.backgroundColor); return getApiUrl(handler: baseUrl, queryString: queryParams); } public final func getImageUrl(item: BaseItemDto, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = getImageTag(item: item, options: newOptions) return getImageUrl(itemId: item.id, options: newOptions) } public final func getImageUrl(itemId: String?, options: ImageOptions) -> String? { if let id = itemId { let url = "Items/\(id)/Images/\(options.imageType)"; return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } return nil } public final func getUserImageUrl(user: UserDto, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = user.primaryImageTag return getUserImageUrl(userId: user.id, options: newOptions) } public final func getUserImageUrl(userId: String?, options: ImageOptions) -> String? { if let id = userId { let url = "Users/\(id)/Images/\(options.imageType)"; return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } return nil } public final func getPersonImageUrl(item: BaseItemPerson, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = item.primaryImageTag return getImageUrl(itemId: item.id, options: newOptions) } private func getImageTag(item: BaseItemDto, options: ImageOptions) -> String? { switch options.imageType { case .Backdrop: return item.backdropImageTags?[options.imageIndex ?? 0] case .Screenshot: return item.screenshotImageTags?[options.imageIndex ?? 0] case .Chapter: return item.chapters?[options.imageIndex ?? 0].imageTag default: return item.imageTags?[options.imageType.rawValue] } } public final func getGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Genres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getMusicGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "MusicGenres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getGameGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "GameGenres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getStudioImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Studios/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getArtistImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Artists/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getBackdropImageUrls(item: BaseItemDto, options: ImageOptions) -> [String]? { var newOptions = options newOptions.imageType = ImageType.Backdrop var backdropItemId: String? var backdropImageTags: [String]? if item.backdropCount == 0 { backdropItemId = item.parentBackdropItemId backdropImageTags = item.parentBackdropImageTags } else { backdropItemId = item.id backdropImageTags = item.backdropImageTags } if backdropItemId == nil { return [String]() } if let bImageTags = backdropImageTags { var files = [String]() /*for var i = 0; i < bImageTags.count; ++i { newOptions.imageIndex = i newOptions.tag = bImageTags[i] files[i] = getImageUrl(backdropItemId, options: newOptions)! }*/ for i in 0..<bImageTags.count { newOptions.imageIndex = i newOptions.tag = bImageTags[i] files[i] = getImageUrl(itemId: backdropItemId, options: newOptions)! } return files } return nil } public final func getLogoImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let logoItemId = item.hasLogo ? item.id : item.parentLogoItemId let imageTag = item.hasLogo ? item.imageTags?[ImageType.Logo.rawValue] : item.parentLogoImageTag if let lItemId = logoItemId { newOptions.tag = imageTag return getImageUrl(itemId: lItemId, options: newOptions) } return nil } public final func getThumbImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let thumbItemId = item.hasThumb ? item.id : item.seriesThumbImageTag != nil ? item.seriesId : item.parentThumbItemId let imageTag = item.hasThumb ? item.imageTags?[ImageType.Thumb.rawValue] : item.seriesThumbImageTag != nil ? item.seriesThumbImageTag : item.parentThumbImageTag if let tItemId = thumbItemId { newOptions.tag = imageTag return getImageUrl(itemId: tItemId, options: newOptions) } return nil } public final func getArtImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let artItemId = item.hasArtImage ? item.id : item.parentArtItemId let imageTag = item.hasArtImage ? item.imageTags?[ImageType.Art.rawValue] : item.parentArtImageTag if let aItemId = artItemId { newOptions.tag = imageTag return getImageUrl(itemId: aItemId, options: newOptions) } return nil } internal final func serializeToJson(obj: AnyObject) -> String { return getJsonSerializer()!.serializeToString(obj: obj) } internal final func addDataFormat(url: String) -> String { let format = "json" var newUrl = url if url.contains("?") { newUrl += "&format=" + format } else { newUrl += "?format=" + format } return newUrl } public func getIsoString(date: NSDate) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone! return formatter.string(from: date as Date) } }
f9ca1b2a84d1daf8b92fc89a1cd63f7d
38.548013
168
0.649098
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Tests/EventDetailComponentTests/Presenter Tests/EventDetailPresenterBindingComponentTests.swift
mit
1
import EurofurenceModel import EventDetailComponent import TestUtilities import XCTest import XCTEurofurenceModel class EventDetailPresenterBindingComponentTests: XCTestCase { func tetsBindingBanner() { let event = FakeEvent.random let graphic = EventGraphicViewModel.random let index = Int.random let viewModel = StubEventGraphicViewModel(graphic: graphic, at: index) let viewModelFactory = FakeEventDetailViewModelFactory(viewModel: viewModel, for: event) let context = EventDetailPresenterTestBuilder().with(viewModelFactory).build(for: event) context.simulateSceneDidLoad() let boundComponent = context.scene.bindComponent(at: IndexPath(item: index, section: 0)) let eventGraphicComponent = boundComponent as? CapturingEventGraphicComponent XCTAssertTrue(eventGraphicComponent === context.scene.stubbedEventGraphicComponent) XCTAssertEqual(graphic.pngGraphicData, context.scene.stubbedEventGraphicComponent.capturedPNGGraphicData) } func testBindingDescription() { let event = FakeEvent.random let eventDescription = EventDescriptionViewModel.random let index = Int.random let viewModel = StubEventDescriptionViewModel(eventDescription: eventDescription, at: index) let viewModelFactory = FakeEventDetailViewModelFactory(viewModel: viewModel, for: event) let context = EventDetailPresenterTestBuilder().with(viewModelFactory).build(for: event) context.simulateSceneDidLoad() let boundComponent = context.scene.bindComponent(at: IndexPath(item: index, section: 0)) let eventDescriptionComponent = boundComponent as? CapturingEventDescriptionComponent let stubbedComponent = context.scene.stubbedEventDescriptionComponent XCTAssertTrue(eventDescriptionComponent === stubbedComponent) XCTAssertEqual(eventDescription.contents, stubbedComponent.capturedEventDescription) } func testBindingSummaryComponent() { let summary = EventSummaryViewModel.random let viewModel = StubEventSummaryViewModel(summary: summary) let scene = prepareSceneForBindingComponent(viewModel: viewModel) let eventSummaryComponent = scene.stubbedEventSummaryComponent XCTAssertEqual(viewModel.numberOfComponents, scene.numberOfBoundsComponents) XCTAssertEqual(summary.title, eventSummaryComponent.capturedTitle) XCTAssertEqual(summary.subtitle, eventSummaryComponent.capturedSubtitle) XCTAssertEqual(summary.abstract, eventSummaryComponent.capturedAbstract) XCTAssertEqual(summary.eventStartEndTime, eventSummaryComponent.capturedEventStartTime) XCTAssertEqual(summary.location, eventSummaryComponent.capturedEventLocation) XCTAssertEqual(summary.trackName, eventSummaryComponent.capturedTrackName) XCTAssertEqual(summary.eventHosts, eventSummaryComponent.capturedEventHosts) } func tetsBindingKageMessage() { let message = String.random let kageMessageViewModel = EventKageMessageViewModel(message: message) let viewModel = StubKageEventViewModel(kageMessageViewModel: kageMessageViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedKageMessageComponent.capturedMessage) } func testBindingMainStage() { let message = String.random let kageMessageViewModel = EventMainStageMessageViewModel(message: message) let viewModel = StubMainStageEventViewModel(mainStageMessageViewModel: kageMessageViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedMainStageMessageComponent.capturedMessage) } func testBindingPhotoshoot() { let message = String.random let kageMessageViewModel = EventPhotoshootMessageViewModel(message: message) let viewModel = StubPhotoshootEventViewModel(photoshootMessageViewModel: kageMessageViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedPhotoshootMessageComponent.capturedMessage) } func testBindingSponsorsOnly() { let message = String.random let sponsorsOnlyViewModel = EventSponsorsOnlyWarningViewModel(message: message) let viewModel = StubSponsorsOnlyEventViewModel(sponsorsOnlyWarningViewModel: sponsorsOnlyViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedSponsorsOnlyComponent.capturedMessage) } func testBindingSuperSponsorsOnly() { let message = String.random let superSponsorsOnlyWarningViewModel = EventSuperSponsorsOnlyWarningViewModel(message: message) let viewModel = StubSuperSponsorsOnlyEventViewModel( superSponsorsOnlyWarningViewModel: superSponsorsOnlyWarningViewModel ) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedSuperSponsorsOnlyComponent.capturedMessage) } func testBindingDealersDen() { let message = String.random let artShowViewModel = EventDealersDenMessageViewModel(message: message) let viewModel = StubDealersDenEventViewModel(dealersDenMessageViewModel: artShowViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedDealersDenMessageComponent.capturedMessage) } func testBindingArtShow() { let message = String.random let artShowViewModel = EventArtShowMessageViewModel(message: message) let viewModel = StubArtShowEventViewModel(artShowMessageViewModel: artShowViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedArtShowMessageComponent.capturedMessage) } func testBindingFaceMaskRequired() { let message = String.random let faceMaskViewModel = EventFaceMaskMessageViewModel(message: message) let viewModel = StubFaceMaskEventViewModel(faceMaskMessageViewModel: faceMaskViewModel) let scene = prepareSceneForBindingComponent(viewModel: viewModel) XCTAssertEqual(message, scene.stubbedFaceMaskMessageComponent.capturedMessage) } private func prepareSceneForBindingComponent( viewModel: EventDetailViewModel ) -> CapturingEventDetailScene { let event = FakeEvent.random let viewModelFactory = FakeEventDetailViewModelFactory(viewModel: viewModel, for: event) let context = EventDetailPresenterTestBuilder().with(viewModelFactory).build(for: event) context.simulateSceneDidLoad() context.scene.bindComponent(at: IndexPath(item: 0, section: 0)) return context.scene } } struct StubFaceMaskEventViewModel: EventDetailViewModel { var faceMaskMessageViewModel: EventFaceMaskMessageViewModel var numberOfComponents: Int { return 1 } func setDelegate(_ delegate: EventDetailViewModelDelegate) { } func describe(componentAt index: Int, to visitor: EventDetailViewModelVisitor) { visitor.visit(faceMaskMessageViewModel) } func favourite() { } func unfavourite() { } }
33e8138188d457a3f84c08b380016b50
45.918239
113
0.75563
false
true
false
false
iOS-mamu/SS
refs/heads/master
P/Pods/PSOperations/PSOperations/UIUserNotifications+Operations.swift
mit
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A convenient extension to UIKit.UIUserNotificationSettings. */ #if os(iOS) import UIKit extension UIUserNotificationSettings { /// Check to see if one Settings object is a superset of another Settings object. func contains(_ settings: UIUserNotificationSettings) -> Bool { // our types must contain all of the other types if !types.contains(settings.types) { return false } let otherCategories = settings.categories ?? [] let myCategories = categories ?? [] return myCategories.isSuperset(of: otherCategories) } /** Merge two Settings objects together. `UIUserNotificationCategories` with the same identifier are considered equal. */ func settingsByMerging(_ settings: UIUserNotificationSettings) -> UIUserNotificationSettings { let mergedTypes = types.union(settings.types) let myCategories = categories ?? [] var existingCategoriesByIdentifier = Dictionary(sequence: myCategories) { $0.identifier } let newCategories = settings.categories ?? [] let newCategoriesByIdentifier = Dictionary(sequence: newCategories) { $0.identifier } for (newIdentifier, newCategory) in newCategoriesByIdentifier { existingCategoriesByIdentifier[newIdentifier] = newCategory } let mergedCategories = Set(existingCategoriesByIdentifier.values) return UIUserNotificationSettings(types: mergedTypes, categories: mergedCategories) } } #endif
576f26a9844a44575111e40e87496e39
33.55102
98
0.684584
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat.ShareExtension/Rooms/SERoomsViewController.swift
mit
1
// // SERoomsViewController.swift // Rocket.Chat.ShareExtension // // Created by Matheus Cardoso on 2/28/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import Social final class SERoomsViewController: SEViewController { private var viewModel = SERoomsViewModel.emptyState { didSet { title = viewModel.title navigationItem.searchController?.searchBar.text = viewModel.searchText navigationItem.searchController?.searchBar.showsCancelButton = viewModel.showsCancelButton tableView.reloadData() } } @IBOutlet weak var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self tableView.register(SERoomCell.self) tableView.register(SEServerCell.self) } } override func viewDidLoad() { super.viewDidLoad() let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.delegate = self searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false navigationItem.searchController = searchController tableView.keyboardDismissMode = .interactive } override func stateUpdated(_ state: SEState) { super.stateUpdated(state) viewModel = SERoomsViewModel(state: state) } @IBAction func cancelButtonPressed(_ sender: Any) { store.dispatch(.finish) } } // MARK: UISearchBarDelegate extension SERoomsViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { store.dispatch(.setSearchRooms(.started)) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { store.dispatch(.setSearchRooms(.none)) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { store.dispatch(.setSearchRooms(.none)) return } store.dispatch(.setSearchRooms(.searching(searchText))) } } // MARK: UITableViewDataSource extension SERoomsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRowsInSection(section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellModel = viewModel.cellForRowAt(indexPath) let cell: UITableViewCell if let cellModel = cellModel as? SEServerCellModel { let serverCell = tableView.dequeue(SEServerCell.self, forIndexPath: indexPath) serverCell.cellModel = cellModel cell = serverCell } else if let cellModel = cellModel as? SERoomCellModel { let roomCell = tableView.dequeue(SERoomCell.self, forIndexPath: indexPath) roomCell.cellModel = cellModel cell = roomCell } else { return UITableViewCell(style: .default, reuseIdentifier: cellModel.reuseIdentifier) } cell.accessoryType = .disclosureIndicator return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(viewModel.heightForRowAt(indexPath)) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForHeaderInSection(section) } } // MARK: UITableViewDelegate extension SERoomsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { viewModel.didSelectRowAt(indexPath) tableView.deselectRow(at: indexPath, animated: true) } }
92232b0eadaf3116a9a69e6fea1685f5
31
102
0.690524
false
false
false
false
lnds/9d9l
refs/heads/master
desafio1/swift/Sources/toque-y-fama/main.swift
mit
1
func validar(tam:Int, acc:String!) -> [Int]? { var num = [Int]() let chars = Array(acc) for (i,c) in chars.enumerated() { if i >= tam { return nil } else if c < "0" || c > "9" { return nil } else { let digito = Int(String(c))! if num.contains(digito) { return nil } num.append(Int(String(c))!) } } if num.count != tam { return nil } return num } func comparar(num:[Int], sec:[Int]) -> (toques:Int, famas:Int) { var toques = 0 var famas = 0 for (i, n) in num.enumerated() { for (j, m) in sec.enumerated() { if n == m { if i == j { famas += 1 } else { toques += 1 } } } } return (toques, famas) } let tam = 5 let numbers = 0...9 var sec = Array(numbers.shuffled().prefix(tam)) print (" Bienvenido a Toque y Fama.\n", "==========================\n\n", "En este juego debes tratar de adivinar una secuencia de \(tam) dígitos generadas por el programa.\n", "Para esto ingresas \(tam) dígitos distintos con el fin de adivinar la secuencia.\n", "Si has adivinado correctamente la posición de un dígito se produce una Fama.\n", "Si has adivinado uno de los dígitos de la secuencia, pero en una posición distinta se trata de un Toque.\n\n", "Ejemplo: Si la secuencia es secuencia: [8, 0, 6, 1, 3] e ingresas 40863, entonces en pantalla aparecerá:\n", "tu ingresaste [4, 0, 8, 6, 3]\n", "resultado: 2 Toques 2 Famas\n\n") var intentos = 0 while true { intentos += 1 print("Ingresa una secuencia de \(tam) dígitos distintos (o escribe salir):") let accion = readLine(strippingNewline:true) if accion == "salir" { break } else { let num = validar(tam:tam, acc:accion!) if num == nil { print("error!\n") } else { print("ingresaste: ", num!) let (toques, famas) = comparar(num: num!, sec:sec) print("resultado: \(toques) Toques, \(famas) Famas\n") if famas == tam { print("Ganaste! Acertaste al intento \(intentos)! La secuencia era \(sec).") break } } } }
f281d3a9ac29ca74fa8ae01e5cb3f111
26.027397
113
0.611562
false
false
false
false
Breinify/brein-api-library-ios
refs/heads/master
BreinifyApi/engine/BreinEngine.swift
mit
1
// // Created by Marco Recchioni // Copyright (c) 2020 Breinify. All rights reserved. // import Foundation /** Creates the Rest Engine and provides the methods to invoke activity and lookup calls */ public class BreinEngine { public typealias apiSuccess = (_ result: BreinResult) -> Void public typealias apiFailure = (_ error: NSDictionary) -> Void /** creation of rest engine - currently it is only Alamofire */ var restEngine: IRestEngine! /** Contains the instance of the locationManager -> this enables the API to detect the location information if the info.plist of the app has the permissions. */ var locationManager = BreinLocationManager(ignoreLocationRequest: false) /** Creates the BreinEngine instance with a given breinEngineType */ public init(engineType: BreinEngineType) { restEngine = URLSessionEngine() } /** Sends an activity to the Breinify server - Parameter activity: data to be send - Parameter successBlock : A callback function that is invoked in case of success. - Parameter failureBlock : A callback function that is invoked in case of an error. Important: * due to the fact that the locationManager will invoke CLLocationManager it must run on the main thread */ public func sendActivity(_ activity: BreinActivity!, success successBlock: @escaping BreinEngine.apiSuccess, failure failureBlock: @escaping BreinEngine.apiFailure) throws { if activity != nil { if activity.getConfig().getWithLocationManagerUsage() == true { // necessary to invoke CLLocationManager // need to come back to main thread DispatchQueue.main.async { self.locationManager.fetchWithCompletion { location, error in // save the retrieved location data activity.getUser()?.setLocationData(location) // print("latitude is: \(location?.coordinate.latitude)") // print("longitude is: \(location?.coordinate.longitude)") do { try self.restEngine.doRequest(activity, success: successBlock, failure: failureBlock) } catch { BreinLogger.shared.log("Breinify activity with locationmanger usage error is: \(error)") } } } } else { do { try restEngine.doRequest(activity, success: successBlock, failure: failureBlock) } catch { BreinLogger.shared.log("Breinify doRequest error is: \(error)") } } } } /** Performs a temporalData request - Parameter breinTemporalData: contains the appropriate data in order to perform the request - Parameter successBlock : A callback function that is invoked in case of success. - Parameter failureBlock : A callback function that is invoked in case of an error. - returns: result from Breinify engine */ public func performTemporalDataRequest(_ breinTemporalData: BreinTemporalData!, success successBlock: @escaping apiSuccess, failure failureBlock: @escaping apiFailure) throws { if breinTemporalData != nil { // necessary to invoke CLLocationManager // need to come back to main thread DispatchQueue.main.async { self.locationManager.fetchWithCompletion { location, error in // save the retrieved location data breinTemporalData.getUser()?.setLocationData(location) BreinLogger.shared.log("Breinify latitude is: \(location?.coordinate.latitude ?? -1)") BreinLogger.shared.log("Breinify longitude is: \(location?.coordinate.longitude ?? -1)") do { return try self.restEngine.doTemporalDataRequest(breinTemporalData, success: successBlock, failure: failureBlock) } catch { BreinLogger.shared.log("Breinify performTemporalDataRequest error is: \(error)") } } } } } /** Performs a lookup. This will be delegated to the configured restEngine. - Parameter breinLookup: contains the appropriate data for the lookup request - Parameter successBlock : A callback function that is invoked in case of success. - Parameter failureBlock : A callback function that is invoked in case of an error. - returns: if succeeded a BreinResponse object or null */ public func performLookUp(_ breinLookup: BreinLookup!, success successBlock: @escaping apiSuccess, failure failureBlock: @escaping apiFailure) throws { if breinLookup != nil { // necessary to invoke CLLocationManager // need to come back to main thread DispatchQueue.main.async { self.locationManager.fetchWithCompletion { location, error in // save the retrieved location data breinLookup.getUser()?.setLocationData(location) BreinLogger.shared.log("Breinify latitude is: \(String(describing: location?.coordinate.latitude))") BreinLogger.shared.log("Breinify longitude is: \(String(describing: location?.coordinate.longitude))") do { if breinLookup != nil { return try self.restEngine.doLookup(breinLookup, success: successBlock, failure: failureBlock) } } catch { BreinLogger.shared.log("Breinify performLookUp error is: \(error)") } } } } } /** Invokes the recommendation request - Parameter breinRecommendation: contains the breinRecommendation object - Parameter successBlock : A callback function that is invoked in case of success. - Parameter failureBlock : A callback function that is invoked in case of an error. - return result of request or null */ public func invokeRecommendation(_ breinRecommendation: BreinRecommendation!, success successBlock: @escaping BreinEngine.apiSuccess, failure failureBlock: @escaping BreinEngine.apiFailure) throws { if breinRecommendation != nil { // necessary to invoke CLLocationManager // need to come back to main thread DispatchQueue.main.async { self.locationManager.fetchWithCompletion { location, error in // save the retrieved location data breinRecommendation.getUser()?.setLocationData(location) if let loc = location { BreinLogger.shared.log("Breinify latitude is: \(loc.coordinate.latitude)") BreinLogger.shared.log("Breinify longitude is: \(loc.coordinate.longitude)") } do { if breinRecommendation != nil { return try self.restEngine.doRecommendation(breinRecommendation, success: successBlock, failure: failureBlock) } } catch { BreinLogger.shared.log("Breinify invokeRecommendation error is: \(error)") } } } } } /** Returns the rest engine - returns: engine itself */ public func getRestEngine() -> IRestEngine! { restEngine } /** Configuration of engine - parameter breinConfig: configuration object */ public func configure(_ breinConfig: BreinConfig!) { restEngine.configure(breinConfig) } }
36a69edccd383fbfce80bd7d84cb372b
35.864407
122
0.553103
false
false
false
false
bestwpw/RxSwift
refs/heads/master
RxSwift/Schedulers/CurrentThreadScheduler.swift
mit
2
// // CurrentThreadScheduler.swift // Rx // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation let CurrentThreadSchedulerKeyInstance = CurrentThreadSchedulerKey() class CurrentThreadSchedulerKey : NSObject, NSCopying { override func isEqual(object: AnyObject?) -> Bool { return object === CurrentThreadSchedulerKeyInstance } override var hashValue: Int { return -904739208 } override func copy() -> AnyObject { return CurrentThreadSchedulerKeyInstance } func copyWithZone(zone: NSZone) -> AnyObject { return CurrentThreadSchedulerKeyInstance } } // WIP class CurrentThreadScheduler : ImmediateScheduler { static var isScheduleRequired: Bool { return NSThread.currentThread().threadDictionary[CurrentThreadSchedulerKeyInstance] == nil } func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable { return NopDisposable.instance } }
ef579de29896f10f1cb29d7aed607b8d
25.948718
98
0.705714
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/Avatar.swift
mit
1
// // Avatar.swift // TranslationEditor // // Created by Mikko Hilpinen on 27.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation import SCrypto // Avatars are project-specific user accounts final class Avatar: Storable { // ATTRIBUTES ------------- static let PROPERTY_PROJECT = "project" static let type = "avatar" let projectId: String let created: TimeInterval let uid: String let accountId: String var name: String var isAdmin: Bool var isDisabled: Bool // COMPUTED PROPERTIES ----- static var idIndexMap: IdIndexMap { return Project.idIndexMap.makeChildPath(parentPathName: PROPERTY_PROJECT, childPath: ["avatar_separator", "avatar_uid"]) } var idProperties: [Any] { return [projectId, "avatar", uid] } var properties: [String : PropertyValue] { return ["name": name.value, "account": accountId.value, "created": created.value, "admin": isAdmin.value, "disabled": isDisabled.value] } // INIT --------------------- init(name: String, projectId: String, accountId: String, isAdmin: Bool = false, isDisabled: Bool = false, uid: String = UUID().uuidString.lowercased(), created: TimeInterval = Date().timeIntervalSince1970) { self.isAdmin = isAdmin self.isDisabled = isDisabled self.projectId = projectId self.name = name self.created = created self.uid = uid self.accountId = accountId } static func create(from properties: PropertySet, withId id: Id) throws -> Avatar { return Avatar(name: properties["name"].string(), projectId: id[PROPERTY_PROJECT].string(), accountId: properties["account"].string(), isAdmin: properties["admin"].bool(), isDisabled: properties["disabled"].bool(), uid: id["avatar_uid"].string(), created: properties["created"].time()) } // IMPLEMENTED METHODS ----- func update(with properties: PropertySet) { if let name = properties["name"].string { self.name = name } if let isAdmin = properties["admin"].bool { self.isAdmin = isAdmin } if let isDisabled = properties["disabled"].bool { self.isDisabled = isDisabled } } // OTHER METHODS --------- // The private infor for this avatar instance func info() throws -> AvatarInfo? { return try AvatarInfo.get(avatarId: idString) } static func project(fromId avatarId: String) -> String { return property(withName: PROPERTY_PROJECT, fromId: avatarId).string() } // Creates a new avatar id based on the provided properties /* static func createId(projectId: String, avatarName: String) -> String { return parseId(from: [projectId, "avatar", avatarName.toKey]) }*/ // Retrieves avatar data from the database /* static func get(projectId: String, avatarName: String) throws -> Avatar? { return try get(createId(projectId: projectId, avatarName: avatarName)) }*/ /* fileprivate static func nameKey(ofId avatarId: String) -> String { return property(withName: "avatar_name_key", fromId: avatarId).string() }*/ } // This class contains avatar info that is only visible in the project scope final class AvatarInfo: Storable { // ATTRIBUTES ------------- static let PROPERTY_AVATAR = "avatar" static let type = "avatar_info" let avatarId: String var isShared: Bool // Phase id -> Carousel id // var carouselIds: [String : String] private var passwordHash: String? private var _image: UIImage? var image: UIImage? { // Reads the image from CB if necessary if let image = _image { return image } else { if let image = attachment(named: "image")?.toImage { _image = image return image } else { return nil } } } // COMPUTED PROPERTIES ---- static var idIndexMap: IdIndexMap { return Avatar.idIndexMap.makeChildPath(parentPathName: PROPERTY_AVATAR, childPath: ["info_separator"]) } var idProperties: [Any] { return [avatarId, "info"] } var properties: [String : PropertyValue] { return ["offline_password": passwordHash.value, "shared": isShared.value] } var projectId: String { return Avatar.project(fromId: avatarId) } // The key version of the avatar's name // var nameKey: String { return Avatar.nameKey(ofId: avatarId) } // Whether the info requires a password for authentication var requiresPassword: Bool { return passwordHash != nil } // INIT -------------------- init(avatarId: String, password: String? = nil, isShared: Bool = false) { self.avatarId = avatarId self.isShared = isShared if let password = password { // Uses the avatar id as salt self.passwordHash = createPasswordHash(password: password) } } private init(avatarId: String, passwordHash: String?, isShared: Bool) { self.avatarId = avatarId self.passwordHash = passwordHash self.isShared = isShared } static func create(from properties: PropertySet, withId id: Id) throws -> AvatarInfo { return AvatarInfo(avatarId: id[PROPERTY_AVATAR].string(), passwordHash: properties["offline_password"].string, isShared: properties["shared"].bool()) } // IMPLEMENTED METHODS --- func update(with properties: PropertySet) { if let isShared = properties["shared"].bool { self.isShared = isShared } if let passwordHash = properties["offline_password"].string { self.passwordHash = passwordHash } } // OTHER METHODS ------- // Changes the image associated with this avatar func setImage(_ image: UIImage) throws { if (_image != image) { _image = image if let attachment = Attachment.parse(fromImage: image) { try saveAttachment(attachment, withName: "image") } } } // Updates the avatar's password func setPassword(_ password: String) { passwordHash = createPasswordHash(password: password) } func resetPassword() { passwordHash = nil } func authenticate(loggedAccountId: String?, password: String) -> Bool { if passwordHash == nil { return true } else { return createPasswordHash(password: password) == passwordHash } } private func createPasswordHash(password: String) -> String { return (avatarId + password).SHA256() } static func get(avatarId: String) throws -> AvatarInfo? { return try get(parseId(from: [avatarId, "info"])) } // The avatar id portion of the avatar info id string static func avatarId(fromAvatarInfoId infoId: String) -> String { return property(withName: PROPERTY_AVATAR, fromId: infoId).string() } }
c85f09a360bce0d92c83ec959aacbec8
22.335766
286
0.685174
false
false
false
false
brokenseal/iOS-exercises
refs/heads/master
Team Treehouse/Contacts/Contacts/Contact.swift
mit
1
// // Contact.swift // Contacts // // Created by Screencast on 3/13/17. // Copyright © 2017 Treehouse Island. All rights reserved. // import Foundation import UIKit struct Contact { let firstName: String let lastName: String let phone: String let email: String let street: String let city: String let state: String let zip: String let image: UIImage? var isFavorite: Bool } extension Contact { struct Key { static let firstName = "firstName" static let lastName = "lastName" static let phone = "phoneNumber" static let email = "email" static let street = "streetAddress" static let city = "city" static let state = "state" static let zip = "zip" static let image = "avatarName" } init?(dictionary: [String: String]) { guard let firstNameString = dictionary[Key.firstName], let lastNameString = dictionary[Key.lastName], let phoneString = dictionary[Key.phone], let emailString = dictionary[Key.email], let streetString = dictionary[Key.street], let cityString = dictionary[Key.city], let stateString = dictionary[Key.state], let zipString = dictionary[Key.zip] else { return nil } self.firstName = firstNameString self.lastName = lastNameString self.phone = phoneString self.email = emailString self.street = streetString self.city = cityString self.state = stateString self.zip = zipString if let imageName = dictionary[Key.image] { self.image = UIImage(named: imageName) } else { image = nil } isFavorite = false } }
b8f54bc901845fc43906b8bddf84db81
25.925373
67
0.594789
false
false
false
false
007HelloWorld/DouYuZhiBo
refs/heads/0331
06-Touch ID /Pods/Alamofire/Source/Notifications.swift
agpl-3.0
745
// // Notifications.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Notification.Name { /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") } } // MARK: - extension Notification { /// Used as a namespace for all `Notification` user info dictionary keys. public struct Key { /// User info dictionary key representing the `URLSessionTask` associated with the notification. public static let Task = "org.alamofire.notification.key.task" } }
363d8b32952f29e07b8593e8b8640578
50.019231
123
0.740671
false
false
false
false
dzindra/toycar
refs/heads/master
iOS/auto/CarService.swift
bsd-2-clause
1
// // CarService.swift // auto // // Created by Džindra on 08.04.16. // Copyright © 2016 Dzindra. All rights reserved. // import UIKit import SystemConfiguration.CaptiveNetwork class CarService { static let motorMin = 0 static let motorMax = 2046 static let motorStop = 1023 static let SSID = "Auto!" static let instance = CarService(host: "192.168.4.1", port: 6666) let port: UInt16 let host: String let socket: GCDAsyncUdpSocket var timer: NSTimer? var motor1: Int = 1023 { didSet { if motor1 > CarService.motorMax { motor1 = CarService.motorMax } if motor1 < CarService.motorMin { motor1 = CarService.motorMin } } } var motor2: Int = 1023 { didSet { if motor2 > CarService.motorMax { motor2 = CarService.motorMax } if motor2 < CarService.motorMin { motor2 = CarService.motorMin } } } var lights: Bool = false init(host: String, port: UInt16) { self.host = host self.port = port self.socket = GCDAsyncUdpSocket() self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(CarService.sendData), userInfo: nil, repeats: true) } @objc func sendData() { let data = String(format:"A%03X%03X%@", motor1, motor2, lights ? "1":"0") //print ("Sending \(data)") socket.sendData(data.dataUsingEncoding(NSUTF8StringEncoding), toHost: host, port: port, withTimeout: 1, tag: 0) } func setSpeed(motor1: Int, _ motor2: Int) { self.motor1 = motor1 self.motor2 = motor2 } func setSpeed(motor1: Int, _ motor2: Int, _ lights: Bool) { self.motor1 = motor1 self.motor2 = motor2 self.lights = lights } func setZeroSpeed() { setSpeed(CarService.motorStop, CarService.motorStop, false) } func currentSSID() -> String? { guard let ifc = CNCopySupportedInterfaces() as [AnyObject]? else { return nil } for intf in ifc { if let intfs = intf as? String, ni = CNCopyCurrentNetworkInfo(intfs) as Dictionary?, ssid = ni[kCNNetworkInfoKeySSID] as? String { return ssid } } return nil } func isReady() -> Bool { return currentSSID() == CarService.SSID } }
0bc59ce75de86f8314a0fa5c00756d8a
28.506173
150
0.598326
false
false
false
false
things-nyc/mapthethings-ios
refs/heads/master
MapTheThings/Provisioning.swift
mit
1
// // Provisioning.swift // MapTheThings // // Created by Frank on 2017/1/14. // Copyright © 2017 The Things Network New York. All rights reserved. // import CoreData import Foundation import MapKit import Alamofire import PromiseKit import ReactiveSwift extension Data { // Thanks: http://stackoverflow.com/a/26502285/1207583 /// Create `NSData` from hexadecimal string representation /// /// This takes a hexadecimal representation and creates a `NSData` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed. /// /// - returns: Data represented by this hexadecimal string. static func dataWithHexString(_ s: String) -> Data? { let data = NSMutableData(capacity: s.count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: s, options: [], range: NSMakeRange(0, s.count)) { match, flags, stop in let byteString = (s as NSString).substring(with: match!.range) var num = UInt8(byteString, radix: 16) data?.append(&num, length: 1) } return data as Data? } } open class Provisioning { var provisionDisposer: Disposable? init() { self.provisionDisposer = appStateObservable.observeValues { update in if let (_, deviceID) = update.new.requestProvisioning, stateValChanged(update, access: { $0.requestProvisioning}) { self.getOTAA(deviceID, host: update.new.host) } } } fileprivate func getOTAA(_ deviceID: UUID, host: String) { let parameters: [String: AnyObject] = ["devName": "My Name" as AnyObject] debugPrint("Params: \(parameters)") let url = "http://\(host)/api/v0/provision-device" debugPrint("URL: \(url)") let rsp = Promise<NSDictionary> { fulfill, reject in return request(url, method: .post, parameters: parameters, encoding: JSONEncoding()) .responseJSON(queue: nil, options: .allowFragments, completionHandler: { response in switch response.result { case .success(let value): fulfill(value as! NSDictionary) case .failure(let error): reject(error) } }) } rsp.then { jsonResponse -> Void in debugPrint(jsonResponse) if let appKey = jsonResponse["app_key"] as? String, let appKeyData = Data.dataWithHexString(appKey), let appEUI = jsonResponse["app_eui"] as? String, let appEUIData = Data.dataWithHexString(appEUI), let devEUI = jsonResponse["dev_eui"] as? String, let devEUIData = Data.dataWithHexString(devEUI), appKeyData.count==16 && appEUIData.count==8 && devEUIData.count==8 { updateAppState { var state = $0 if var dev = state.bluetooth[deviceID] { dev.appKey = appKeyData dev.appEUI = appEUIData dev.devEUI = devEUIData state.bluetooth[deviceID] = dev state.assignProvisioning = (UUID(), deviceID) } return state } } else { var msg = "Invalid JSON response" if let reason = jsonResponse["error"] as? String { msg = reason } let userInfo = [NSLocalizedFailureReasonErrorKey: msg] throw NSError(domain: "web", code: 0, userInfo: userInfo) } }.catch { (error) in debugPrint("\(error)") setAppError(error, fn: "getOTAA", domain: "web") } } }
d781b58de84ee9c81728668d1a083db2
38.72549
231
0.552813
false
false
false
false
klaus01/Centipede
refs/heads/master
Centipede/UIKit/CE_UIActionSheet.swift
mit
1
// // CE_UIActionSheet.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import UIKit extension UIActionSheet { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: UIActionSheet_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIActionSheet_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: UIActionSheet_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is UIActionSheet_Delegate { return obj as! UIActionSheet_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal func getDelegateInstance() -> UIActionSheet_Delegate { return UIActionSheet_Delegate() } @discardableResult public func ce_actionSheet_clickedButtonAt(handle: @escaping (UIActionSheet, Int) -> Void) -> Self { ce._actionSheet_clickedButtonAt = handle rebindingDelegate() return self } @discardableResult public func ce_actionSheetCancel(handle: @escaping (UIActionSheet) -> Void) -> Self { ce._actionSheetCancel = handle rebindingDelegate() return self } @discardableResult public func ce_willPresent(handle: @escaping (UIActionSheet) -> Void) -> Self { ce._willPresent = handle rebindingDelegate() return self } @discardableResult public func ce_didPresent(handle: @escaping (UIActionSheet) -> Void) -> Self { ce._didPresent = handle rebindingDelegate() return self } @discardableResult public func ce_actionSheet_willDismissWithButtonIndex(handle: @escaping (UIActionSheet, Int) -> Void) -> Self { ce._actionSheet_willDismissWithButtonIndex = handle rebindingDelegate() return self } @discardableResult public func ce_actionSheet_didDismissWithButtonIndex(handle: @escaping (UIActionSheet, Int) -> Void) -> Self { ce._actionSheet_didDismissWithButtonIndex = handle rebindingDelegate() return self } } internal class UIActionSheet_Delegate: NSObject, UIActionSheetDelegate { var _actionSheet_clickedButtonAt: ((UIActionSheet, Int) -> Void)? var _actionSheetCancel: ((UIActionSheet) -> Void)? var _willPresent: ((UIActionSheet) -> Void)? var _didPresent: ((UIActionSheet) -> Void)? var _actionSheet_willDismissWithButtonIndex: ((UIActionSheet, Int) -> Void)? var _actionSheet_didDismissWithButtonIndex: ((UIActionSheet, Int) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(actionSheet(_:clickedButtonAt:)) : _actionSheet_clickedButtonAt, #selector(actionSheetCancel(_:)) : _actionSheetCancel, #selector(willPresent(_:)) : _willPresent, #selector(didPresent(_:)) : _didPresent, #selector(actionSheet(_:willDismissWithButtonIndex:)) : _actionSheet_willDismissWithButtonIndex, #selector(actionSheet(_:didDismissWithButtonIndex:)) : _actionSheet_didDismissWithButtonIndex, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { _actionSheet_clickedButtonAt!(actionSheet, buttonIndex) } @objc func actionSheetCancel(_ actionSheet: UIActionSheet) { _actionSheetCancel!(actionSheet) } @objc func willPresent(_ actionSheet: UIActionSheet) { _willPresent!(actionSheet) } @objc func didPresent(_ actionSheet: UIActionSheet) { _didPresent!(actionSheet) } @objc func actionSheet(_ actionSheet: UIActionSheet, willDismissWithButtonIndex buttonIndex: Int) { _actionSheet_willDismissWithButtonIndex!(actionSheet, buttonIndex) } @objc func actionSheet(_ actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) { _actionSheet_didDismissWithButtonIndex!(actionSheet, buttonIndex) } }
18074e610a228f6ab767a26dfb38091a
34.804688
128
0.654157
false
false
false
false
amosavian/FileProvider
refs/heads/master
Sources/SMBTypes/SMB2FileOperation.swift
mit
2
// // SMB2FileOperation.swift // ExtDownloader // // Created by Amir Abbas Mousavian on 4/30/95. // Copyright © 1395 Mousavian. All rights reserved. // import Foundation extension SMB2 { // MARK: SMB2 Read struct ReadRequest: SMBRequestBody { static var command: SMB2.Command = .READ let size: UInt16 fileprivate let padding: UInt8 let flags: ReadRequest.Flags let length: UInt32 let offset: UInt64 let fileId: FileId let minimumLength: UInt32 let channel: Channel let remainingBytes: UInt32 fileprivate let channelInfoOffset: UInt16 fileprivate let channelInfoLength: UInt16 fileprivate let channelBuffer: UInt8 init (fileId: FileId, offset: UInt64, length: UInt32, flags: ReadRequest.Flags = [], minimumLength: UInt32 = 0, remainingBytes: UInt32 = 0, channel: Channel = .NONE) { self.size = 49 self.padding = 0 self.flags = flags self.length = length self.offset = offset self.fileId = fileId self.minimumLength = minimumLength self.channel = channel self.remainingBytes = remainingBytes self.channelInfoOffset = 0 self.channelInfoLength = 0 self.channelBuffer = 0 } struct Flags: OptionSet { let rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static let UNBUFFERED = Flags(rawValue: 0x01) } } struct ReadRespone: SMBResponseBody { struct Header { let size: UInt16 let offset: UInt8 fileprivate let reserved: UInt8 let length: UInt32 let remaining: UInt32 fileprivate let reserved2: UInt32 } let header: ReadRespone.Header let buffer: Data init?(data: Data) { guard data.count > 16 else { return nil } self.header = data.scanValue()! let headersize = MemoryLayout<Header>.size self.buffer = data.subdata(in: headersize..<data.count) } } struct Channel: Option { init(rawValue: UInt32) { self.rawValue = rawValue } let rawValue: UInt32 public static let NONE = Channel(rawValue: 0x00000000) public static let RDMA_V1 = Channel(rawValue: 0x00000001) public static let RDMA_V1_INVALIDATE = Channel(rawValue: 0x00000002) } // MARK: SMB2 Write struct WriteRequest: SMBRequestBody { static var command: SMB2.Command = .WRITE let header: WriteRequest.Header let channelInfo: ChannelInfo? let fileData: Data struct Header { let size: UInt16 let dataOffset: UInt16 let length: UInt32 let offset: UInt64 let fileId: FileId let channel: Channel let remainingBytes: UInt32 let channelInfoOffset: UInt16 let channelInfoLength: UInt16 let flags: WriteRequest.Flags } // codebeat:disable[ARITY] init(fileId: FileId, offset: UInt64, remainingBytes: UInt32 = 0, data: Data, channel: Channel = .NONE, channelInfo: ChannelInfo? = nil, flags: WriteRequest.Flags = []) { var channelInfoOffset: UInt16 = 0 var channelInfoLength: UInt16 = 0 if channel != .NONE, let _ = channelInfo { channelInfoOffset = UInt16(MemoryLayout<SMB2.Header>.size + MemoryLayout<WriteRequest.Header>.size) channelInfoLength = UInt16(MemoryLayout<SMB2.ChannelInfo>.size) } let dataOffset = UInt16(MemoryLayout<SMB2.Header>.size + MemoryLayout<WriteRequest.Header>.size) + channelInfoLength self.header = WriteRequest.Header(size: UInt16(49), dataOffset: dataOffset, length: UInt32(data.count), offset: offset, fileId: fileId, channel: channel, remainingBytes: remainingBytes, channelInfoOffset: channelInfoOffset, channelInfoLength: channelInfoLength, flags: flags) self.channelInfo = channelInfo self.fileData = data } // codebeat:enable[ARITY] func data() -> Data { var result = Data(value: self.header) if let channelInfo = channelInfo { result.append(channelInfo.data()) } result.append(fileData) return result } struct Flags: OptionSet { let rawValue: UInt32 init(rawValue: UInt32) { self.rawValue = rawValue } static let THROUGH = Flags(rawValue: 0x00000001) static let UNBUFFERED = Flags(rawValue: 0x00000002) } } struct WriteResponse: SMBResponseBody { let size: UInt16 fileprivate let reserved: UInt16 let writtenBytes: UInt32 fileprivate let remaining: UInt32 fileprivate let channelInfoOffset: UInt16 fileprivate let channelInfoLength: UInt16 } struct ChannelInfo: SMBRequestBody { static var command: SMB2.Command = .WRITE let offset: UInt64 let token: UInt32 let length: UInt32 } // MARK: SMB2 Lock struct LockElement: SMBRequestBody { static var command: SMB2.Command = .LOCK let offset: UInt64 let length: UInt64 let flags: LockElement.Flags fileprivate let reserved: UInt32 struct Flags: OptionSet { let rawValue: UInt32 init(rawValue: UInt32) { self.rawValue = rawValue } static let SHARED_LOCK = Flags(rawValue: 0x00000001) static let EXCLUSIVE_LOCK = Flags(rawValue: 0x00000002) static let UNLOCK = Flags(rawValue: 0x00000004) static let FAIL_IMMEDIATELY = Flags(rawValue: 0x00000010) } } struct LockRequest: SMBRequestBody { static var command: SMB2.Command = .LOCK let header: LockRequest.Header let locks: [LockElement] init(fileId: FileId,locks: [LockElement], lockSequenceNumber : Int8 = 0, lockSequenceIndex: UInt32 = 0) { self.header = LockRequest.Header(size: 48, lockCount: UInt16(locks.count), lockSequence: UInt32(lockSequenceNumber << 28) + lockSequenceIndex, fileId: fileId) self.locks = locks } func data() -> Data { var result = Data(value: header) for lock in locks { result.append(Data(value: lock)) } return result } struct Header { let size: UInt16 fileprivate let lockCount: UInt16 let lockSequence: UInt32 let fileId : FileId } } struct LockResponse: SMBResponseBody { let size: UInt16 let reserved: UInt16 init() { self.size = 4 self.reserved = 0 } } // MARK: SMB2 Cancel struct CancelRequest: SMBRequestBody { static var command: SMB2.Command = .CANCEL let size: UInt16 let reserved: UInt16 init() { self.size = 4 self.reserved = 0 } } }
30830b43dec74c7f51876459fba33f43
31.25
287
0.557106
false
false
false
false
heptal/kathy
refs/heads/master
Kathy/TableViews.swift
apache-2.0
1
// // TableViews.swift // Kathy // // Created by Michael Bujol on 6/13/16. // Copyright © 2016 heptal. All rights reserved. // import Cocoa class ChannelView: NSScrollView, NSTableViewDelegate { override init(frame frameRect: NSRect) { super.init(frame: frameRect) let tableView = NSTableView() tableView.identifier = "channelTableView" tableView.allowsEmptySelection = false tableView.allowsMultipleSelection = false tableView.addTableColumn(NSTableColumn()) tableView.headerView = nil tableView.delegate = self documentView = tableView } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let identifier = "channel" guard let textField = tableView.make(withIdentifier: identifier, owner: self) else { let textField = NSTextField() textField.identifier = identifier textField.isBordered = false textField.drawsBackground = false textField.isEditable = false return textField } return textField } } class UserView: NSScrollView, NSTableViewDelegate { override init(frame frameRect: NSRect) { super.init(frame: frameRect) let tableView = NSTableView() tableView.identifier = "userTableView" tableView.allowsMultipleSelection = false tableView.addTableColumn(NSTableColumn()) tableView.headerView = nil tableView.delegate = self documentView = tableView } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let identifier = "user" guard let textField = tableView.make(withIdentifier: identifier, owner: self) else { let textField = NSTextField() textField.identifier = identifier textField.isBordered = false textField.drawsBackground = false textField.isEditable = false return textField } return textField } }
3750ede189532e8a2cc634569724918c
27.567901
104
0.642178
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/SILGen/optional.swift
apache-2.0
3
// RUN: %target-swift-emit-silgen -module-name optional %s | %FileCheck %s func testCall(_ f: (() -> ())?) { f?() } // CHECK: sil hidden [ossa] @{{.*}}testCall{{.*}} // CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> ()>): // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK-NEXT: switch_enum [[T0_COPY]] : $Optional<@callee_guaranteed () -> ()>, case #Optional.some!enumelt: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]] // // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: [[SOME]]([[FN0:%.*]] : // .... then call it // CHECK-NEXT: [[B:%.*]] = begin_borrow [[FN0]] // CHECK-NEXT: apply [[B]]() // CHECK: destroy_value [[FN0]] // CHECK: br [[EXIT:bb[0-9]+]]( // (first nothing block) // CHECK: [[NONE]]: // CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt // CHECK-NEXT: br [[EXIT]] // CHECK: } // end sil function '$s8optional8testCallyyyycSgF' func testAddrOnlyCallResult<T>(_ f: (() -> T)?) { var f = f var x = f?() } // CHECK-LABEL: sil hidden [ossa] @{{.*}}testAddrOnlyCallResult{{.*}} : // CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <T>>): // CHECK: [[F:%.*]] = alloc_box $<τ_0_0> { var Optional<@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <τ_0_0>> } <T>, var, name "f" // CHECK-NEXT: [[PBF:%.*]] = project_box [[F]] // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK: store [[T0_COPY]] to [init] [[PBF]] // CHECK-NEXT: [[X:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>, var, name "x" // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]] // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBF]] // Check whether 'f' holds a value. // CHECK: [[HASVALUE:%.*]] = select_enum_addr [[READ]] // CHECK-NEXT: cond_br [[HASVALUE]], bb1, bb3 // If so, pull out the value... // CHECK: bb1: // CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[READ]] // CHECK-NEXT: [[T0:%.*]] = load [copy] [[T1]] // CHECK-NEXT: end_access [[READ]] // ...evaluate the rest of the suffix... // CHECK: [[B:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: apply [[B]]([[TEMP]]) // ...and coerce to T? // CHECK: inject_enum_addr [[PBX]] {{.*}}some // CHECK: destroy_value [[T0]] // CHECK-NEXT: br bb2 // Continuation block. // CHECK: bb2 // CHECK-NEXT: destroy_value [[X]] // CHECK-NEXT: destroy_value [[F]] // CHECK-NOT: destroy_value %0 // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() // Nothing block. // CHECK: bb3: // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none // CHECK-NEXT: br bb2 // <rdar://problem/15180622> func wrap<T>(_ x: T) -> T? { return x } // CHECK-LABEL: sil hidden [ossa] @$s8optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F func wrap_then_unwrap<T>(_ x: T) -> T { // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]] // CHECK: [[FAIL]]: // CHECK: unreachable // CHECK: [[OK]]: // CHECK: unchecked_take_enum_data_addr return wrap(x)! } // CHECK-LABEL: sil hidden [ossa] @$s8optional10tuple_bind{{[_0-9a-zA-Z]*}}F func tuple_bind(_ x: (Int, String)?) -> String? { return x?.1 // CHECK: switch_enum {{%.*}}, case #Optional.some!enumelt: [[NONNULL:bb[0-9]+]], case #Optional.none!enumelt: [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]([[TUPLE:%.*]] : // CHECK: ({{%.*}}, [[STRING:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: [[RESULT:%.*]] = enum $Optional<String>, #Optional.some!enumelt, [[STRING]] // CHECK-NOT: destroy_value [[STRING]] // CHECK: br {{bb[0-9]+}}([[RESULT]] : } // rdar://21883752 - We were crashing on this function because the deallocation happened // out of scope. // CHECK-LABEL: sil hidden [ossa] @$s8optional16crash_on_deallocyySDySiSaySiGGFfA_ func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) { var dict = dict dict[1]?.append(2) } func use_unwrapped(_: Int) {} // CHECK-LABEL: sil hidden [ossa] @$s8optional15explicit_unwrap{{[_0-9a-zA-Z]*}}F // CHECK: [[FILESTR:%.*]] = string_literal utf8 "{{.*}}optional.swift" // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) func explicit_unwrap(_ value: Int?) { use_unwrapped(value!) } // CHECK-LABEL: sil hidden [ossa] @$s8optional19explicit_iuo_unwrap{{[_0-9a-zA-Z]*}}F // CHECK: [[FILESTR:%.*]] = string_literal utf8 "{{.*}}optional.swift" // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) func explicit_iuo_unwrap(_ value: Int!) { use_unwrapped(value!) } // CHECK-LABEL: sil hidden [ossa] @$s8optional19implicit_iuo_unwrap{{[_0-9a-zA-Z]*}}F // CHECK: [[FILESTR:%.*]] = string_literal utf8 "{{.*}}optional.swift" // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) func implicit_iuo_unwrap(_ value: Int!) { use_unwrapped(value) } // CHECK-LABEL: sil hidden [ossa] @$s8optional34implicit_iuo_unwrap_sourceLocation{{[_0-9a-zA-Z]*}}F // CHECK: [[FILESTR:%.*]] = string_literal utf8 "custom.swuft" // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, 2000 // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) func implicit_iuo_unwrap_sourceLocation(_ value: Int!) { #sourceLocation(file: "custom.swuft", line: 2000) use_unwrapped(value) #sourceLocation() // reset }
208b60a354e7faf122e7134a457f8669
45.515723
175
0.576528
false
false
false
false
ccwuzhou/WWZSwift
refs/heads/master
Source/Models/WWZArchiver.swift
mit
1
// // WWZArchiver.swift // WWZSwift // // Created by wwz on 17/3/14. // Copyright © 2017年 tijio. All rights reserved. // import UIKit class WWZArchiver: NSObject, NSCoding { required convenience init?(coder aDecoder: NSCoder) { self.init() for children in Mirror(reflecting: self).children { if let key = children.label { setValue(aDecoder.decodeObject(forKey: key), forKey: key) } } } func encode(with aCoder: NSCoder) { for children in Mirror(reflecting: self).children { if let key = children.label { aCoder.encode(value(forKey: key), forKey: key) } } } } final class PreferenceKey<T>: PreferenceKeys { } class PreferenceKeys: RawRepresentable, Hashable { let rawValue: String required init!(rawValue: String) { self.rawValue = rawValue } convenience init(_ key: String) { self.init(rawValue: key) } var hashValue: Int { return rawValue.hashValue } } extension PreferenceKeys { static let launchAtLogin = PreferenceKey<Bool>("LaunchAtLogin") static let launchCount = PreferenceKey<Int>("LaunchCount") static let userInfo = PreferenceKey<WWZArchiver>("UserInfo") } let defaultPreferences: [PreferenceKeys: Any] = [ .launchAtLogin: false, .launchCount: 0, .userInfo: NSKeyedArchiver.archivedData(withRootObject: WWZArchiver()), ] let Preferences = PreferenceManager.shared final class PreferenceManager { static let shared = PreferenceManager() let defaults = UserDefaults.standard private init() { registerDefaultPreferences() } private func registerDefaultPreferences() { // Convert dictionary of type [PreferenceKey: Any] to [String: Any]. let defaultValues: [String: Any] = defaultPreferences.reduce([:]) { var dictionary = $0 dictionary[$1.key.rawValue] = $1.value return dictionary } defaults.register(defaults: defaultValues) } } extension PreferenceManager { subscript(key: PreferenceKey<Any>) -> Any? { get { return defaults.object(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<URL>) -> URL? { get { return defaults.url(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<[Any]>) -> [Any]? { get { return defaults.array(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<[String: Any]>) -> [String: Any]? { get { return defaults.dictionary(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<String>) -> String? { get { return defaults.string(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<[String]>) -> [String]? { get { return defaults.stringArray(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<Data>) -> Data? { get { return defaults.data(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<Bool>) -> Bool { get { return defaults.bool(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<Int>) -> Int { get { return defaults.integer(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<Float>) -> Float { get { return defaults.float(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<Double>) -> Double { get { return defaults.double(forKey: key.rawValue) } set { defaults.set(newValue, forKey: key.rawValue) } } subscript(key: PreferenceKey<WWZArchiver>) -> WWZArchiver? { get { var object: WWZArchiver? if let data = defaults.data(forKey: key.rawValue) { object = NSKeyedUnarchiver.unarchiveObject(with: data) as? WWZArchiver } return object } set { if let object = newValue { let data = NSKeyedArchiver.archivedData(withRootObject: object) defaults.set(data, forKey: key.rawValue) } } } }
6a00924ce683a13298ba5fbcfab8c6e8
28.763975
86
0.602254
false
false
false
false
ALHariPrasad/BluetoothKit
refs/heads/master
Example/Vendor/CryptoSwift/CryptoSwift/NSDataExtension.swift
mit
11
// // PGPDataExtension.swift // SwiftPGP // // Created by Marcin Krzyzanowski on 05/07/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation extension NSMutableData { /** Convenient way to append bytes */ internal func appendBytes(arrayOfBytes: [UInt8]) { self.appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } extension NSData { public func checksum() -> UInt16 { var s:UInt32 = 0; var bytesArray = self.arrayOfBytes() for (var i = 0; i < bytesArray.count; i++) { _ = bytesArray[i] s = s + UInt32(bytesArray[i]) } s = s % 65536; return UInt16(s); } public func md5() -> NSData? { return Hash.md5(self).calculate() } public func sha1() -> NSData? { return Hash.sha1(self).calculate() } public func sha224() -> NSData? { return Hash.sha224(self).calculate() } public func sha256() -> NSData? { return Hash.sha256(self).calculate() } public func sha384() -> NSData? { return Hash.sha384(self).calculate() } public func sha512() -> NSData? { return Hash.sha512(self).calculate() } public func crc32() -> NSData? { return Hash.crc32(self).calculate() } public func encrypt(cipher: Cipher) throws -> NSData? { let encrypted = try cipher.encrypt(self.arrayOfBytes()) return NSData.withBytes(encrypted) } public func decrypt(cipher: Cipher) throws -> NSData? { let decrypted = try cipher.decrypt(self.arrayOfBytes()) return NSData.withBytes(decrypted) } public func authenticate(authenticator: Authenticator) -> NSData? { if let result = authenticator.authenticate(self.arrayOfBytes()) { return NSData.withBytes(result) } return nil } } extension NSData { public var hexString: String { return self.toHexString() } func toHexString() -> String { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) var s:String = ""; for byte in bytesArray { s = s + String(format:"%02x", byte) } return s } public func arrayOfBytes() -> [UInt8] { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) return bytesArray } class public func withBytes(bytes: [UInt8]) -> NSData { return NSData(bytes: bytes, length: bytes.count) } }
29e63554149603652cfd2db4db70e5fa
24.318182
73
0.584201
false
false
false
false
frtlupsvn/Vietnam-To-Go
refs/heads/master
Pods/Former/Former/Cells/FormSwitchCell.swift
mit
1
// // FormSwitchCell.swift // Former-Demo // // Created by Ryo Aoyama on 7/27/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public class FormSwitchCell: FormCell, SwitchFormableRow { // MARK: Public public private(set) weak var titleLabel: UILabel! public private(set) weak var switchButton: UISwitch! public func formTitleLabel() -> UILabel? { return titleLabel } public func formSwitch() -> UISwitch { return switchButton } public override func setup() { super.setup() let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, atIndex: 0) self.titleLabel = titleLabel let switchButton = UISwitch() accessoryView = switchButton self.switchButton = switchButton let constraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[label]-0-|", options: [], metrics: nil, views: ["label": titleLabel] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-15-[label(>=0)]", options: [], metrics: nil, views: ["label": titleLabel] ) ].flatMap { $0 } contentView.addConstraints(constraints) } }
909b34fc3c92ef39f7a235e621116abe
26.12963
68
0.56694
false
false
false
false
sun409377708/swiftDemo
refs/heads/master
SinaSwiftPractice/SinaSwiftPractice/Classes/View/Discover/View/JQSearchView.swift
mit
1
// // JQSearchView.swift // SinaSwiftPractice // // Created by maoge on 16/11/12. // Copyright © 2016年 maoge. All rights reserved. // import UIKit class JQSearchView: UIButton { //定义类方法 class func loadSearchView() -> JQSearchView { let v = UINib.init(nibName: "SearchView", bundle: nil).instantiate(withOwner: nil, options: nil).last as! JQSearchView return v } //视图被激活时 override func awakeFromNib() { self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) self.layer.cornerRadius = 17 self.bounds.size.width = UIScreen.main.bounds.size.width } }
db8346de357254e34e0f232aaa9812be
25.068966
126
0.624339
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGeometry/ApplePlatform/Geometry/CGRect.swift
mit
1
// // CGRect.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension CGRect { @inlinable @inline(__always) public init(_ r: Rect) { if r.isNull { self = .null } else if r.isInfinite { self = .infinite } else { self.init(origin: CGPoint(r.origin), size: CGSize(r.size)) } } @inlinable @inline(__always) public init(origin: Point, size: Size) { self.init(Rect(origin: origin, size: size)) } @inlinable @inline(__always) public init<T: BinaryInteger>(x: T, y: T, width: T, height: T) { self.init(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height)) } @inlinable @inline(__always) public init<T: BinaryFloatingPoint>(x: T, y: T, width: T, height: T) { self.init(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height)) } } extension Rect { @inlinable @inline(__always) public init(_ r: CGRect) { if r.isNull { self = .null } else if r.isInfinite { self = .infinite } else { self.init(origin: Point(r.origin), size: Size(r.size)) } } @inlinable @inline(__always) public init(origin: CGPoint, size: CGSize) { self.init(CGRect(origin: origin, size: size)) } } extension CGRect { @inlinable @inline(__always) public var center: CGPoint { return CGPoint(x: midX, y: midY) } } @inlinable @inline(__always) public func *(lhs: CGFloat, rhs: CGRect) -> CGRect { if rhs.isNull || rhs.isInfinite { return .null } return CGRect(origin: lhs * rhs.origin, size: lhs * rhs.size) } @inlinable @inline(__always) public func *(lhs: CGRect, rhs: CGFloat) -> CGRect { if lhs.isNull || lhs.isInfinite { return .null } return CGRect(origin: lhs.origin * rhs, size: lhs.size * rhs) } @inlinable @inline(__always) public func /(lhs: CGRect, rhs: CGFloat) -> CGRect { if lhs.isNull || lhs.isInfinite { return .null } return CGRect(origin: lhs.origin / rhs, size: lhs.size / rhs) } @inlinable @inline(__always) public func *= (lhs: inout CGRect, rhs: CGFloat) { lhs = lhs * rhs } @inlinable @inline(__always) public func /= (lhs: inout CGRect, rhs: CGFloat) { lhs = lhs / rhs }
4fd7afcded43e4159a51aa377fbf3b64
28.837607
95
0.634202
false
false
false
false
blitzagency/ParsedObject
refs/heads/master
Source/ParsedObject.swift
mit
1
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 //// MARK: - Error ///Error domain public let ErrorDomain: String! = "ParsedObjectErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknow } // MARK: - JSON Base @objc public final class ParsedObject: NSObject { /** Creates a JSON using the data. :param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary :param: opt The JSON serialization reading options. `.AllowFragments` by default. :param: error error The NSErrorPointer used to return the error. `nil` by default. :returns: The created JSON */ public convenience init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) { self.init(object) } else { self.init(NSNull()) } } /** Creates a JSON using the object. :param: object The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. :returns: The created JSON */ public required init(_ object: AnyObject) { super.init() self.object = object } /// Private object internal var _object: AnyObject = NSNull() /// Private type internal var _type: Type = .Null /// prviate error internal var _error: NSError? = nil /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case let string as NSString: _type = .String case let null as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array case let dictionary as [String : AnyObject]: _type = .Dictionary default: _type = .Unknow _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public class func nullParsedObject() -> ParsedObject { return ParsedObject(NSNull()) } } //// MARK: - SequenceType //extension ParsedObject: SequenceType{ // // /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. // var isEmpty: Bool { // get { // switch self.type { // case .Array: // return (self.object as [AnyObject]).isEmpty // case .Dictionary: // return (self.object as [String : AnyObject]).isEmpty // default: // return false // } // } // } // // /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. // public var count: Int { // get { // switch self.type { // case .Array: // return self.arrayValue.count // case .Dictionary: // return self.dictionaryValue.count // default: // return 0 // } // } // } // // /** // If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary, otherwise return a generator over empty. // // :returns: Return a *generator* over the elements of this *sequence*. // */ // public func generate() -> GeneratorOf <(String, ParsedObject)> { // switch self.type { // case .Array: // let array_ = object as [AnyObject] // var generate_ = array_.generate() // var index_: Int = 0 // return GeneratorOf<(String, ParsedObject)> { // if let element_: AnyObject = generate_.next() { // return ("\(index_++)", ParsedObject(element_)) // } else { // return nil // } // } // case .Dictionary: // let dictionary_ = object as [String : AnyObject] // var generate_ = dictionary_.generate() // return GeneratorOf<(String, ParsedObject)> { // if let (key_: String, value_: AnyObject) = generate_.next() { // return (key_, ParsedObject(value_)) // } else { // return nil // } // } // default: // return GeneratorOf<(String, ParsedObject)> { // return nil // } // } // } //} //// MARK: - Subscript // ///** //* To mark both String and Int can be used in subscript. //*/ //public protocol SubscriptType {} // //extension Int: SubscriptType {} // //extension String: SubscriptType {} // //extension ParsedObject { // // /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. // private subscript(#index: Int) -> ParsedObject { // get { // // if self.type != .Array { // var errorResult_ = ParsedObject.nullJSON() // errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) // return errorResult_ // } // // let array_ = self.object as [AnyObject] // // if index >= 0 && index < array_.count { // return ParsedObject(array_[index]) // } // // var errorResult_ = ParsedObject.nullJSON() // errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) // return errorResult_ // } // set { // if self.type == .Array { // var array_ = self.object as [AnyObject] // if array_.count > index { // array_[index] = newValue.object // self.object = array_ // } // } // } // } // // /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. // private subscript(#key: String) -> ParsedObject { // get { // var returnJSON = ParsedObject.nullJSON() // if self.type == .Dictionary { // if let object_: AnyObject = self.object[key] { // returnJSON = ParsedObject(object_) // } else { // returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) // } // } else { // returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) // } // return returnJSON // } // set { // if self.type == .Dictionary { // var dictionary_ = self.object as [String : AnyObject] // dictionary_[key] = newValue.object // self.object = dictionary_ // } // } // } // // /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. // private subscript(#sub: SubscriptType) -> ParsedObject { // get { // if sub is String { // return self[key:sub as String] // } else { // return self[index:sub as Int] // } // } // set { // if sub is String { // self[key:sub as String] = newValue // } else { // self[index:sub as Int] = newValue // } // } // } // // /** // Find a json in the complex data structuresby using the Int/String's array. // // :param: path The target json's path. Example: // // let json = JSON[data] // let path = [9,"list","person","name"] // let name = json[path] // // The same as: let name = json[9]["list"]["person"]["name"] // // :returns: Return a json found by the path or a null json with error // */ // public subscript(path: [SubscriptType]) -> ParsedObject { // get { // if path.count == 0 { // return ParsedObject.nullJSON() // } // // var next = self // for sub in path { // next = next[sub:sub] // } // return next // } // set { // // switch path.count { // case 0: return // case 1: self[sub:path[0]] = newValue // default: // var last = newValue // var newPath = path // newPath.removeLast() // for sub in path.reverse() { // var previousLast = self[newPath] // previousLast[sub:sub] = last // last = previousLast // if newPath.count <= 1 { // break // } // newPath.removeLast() // } // self[sub:newPath[0]] = last // } // } // } // // /** // Find a json in the complex data structuresby using the Int/String's array. // // :param: path The target json's path. Example: // // let name = json[9,"list","person","name"] // // The same as: let name = json[9]["list"]["person"]["name"] // // :returns: Return a json found by the path or a null json with error // */ // public subscript(path: SubscriptType...) -> ParsedObject { // get { // return self[path] // } // set { // self[path] = newValue // } // } //} // //// MARK: - LiteralConvertible // //extension ParsedObject: StringLiteralConvertible { // // public convenience init(stringLiteral value: StringLiteralType) { // self.init(value) // } // // public convenience init(extendedGraphemeClusterLiteral value: StringLiteralType) { // self.init(value) // } // // public convenience init(unicodeScalarLiteral value: StringLiteralType) { // self.init(value) // } //} // //extension ParsedObject: IntegerLiteralConvertible { // // public convenience init(integerLiteral value: IntegerLiteralType) { // self.init(value) // } //} // //extension ParsedObject: BooleanLiteralConvertible { // // public convenience init(booleanLiteral value: BooleanLiteralType) { // self.init(value) // } //} // //extension ParsedObject: FloatLiteralConvertible { // // public convenience init(floatLiteral value: FloatLiteralType) { // self.init(value) // } //} // //extension ParsedObject: DictionaryLiteralConvertible { // // public convenience init(dictionaryLiteral elements: (String, AnyObject)...) { // var dictionary_ = [String : AnyObject]() // for (key_, value) in elements { // dictionary_[key_] = value // } // self.init(dictionary_) // } //} // //extension ParsedObject: ArrayLiteralConvertible { // // public convenience init(arrayLiteral elements: AnyObject...) { // self.init(elements) // } //} // //extension ParsedObject: NilLiteralConvertible { // // public convenience init(nilLiteral: ()) { // self.init(NSNull()) // } //} // //// MARK: - Raw // //extension ParsedObject: RawRepresentable { // // public convenience init?(rawValue: AnyObject) { // if ParsedObject(rawValue).type == .Unknow { // return nil // } else { // self.init(rawValue) // } // } // // public var rawValue: AnyObject { // return self.object // } // // public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(0), error: NSErrorPointer = nil) -> NSData? { // return NSJSONSerialization.dataWithJSONObject(self.object, options: opt, error:error) // } // // public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { // switch self.type { // case .Array, .Dictionary: // if let data = self.rawData(options: opt) { // return NSString(data: data, encoding: encoding) // } else { // return nil // } // case .String: // return (self.object as String) // case .Number: // return (self.object as NSNumber).stringValue // case .Bool: // return (self.object as Bool).description // case .Null: // return "null" // default: // return nil // } // } //} // //// MARK: - Printable, DebugPrintable // //extension ParsedObject: Printable, DebugPrintable { // // public override var description: String { // if let string = self.rawString(options:.PrettyPrinted) { // return string // } else { // return "unknown" // } // } // // public override var debugDescription: String { // return description // } //} // MARK: - Array //extension ParsedObject { // // //Optional [JSON] // public var array: [ParsedObject]? { // get { // if self.type == .Array { // return map(self.object as [AnyObject]){ ParsedObject($0) } // } else { // return nil // } // } // } // // //Non-optional [JSON] // public var arrayValue: [ParsedObject] { // get { // return self.array ?? [] // } // } // // //Optional [AnyObject] // public var arrayObject: [AnyObject]? { // get { // switch self.type { // case .Array: // return self.object as? [AnyObject] // default: // return nil // } // } // set { // if newValue != nil { // self.object = NSMutableArray(array: newValue!, copyItems: true) // } else { // self.object = NSNull() // } // } // } //} // MARK: - Dictionary //extension ParsedObject { // // private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { // var result = [Key: NewValue](minimumCapacity:source.count) // for (key,value) in source { // result[key] = transform(value) // } // return result // } // // //Optional [String : JSON] // public var dictionary: [String : ParsedObject]? { // get { // if self.type == .Dictionary { // return _map(self.object as [String : AnyObject]){ ParsedObject($0) } // } else { // return nil // } // } // } // // //Non-optional [String : JSON] // public var dictionaryValue: [String : ParsedObject] { // get { // return self.dictionary ?? [:] // } // } // // //Optional [String : AnyObject] // public var dictionaryObject: [String : AnyObject]? { // get { // switch self.type { // case .Dictionary: // return self.object as? [String : AnyObject] // default: // return nil // } // } // set { // if newValue != nil { // self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) // } else { // self.object = NSNull() // } // } // } //} // MARK: - Bool //extension ParsedObject: BooleanType { // // //Optional bool // public var bool: Bool? { // get { // switch self.type { // case .Bool: // return self.object.boolValue // default: // return nil // } // } // set { // if newValue != nil { // self.object = NSNumber(bool: newValue!) // } else { // self.object = NSNull() // } // } // } // // //Non-optional bool // public var boolValue: Bool { // get { // switch self.type { // case .Bool, .Number, .String: // return self.object.boolValue // default: // return false // } // } // set { // self.object = NSNumber(bool: newValue) // } // } //} // MARK: - String //extension ParsedObject { // // //Optional string // public var string: String? { // get { // switch self.type { // case .String: // return self.object as? String // default: // return nil // } // } // set { // if newValue != nil { // self.object = NSString(string:newValue!) // } else { // self.object = NSNull() // } // } // } // // //Non-optional string // public var stringValue: String { // get { // switch self.type { // case .String: // return self.object as String // case .Number: // return self.object.stringValue // case .Bool: // return (self.object as Bool).description // default: // return "" // } // } // set { // self.object = NSString(string:newValue) // } // } //} // MARK: - Number //extension ParsedObject { // // //Optional number // public var number: NSNumber? { // get { // switch self.type { // case .Number, .Bool: // return self.object as? NSNumber // default: // return nil // } // } // set { // self.object = newValue?.copy() ?? NSNull() // } // } // // //Non-optional number // public var numberValue: NSNumber { // get { // switch self.type { // case .String: // let scanner = NSScanner(string: self.object as String) // if scanner.scanDouble(nil){ // if (scanner.atEnd) { // return NSNumber(double:(self.object as NSString).doubleValue) // } // } // return NSNumber(double: 0.0) // case .Number, .Bool: // return self.object as NSNumber // default: // return NSNumber(double: 0.0) // } // } // set { // self.object = newValue.copy() // } // } //} //MARK: - Null //extension ParsedObject { // // public var null: NSNull? { // get { // switch self.type { // case .Null: // return NSNull() // default: // return nil // } // } // set { // self.object = NSNull() // } // } //} //MARK: - URL //extension ParsedObject { // // //Optional URL // public var URL: NSURL? { // get { // switch self.type { // case .String: // if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { // return NSURL(string: encodedString_) // } else { // return nil // } // default: // return nil // } // } // set { // self.object = newValue?.absoluteString ?? NSNull() // } // } //} // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 //extension ParsedObject { // // public var double: Double? { // get { // return self.number?.doubleValue // } // set { // if newValue != nil { // self.object = NSNumber(double: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var doubleValue: Double { // get { // return self.numberValue.doubleValue // } // set { // self.object = NSNumber(double: newValue) // } // } // // public var float: Float? { // get { // return self.number?.floatValue // } // set { // if newValue != nil { // self.object = NSNumber(float: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var floatValue: Float { // get { // return self.numberValue.floatValue // } // set { // self.object = NSNumber(float: newValue) // } // } // // public var int: Int? { // get { // return self.number?.longValue // } // set { // if newValue != nil { // self.object = NSNumber(integer: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var intValue: Int { // get { // return self.numberValue.integerValue // } // set { // self.object = NSNumber(integer: newValue) // } // } // // public var uInt: UInt? { // get { // return self.number?.unsignedLongValue // } // set { // if newValue != nil { // self.object = NSNumber(unsignedLong: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var uIntValue: UInt { // get { // return self.numberValue.unsignedLongValue // } // set { // self.object = NSNumber(unsignedLong: newValue) // } // } // // public var int8: Int8? { // get { // return self.number?.charValue // } // set { // if newValue != nil { // self.object = NSNumber(char: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var int8Value: Int8 { // get { // return self.numberValue.charValue // } // set { // self.object = NSNumber(char: newValue) // } // } // // public var uInt8: UInt8? { // get { // return self.number?.unsignedCharValue // } // set { // if newValue != nil { // self.object = NSNumber(unsignedChar: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var uInt8Value: UInt8 { // get { // return self.numberValue.unsignedCharValue // } // set { // self.object = NSNumber(unsignedChar: newValue) // } // } // // public var int16: Int16? { // get { // return self.number?.shortValue // } // set { // if newValue != nil { // self.object = NSNumber(short: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var int16Value: Int16 { // get { // return self.numberValue.shortValue // } // set { // self.object = NSNumber(short: newValue) // } // } // // public var uInt16: UInt16? { // get { // return self.number?.unsignedShortValue // } // set { // if newValue != nil { // self.object = NSNumber(unsignedShort: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var uInt16Value: UInt16 { // get { // return self.numberValue.unsignedShortValue // } // set { // self.object = NSNumber(unsignedShort: newValue) // } // } // // public var int32: Int32? { // get { // return self.number?.intValue // } // set { // if newValue != nil { // self.object = NSNumber(int: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var int32Value: Int32 { // get { // return self.numberValue.intValue // } // set { // self.object = NSNumber(int: newValue) // } // } // // public var uInt32: UInt32? { // get { // return self.number?.unsignedIntValue // } // set { // if newValue != nil { // self.object = NSNumber(unsignedInt: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var uInt32Value: UInt32 { // get { // return self.numberValue.unsignedIntValue // } // set { // self.object = NSNumber(unsignedInt: newValue) // } // } // // public var int64: Int64? { // get { // return self.number?.longLongValue // } // set { // if newValue != nil { // self.object = NSNumber(longLong: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var int64Value: Int64 { // get { // return self.numberValue.longLongValue // } // set { // self.object = NSNumber(longLong: newValue) // } // } // // public var uInt64: UInt64? { // get { // return self.number?.unsignedLongLongValue // } // set { // if newValue != nil { // self.object = NSNumber(unsignedLongLong: newValue!) // } else { // self.object = NSNull() // } // } // } // // public var uInt64Value: UInt64 { // get { // return self.numberValue.unsignedLongLongValue // } // set { // self.object = NSNumber(unsignedLongLong: newValue) // } // } //} //MARK: - Comparable //extension ParsedObject: Comparable {} // //public func ==(lhs: ParsedObject, rhs: ParsedObject) -> Bool { // // switch (lhs.type, rhs.type) { // case (.Number, .Number): // return (lhs.object as NSNumber) == (rhs.object as NSNumber) // case (.String, .String): // return (lhs.object as String) == (rhs.object as String) // case (.Bool, .Bool): // return (lhs.object as Bool) == (rhs.object as Bool) // case (.Array, .Array): // return (lhs.object as NSArray) == (rhs.object as NSArray) // case (.Dictionary, .Dictionary): // return (lhs.object as NSDictionary) == (rhs.object as NSDictionary) // case (.Null, .Null): // return true // default: // return false // } //} // //public func <=(lhs: ParsedObject, rhs: ParsedObject) -> Bool { // // switch (lhs.type, rhs.type) { // case (.Number, .Number): // return (lhs.object as NSNumber) <= (rhs.object as NSNumber) // case (.String, .String): // return (lhs.object as String) <= (rhs.object as String) // case (.Bool, .Bool): // return (lhs.object as Bool) == (rhs.object as Bool) // case (.Array, .Array): // return (lhs.object as NSArray) == (rhs.object as NSArray) // case (.Dictionary, .Dictionary): // return (lhs.object as NSDictionary) == (rhs.object as NSDictionary) // case (.Null, .Null): // return true // default: // return false // } //} // //public func >=(lhs: ParsedObject, rhs: ParsedObject) -> Bool { // // switch (lhs.type, rhs.type) { // case (.Number, .Number): // return (lhs.object as NSNumber) >= (rhs.object as NSNumber) // case (.String, .String): // return (lhs.object as String) >= (rhs.object as String) // case (.Bool, .Bool): // return (lhs.object as Bool) == (rhs.object as Bool) // case (.Array, .Array): // return (lhs.object as NSArray) == (rhs.object as NSArray) // case (.Dictionary, .Dictionary): // return (lhs.object as NSDictionary) == (rhs.object as NSDictionary) // case (.Null, .Null): // return true // default: // return false // } //} // //public func >(lhs: ParsedObject, rhs: ParsedObject) -> Bool { // // switch (lhs.type, rhs.type) { // case (.Number, .Number): // return (lhs.object as NSNumber) > (rhs.object as NSNumber) // case (.String, .String): // return (lhs.object as String) > (rhs.object as String) // default: // return false // } //} // //public func <(lhs: ParsedObject, rhs: ParsedObject) -> Bool { // // switch (lhs.type, rhs.type) { // case (.Number, .Number): // return (lhs.object as NSNumber) < (rhs.object as NSNumber) // case (.String, .String): // return (lhs.object as String) < (rhs.object as String) // default: // return false // } //} // //private let trueNumber = NSNumber(bool: true) //private let falseNumber = NSNumber(bool: false) //private let trueObjCType = String.fromCString(trueNumber.objCType) //private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable //extension NSNumber: Comparable { // var isBool:Bool { // get { // let objCType = String.fromCString(self.objCType) // if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ // return true // } else { // return false // } // } // } //} // //public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { // switch (lhs.isBool, rhs.isBool) { // case (false, true): // return false // case (true, false): // return false // default: // return lhs.compare(rhs) == NSComparisonResult.OrderedSame // } //} // //public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { // return !(rhs == rhs) //} // //public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { // // switch (lhs.isBool, rhs.isBool) { // case (false, true): // return false // case (true, false): // return false // default: // return lhs.compare(rhs) == NSComparisonResult.OrderedAscending // } //} // //public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { // // switch (lhs.isBool, rhs.isBool) { // case (false, true): // return false // case (true, false): // return false // default: // return lhs.compare(rhs) == NSComparisonResult.OrderedDescending // } //} // //public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { // // switch (lhs.isBool, rhs.isBool) { // case (false, true): // return false // case (true, false): // return false // default: // return lhs.compare(rhs) != NSComparisonResult.OrderedDescending // } //} // //public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { // // switch (lhs.isBool, rhs.isBool) { // case (false, true): // return false // case (true, false): // return false // default: // return lhs.compare(rhs) != NSComparisonResult.OrderedAscending // } //} //MARK:- Unavailable //@availability(*, unavailable, renamed="JSON") //public typealias JSONValue = ParsedObject // //extension ParsedObject { // //// @availability(*, unavailable, message="use 'init(_ object:AnyObject)' instead") //// public convenience init(object: AnyObject) { //// self = ParsedObject(object) //// } // // @availability(*, unavailable, renamed="dictionaryObject") // public var dictionaryObjects: [String : AnyObject]? { // get { return self.dictionaryObject } // } // // @availability(*, unavailable, renamed="arrayObject") // public var arrayObjects: [AnyObject]? { // get { return self.arrayObject } // } // // @availability(*, unavailable, renamed="int8") // public var char: Int8? { // get { // return self.number?.charValue // } // } // // @availability(*, unavailable, renamed="int8Value") // public var charValue: Int8 { // get { // return self.numberValue.charValue // } // } // // @availability(*, unavailable, renamed="uInt8") // public var unsignedChar: UInt8? { // get{ // return self.number?.unsignedCharValue // } // } // // @availability(*, unavailable, renamed="uInt8Value") // public var unsignedCharValue: UInt8 { // get{ // return self.numberValue.unsignedCharValue // } // } // // @availability(*, unavailable, renamed="int16") // public var short: Int16? { // get{ // return self.number?.shortValue // } // } // // @availability(*, unavailable, renamed="int16Value") // public var shortValue: Int16 { // get{ // return self.numberValue.shortValue // } // } // // @availability(*, unavailable, renamed="uInt16") // public var unsignedShort: UInt16? { // get{ // return self.number?.unsignedShortValue // } // } // // @availability(*, unavailable, renamed="uInt16Value") // public var unsignedShortValue: UInt16 { // get{ // return self.numberValue.unsignedShortValue // } // } // // @availability(*, unavailable, renamed="int") // public var long: Int? { // get{ // return self.number?.longValue // } // } // // @availability(*, unavailable, renamed="intValue") // public var longValue: Int { // get{ // return self.numberValue.longValue // } // } // // @availability(*, unavailable, renamed="uInt") // public var unsignedLong: UInt? { // get{ // return self.number?.unsignedLongValue // } // } // // @availability(*, unavailable, renamed="uIntValue") // public var unsignedLongValue: UInt { // get{ // return self.numberValue.unsignedLongValue // } // } // // @availability(*, unavailable, renamed="int64") // public var longLong: Int64? { // get{ // return self.number?.longLongValue // } // } // // @availability(*, unavailable, renamed="int64Value") // public var longLongValue: Int64 { // get{ // return self.numberValue.longLongValue // } // } // // @availability(*, unavailable, renamed="uInt64") // public var unsignedLongLong: UInt64? { // get{ // return self.number?.unsignedLongLongValue // } // } // // @availability(*, unavailable, renamed="uInt64Value") // public var unsignedLongLongValue: UInt64 { // get{ // return self.numberValue.unsignedLongLongValue // } // } // // @availability(*, unavailable, renamed="int") // public var integer: Int? { // get { // return self.number?.integerValue // } // } // // @availability(*, unavailable, renamed="intValue") // public var integerValue: Int { // get { // return self.numberValue.integerValue // } // } // // @availability(*, unavailable, renamed="uInt") // public var unsignedInteger: Int? { // get { // return self.number?.unsignedIntegerValue // } // } // // @availability(*, unavailable, renamed="uIntValue") // public var unsignedIntegerValue: Int { // get { // return self.numberValue.unsignedIntegerValue // } // } //}
3907d9c6e7a48d1755c194c5b1220712
27.441462
259
0.507184
false
false
false
false
planvine/Line-Up-iOS-SDK
refs/heads/master
Pod/Classes/Line-Up_ExtPaymentBtnsPressed.swift
mit
1
/** * Copyright (c) 2016 Line-Up * * 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 Stripe //MARK: - Buttons Pressed extension LineUp { //MARK: GET TICKETS PRESSED /** * Generate a UINavigationController which contains a main UIViewController for leading the user to pay and it is modally presented to the viewController provided * - Parameters: * - selectedTickets: is an Array of PVTicket that the user is going to purchase * - userEmail: is the email address of the user is going to purchase the tickets (if not provided the user will have to type in a valid email address before finalizing the payment) * - userToken: is the Line-Up user token * - viewController: is the UIViewController in which the Line-Up payment flow is going to be presented * - performanceId: is the id of the performance that the user is purchasing tickets of * - completion: 'reservation' is the reservation number (String). Keep this value and send it to 'postOrderToComplete' for completing the payment process, 'error' is NSError */ public class func getTicketsPressed(selectedTickets: Array<PVTicket>, userEmail: String?, userToken:String?, viewController: UIViewController, performanceId: NSNumber, completion: (reservation:String?, error: NSError?) ->() ) { if Reachability.isConnectedToNetwork() { reserveTickets(selectedTickets, userToken: userToken, completion: { (status, reservation, error) -> () in dispatch_async(dispatch_get_main_queue(), { if status == .Success && reservation != nil { completion(reservation: reservation, error: error) let paymentVC : PaymentViewController = PaymentViewController(userEmail: userEmail, userToken: userToken) let navigationController: UINavigationController = UINavigationController(rootViewController: paymentVC) let checkoutDictionary : Dictionary <PVTicket,NSNumber> = setCheckoutDictionary(selectedTickets) let dictionaryCheckout = setCheckoutSummary(checkoutDictionary) navigationController.setNavigationBarHidden(false, animated: true) navigationController.navigationItem.setHidesBackButton(false, animated: true) navigationController.navigationBar.barTintColor = PVColor.mainColor let navBarView : NavBarView = NavBarView(origin: CGPointZero, size: CGSizeMake(UIScreen.mainScreen().bounds.width, PVConstant.barHeight)) let performance: PVPerformance? = LineUp.getPerformanceFromCoreData(performanceId) if performance != nil && performance!.startDate != nil && performance!.event != nil && performance!.event!.title != nil { navBarView.setTitleText(performance!.event!.title!, secondRow: performance!.startDate!.formatForModalSectionTitle() + ", " + performance!.startDate!.formatYear()) } else { navBarView.setTitleText("Payment Checkout", secondRow: "") } navigationController.navigationBar.topItem?.titleView = navBarView.setupTitleView() navigationController.navigationBar.topItem?.titleView?.center = navigationController.navigationBar.center paymentVC.dictionaryCheckout = dictionaryCheckout paymentVC.selectedTickets = selectedTickets paymentVC.reservationNumber = reservation if viewController.parentViewController != nil { viewController.parentViewController!.presentViewController(navigationController, animated: true, completion: nil) } else { viewController.presentViewController(navigationController, animated: true, completion: nil) } } else { PVHud.removeCustomActivityIndicator() completion(reservation: nil, error: error) } }) }) } else { PVHud.removeCustomActivityIndicator() completion(reservation: nil, error: NSError(domain: PVError.alertNoConnection, code: 500, userInfo: nil)) } } //MARK: APPLE PAY PRESSED /** * Method to call when Pay button is pressed (for paying by Pay with the Line-Up flow). It generates the request to Line-Up Stripe account for making payments and it fills up the Pay view to show to the user * * - Parameters: * - selectedTickets: is an Array of PVTicket that the user is going to purchase * - viewController: Pay (view) will be presented on the provided 'viewController' * - completion: 'error' is NSError */ public class func applePayPressed(selectedTickets: Array<PVTicket>, viewController:UIViewController, completion:(error: String?) ->() ) { // check if it is possible to connect to 'Line-Up Stripe account' var (request,error) = LineUp.applePayStripeConnection(selectedTickets) if request != nil && error == nil && Stripe.canSubmitPaymentRequest(request) { dispatch_async(dispatch_get_main_queue(), { let paymentController = PKPaymentAuthorizationViewController(paymentRequest: request!) paymentController.delegate = viewController as? PKPaymentAuthorizationViewControllerDelegate viewController.presentViewController(paymentController, animated: true, completion: nil) }) } else { if error == nil || Stripe.canSubmitPaymentRequest(request) == false { error = PVError.alert_ApplePayNotAvailable } dispatch_async(dispatch_get_main_queue(), { completion(error: error) let message: String = LineUp.mapErrorMessage(error) let alert : UIAlertController! = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert) let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in }) alert.addAction(cancelAction) viewController.presentViewController(alert, animated: true, completion: nil) }) } } //It is the same of the method above, but it returns the PKPaymentAuthorizationViewController in the completion handler instead of presenting it on the viewController. /** * Method to call when Pay is pressed. It generates the request to Line-Up Stripe account for making payments and it fills up the Pay view to show to the user. * * - Parameters: * - selectedTickets: is an Array of PVTicket that the user is going to purchase * - userToken: is the Line-Up user token * - viewController: Pay (view) will be presented on the provided 'viewController' * - completion: 'paymentController' is PKPaymentAuthorizationViewController, 'error' is NSError */ public class func applePayPressed(selectedTickets: Array<PVTicket>, completion: (paymentController: PKPaymentAuthorizationViewController?, error: String?) ->() ) { // check if it is possible to connect to 'Line-Up Stripe account' var (request,error) = LineUp.applePayStripeConnection(selectedTickets) if request != nil && error == nil && Stripe.canSubmitPaymentRequest(request) { let paymentController = PKPaymentAuthorizationViewController(paymentRequest: request!) dispatch_async(dispatch_get_main_queue(), { completion(paymentController: paymentController, error: nil) }) } else { if error == nil { error = PVError.alert_ApplePayNotAvailable } dispatch_async(dispatch_get_main_queue(), { completion(paymentController: nil, error: error) }) } } /** Implementation of Pay delegate method: paymentAuthorizationViewControllerDidFinish. It dismisses the viewController if presented */ public class func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController,viewController: UIViewController?) { if viewController != nil { viewController!.dismissViewControllerAnimated(true, completion: nil) } } //MARK: PASSKIT PASS /** Method to call for showing a PKPass on the viewController. */ public class func showPassKitPasses(viewController: UIViewController, pkPasses:[PKPass]) { let passController = PKAddPassesViewController(passes: pkPasses) passController.delegate = viewController as? PKAddPassesViewControllerDelegate viewController.presentViewController(passController, animated: true, completion: nil) } }
7a93564233a8574c682e3f8e282025cc
60.257485
231
0.66129
false
false
false
false
amujic5/AFEA
refs/heads/master
AFEA-EndProject/AFEA-EndProject/Custom Views/EFCountingLabel.swift
mit
1
// // EFCountingLabel.swift // // Copyright (c) 2016 EyreFree ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public enum EFLabelCountingMethod: Int { case linear = 0 case easeIn = 1 case easeOut = 2 case easeInOut = 3 } //MARK: - UILabelCounter let kUILabelCounterRate = Float(3.0) public protocol UILabelCounter { func update(_ t: CGFloat) -> CGFloat } public class UILabelCounterLinear: UILabelCounter { public func update(_ t: CGFloat) -> CGFloat { return t } } public class UILabelCounterEaseIn: UILabelCounter { public func update(_ t: CGFloat) -> CGFloat { return CGFloat(powf(Float(t), kUILabelCounterRate)) } } public class UILabelCounterEaseOut: UILabelCounter { public func update(_ t: CGFloat) -> CGFloat { return CGFloat(1.0 - powf(Float(1.0 - t), kUILabelCounterRate)) } } public class UILabelCounterEaseInOut: UILabelCounter { public func update(_ t: CGFloat) -> CGFloat { let newt: CGFloat = 2 * t if newt < 1 { return CGFloat(0.5 * powf (Float(newt), kUILabelCounterRate)) } else { return CGFloat(0.5 * (2.0 - powf(Float(2.0 - newt), kUILabelCounterRate))) } } } //MARK: - EFCountingLabel public class EFCountingLabel: UILabel { public var format = "%f" public var method = EFLabelCountingMethod.linear public var animationDuration = TimeInterval(2) public var formatBlock: ((CGFloat) -> String)? public var attributedFormatBlock: ((CGFloat) -> NSAttributedString)? public var completionBlock: (() -> Void)? private var startingValue: CGFloat! private var destinationValue: CGFloat! private var progress: TimeInterval = 0 private var lastUpdate: TimeInterval! private var totalTime: TimeInterval! private var easingRate: CGFloat! private var timer: CADisplayLink? private var counter: UILabelCounter = UILabelCounterLinear() public func countFrom(_ startValue: CGFloat, to endValue: CGFloat) { self.countFrom(startValue, to: endValue, withDuration: self.animationDuration) } public func countFrom(_ startValue: CGFloat, to endValue: CGFloat, withDuration duration: TimeInterval) { self.startingValue = startValue self.destinationValue = endValue // remove any (possible) old timers self.timer?.invalidate() self.timer = nil if duration == 0.0 { // No animation self.setTextValue(endValue) self.runCompletionBlock() return } self.easingRate = 3.0 self.progress = 0 self.totalTime = duration self.lastUpdate = Date.timeIntervalSinceReferenceDate switch self.method { case .linear: self.counter = UILabelCounterLinear() break case .easeIn: self.counter = UILabelCounterEaseIn() break case .easeOut: self.counter = UILabelCounterEaseOut() break case .easeInOut: self.counter = UILabelCounterEaseInOut() break } let timer = CADisplayLink(target: self, selector: #selector(EFCountingLabel.updateValue(_:))) if #available(iOS 10.0, *) { timer.preferredFramesPerSecond = 30 } else { timer.frameInterval = 2 } timer.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) timer.add(to: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode) self.timer = timer } public func countFromCurrentValueTo(_ endValue: CGFloat) { self.countFrom(self.currentValue(), to: endValue) } public func countFromCurrentValueTo(_ endValue: CGFloat, withDuration duration: TimeInterval) { self.countFrom(self.currentValue(), to: endValue, withDuration: duration) } public func countFromZeroTo(_ endValue: CGFloat) { self.countFrom(0, to: endValue) } public func countFromZeroTo(_ endValue: CGFloat, withDuration duration: TimeInterval) { self.countFrom(0, to: endValue, withDuration: duration) } public func currentValue() -> CGFloat { if self.progress == 0 { return 0 } else if self.progress >= self.totalTime { return self.destinationValue } let percent = self.progress / self.totalTime let updateVal = self.counter.update(CGFloat(percent)) return self.startingValue + updateVal * (self.destinationValue - self.startingValue) } public func updateValue(_ timer: Timer) { // update progress let now = Date.timeIntervalSinceReferenceDate self.progress = self.progress + now - self.lastUpdate self.lastUpdate = now if self.progress >= self.totalTime { self.timer?.invalidate() self.timer = nil self.progress = self.totalTime } self.setTextValue(self.currentValue()) if self.progress == self.totalTime { self.runCompletionBlock() } } private func setTextValue(_ value: CGFloat) { if let tryAttributedFormatBlock = self.attributedFormatBlock { self.attributedText = tryAttributedFormatBlock(value) } else if let tryFormatBlock = self.formatBlock { self.text = tryFormatBlock(value) } else { // check if counting with ints - cast to int if nil != self.format.range(of: "%(.*)d", options: String.CompareOptions.regularExpression, range: nil) || nil != self.format.range(of: "%(.*)i") { self.text = String(format: self.format, Int(value)) } else { self.text = String(format: self.format, value) } } } private func setFormat(_ format: String) { self.format = format self.setTextValue(self.currentValue()) } private func runCompletionBlock() { if let tryCompletionBlock = self.completionBlock { tryCompletionBlock() self.completionBlock = nil } } }
09c94bbf2b717c2a5f920ccb1969ea94
33.166667
115
0.63374
false
false
false
false
AndrewBennet/readinglist
refs/heads/master
ReadingList_Foundation/UI/ExpandableLabel.swift
gpl-3.0
1
import Foundation import UIKit @IBDesignable public class ExpandableLabel: UIView { private let label = UILabel(frame: .zero) private let seeMore = UILabel(frame: .zero) private let gradientView = UIView(frame: .zero) private let gradient = CAGradientLayer() public override init(frame: CGRect) { super.init(frame: .zero) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { if let previousTraitCollection = previousTraitCollection, previousTraitCollection.hasDifferentColorAppearance(comparedTo: traitCollection) { setupGradient() } } @IBInspectable public var text: String? { didSet { label.text = text showOrHideSeeMoreButton() invalidateIntrinsicContentSize() } } @IBInspectable public var color: UIColor = .label { didSet { label.textColor = color } } @IBInspectable public var gradientColor: UIColor = .systemBackground { didSet { if seeMore.backgroundColor != gradientColor { seeMore.backgroundColor = gradientColor setupGradient() } } } public var buttonColor: UIColor = .systemBlue { didSet { seeMore.textColor = buttonColor } } func setupGradient() { let opaque = gradientColor.withAlphaComponent(1.0) let clear = gradientColor.withAlphaComponent(0.0) gradient.colors = [clear.cgColor, opaque.cgColor] gradient.locations = [0.0, 0.4] gradient.startPoint = CGPoint(x: 0, y: 0) gradient.endPoint = CGPoint(x: 1, y: 0) } @IBInspectable public var numberOfLines: Int = 4 { didSet { if !labelIsExpanded { label.numberOfLines = numberOfLines } } } public var font: UIFont { get { return label.font } set { if label.font != newValue { label.font = newValue seeMore.font = newValue } } } private var labelIsExpanded = false private func setup() { super.awakeFromNib() seeMore.text = "see more" seeMore.textColor = tintColor label.translatesAutoresizingMaskIntoConstraints = false label.lineBreakMode = .byClipping seeMore.translatesAutoresizingMaskIntoConstraints = false gradientView.translatesAutoresizingMaskIntoConstraints = false addSubview(label) addSubview(gradientView) addSubview(seeMore) label.pin(to: self, attributes: .leading, .trailing, .top, .bottom) seeMore.pin(to: self, attributes: .trailing, .bottom) gradientView.pin(to: seeMore, attributes: .top, .trailing, .bottom) gradientView.pin(to: seeMore, multiplier: 2.0, attributes: .width) gradientView.isOpaque = true gradientView.layer.insertSublayer(gradient, at: 0) addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seeMoreTapped))) } func showOrHideSeeMoreButton() { if labelIsExpanded { gradientView.isHidden = true seeMore.isHidden = true } else { let isTruncated = label.isTruncated gradientView.isHidden = !isTruncated seeMore.isHidden = !isTruncated } } override public func layoutSubviews() { super.layoutSubviews() showOrHideSeeMoreButton() gradientView.layoutIfNeeded() gradient.frame = gradientView.bounds } override public var intrinsicContentSize: CGSize { return label.intrinsicContentSize } @objc private func seeMoreTapped() { guard !labelIsExpanded else { return } label.numberOfLines = 0 labelIsExpanded = true showOrHideSeeMoreButton() } }
c31ef12f9bf0947237894ef789218290
28.605839
100
0.623521
false
false
false
false
alickbass/SweetRouter
refs/heads/master
SweetRouter/Scheme.swift
mit
1
// // Scheme.swift // SweetRouter // // Created by Oleksii on 16/03/2017. // Copyright © 2017 ViolentOctopus. All rights reserved. // import Foundation public struct Scheme: RawRepresentable { public let rawValue: String public init(_ rawValue: String) { self.init(rawValue: rawValue) } public init(rawValue: String) { self.rawValue = rawValue } } public extension Scheme { public static let http = Scheme("http") public static let https = Scheme("https") public static let ws = Scheme("ws") public static let wss = Scheme("wss") } extension Scheme: Hashable { public var hashValue: Int { return rawValue.hashValue } public static func == (lhs: Scheme, rhs: Scheme) -> Bool { return lhs.rawValue == rhs.rawValue } }
a4442b64ac0c0797ec4c33ed81a091ad
20.815789
62
0.630881
false
false
false
false
Gowiem/EmojiMenuBar
refs/heads/master
EmojiMenuBar/AppDelegate.swift
mit
1
// // AppDelegate.swift // EmojiMenuBar // // Created by Matt Gowie on 6/21/14. // Copyright (c) 2014 Artisan. All rights reserved. // import Cocoa import Foundation class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { @IBOutlet var mainPopover: NSPopover! var statusItem: NSStatusItem? var hipchatEmoticons: NSArray var emojis: NSArray var testImage: NSImage? var popoverTransiencyMonitor: NSEvent? override init() { NSLog("AppDelegate init!") hipchatEmoticons = AppDelegate.buildHipchatEmoticons() emojis = AppDelegate.buildEmojiModels() super.init() } func applicationDidFinishLaunching(aNotification: NSNotification?) { let bar = NSStatusBar.systemStatusBar() statusItem = bar.statusItemWithLength(-1) statusItem!.title = nil statusItem!.highlightMode = true statusItem!.action = "showPopover:" if let icon = NSImage(named: "Icon") { icon.size = NSSize(width: 16, height: 16) icon.setTemplate(true) statusItem!.image = icon } NSLog("didFinishLaunching - hipchatEmoticons.count: \(hipchatEmoticons.count)") } func showPopover(sender: AnyObject) { // Need to downcast our sender as a view since it's a private class (NSStatusBarButton) let statusBarButton = sender as NSView mainPopover.showRelativeToRect(NSZeroRect, ofView: statusBarButton, preferredEdge: NSRectEdge.min) if (self.popoverTransiencyMonitor == nil) { NSEvent.addGlobalMonitorForEventsMatchingMask((NSEventMask.LeftMouseDownMask | NSEventMask.RightMouseDownMask | NSEventMask.KeyUpMask), handler: handleClickOffEvent) } } func handleClickOffEvent(aEvent: (NSEvent!)) -> Void { // Remove the monitor and set it to nil so we set it again when the user clicks the menu item. if let monitor = self.popoverTransiencyMonitor { NSEvent.removeMonitor(monitor) } self.popoverTransiencyMonitor = nil // Close our popover self.mainPopover.close() } class func buildHipchatEmoticons() -> [EMEmoticonModel] { if let resourcePath = NSBundle.mainBundle().resourcePath { let hipchatIconsPath = resourcePath.stringByAppendingPathComponent("hipchat-emoticons") var contents: [String] = NSFileManager.defaultManager().contentsOfDirectoryAtPath(hipchatIconsPath, error: nil) as [String] return contents.map({ EMEmoticonModel.instanceOrNil($0) }).filter({ $0 != nil }).map({ $0! }) } else { return Array() } } class func buildEmojiModels() -> NSArray { var result: NSArray = NSArray() if let resourcePath = NSBundle.mainBundle().resourcePath { let emojiDotJson = resourcePath.stringByAppendingPathComponent("emoji.json") NSLog("emojiDotJson \(emojiDotJson)") let emojiString = String(contentsOfFile: emojiDotJson, encoding: NSUTF8StringEncoding, error: nil) let emojiJson = JSON.parse(emojiString!) NSLog("jsonObject: \(emojiJson)") if let emojiArray = emojiJson.asArray { result = emojiArray.map { (singleJson: JSON) -> EMEmojiModel in NSLog("single json: \(singleJson)") return EMEmojiModel(json: singleJson) } } } return result } }
97b0a7b2815c3b4a5b9207151f46db35
35.363636
135
0.631111
false
false
false
false
gkgy/smallios
refs/heads/master
MysmallPlayground.playground/Contents.swift
gpl-3.0
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //哈哈,璀璨一下学弟学妹,5年高考3年模拟加起来几年 var five年高考 = 5 var three年模拟 = 3 print(five年高考+three年模拟) print(five年高考-three年模拟) print(five年高考*three年模拟) print(five年高考/three年模拟) //我哥的岁数和我弟的岁数 var 我哥 = 5 var 我弟 = 3 if 我哥 > 我弟 { print("厉害了,我的哥") } else if 我哥 == 我弟{ print("一样厉害") } else{ print("太逊了") } //加入与或非 && || ! if 我哥 > 我弟 && five年高考 == 5 { //注意 == 两面都要留有空格 print("厉害了,我的哥") } else if 我哥 == 我弟{ print("一样厉害") } else{ print("太逊了") } //while 条件满足直到不满足退出 比如智商 < 180{ // 条件变化 不停地做题 // 智商 = 智商 + 1 // //} //print ("天才诞生") while five年高考 < 8{ five年高考 += 1 print("你学了\(five年高考)年") } //水果选择 var 水果 = "菠萝" switch 水果 { case "橘子": print("选择橘子") case "菠萝": print("选择了菠萝") default: print("什么都不选") }
c2b195bc3eb7ade0b76e160cb4dd4d8b
11.628571
52
0.552036
false
false
false
false
frootloops/swift
refs/heads/master
test/Sema/diag_erroneous_iuo.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -swift-version 5 // These are all legal uses of '!'. struct Fine { var value: Int! func m(_ unnamed: Int!, named: Int!) -> Int! { return unnamed } static func s(_ unnamed: Int!, named: Int!) -> Int! { return named } init(_ value: Int) { self.value = value } init!() { return nil } subscript ( index: Int! ) -> Int! { return index } subscript<T> ( index: T! ) -> T! { return index } } let _: ImplicitlyUnwrappedOptional<Int> = 1 // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{8-36=}} {{39-39=!}} {{39-40=}} let _: ImplicitlyUnwrappedOptional = 1 // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use an explicit type followed by '!'}} extension ImplicitlyUnwrappedOptional {} // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use 'Optional' instead}}{{11-38=Optional}} func functionSpelling( _: ImplicitlyUnwrappedOptional<Int> // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{6-34=}} {{37-37=!}} {{37-38=}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{6-34=}} {{37-37=!}} {{37-38=}} return 1 } // Okay, like in the method case. func functionSigil( _: Int! ) -> Int! { return 1 } // Not okay because '!' is not at the top level of the type. func functionSigilArray( _: [Int!] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} ) -> [Int!] { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} return [1] } func genericFunction<T>( iuo: ImplicitlyUnwrappedOptional<T> // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{8-36=}} {{37-37=!}} {{37-38=}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{6-34=}} {{35-35=!}} {{35-36=}} return iuo } // Okay, like in the non-generic case. func genericFunctionSigil<T>( iuo: T! ) -> T! { return iuo } func genericFunctionSigilArray<T>( // FIXME: We validate these types multiple times resulting in multiple diagnostics iuo: [T!] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} // expected-error@-1 {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} // expected-error@-2 {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} ) -> [T!] { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} // expected-error@-1 {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} // expected-error@-2 {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} return iuo } protocol P { associatedtype T associatedtype U } struct S : P { typealias T = ImplicitlyUnwrappedOptional<Int> // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{17-45=}} {{48-48=?}} {{48-49=}} typealias U = Optional<ImplicitlyUnwrappedOptional<Int>> // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{26-54=}} {{57-57=?}} {{57-58=}} typealias V = Int! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} typealias W = Int!? // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} var x: V var y: W var fn1: (Int!) -> Int // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{16-17=?}} var fn2: (Int) -> Int! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{24-25=?}} subscript ( index: ImplicitlyUnwrappedOptional<Int> // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{12-40=}} {{43-43=!}} {{43-44=}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{12-40=}} {{43-43=!}} {{43-44=}} return index } subscript<T> ( index: ImplicitlyUnwrappedOptional<T> // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{12-40=}} {{41-41=!}} {{41-42=}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{12-40=}} {{41-41=!}} {{41-42=}} return index } } func generic<T : P>(_: T) where T.T == ImplicitlyUnwrappedOptional<Int> { } // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{40-68=}} {{71-71=?}} {{71-72=}} func genericOptIUO<T : P>(_: T) where T.U == Optional<ImplicitlyUnwrappedOptional<Int>> {} // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{55-83=}} {{86-86=?}} {{86-87=}} func testClosure() -> Int { return { (i: ImplicitlyUnwrappedOptional<Int>) // expected-error {{the spelling 'ImplicitlyUnwrappedOptional' is unsupported; use '!' after the type name}}{{9-37=}} {{40-40=!}} {{40-41=}} -> ImplicitlyUnwrappedOptional<Int> in // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{9-37=}} {{40-40=?}} {{40-41=}} return i }(1) } _ = Array<Int!>() // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{14-15=?}} let _: Array<Int!> = [1] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{17-18=?}} _ = [Int!]() // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} let _: [Int!] = [1] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{12-13=?}} _ = Optional<Int!>(nil) // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{17-18=?}} let _: Optional<Int!> = nil // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} _ = Int!?(0) // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} let _: Int!? = 0 // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{11-12=?}} _ = ( Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{6-7=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} String! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} )(1, 2.0, "3") let _: ( Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{6-7=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} String! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} ) = (1, 2.0, "3") struct Generic<T, U, C> { init(_ t: T, _ u: U, _ c: C) {} } _ = Generic<Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{16-17=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{18-19=?}} String!>(1, 2.0, "3") // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{19-20=?}} let _: Generic<Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{19-20=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{21-22=?}} String!> = Generic(1, 2.0, "3") // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{22-23=?}} func vararg(_ first: Int, more: Int!...) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{36-37=?}} } func varargIdentifier(_ first: Int, more: ImplicitlyUnwrappedOptional<Int>...) { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{43-71=}} {{74-74=?}} {{74-75=}} } func iuoInTuple() -> (Int!) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{26-27=?}} return 1 } func iuoInTupleIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{33-61=}} {{64-64=?}} {{64-65=}} return 1 } func iuoInTuple2() -> (Float, Int!) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{34-35=?}} return (1.0, 1) } func iuoInTuple2Identifier() -> (Float, ImplicitlyUnwrappedOptional<Int>) { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{41-69=}} {{72-72=?}} {{72-73=}} return (1.0, 1) } func takesFunc(_ fn: (Int!) -> Int) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{26-27=?}} return fn(0) } func takesFuncIdentifier(_ fn: (ImplicitlyUnwrappedOptional<Int>) -> Int) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{33-61=}} {{64-64=?}} {{64-65=}} return fn(0) } func takesFunc2(_ fn: (Int) -> Int!) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{35-36=?}} return fn(0)! } func takesFunc2Identifier(_ fn: (Int) -> ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{42-70=}} {{73-73=?}} {{73-74=}} return fn(0) } func returnsFunc() -> (Int!) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{27-28=?}} return { $0! } } func returnsFuncIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{34-62=}} {{65-65=?}} {{65-66=}} return { $0 } } func returnsFunc2() -> (Int) -> Int! { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{36-37=?}} return { $0 } } func returnsFunc2Identifier() -> (Int) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{'ImplicitlyUnwrappedOptional' is not allowed here; perhaps 'Optional' was intended?}}{{43-71=}} {{74-74=?}} {{74-75=}} return { $0 } }
59acc3d8cffe2f5393ac984df545728b
51.632653
229
0.631737
false
false
false
false
HWdan/DYTV
refs/heads/master
DYTV/DYTV/Classes/Tools/NetworkTools.swift
mit
1
// // NetworkTools.swift // Alamofire的测试 // // Created by hegaokun on 2017/3/20. // Copyright © 2017年 AAS. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) { // 1.获取类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 2.发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in // 3.获取结果 guard let result = response.result.value else { print(response.result.error!) return } // 4.将结果回调出去 finishedCallback(result) } } }
447a1a8c5812e98f5419b6e448d15238
23.944444
159
0.557906
false
false
false
false
badoo/Chatto
refs/heads/master
Chatto/sources/SerialTaskQueue.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public typealias TaskClosure = (_ completion: @escaping () -> Void) -> Void public protocol SerialTaskQueueProtocol { func addTask(_ task: @escaping TaskClosure) func start() func stop() func flushQueue() var isEmpty: Bool { get } var isStopped: Bool { get } } public final class SerialTaskQueue: SerialTaskQueueProtocol { public private(set) var isBusy = false public private(set) var isStopped = true private var tasksQueue = [TaskClosure]() public init() {} public func addTask(_ task: @escaping TaskClosure) { self.tasksQueue.append(task) self.maybeExecuteNextTask() } public func start() { self.isStopped = false self.maybeExecuteNextTask() } public func stop() { self.isStopped = true } public func flushQueue() { self.tasksQueue.removeAll() } public var isEmpty: Bool { return self.tasksQueue.isEmpty } private func maybeExecuteNextTask() { if !self.isStopped && !self.isBusy { if !self.isEmpty { let firstTask = self.tasksQueue.removeFirst() self.isBusy = true firstTask({ [weak self] () -> Void in self?.isBusy = false self?.maybeExecuteNextTask() }) } } } }
bc7557110046e42dfa630124f623a73e
30.325
78
0.675579
false
false
false
false
zhangliangzhi/iosStudyBySwift
refs/heads/master
xxcolor/xxcolor/GcViewController.swift
mit
1
// // GcViewController.swift // xxcolor // // Created by ZhangLiangZhi on 2017/2/26. // Copyright © 2017年 xigk. All rights reserved. // import UIKit import GameKit class GcViewController: UIViewController, GKGameCenterControllerDelegate { @IBOutlet weak var ScoreLbl: UILabel! var score = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. autoPlayer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. ScoreLbl.text = "\(score)" } @IBAction func AddScore(_ sender: Any) { score += 1 ScoreLbl.text = "\(score)" SaveHightScore(num: score) } @IBAction func OpenGC(_ sender: Any) { let VC = self.view.window?.rootViewController let GCVC = GKGameCenterViewController() GCVC.gameCenterDelegate = self VC?.present(GCVC, animated: true, completion: nil) } func SaveHightScore(num:Int){ if GKLocalPlayer.localPlayer().isAuthenticated { let scoreReport = GKScore(leaderboardIdentifier: "1") scoreReport.value = Int64(num) let scoreArray:[GKScore] = [scoreReport] GKScore.report(scoreArray, withCompletionHandler: nil) } } func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismiss(animated: true, completion: nil) } func autoPlayer() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = { (view, error) in if view != nil{ self.present(view!, animated: true, completion:nil) }else{ print(GKLocalPlayer.localPlayer().isAuthenticated) } } } /* // 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. } */ }
cfaf003cc7be17aea53a495a679298f0
28.1875
106
0.625268
false
false
false
false
oscarqpe/machine-learning-algorithms
refs/heads/master
Swift CNN/CapaPool.swift
gpl-3.0
1
// // CapaPool.swift // Swift CNN // // Created by Andre Valdivia on 15/05/16. // Copyright © 2016 Andre Valdivia. All rights reserved. // import Foundation class CapaPool: CapaCNN { var pools = Array<Pool>() private let step:Int private let type:typePool init (rows:Int, cols:Int,step:Int,type:typePool, numPool:Int = 0){ self.type = type self.step = step super.init(rows: rows, cols: cols) for _ in 0..<numPool{ pools.append(Pool(rows: rows, columns: cols, step: step, id: id,type: type)) self.id++ } } func addMatrix(){ pools.append(Pool(rows: rows, columns: cols, step: step, id: id, type: type)) self.id++ } func addPool(m:Pool){ if(m.rows == rows && m.columns == cols){ pools.append(m) self.id++ }else{ print("Error en addMatrix no coincide Rows o Cols") } } func connect(matrix: Int, poolAnterior:Pool){ pools[matrix].connect(poolAnterior) } }
fbca9b1283db81c93154fbec29f89037
24.452381
88
0.558052
false
false
false
false
grehujt/learningSwift
refs/heads/master
chapter-3-6 UINavigationController 4/demoApp/demoApp/FirstSubViewController.swift
mit
1
// // FirstSubViewController.swift // demoApp // // Created by kris on 8/5/16. // Copyright © 2016 kris. All rights reserved. // import UIKit class FirstSubViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "First Page" self.view.backgroundColor = UIColor.brownColor() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: #selector(FirstSubViewController.nextPage)) } func nextPage() { let v2 = SecondSubViewController() self.navigationController?.pushViewController(v2, animated: true) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationItem.prompt = "loading" self.navigationController?.navigationBar.translucent = false self.navigationController?.navigationBar.barStyle = .Black self.navigationController?.navigationBar.tintColor = UIColor.orangeColor() } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
fce5171989efe34faa87aace425264d1
31.039216
160
0.687882
false
false
false
false
frtlupsvn/Vietnam-To-Go
refs/heads/master
Pods/Former/Former/RowFormers/PickerRowFormer.swift
mit
1
// // PickerRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 8/2/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol PickerFormableRow: FormableRow { func formPickerView() -> UIPickerView } public class PickerItem<S> { public let title: String public let value: S? public init(title: String, value: S? = nil) { self.title = title self.value = value } } public final class PickerRowFormer<T: UITableViewCell, S where T: PickerFormableRow> : BaseRowFormer<T>, Formable, ConfigurableForm { // MARK: Public public var pickerItems: [PickerItem<S>] = [] public var selectedRow: Int = 0 public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } deinit { let picker = cell.formPickerView() picker.delegate = nil picker.dataSource = nil } public final func onValueChanged(handler: (PickerItem<S> -> Void)) -> Self { onValueChanged = handler return self } public override func initialized() { super.initialized() rowHeight = 216 } public override func cellInitialized(cell: T) { let picker = cell.formPickerView() picker.delegate = observer picker.dataSource = observer } public override func update() { super.update() cell.selectionStyle = .None let picker = cell.formPickerView() picker.selectRow(selectedRow, inComponent: 0, animated: false) picker.userInteractionEnabled = enabled picker.layer.opacity = enabled ? 1 : 0.5 } // MARK: Private private final var onValueChanged: (PickerItem<S> -> Void)? private lazy var observer: Observer<T, S> = Observer<T, S>(pickerRowFormer: self) } private class Observer<T: UITableViewCell, S where T: PickerFormableRow> : NSObject, UIPickerViewDelegate, UIPickerViewDataSource { private weak var pickerRowFormer: PickerRowFormer<T, S>? init(pickerRowFormer: PickerRowFormer<T, S>) { self.pickerRowFormer = pickerRowFormer } private dynamic func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { guard let pickerRowFormer = pickerRowFormer else { return } if pickerRowFormer.enabled { pickerRowFormer.selectedRow = row let pickerItem = pickerRowFormer.pickerItems[row] pickerRowFormer.onValueChanged?(pickerItem) } } private dynamic func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } private dynamic func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { guard let pickerRowFormer = pickerRowFormer else { return 0 } return pickerRowFormer.pickerItems.count } private dynamic func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { guard let pickerRowFormer = pickerRowFormer else { return nil } return pickerRowFormer.pickerItems[row].title } }
cf6094c15f475d0961236be0d4f0e630
29.385321
125
0.657203
false
false
false
false
Skyricher/DYZB
refs/heads/master
DYZBTV/DYZBTV/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DYZBTV // // Created by 鲁俊 on 2016/9/23. // Copyright © 2016年 amao24.com. All rights reserved. // import UIKit private let contentCellID = "contentCellID" class PageContentView: UIView { //MARK: -懒加载 internal lazy var collectionView: UICollectionView = { [weak self] in //1创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //2。创建 UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:contentCellID ) return collectionView }() //MARK: -定义属性 internal var childVcs: [UIViewController] internal weak var parentViewController: UIViewController? //MARK:-自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewControll: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewControll super.init(frame: frame) //设置 UI 界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: -设置UI界面 private extension PageContentView{ func setupUI(){ //1.将所有的子控制器添加到父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //2.添加 UICollectionView,用于在 cell 中存放控制器的 View addSubview(collectionView) collectionView.frame = bounds } } //实现数据源方法 extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建 cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) //给 cell 设置内容 for view in cell.contentView.subviews{ view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } }
1c32681206d05e117fdad963f6cb2312
26.401961
121
0.645081
false
false
false
false
strike65/SwiftyStats
refs/heads/master
SwiftyStats/CommonSource/ProbDist/ProbDist-Weibull.swift
gpl-3.0
1
// // Created by VT on 20.07.18. // Copyright © 2018 strike65. All rights reserved. /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif extension SSProbDist { /// Weibull distribution public enum Weibull { /// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Weibull distribution. /// - Parameter a: Location parameter /// - Parameter b: Scale parameter /// - Parameter c: Shape parameter /// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 public static func para<FPT: SSFloatingPoint & Codable>(location loc: FPT, scale: FPT, shape: FPT) throws -> SSProbDistParams<FPT> { if (scale <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter b is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if (shape <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("shape parameter c is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var ex1: FPT var ex2: FPT var ex3: FPT var ex4: FPT var ex5: FPT var ex6: FPT var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>() ex1 = FPT.one + SSMath.reciprocal(shape) ex2 = scale * SSMath.tgamma1(ex1) result.mean = loc + ex2 var a: FPT = SSMath.tgamma1(FPT.one + 2 / shape) var b: FPT = SSMath.tgamma1(FPT.one + FPT.one / shape) var c: FPT = SSMath.pow1(b, 2) result.variance = SSMath.pow1(scale, 2) * (a - SSMath.pow1(b, 2)) a = -3 * SSMath.pow1(SSMath.tgamma1(1 + 1 / shape), 4) ex1 = FPT.one + SSMath.reciprocal(shape) ex2 = SSMath.tgamma1(ex1) ex3 = SSMath.pow1(ex2, 2) ex4 = 2 * SSMath.reciprocal(shape) ex5 = FPT.one + ex4 ex6 = SSMath.tgamma1(ex5) b = 6 * ex3 * ex6 ex4 = 3 * SSMath.reciprocal(shape) ex5 = FPT.one + ex4 ex6 = SSMath.tgamma1(ex5) c = -4 * ex2 * ex6 var d: FPT = SSMath.tgamma1(1 + 4 / shape) ex1 = SSMath.tgamma1(FPT.one + 2 / shape) ex2 = SSMath.tgamma1(FPT.one + SSMath.reciprocal(shape)) let e: FPT = ex1 - SSMath.pow1(ex2, 2) ex1 = a + b ex2 = ex1 + c + d result.kurtosis = ex2 / SSMath.pow1(e, 2) ex2 = SSMath.tgamma1(FPT.one + SSMath.reciprocal(shape)) a = 2 * SSMath.pow1(SSMath.tgamma1(1 + 1 / shape), 3) ex4 = 2 * SSMath.reciprocal(shape) ex5 = FPT.one + ex4 ex6 = SSMath.tgamma1(ex5) b = -3 * ex2 * ex6 c = SSMath.tgamma1(1 + 3 / shape) d = ex6 - ex3 result.skewness = (a + b + c) / SSMath.pow1(d, Helpers.makeFP(1.5)) return result } /// Returns the pdf of the Weibull distribution. /// - Parameter x: x /// - Parameter a: Location parameter /// - Parameter b: Scale parameter /// - Parameter c: Shape parameter /// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, location a: FPT, scale b: FPT, shape c: FPT) throws -> FPT { if (b <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter b is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if (c <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("shape parameter c is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if x < a { return 0 } let ex1: FPT = (x - a) / b let ex2: FPT = SSMath.pow1(ex1, c - FPT.one) let ex3: FPT = FPT.minusOne * SSMath.pow1(ex1, c) let ex4: FPT = c / b let result = ex4 * ex2 * SSMath.exp1(ex3) return result } /// Returns the cdf of the Weibull distribution. /// - Parameter x: x /// - Parameter a: Location parameter /// - Parameter b: Scale parameter /// - Parameter c: Shape parameter /// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, location a: FPT, scale b: FPT, shape c: FPT) throws -> FPT { if (b <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter b is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if (c <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("shape parameter c is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var ex1: FPT var ex2: FPT var ex3: FPT if x < a { return 0 } ex1 = x - a ex2 = ex1 / b ex3 = SSMath.pow1(ex2, c) let result = FPT.one - SSMath.exp1(-ex3) return result } /// Returns the quantile of the Weibull distribution. /// - Parameter p: p /// - Parameter a: Location parameter /// - Parameter b: Scale parameter /// - Parameter c: Shape parameter /// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 || p < 0 || p > 1 public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, location a: FPT, scale b: FPT, shape c: FPT) throws -> FPT { if (b <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("scale parameter b is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if (c <= 0) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("shape parameter c is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if p < 0 || p > 1 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("p is expected to be >= 0 and <= 1 ", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if p == 0 { return a } if p == 1 { return FPT.infinity } var ex1: FPT var ex2: FPT var ex3: FPT ex1 = -SSMath.log1p1((FPT.one - p) - FPT.one) ex2 = SSMath.pow1(ex1, SSMath.reciprocal(c)) ex3 = b * ex2 let result = a + ex3 return result } } }
b2a825966996489717c611428b652124
39.065306
140
0.486756
false
false
false
false
CoderST/DYZB
refs/heads/master
DYZB/DYZB/Class/Profile/Controller/ProfileInforViewController.swift
mit
1
// // ProfileInforViewController.swift // DYZB // // Created by xiudou on 2017/7/9. // Copyright © 2017年 xiudo. All rights reserved. // 我的详情页面 import UIKit import SVProgressHUD import TZImagePickerController let BasicSettingCellIdentifier = "BasicSettingCellIdentifier" let headImageCellHeight : CGFloat = 60 let normalCellHeight : CGFloat = 44 class ProfileInforViewController: BaseViewController { fileprivate var user : User?{ didSet{ guard let user = user else { return } // if let user = user { groups.removeAll() profileInforDataFrameModel = ProfileInforDataFrameModel(user: user) // 第一组 setuoGroupOne(profileInforDataFrameModel) // 第二组 setuoGroupTwo(profileInforDataFrameModel) // 第三组 setuoGroupThree(profileInforDataFrameModel) endAnimation() collectionView.reloadData() // } } } var profileInforDataFrameModel : ProfileInforDataFrameModel! fileprivate lazy var profileInforVM : ProfileInforVM = ProfileInforVM() lazy var groups : [SettingGroup] = [SettingGroup]() lazy var collectionView : UICollectionView = { // 设置layout属性 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: sScreenW, height: 44) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 // 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y:sStatusBarH + sNavatationBarH, width: sScreenW, height: sScreenH - (sStatusBarH + sNavatationBarH)), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor(r: 239, g: 239, b: 239) collectionView.register(BasicSettingCell.self, forCellWithReuseIdentifier: BasicSettingCellIdentifier) return collectionView; }() // MARK:- 生命周期 override func viewDidLoad() { automaticallyAdjustsScrollViewInsets = false baseContentView = collectionView view.addSubview(collectionView) super.viewDidLoad() title = "个人信息" // 请求一下最新数据 setupData() // 接收通知 notificationCenter.addObserver(self, selector: #selector(reLoadProfileInforData), name: NSNotification.Name(rawValue: sNotificationName_ReLoadProfileInforData), object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } deinit { debugLog("ProfileInforViewController -- 销毁") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) debugLog("viewWillAppear") } } // MARK:- 获取数据 extension ProfileInforViewController { fileprivate func setupData(){ profileInforVM.loadProfileInforDatas({ self.user = self.profileInforVM.user }, { (message) in }) { } } } // MARK:- 创建组 extension ProfileInforViewController { fileprivate func setuoGroupOne(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ /// 头像 // 1 创建需要类型的item let avaModel = ArrowImageItem(icon: "", title: "头像", rightImageName: profileInforDataFrameModel.avatarName, VcClass: nil) // 2 计算出item的frame let avaModelFrame = SettingItemFrame(avaModel) // 3 是否需要定义特殊处理(有实现,没有不用实现) avaModel.optionHandler = {[weak self] in // 创建 // preferredStyle 为 ActionSheet let alertController = UIAlertController(title: "上传头像", message: nil, preferredStyle:.actionSheet) // 设置2个UIAlertAction let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let photographAction = UIAlertAction(title: "拍照", style: .default, handler: { (alertAction) in }) let photoAlbumAction = UIAlertAction(title: "从相册选择", style: .default, handler: { (alertAction) in guard let imagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self) else { return } imagePickerVc.sortAscendingByModificationDate = false imagePickerVc.photoWidth = 1024.0 imagePickerVc.photoPreviewMaxWidth = 3072.0 self?.navigationController?.present(imagePickerVc, animated: true, completion: nil) }) // 添加到UIAlertController alertController.addAction(cancelAction) alertController.addAction(photoAlbumAction) alertController.addAction(photographAction) // 弹出 self?.present(alertController, animated: true, completion: nil) } avaModel.optionHeight = { return headImageCellHeight } /// 昵称 let nickNameModel = ArrowItem(icon: "", title: "昵称", subtitle: profileInforDataFrameModel.nickname, VcClass: TestViewController.self) let nickNameModelFrame = SettingItemFrame(nickNameModel) /// 性别 let sexModel = ArrowItem(icon: "", title: "性别", subtitle: profileInforDataFrameModel.sexString, VcClass: nil) let sexModelFrame = SettingItemFrame(sexModel) sexModel.optionHandler = {[weak self] in // preferredStyle 为 ActionSheet let alertController = UIAlertController(title: "上传头像", message: nil, preferredStyle:.actionSheet) // 设置2个UIAlertAction let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let womanAction = UIAlertAction(title: "女", style: .default, handler: { (alertAction) in self?.profileInforVM.loadSexProfileInforDatas(sexString: "2", { SVProgressHUD.showSuccess(withStatus: "成功") // 再次请求个人详情的数据 // self?.profileInforVM.loadProfileInforDatas({ // self?.user = self?.profileInforVM.user // }, { (message) in // // }, { // // }) self?.reLoadProfileInforData() }, { (message) in SVProgressHUD.showInfo(withStatus: message) }, { SVProgressHUD.showError(withStatus: "") }) }) let manAction = UIAlertAction(title: "男", style: .default, handler: { (alertAction) in self?.profileInforVM.loadSexProfileInforDatas(sexString: "1", { // 再次请求个人详情的数据 self?.reLoadProfileInforData() // self?.profileInforVM.loadProfileInforDatas({ // self?.user = self?.profileInforVM.user // SVProgressHUD.showSuccess(withStatus: "成功") // }, { (message) in // // }, { // // }) }, { (message) in SVProgressHUD.showInfo(withStatus: message) }, { SVProgressHUD.showError(withStatus: "") }) }) // 添加到UIAlertController alertController.addAction(cancelAction) alertController.addAction(manAction) alertController.addAction(womanAction) // 弹出 self?.present(alertController, animated: true, completion: nil) } /// 生日 let birthDayModel = ArrowItem(icon: "", title: "生日", subtitle: profileInforDataFrameModel.birthdayString, VcClass: nil) let birthDayModelFrame = SettingItemFrame(birthDayModel) birthDayModel.optionHandler = { guard let birthdayString = self.user?.birthday else { return } guard let date = Date.dateFromString("yyyyMMdd", birthdayString) else { return } let showDate = DatePackerView(frame: self.view.bounds, date) showDate.showDatePicker(self.view) showDate.delegate = self } /// 所在地 let locationModel = ArrowItem(icon: "", title: "所在地", subtitle: profileInforDataFrameModel.locationString, VcClass: LocationViewController.self) let locationModelFrame = SettingItemFrame(locationModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [avaModelFrame,nickNameModelFrame,sexModelFrame,birthDayModelFrame,locationModelFrame] groups.append(settingGroup) } fileprivate func setuoGroupTwo(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ let avaModel = ArrowItem(icon: "", title: "实名认证", subtitle: profileInforDataFrameModel.realNameAuthentication, VcClass: nil) let avaModelFrame = SettingItemFrame(avaModel) avaModel.optionHandler = {[weak self] in print("setuoGroupTwo点击了实名认证") } let nickNameModel = ArrowItem(icon: "", title: "密码", subtitle: profileInforDataFrameModel.passWord, VcClass: MyTaskViewController.self) let nickNameModelFrame = SettingItemFrame(nickNameModel) // 如果邮箱有值则不能跳转 没哟值则跳转绑定 var sexModel : SettingItem! if profileInforDataFrameModel.emailString.characters.count > 0{ sexModel = SettingItem(icon: "", title: "邮箱", subTitle: profileInforDataFrameModel.emailString) }else{ sexModel = ArrowItem(icon: "", title: "邮箱", subtitle: profileInforDataFrameModel.emailString, VcClass: TestViewController.self) } let sexModelFrame = SettingItemFrame(sexModel) let birthDayModel = ArrowItem(icon: "", title: "手机", subtitle: profileInforDataFrameModel.mobile_phoneString, VcClass: IPhoneBindingViewController.self) let birthDayModelFrame = SettingItemFrame(birthDayModel) let locationModel = ArrowItem(icon: "", title: "QQ", subtitle: profileInforDataFrameModel.qq, VcClass: BindQQViewController.self) let locationModelFrame = SettingItemFrame(locationModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [avaModelFrame,nickNameModelFrame,sexModelFrame,birthDayModelFrame,locationModelFrame] groups.append(settingGroup) } fileprivate func setuoGroupThree(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ let nickNameModel = SettingItem(icon: "", title: "经验值", subTitle: profileInforDataFrameModel.empiricalValue) let nickNameModelFrame = SettingItemFrame(nickNameModel) let sexModel = SettingItem(icon: "", title: "鱼丸", subTitle: profileInforDataFrameModel.fishBall) let sexModelFrame = SettingItemFrame(sexModel) let birthDayModel = ArrowItem(icon: "", title: "鱼翅", subtitle: profileInforDataFrameModel.fin, VcClass: FishboneRechargeViewController.self) let birthDayModelFrame = SettingItemFrame(birthDayModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [nickNameModelFrame,sexModelFrame,birthDayModelFrame] groups.append(settingGroup) } } extension ProfileInforViewController { @objc fileprivate func reLoadProfileInforData(){ // 再次请求个人详情的数据 profileInforVM.loadProfileInforDatas({ self.user = self.profileInforVM.user }, { (message) in }, { }) } } // MARK:- UICollectionViewDataSource extension ProfileInforViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ return groups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let group = groups[section] return group.settingGroup.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BasicSettingCellIdentifier, for: indexPath) as! BasicSettingCell let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] cell.settingItemFrame = settingItemFrame return cell } } // MARK:- UICollectionViewDelegateFlowLayout extension ProfileInforViewController : UICollectionViewDelegateFlowLayout { // 组间距 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{ return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] if settingItemFrame.settingItem.optionHandler != nil { settingItemFrame.settingItem.optionHandler!() }else if settingItemFrame.settingItem is ArrowItem{ let arrowItem = settingItemFrame.settingItem as! ArrowItem guard let desClass = arrowItem.VcClass else { return } guard let desVCType = desClass as? UIViewController.Type else { return } let desVC = desVCType.init() // 修改密码 if desVC is MyTaskViewController{ let desvc = desVC as! MyTaskViewController desvc.open_url = "http://www.douyu.com/api/v1/change_password?client_sys=ios&token=\(TOKEN)&auth=\(AUTH)" } // QQ if desVC is BindQQViewController{ let desvc = desVC as! BindQQViewController desvc.completeButtonValue(completeButtoncallBack: { (isok) in // 刷新页面 self.reLoadProfileInforData() }) } desVC.title = arrowItem.title navigationController?.pushViewController(desVC, animated: true) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] if settingItemFrame.settingItem.optionHeight != nil { let height = settingItemFrame.settingItem.optionHeight!() return CGSize(width: sScreenW, height: height) } return CGSize(width: sScreenW, height: normalCellHeight) } } // MARK:- TZImagePickerControllerDelegate extension ProfileInforViewController : TZImagePickerControllerDelegate{ func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!){ guard let image = photos.first else { return } guard let imageData = UIImageJPEGRepresentation(image, 0.3) else { return } debugLog(imageData) profileInforVM.loadUpImageProfileInforDatas(imageData: imageData, { }, { (message) in }) { } } } extension ProfileInforViewController : DatePackerViewDelegate { func datePackerView(_ datePackerView: DatePackerView, indexItem: String) { print(indexItem) profileInforVM.loadBirthDayProfileInforDatas(birthDay: indexItem, { self.reLoadProfileInforData() }, { (message) in }) { } } }
991adfba2c8fe20462be57f1875e5fb5
39.002427
199
0.619319
false
false
false
false
dkerzig/CAJ-Einschreibungen
refs/heads/master
CAJ-Einschreibungen/CAJController.swift
mit
1
// // CAJController.swift // CAJ-Einschreibungen // // Webkit includes the invisible 'WKWebView' which we use // to load the CAJ, inject out JavaScript and fetch the results. // Informations: https://goo.gl/O4M2Q3 // Great Tutorial: http://goo.gl/EgrTD1 import WebKit import UIKit // A protocol what our 'TableViewController' implements to // get notified when this controller has finished fetching. protocol CAJControllerDelegate: class { func didLoadCAJCourses(fetchedCourses: [CAJCourse]?) } // Collecting all course-relevant informations into on data-structure // A 'struct' in Swift offers great performance and isn't a memory/performance-overhead struct CAJCourse { let typ: String let name: String let dozent: String let ort: String let zeit: String } // Our class which does the actual fetching-work. It get's a username/password, // loads the CAJ into a WKWebView, injects the credentials, fires the login-event, // waits for the course-page to be displayed and crawls any course-informations // from the DOM. (See: Injection.js and try the functions in the chrome-/safari-console) class CAJController: NSObject, WKScriptMessageHandler, WKNavigationDelegate { // MARK: - VARIABLES private var username: String private var password: String // Our reference to our 'TableViewController' which implements the delegate-protocol weak var delegate: CAJControllerDelegate? = nil // Once again a lazy property which contains our a 'WKWebView' which will be // configured with the JavaScript-file 'Insertion.js'. Also we set ourself // the 'WKScriptMessageHandler' (which is also a delegate) to handle data // sent by our javascript function 'getAllCourses()' in 'Injection.js'. lazy var webView: WKWebView = { [unowned self] in // A WKUserContentController object provides a way for JavaScript to post messages to a web view. let webViewConfiguration = WKWebViewConfiguration() let userContentController = WKUserContentController() // Load JS-Script let jsPath = NSBundle.mainBundle().pathForResource("Injection", ofType: "js") let js = String(contentsOfFile: jsPath!, encoding: NSUTF8StringEncoding, error: nil) // Create a WKUserscript and add it to the contentController let userScript = WKUserScript(source: js!, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) userContentController.addUserScript(userScript) userContentController.addScriptMessageHandler(self, name: "courses") webViewConfiguration.userContentController = userContentController // Create WKWebView let webView = WKWebView(frame: CGRectZero, configuration: webViewConfiguration) return webView }() // MARK: - INITIALIZER init(username: String, password: String) { self.username = username self.password = password } // MARK: - Login- and Fetch-Method func loginAndGetCourses() { // Load initial request with WebView let url = NSURL(string: "https://caj.informatik.uni-jena.de/caj/login") let urlRequest = NSURLRequest(URL: url!) webView.navigationDelegate = self webView.loadRequest(urlRequest) } // MARK: - WKScriptMessageHandler // This function is called because of line 30 in 'Injection.js' where data // is returned to the webview-object. We parse the array of course-dictionaries // into our custom 'CAJCourse'-struct (see in 'TableViewController.swift'). func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if (message.name == "courses") { // Convert Message into Array of Dictionaries let jsCourses = message.body as! [AnyObject] var cajCourses = [CAJCourse]() // Convert JS-Objects into CAJCourse-Structs for course in jsCourses { if let course = course as? NSDictionary, let typ = course["typ"] as? String, let name = course["name"] as? String, let dozent = course["dozent"] as? String, let ort = course["ort"] as? String, let zeit = course["zeit"] as? String { // Construct CAJCourse with fetched data cajCourses.append(CAJCourse(typ: typ, name: name, dozent: dozent, ort: ort, zeit: zeit)) } } // Inform Delegate about self.delegate?.didLoadCAJCourses(cajCourses) } } // MARK: - WKNavigationDelegate // This function is called when a site (i.e. CAJ-Login and CAJ-Details) is loaded // successfully by our 'webView'. At this point our JavaScript-functions have been // inserted and we can call them via 'self.webView.evaluateJavaScript(...)'. func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { // Call functions depending on the current state if let url = webView.URL { var javascriptCode = "" // Login-Case: Fill in credentials and execute Login-Button if url.description.hasSuffix("login") { javascriptCode = "login('\(self.username)', '\(self.password)');" // Logged-in-Case: Crawl all Veranstaltungen } else if url.description.hasSuffix("details") { javascriptCode = "getAllCourses();" } self.webView.evaluateJavaScript(javascriptCode, completionHandler: nil) } } }
e479237f682dbbb443524e10e83967c7
37.019355
130
0.643815
false
false
false
false
apple/swift
refs/heads/main
SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift
apache-2.0
3
//===--- ModulePassContext.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL import OptimizerBridging /// The context which is passed to a `ModulePass`'s run-function. /// /// It provides access to all functions, v-tables and witness tables of a module, /// but it doesn't provide any APIs to modify functions. /// In order to modify a function, a module pass must use `transform(function:)`. struct ModulePassContext { let _bridged: BridgedPassContext struct FunctionList : CollectionLikeSequence, IteratorProtocol { private var currentFunction: Function? fileprivate init(first: Function?) { currentFunction = first } mutating func next() -> Function? { if let f = currentFunction { currentFunction = PassContext_nextFunctionInModule(f.bridged).function return f } return nil } } struct VTableArray : BridgedRandomAccessCollection { fileprivate let bridged: BridgedVTableArray var startIndex: Int { return 0 } var endIndex: Int { return Int(bridged.count) } subscript(_ index: Int) -> VTable { assert(index >= 0 && index < bridged.count) return VTable(bridged: bridged.vTables![index]) } } struct WitnessTableList : CollectionLikeSequence, IteratorProtocol { private var currentTable: WitnessTable? fileprivate init(first: WitnessTable?) { currentTable = first } mutating func next() -> WitnessTable? { if let t = currentTable { currentTable = PassContext_nextWitnessTableInModule(t.bridged).table return t } return nil } } struct DefaultWitnessTableList : CollectionLikeSequence, IteratorProtocol { private var currentTable: DefaultWitnessTable? fileprivate init(first: DefaultWitnessTable?) { currentTable = first } mutating func next() -> DefaultWitnessTable? { if let t = currentTable { currentTable = PassContext_nextDefaultWitnessTableInModule(t.bridged).table return t } return nil } } var functions: FunctionList { FunctionList(first: PassContext_firstFunctionInModule(_bridged).function) } var vTables: VTableArray { VTableArray(bridged: PassContext_getVTables(_bridged)) } var witnessTables: WitnessTableList { WitnessTableList(first: PassContext_firstWitnessTableInModule(_bridged).table) } var defaultWitnessTables: DefaultWitnessTableList { DefaultWitnessTableList(first: PassContext_firstDefaultWitnessTableInModule(_bridged).table) } var options: Options { Options(_bridged: _bridged) } /// Run a closure with a `PassContext` for a function, which allows to modify that function. /// /// Only a single `transform` can be alive at the same time, i.e. it's not allowed to nest /// calls to `transform`. func transform(function: Function, _ runOnFunction: (PassContext) -> ()) { PassContext_beginTransformFunction(function.bridged, _bridged) runOnFunction(PassContext(_bridged: _bridged)) PassContext_endTransformFunction(_bridged); } }
fa68533c2f1eb4e8862857e02b72514f
32.390476
96
0.683685
false
false
false
false
mojidabckuu/CRUDRecord
refs/heads/master
Example/Models/User.swift
mit
1
// // User.swift // CRUDRecord // // Created by Vlad Gorbenko on 7/26/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import CRUDRecord import Alamofire import ApplicationSupport class User: CRUDRecord { var id: String! var username: String? required init() {} //MARK: - func setAttributes(attributes: JSONObject) { self.id = attributes["id"] as! String self.username = attributes["username"] as? String } func getAttributes() -> JSONObject { return ["id" : self.id, "username" : self.username ?? NSNull()] } } typealias Author = User extension Author { class Comment: CRUDRecord { var id: String! var text: String! //MARK: - Lifecycle required init() {} //MARK: - func setAttributes(attributes: JSONObject) { self.id = attributes["id"] as! String self.text = attributes["text"] as! String } func getAttributes() -> JSONObject { return ["id" : self.id, "text" : self.text] } } }
f714b30a9a6163cfb694396bc2db3703
20.054545
71
0.555748
false
false
false
false
AlexLittlejohn/ALPlacesViewController
refs/heads/master
ALPlacesViewController/Cells/ALCollectionViewCell.swift
mit
1
// // ALCollectionViewCell.swift // ALPlacesViewController // // Created by Alex Littlejohn on 2015/07/15. // Copyright (c) 2015 zero. All rights reserved. // import UIKit class ALCollectionViewCell: UICollectionViewCell { static let horizontalPadding: CGFloat = 14 static let horizontalSpacing: CGFloat = 10 static let verticalPadding: CGFloat = 8 static let verticalSpacing: CGFloat = 2 static let nameFont = UIFont(name: "AppleSDGothicNeo-Regular", size: 18)! static let addressFont = UIFont(name: "AppleSDGothicNeo-Regular", size: 13)! static func cellSize() -> CGSize { let height = verticalPadding + nameFont.lineHeight + verticalSpacing + addressFont.lineHeight + verticalPadding let width = UIScreen.mainScreen().bounds.size.width return CGSizeMake(width, height) } let nameLabel = UILabel() let addressLabel = UILabel() let divider = UIView() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { } }
2911427f52b37b395a3d339ba0873e0a
26.906977
119
0.66
false
false
false
false
southfox/JFAlgo
refs/heads/master
Example/JFAlgo/BaseCollectionViewController.swift
mit
1
// // BaseCollectionViewController.swift // JFAlgo // // Created by Javier Fuchs on 9/8/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit class BaseCollectionViewController : BaseViewController, UICollectionViewDataSource { @IBOutlet weak var numberField: UITextField! @IBOutlet weak var runButton: UIButton! @IBOutlet weak var generateButton: UIButton! @IBOutlet weak var collectionView: UICollectionView! var A : [Int]? lazy var closure : (()->())? = { [weak self] in if let strong = self { if let array = strong.A { strong.runButton.enabled = array.count > 0 ? true : false } else { strong.runButton.enabled = false } strong.generateButton.enabled = true } } override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) self.view.addGestureRecognizer(tap) } func handleTap() { for indexPath in self.collectionView.indexPathsForVisibleItems() { guard let cell = self.collectionView.cellForItemAtIndexPath(indexPath) else { continue } if let tf : UITextField = cell.contentView.subviews.first as? UITextField { tf.endEditing(true) if let text = tf.text, let n = Int(text) { A![indexPath.row] = n } } } } @IBAction func runAction() { numberField.endEditing(true) handleTap() runButton.enabled = false } @IBAction func generateAction(sender: AnyObject) { numberField.endEditing(true) generateButton.enabled = false } func reload() { self.collectionView.reloadData() self.generateButton.enabled = true self.runButton.enabled = false if let a = A { self.runButton.enabled = a.count > 0 ? true : false } } /// UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let array = A { return array.count } return 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("odds", forIndexPath: indexPath) if let textfield : UITextField = cell.contentView.subviews.first as? UITextField, let array = A { textfield.text = String(array[indexPath.row]) } return cell } }
1b4a1c2980891906429d1bf6d1fedb12
28.42268
130
0.587452
false
false
false
false
tbaranes/VersionTrackerSwift
refs/heads/master
VersionTracker Example/macOS Example/MainWindow.swift
mit
1
// // MainWindow.swift // VersionTracker Demo // // Created by Tom Baranes on 18/02/16. // Copyright © 2016 Tom Baranes. All rights reserved. // import Cocoa import VersionTracker class MainWindow: NSWindow { // MARK: - Properties @IBOutlet weak var labelIsFirstLaunchEver: NSTextField! @IBOutlet weak var labelIsFirstVersionLaunch: NSTextField! @IBOutlet weak var labelIsFirstBuildLaunch: NSTextField! @IBOutlet weak var labelVersionHistory: NSTextField! @IBOutlet weak var labelBuildHistory: NSTextField! // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() VersionTracker.shared.track() labelVersionHistory.stringValue = "Versions history: " + VersionTracker.shared.versionHistory.description labelBuildHistory.stringValue = "Builds history: " + VersionTracker.shared.buildHistory.description labelIsFirstLaunchEver.stringValue = "Is first launch ever: \(VersionTracker.shared.isFirstLaunchEver)" labelIsFirstVersionLaunch.stringValue = "Is first version launch: \(VersionTracker.shared.isFirstVersionLaunch)" labelIsFirstBuildLaunch.stringValue = "Is first build launch: \(VersionTracker.shared.isFirstBuildLaunch)" } }
c9ea406952341e68706d0e7b05b0f6af
34.8
120
0.742219
false
false
false
false
troystribling/BlueCap
refs/heads/master
Tests/FutureLocationTests/FLMocks.swift
mit
1
// // FLMocks.swift // FutureLocation // // Created by Troy Stribling on 4/12/15. // Copyright (c) 2015 Troy Stribling. The MIT License (MIT). // import UIKit import CoreLocation @testable import BlueCapKit // MARK: - CLLocationManagerMock - class CLLocationManagerMock : CLLocationManagerInjectable { static var _authorizationStatus = CLAuthorizationStatus.notDetermined static var _isRangingAvailable = true static var _significantLocationChangeMonitoringAvailable = true static var _deferredLocationUpdatesAvailable = true static var _locationServicesEnabled = true var requestAlwaysAuthorizationCalled = false var requestWhenInUseAuthorizationCalled = false var startUpdatingLocationCalled = false var stopUpdatingLocationCalled = false var requestLocationCalled = false var allowDeferredLocationUpdatesUntilTraveledCalled = false var startMonitoringSignificantLocationChangesCalled = false var stopMonitoringSignificantLocationChangesCalled = false var startMonitoringForRegionCalled = false var stopMonitoringForRegionCalled = false var startRangingBeaconsInRegionCalled = false var stopRangingBeaconsInRegionCalled = false var requestStateForRegionCalled = false var allowDeferredLocationUpdatesUntilTraveledDistance: CLLocationDistance? var allowDeferredLocationUpdatesUntilTraveledTimeout: TimeInterval? var startMonitoringForRegionRegion: CLRegion? var stopMonitoringForRegionRegion: CLRegion? var requestStateForRegionRegion: CLRegion? var startRangingBeaconsInRegionRegion: CLBeaconRegion? var stopRangingBeaconsInRegionRegion: CLBeaconRegion? var delegate: CLLocationManagerDelegate? // MARK: Authorization class func authorizationStatus() -> CLAuthorizationStatus { return self._authorizationStatus } func requestAlwaysAuthorization() { self.requestAlwaysAuthorizationCalled = true } func requestWhenInUseAuthorization() { self.requestWhenInUseAuthorizationCalled = true } // MARK: Configure var pausesLocationUpdatesAutomatically = false var allowsBackgroundLocationUpdates = false var activityType = CLActivityType.fitness var distanceFilter: CLLocationDistance = kCLDistanceFilterNone var desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyBest // MARK: Location Updates var location: CLLocation? static func locationServicesEnabled() -> Bool { return _locationServicesEnabled } func startUpdatingLocation() { startUpdatingLocationCalled = true } func stopUpdatingLocation() { stopUpdatingLocationCalled = true } // MARK: request location func requestLocation() { requestLocationCalled = true } // MARK: Deferred Location Updates class func deferredLocationUpdatesAvailable() -> Bool { return _deferredLocationUpdatesAvailable } func allowDeferredLocationUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval) { allowDeferredLocationUpdatesUntilTraveledCalled = true allowDeferredLocationUpdatesUntilTraveledDistance = distance allowDeferredLocationUpdatesUntilTraveledTimeout = timeout } // MARK: Significant Change in Location class func significantLocationChangeMonitoringAvailable() -> Bool { return _significantLocationChangeMonitoringAvailable } func startMonitoringSignificantLocationChanges() { startMonitoringSignificantLocationChangesCalled = true } func stopMonitoringSignificantLocationChanges() { stopMonitoringSignificantLocationChangesCalled = true } // MARK: Region Monitoring var maximumRegionMonitoringDistance: CLLocationDistance = 1000.0 var monitoredRegions = Set<CLRegion>() func startMonitoring(for region: CLRegion) { startMonitoringForRegionCalled = true startMonitoringForRegionRegion = region } func stopMonitoring(for region: CLRegion) { stopMonitoringForRegionCalled = true stopMonitoringForRegionRegion = region } func requestState(for region: CLRegion) { requestStateForRegionCalled = true requestStateForRegionRegion = region } // MARK: Beacons class func isRangingAvailable() -> Bool { return _isRangingAvailable } var rangedRegions = Set<CLRegion>() func startRangingBeacons(in region: CLBeaconRegion) { startRangingBeaconsInRegionCalled = true startRangingBeaconsInRegionRegion = region } func stopRangingBeacons(in region: CLBeaconRegion) { stopRangingBeaconsInRegionCalled = true stopRangingBeaconsInRegionRegion = region } init() {} } // MARK: - Test Classes - class LocationManagerUT : LocationManager { override func authorizationStatus() -> CLAuthorizationStatus { return CLLocationManagerMock.authorizationStatus() } } class RegionManagerUT : RegionManager { override func authorizationStatus() -> CLAuthorizationStatus { return CLLocationManagerMock.authorizationStatus() } } class BeaconManagerUT : BeaconManager { override func authorizationStatus() -> CLAuthorizationStatus { return CLLocationManagerMock.authorizationStatus() } } // MARK: - CLBeaconMock - class CLBeaconMock : CLBeaconInjectable { let proximityUUID: UUID let major: NSNumber let minor: NSNumber let proximity: CLProximity let accuracy: CLLocationAccuracy let rssi: Int init(proximityUUID: UUID, major: NSNumber, minor: NSNumber, proximity: CLProximity, accuracy: CLLocationAccuracy, rssi: Int) { self.proximityUUID = proximityUUID self.major = major self.minor = minor self.proximity = proximity self.accuracy = accuracy self.rssi = rssi } }
2589bbb14aef2b24f393ef414e2ad707
29.230769
130
0.742494
false
false
false
false
Osnobel/GDGameExtensions
refs/heads/master
GDGameExtensions/GDAds/GDAdBannerIAd.swift
mit
1
// // GDAdBannerIAd.swift // GDAds // // Created by Bell on 16/5/26. // Copyright © 2016年 GoshDo <http://goshdo.sinaapp.com>. All rights reserved. // import iAd // Starting July 1, 2016, iAd will no longer be available for developers to earn revenue by running ads sold by iAd or promote their apps on the iAd App Network. @available(*, deprecated) class GDAdBannerIAd: GDAdBannerBase, ADBannerViewDelegate { var availableCountryCode: [String] = [] private var _statusCode: UInt64 = 0 private var _weight: UInt64 = 0 override init() { super.init() self.bannerView = ADBannerView(adType: .Banner) } override func create(superview: UIView) { if let bannerView = self.bannerView as? ADBannerView { bannerView.delegate = self superview.addSubview(bannerView) bannerView.hidden = true print("[GDAdBannerIAd]#create.") } super.create(superview) } override func destroy() { super.destroy() if let bannerView = self.bannerView as? ADBannerView { bannerView.delegate = nil bannerView.removeFromSuperview() self.visible = false print("[GDAdBannerIAd]#destroy.") } } override var weight: UInt64 { get { let available: UInt64 = self.availableCountryCode.contains(NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String) ? 1 : 0 print("[GDAdBannerIAd]#weight=\(self._weight), status_code=\(self._statusCode), country_code_is_available=\(available).") return self._weight * self._statusCode * available } set { self._weight = newValue } } //MARK: ADBannerViewDelegate methods // 当 requiredContentSizeIdentifiers 成功时发送 func bannerViewDidLoadAd(banner: ADBannerView!) { self._statusCode = 1 self.delegate?.bannerBaseDidReceiveAd?(self) } // 当 requiredContentSizeIdentifiers 失败时发送 func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { self._statusCode = 0 self.delegate?.bannerBase?(self, didFailToReceiveAdWithError: error) } // 在系统响应用户触摸发送者的操作而即将向其展示全屏广告用户界面时发送 func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool { self.delegate?.bannerBaseWillPresentScreen?(self) if willLeave { self.delegate?.bannerBaseWillLeaveApplication?(self) } return true } // 当用户已退出发送者的全屏用户界面时发送 func bannerViewActionDidFinish(banner: ADBannerView!) { self.delegate?.bannerBaseDidDismissScreen?(self) } }
7d176aa3b8c17a14a38bbc2b47e4f9a5
34.644737
161
0.651773
false
false
false
false
calleerlandsson/Tofu
refs/heads/master
Tofu/AlgorithmsViewController.swift
isc
1
import UIKit private let algorithmCellIdentifier = "AlgorithmCell" class AlgorithmsViewController: UITableViewController { var algorithms = [Algorithm]() var selected: Algorithm! var delegate: AlgorithmSelectionDelegate? // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return algorithms.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: algorithmCellIdentifier, for: indexPath) let algorithm = algorithms[indexPath.row] cell.textLabel?.text = algorithm.name cell.accessoryType = selected == algorithm ? .checkmark : .none return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let previouslySelectedCell = tableView.cellForRow( at: IndexPath(row: algorithms.firstIndex(of: selected)!, section: 0))! previouslySelectedCell.accessoryType = .none let selectedCell = tableView.cellForRow(at: indexPath)! selectedCell.accessoryType = .checkmark selected = algorithms[indexPath.row] delegate?.selectAlgorithm(selected) } }
98c9b3f5ef8d736d4313846d3745115d
37.309524
98
0.666252
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/Service/ServiceError.swift
mit
1
// // ServiceError.swift // 12306ForMac // // Created by fancymax on 16/3/9. // Copyright © 2016年 fancy. All rights reserved. // import Foundation func translate(_ error:NSError)->String{ logger.error(error) if error.domain == "NSURLErrorDomain"{ if error.code == -1009 { return "网络连接失败,请检查连接或稍后再试" } } if let err = error.localizedFailureReason{ return err } else{ return error.localizedDescription } } struct ServiceError { static let Domain = "com.12306Service.error" enum Code: Int { case loginFailed = -7000 case queryTicketFailed = -7001 case getRandCodeFailed = -7003 case checkRandCodeFailed = -7004 case checkUserFailed = -7005 case submitOrderFailed = -7006 case checkOrderInfoFailed = -7007 case confirmSingleForQueueFailed = -7008 case cancelOrderFailed = -7009 case zeroOrderFailed = -7010 case queryTicketNoFailed = -7011 case queryTicketPriceFailed = -7012 case getPassengerFailed = -7013 case loginUserFailed = -7014 case autoSumbitOrderFailed = -7015 case queryOrderWaitTimeFailed = -7016 case getQueueCountFailed = -7017 } static let errorDic = [ Code.loginFailed:"登录失败", Code.queryTicketFailed:"未能查到任何车次,请检查查询设置", Code.autoSumbitOrderFailed: "自动提交订单失败", Code.getRandCodeFailed: "获取验证码失败", Code.checkRandCodeFailed: "验证码错误", Code.checkUserFailed: "非登录状态,需要重新登录", Code.submitOrderFailed: "提交订单失败", Code.checkOrderInfoFailed: "订单信息错误", Code.confirmSingleForQueueFailed: "锁定订单失败", Code.getQueueCountFailed: "获取排队信息失败", Code.queryOrderWaitTimeFailed: "查询订单剩余时间失败", Code.cancelOrderFailed: "取消订单失败", Code.zeroOrderFailed:"您没有历史订单", Code.queryTicketNoFailed:"查询车次详细信息失败", Code.getPassengerFailed:"查询乘客信息失败", Code.queryTicketPriceFailed:"查询票价失败", Code.loginUserFailed:"登录用户失败"] static func errorWithCode(_ code:Code)->NSError{ if errorDic.keys.contains(code) { return errorWithCode(code, failureReason: errorDic[code]!) } else { return errorWithCode(code, failureReason: "未知错误, 错误码 = \(code.rawValue)") } } static func errorWithCode(_ code: Code, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code.rawValue, userInfo: userInfo) } static func isCheckRandCodeError(_ error:NSError)->Bool { if error.code == Code.checkRandCodeFailed.rawValue { return true } else { return false } } }
89e091de645b18b20eba4c368daa41b3
30.315217
85
0.620965
false
false
false
false
carabina/Butterfly
refs/heads/master
Butterfly/ButterflyTextView.swift
mit
2
// // ButterflyTextView.swift // Butterfly // // Created by Zhijie Huang on 15/6/20. // // Copyright (c) 2015 Zhijie Huang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit private let textViewCornerRadius: CGFloat = 10 private let textViewWidthMargin: CGFloat = 10 private let textViewHeight = UIScreen.mainScreen().bounds.size.height / 5 internal class ButterflyTextView : UITextView, UITextViewDelegate { var isShowing: Bool! init() { let frame = CGRect( x: textViewWidthMargin, y: -textViewHeight, width: UIScreen.mainScreen().bounds.size.width - 2*textViewWidthMargin, height: textViewHeight) super.init(frame: frame, textContainer: nil) layer.cornerRadius = textViewCornerRadius clipsToBounds = true isShowing = false } required init(coder aDecode : NSCoder) { fatalError("init(coder:) has not been implemented\n") } func show() { if isShowing == false { isShowing = true UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in self.frame = CGRect( x: self.frame.origin.x, y: -self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) }) { (Bool) -> Void in self.becomeFirstResponder() } } } func hide() { if isShowing == true { isShowing = false UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in self.frame = CGRect( x: self.frame.origin.x, y: -self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) }) { (Bool) -> Void in self.resignFirstResponder() } } } }
f74433d3cff1c21fa45214bc831d7287
36.608696
83
0.594509
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/master
Steps4Impact/Settings/Cells/SettingsTitleCell.swift
bsd-3-clause
1
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit struct SettingsTitleCellContext: CellContext { let identifier: String = SettingsTitleCell.identifier let title: String? } class SettingsTitleCell: ConfigurableTableViewCell { static let identifier = "SettingsTitleCell" private let titleLabel = UILabel(typography: .title) override func commonInit() { super.commonInit() contentView.addSubview(titleLabel) { $0.top.equalToSuperview().inset(Style.Padding.p48) $0.leading.trailing.bottom.equalToSuperview().inset(Style.Padding.p32) } } func configure(context: CellContext) { guard let context = context as? SettingsTitleCellContext else { return } titleLabel.text = context.title } }
7ab44969734ab1bbdf44c1ea1987c681
37.910714
79
0.755392
false
false
false
false
Guicai-Li/iOS_Tutorial
refs/heads/master
DynamicsDemo/DynamicsDemo/ViewController.swift
apache-2.0
1
// // ViewController.swift // DynamicsDemo // // Created by 力贵才 on 15/11/30. // Copyright © 2015年 Guicai.Li. All rights reserved. // import UIKit class ViewController: UIViewController, UICollisionBehaviorDelegate { /* UIDynamicAnimator是UIkit的物理引擎。它根据物体指定的物理效果而产生运动轨迹,比如重力等效果。 */ var animator: UIDynamicAnimator! // 动力动画 var gravity: UIGravityBehavior! // 重力 var collision: UICollisionBehavior! // 碰撞 通过UICollisionBehavior指定一个边界 var snap : UISnapBehavior! var square : UIView! var firstContact = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. square = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) square.backgroundColor = UIColor.grayColor() view.addSubview(square) animator = UIDynamicAnimator(referenceView: view) gravity = UIGravityBehavior(items: [square]) animator.addBehavior(gravity) /* 重力效果公式:distance = 0.5 * g * time2; (g = 9.8m/s^2) */ collision = UICollisionBehavior(items: [square]) collision.collisionDelegate = self collision.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(collision) let barrier = UIView(frame: CGRect(x: 0, y: 300, width: 130, height: 20)) barrier.backgroundColor = UIColor.redColor() view.addSubview(barrier) // 思考?从目前看到的效果来说,并没有产生任何物理碰撞,那如何才能产生碰撞效果? // 重点:Dynamic-Behavior 必须产生关联才能产生物理效果 collision = UICollisionBehavior(items: [square, barrier]) animator.addBehavior(collision) collision.addBoundaryWithIdentifier("barrier", forPath: UIBezierPath(rect: barrier.frame)) collision.action = { print("\(NSStringFromCGAffineTransform(self.square.transform)) \(NSStringFromCGPoint(self.square.center))") } let itemBehaviour = UIDynamicItemBehavior(items: [square]) itemBehaviour.elasticity = 0.6 itemBehaviour.density = 30 animator.addBehavior(itemBehaviour) /* 介绍几个属性: elasticity:弹性系数 // Usually between 0 (inelastic) and 1 (collide elastically) friction:摩擦系数 0 being no friction between objects slide along each other density:质量 1 by default resistance:阻力系数 0: no velocity damping angularResistance:旋转系数 0: no angular velocity damping allowsRotation:是否能旋转 */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UICollisionBehaviorDelegate func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) { print("behavior: \(behavior) item:\(item) identifier:\(identifier) point:\(p)") let collidingView = item as! UIView collidingView.backgroundColor = UIColor.yellowColor() UIView.animateWithDuration(0.3) { collidingView.backgroundColor = UIColor.grayColor() } } func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint p: CGPoint) { print("behavior: \(behavior) item1:\(item1) item2:\(item2) point:\(p)") } func collisionBehavior(behavior: UICollisionBehavior, endedContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?) { print("behavior: \(behavior) item:\(item) identifier:\(identifier)") } func collisionBehavior(behavior: UICollisionBehavior, endedContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem) { print("behavior: \(behavior) item1:\(item1) item2:\(item2)") } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (snap != nil) { animator.removeBehavior(snap) } let touch = touches.first snap = UISnapBehavior(item: square, snapToPoint: touch!.locationInView(view)) animator.addBehavior(snap) } }
ba8f12caef45cdc86027a94f15ddcc9b
35.864407
167
0.653103
false
false
false
false
jeremyabannister/JABSwiftCore
refs/heads/master
JABSwiftCore/Size.swift
mit
1
// // Size.swift // JABSwiftCore // // Created by Jeremy Bannister on 5/23/18. // Copyright © 2018 Jeremy Bannister. All rights reserved. // public struct Size { public var width: Double public var height: Double public init (width: Double, height: Double) { self.width = width self.height = height } } // MARK: - Init public extension Size { public init (_ width: Double, _ height: Double) { self.init(width: width, height: height) } } // MARK: - Static Members public extension Size { public static let zero = Size(0, 0) } // MARK: - Hashable extension Size: Hashable { public static func == (lhs: Size, rhs: Size) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } public var hashValue: Int { return width.hashValue ^ height.hashValue } }
92cd1e83fcd481a785f7dfed86239ef8
21.914286
116
0.662095
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
Example/Example/OMShadingGradientLayer/Classes/Categories/CGAffineTransform+Extensions.swift
apache-2.0
6
// // CGAffineTransform+Extensions.swift // ExampleSwift // // Created by Jorge Ouahbi on 8/10/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // import UIKit public extension CGAffineTransform { static func randomRotate() -> CGAffineTransform { return CGAffineTransform(rotationAngle: CGFloat((drand48() * 360.0).degreesToRadians())) } static func randomScale(scaleXMax:CGFloat = 16,scaleYMax:CGFloat = 16) -> CGAffineTransform { let scaleX = (CGFloat(drand48()) * scaleXMax) + 1.0 let scaleY = (CGFloat(drand48()) * scaleYMax) + 1.0 let flip:CGFloat = drand48() < 0.5 ? -1 : 1 return CGAffineTransform(scaleX: scaleX, y:scaleY * flip) } }
6c19a435ed48c64969b0134efbbb8377
32.136364
97
0.654321
false
false
false
false
loudnate/Loop
refs/heads/master
WatchApp Extension/Controllers/HUDRowController.swift
apache-2.0
1
// // HUDRowController.swift // WatchApp Extension // // Copyright © 2019 LoopKit Authors. All rights reserved. // import HealthKit import LoopCore import LoopKit import WatchKit class HUDRowController: NSObject, IdentifiableClass { @IBOutlet private var textLabel: WKInterfaceLabel! @IBOutlet private var detailTextLabel: WKInterfaceLabel! @IBOutlet private var outerGroup: WKInterfaceGroup! @IBOutlet private var bottomSeparator: WKInterfaceSeparator! } extension HUDRowController { func setTitle(_ title: String) { textLabel.setText(title.localizedUppercase) } func setDetail(_ detail: String?) { detailTextLabel.setText(detail ?? "—") } func setContentInset(_ inset: NSDirectionalEdgeInsets) { outerGroup.setContentInset(inset.deviceInsets) } func setIsLastRow(_ isLastRow: Bool) { bottomSeparator.setHidden(isLastRow) } } extension HUDRowController { func setActiveInsulin(_ activeInsulin: HKQuantity?) { guard let activeInsulin = activeInsulin else { setDetail(nil) return } let insulinFormatter: QuantityFormatter = { let insulinFormatter = QuantityFormatter() insulinFormatter.numberFormatter.minimumFractionDigits = 1 insulinFormatter.numberFormatter.maximumFractionDigits = 1 return insulinFormatter }() setDetail(insulinFormatter.string(from: activeInsulin, for: .internationalUnit())) } func setActiveCarbohydrates(_ activeCarbohydrates: HKQuantity?) { guard let activeCarbohydrates = activeCarbohydrates else { setDetail(nil) return } let carbFormatter = QuantityFormatter() carbFormatter.numberFormatter.maximumFractionDigits = 0 setDetail(carbFormatter.string(from: activeCarbohydrates, for: .gram())) } func setNetTempBasalDose(_ tempBasal: Double?) { guard let tempBasal = tempBasal else { setDetail(nil) return } let basalFormatter = NumberFormatter() basalFormatter.numberStyle = .decimal basalFormatter.minimumFractionDigits = 1 basalFormatter.maximumFractionDigits = 3 basalFormatter.positivePrefix = basalFormatter.plusSign let unit = NSLocalizedString( "U/hr", comment: "The short unit display string for international units of insulin delivery per hour" ) setDetail(basalFormatter.string(from: tempBasal, unit: unit)) } func setReservoirVolume(_ reservoirVolume: HKQuantity?) { guard let reservoirVolume = reservoirVolume else { setDetail(nil) return } let insulinFormatter: QuantityFormatter = { let insulinFormatter = QuantityFormatter() insulinFormatter.unitStyle = .long insulinFormatter.numberFormatter.minimumFractionDigits = 0 insulinFormatter.numberFormatter.maximumFractionDigits = 0 return insulinFormatter }() setDetail(insulinFormatter.string(from: reservoirVolume, for: .internationalUnit())) } } fileprivate extension NSDirectionalEdgeInsets { var deviceInsets: UIEdgeInsets { let left: CGFloat let right: CGFloat switch WKInterfaceDevice.current().layoutDirection { case .rightToLeft: right = leading left = trailing case .leftToRight: fallthrough @unknown default: left = leading right = trailing } return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } }
5ae22911000be67a2acf4cd872de5cce
28.484127
105
0.660296
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/master
08--Validation/JackPot Deluxe/LotteryNumber/Ticket.swift
cc0-1.0
1
// // TicketModel.swift // LotteryNumber // // Created by Pedro Trujillo on 10/14/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import Foundation class Ticket { var ArrayNumbers = Array<Int>() var winningStatus: Bool! var dollarAmount:Int! init(arrayNumbers:Array<Int>, winningStatus:Bool, dollarAmount:Int ) { self.ArrayNumbers = arrayNumbers self.winningStatus = winningStatus self.dollarAmount = dollarAmount } func getStringTicketNumbers() ->String { var stringNumber:String = "" for num in self.ArrayNumbers { stringNumber += "\(num) " } return stringNumber } }
342a8b694a25810a7a0c875def261c31
18.810811
72
0.603001
false
false
false
false
Kalito98/Find-me-a-band
refs/heads/master
Find me a band/Find me a band/AppDelegate.swift
mit
1
// // AppDelegate.swift // Find me a band // // Created by Kaloyan Yanev on 3/23/17. // Copyright © 2017 Kaloyan Yanev. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, HttpRequesterDelegate { var window: UIWindow? var tabBarController: UIViewController? var baseUrl: String = "https://find-me-a-band.herokuapp.com" var http: HttpRequester? var sessionManager: SessionManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.http = HttpRequester() self.sessionManager = SessionManager() sessionManager?.removeSession() if (sessionManager?.isLogged())! { tabBarAuthorized() } else { tabBarUnauthorized() } return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } func tabBarAuthorized() { let storyboardName: String = "Main" let storyboard = UIStoryboard(name: storyboardName, bundle: nil) tabBarController = storyboard.instantiateViewController(withIdentifier: "navigationControllerAuth") window?.rootViewController = tabBarController } func tabBarUnauthorized() { let storyboardName: String = "Main" let storyboard = UIStoryboard(name: storyboardName, bundle: nil) tabBarController = storyboard.instantiateViewController(withIdentifier: "navigationControllerUnauth") window?.rootViewController = tabBarController } }
ff58fc073a722d9bba04fbdd83dfe421
27.217391
144
0.69132
false
false
false
false
dmrschmidt/QRCode
refs/heads/main
QRCode/QRCodeImageGenerator.swift
mit
1
import Foundation import UIKit protocol QRCodeImageGenerator { func image(for code: QRCode) throws -> UIImage } struct DefaultQRCodeImageGenerator: QRCodeImageGenerator { func image(for code: QRCode) throws -> UIImage { let ciImage = try qrCodeScaledCiImage(for: code) // for proper scaling, e.g. in UIImageViews, we need a CGImage as the base let context = CIContext(options: nil) let cgImage = context.createCGImage(ciImage, from: ciImage.extent)! return UIImage(cgImage: cgImage, scale: code.scale, orientation: .up) } private func qrCodeScaledCiImage(for code: QRCode) throws -> CIImage { let ciImage = try qrCodeColoredCiImage(for: code) guard desiredSizeIsSufficient(for: code, with: ciImage) else { throw QRCode.GenerationError.desiredSizeTooSmall(desired: code.size!, actual: ciImage.extent.size) } let resizeFactorX = (code.size == nil) ? 1 : code.size!.width / ciImage.extent.size.width let resizeFactorY = (code.size == nil) ? 1 : code.size!.height / ciImage.extent.size.height let scaleX: CGFloat = code.scale * resizeFactorX let scaleY: CGFloat = code.scale * resizeFactorY return ciImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY)) } private func qrCodeColoredCiImage(for code: QRCode) throws -> CIImage { let qrCodeImage = try qrCodeBaseImage(for: code) let colorFilter = CIFilter(name: "CIFalseColor")! colorFilter.setDefaults() colorFilter.setValue(qrCodeImage, forKey: "inputImage") colorFilter.setValue(CIColor(cgColor: code.color.cgColor), forKey: "inputColor0") colorFilter.setValue(CIColor(cgColor: code.backgroundColor.cgColor), forKey: "inputColor1") return colorFilter.outputImage! } private func qrCodeBaseImage(for code: QRCode) throws -> CIImage { let qrCodeFilter = CIFilter(name: "CIQRCodeGenerator")! qrCodeFilter.setDefaults() qrCodeFilter.setValue(code.data, forKey: "inputMessage") qrCodeFilter.setValue(code.inputCorrection.rawValue, forKey: "inputCorrectionLevel") guard let outputImage = qrCodeFilter.outputImage else { throw QRCode.GenerationError.inputDataTooLarge(size: code.data.count) } return outputImage } private func desiredSizeIsSufficient(for code: QRCode, with image: CIImage) -> Bool { guard let desiredSize = code.size else { return true } let hasSufficientWidth = desiredSize.width >= image.extent.size.width let hasSufficientHeight = desiredSize.height >= image.extent.size.height return hasSufficientWidth && hasSufficientHeight } }
ad6e6ebd8aca4dbafac7631dd629a6ad
41.092308
110
0.696272
false
false
false
false
KaiCode2/swift-corelibs-foundation
refs/heads/master
TestFoundation/TestNSPropertyList.swift
apache-2.0
2
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSPropertyList : XCTestCase { static var allTests: [(String, (TestNSPropertyList) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction ), ("test_decode", test_decode ), ] } func test_BasicConstruction() { let dict = NSMutableDictionary(capacity: 0) // dict["foo"] = "bar" var data: NSData? = nil do { data = try NSPropertyListSerialization.dataWithPropertyList(dict, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0) } catch { } XCTAssertNotNil(data) XCTAssertEqual(data!.length, 42, "empty dictionary should be 42 bytes") } func test_decode() { var decoded: Any? var fmt = NSPropertyListFormat.BinaryFormat_v1_0 let path = testBundle().pathForResource("Test", ofType: "plist") let data = NSData(contentsOfFile: path!) do { decoded = try withUnsafeMutablePointer(&fmt) { (format: UnsafeMutablePointer<NSPropertyListFormat>) -> Any in return try NSPropertyListSerialization.propertyListWithData(data!, options: [], format: format) } } catch { } XCTAssertNotNil(decoded) let dict = decoded as! Dictionary<String, Any> XCTAssertEqual(dict.count, 3) let val = dict["Foo"] XCTAssertNotNil(val) if let str = val as? String { XCTAssertEqual(str, "Bar") } else { XCTFail("value stored is not a string") } } }
865c5f961598c2b88de1668a2e108467
30.772727
137
0.62041
false
true
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Main/Metting/View/MettingListTableViewCell.swift
mit
1
// // MettingListTableViewCell.swift // YCOA // // Created by Jerry on 2016/12/16. // Copyright © 2016年 com.baochunsteel. All rights reserved. // import UIKit class MettingListTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var roomLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var participantLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configure(title: String?, time: String?, room: String?, status: String?, participant: String?) { self.titleLabel.text = title self.timeLabel.text = time self.roomLabel.text = room self.participantLabel.text = participant //HTML文本 guard status != nil else {return} let attrStr = try? NSAttributedString(data: status!.data(using: String.Encoding.unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) guard attrStr != nil else {return} self.statusLabel.attributedText = attrStr self.statusLabel.font = UIFont.systemFont(ofSize: 16) } }
93155b4426ed28380ae27467b1291b04
31.930233
191
0.680085
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/RightSide/Ranking/Service/ZSRankService.swift
mit
1
// // ZSRankService.swift // zhuishushenqi // // Created by yung on 2018/8/13. // Copyright © 2018年 QS. All rights reserved. // import Foundation import ZSAPI class ZSRankService { func fetchRanking(_ handler:ZSBaseCallback<[[QSRankModel]]>?){ let api = ZSAPI.ranking("" as AnyObject) zs_get(api.path).responseJSON { (response) in if let data = response.data { if let obj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:Any] { var ranking:[[QSRankModel]] = [] if let male = obj["male"] as? [Any] { if let maleModels = [QSRankModel].deserialize(from: male) as? [QSRankModel] { var males = maleModels let otherRank = self.rankModel(title: "别人家的榜单", image: "ranking_other") males.insert(otherRank, at: self.collapse(maleRank: males)) ranking.append(males) } } if let female = obj["female"] as? [Any] { if let femaleModels = [QSRankModel].deserialize(from: female) as? [QSRankModel] { var females = femaleModels let otherRank = self.rankModel(title: "别人家的榜单", image: "ranking_other") females.insert(otherRank, at: self.collapse(maleRank: females)) ranking.append(females) } } handler?(ranking) } } } } func collapse(maleRank:[QSRankModel]?)->Int{ var collapseIndex = 0 if let models = maleRank { for model in models { if model.collapse == 1 { break } collapseIndex += 1 } } return collapseIndex } fileprivate func rankModel(title:String,image:String)->QSRankModel{ let otherRank = QSRankModel() otherRank.title = title otherRank.image = image return otherRank } }
af9790a3fcb145305213ede3c8902719
35.403226
152
0.499778
false
false
false
false
stevethemaker/WoodpeckerPole-ControlPanel-iOS
refs/heads/master
PoleControlPanel/RobotPeripheralManager.swift
mit
1
// // PeripheralManager.swift // PoleControlPanel // // Created by Steven Knodl on 4/7/17. // Copyright © 2017 Steve Knodl. All rights reserved. // import Foundation import CoreBluetooth enum PeripheralError : Error { case notConnected case badCharacteristicIdentifier case readTimeout case readNoData case writeTimeout } typealias ReadOperationClosure = (Result<Data>) -> () typealias WriteOperationClosure = (Result<Bool>) -> () struct ReadOperation { let identifier: CBUUID let completion: ReadOperationClosure } struct WriteOperation { let identifier: CBUUID let data: Data let confirmWrite: Bool let completion: WriteOperationClosure } let readCommandTimeoutSeconds = 5.0 let writeCommandTimeoutSeconds = 5.0 class RobotPeripheralManager : NSObject { let serviceIdentifier = RobotDevice.ControlService.identifier let serviceCharacteristicIdentifiers = [RobotDevice.ControlService.CharacteristicIdentifiers.robotPosition, RobotDevice.ControlService.CharacteristicIdentifiers.motorControl, RobotDevice.ControlService.CharacteristicIdentifiers.latchPosition, RobotDevice.ControlService.CharacteristicIdentifiers.launcherPosition, RobotDevice.ControlService.CharacteristicIdentifiers.batteryVoltage] let characteristicsToNotify = [CBUUID]() // let characteristicsToNotify = [RobotDevice.ControlService.CharacteristicIdentifiers.robotPosition, // RobotDevice.ControlService.CharacteristicIdentifiers.batteryVoltage] let peripheral: CBPeripheral var services = [CBUUID : CBService]() var characteristics = [CBUUID : CBCharacteristic]() var lastRSSI = (-Double.infinity, Date.distantPast) var readCommandTimer: Timer? = nil var readCommandQueue = Queue<ReadOperation>() var readCurrentCommand: ReadOperation? var writeCommandTimer: Timer? = nil var writeCommandQueue = Queue<WriteOperation>() var writeCurrentCommand: WriteOperation? init(peripheral: CBPeripheral) { self.peripheral = peripheral super.init() peripheral.delegate = self peripheral.discoverServices(nil) } } extension RobotPeripheralManager : CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let discoveredServices = peripheral.services else { return } for service in discoveredServices { print("\(service)") services[service.uuid] = service peripheral.discoverCharacteristics(serviceCharacteristicIdentifiers, for: service) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard let discoveredCharacteristics = service.characteristics else { return } for characteristic in discoveredCharacteristics { print("\(characteristic)") characteristics[characteristic.uuid] = characteristic if characteristicsToNotify.contains(characteristic.uuid) { peripheral.setNotifyValue(true, for: characteristic) } } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { writeCommandTimer?.invalidate() writeCommandTimer = nil if let writeCurrentCommand = writeCurrentCommand { if let error = error { writeCurrentCommand.completion(Result.failure(error)) } else { writeCurrentCommand.completion(Result.success(true)) } } processNextWriteCommand() // Just keep processing } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let readCurrentCommand = readCurrentCommand { readCommandTimer?.invalidate() readCommandTimer = nil if let error = error { readCurrentCommand.completion(Result.failure(error)) } else { if let value = characteristic.value { readCurrentCommand.completion(Result.success(value)) } else { readCurrentCommand.completion(Result.failure(PeripheralError.readNoData)) } } processNextReadCommand() } else { //TODO: Notify data coming in --> Translate into notification } } func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { if let readCurrentCommand = readCurrentCommand { readCommandTimer?.invalidate() readCommandTimer = nil if let error = error { readCurrentCommand.completion(Result.failure(error)) } else { readCurrentCommand.completion(Result.success(NSKeyedArchiver.archivedData(withRootObject: RSSI))) } processNextReadCommand() } else { //TODO: Notify data coming in --> Translate into notification } print("RSSI read: \(RSSI.doubleValue)") lastRSSI = (RSSI.doubleValue, Date()) } //MARK: - Read Command Queue func enqueueReadOperation(_ operation: ReadOperation) { readCommandQueue.enqueue(operation) if readCurrentCommand == nil { processNextReadCommand() } } func processNextReadCommand() { if let nextCommand = readCommandQueue.dequeue() { readCurrentCommand = nextCommand guard peripheral.state == .connected else { nextCommand.completion(Result.failure(PeripheralError.notConnected)) processNextReadCommand() return } guard nextCommand.identifier != RobotDevice.ControlService.rssiIdentifier else { readCommandTimer = Timer.scheduledTimer(timeInterval: readCommandTimeoutSeconds, target: self, selector: #selector(RobotPeripheralManager.readTimeoutOccurred), userInfo: nil, repeats: false) peripheral.readRSSI() return } guard let characteristic = characteristics[nextCommand.identifier] else { nextCommand.completion(Result.failure(PeripheralError.badCharacteristicIdentifier)) processNextReadCommand() return } readCommandTimer = Timer.scheduledTimer(timeInterval: readCommandTimeoutSeconds, target: self, selector: #selector(RobotPeripheralManager.readTimeoutOccurred), userInfo: nil, repeats: false) peripheral.readValue(for: characteristic) } else { readCurrentCommand = nil } } func readTimeoutOccurred() { readCommandTimer?.invalidate() readCommandTimer = nil if let readCurrentCommand = readCurrentCommand { readCurrentCommand.completion(Result.failure(PeripheralError.readTimeout)) } processNextReadCommand() } //MARK: - Write Command Queue func enqueueWriteOperation(_ operation: WriteOperation) { writeCommandQueue.enqueue(operation) if writeCurrentCommand == nil { processNextWriteCommand() } } func processNextWriteCommand() { if let nextCommand = writeCommandQueue.dequeue() { writeCurrentCommand = nextCommand guard peripheral.state == .connected else { nextCommand.completion(Result.failure(PeripheralError.notConnected)) processNextWriteCommand() return } guard let characteristic = characteristics[nextCommand.identifier] else { nextCommand.completion(Result.failure(PeripheralError.badCharacteristicIdentifier)) processNextWriteCommand() return } writeCommandTimer = Timer.scheduledTimer(timeInterval: writeCommandTimeoutSeconds, target: self, selector: #selector(RobotPeripheralManager.writeTimeoutOccurred), userInfo: nil, repeats: false) peripheral.writeValue(nextCommand.data, for: characteristic, type: nextCommand.confirmWrite ? .withResponse : .withoutResponse) if !nextCommand.confirmWrite { processNextWriteCommand() } } else { writeCurrentCommand = nil } } func writeTimeoutOccurred() { writeCommandTimer?.invalidate() writeCommandTimer = nil if let writeCurrentCommand = writeCurrentCommand { writeCurrentCommand.completion(Result.failure(PeripheralError.writeTimeout)) } processNextWriteCommand() } } extension RobotPeripheralManager { func readCharacteristicValue(forIdentifier identifier: CBUUID, completion: @escaping (Result<Data>) -> ()) { guard peripheral.state == .connected else { completion(Result.failure(PeripheralError.notConnected)); return } guard let _ = characteristics[identifier] else { completion(Result.failure(PeripheralError.badCharacteristicIdentifier)); return } enqueueReadOperation(ReadOperation(identifier: identifier, completion: completion)) } func writeCharacteristicValue(data: Data, confirmWrite: Bool, forIdentifier identifier: CBUUID, completion: @escaping (Result<Bool>) -> () ) { guard peripheral.state == .connected else { completion(Result.failure(PeripheralError.notConnected)); return } guard let _ = characteristics[identifier] else { completion(Result.failure(PeripheralError.badCharacteristicIdentifier)); return } enqueueWriteOperation(WriteOperation(identifier: identifier, data: data, confirmWrite: confirmWrite, completion: completion)) } func readRSSIValue(completion: @escaping (Result<Data>) -> ()) { guard peripheral.state == .connected else { completion(Result.failure(PeripheralError.notConnected)); return } enqueueReadOperation(ReadOperation(identifier: RobotDevice.ControlService.rssiIdentifier, completion: completion)) } }
3ad2d63e70225fbb2cd94d2a4c18529d
39.712062
206
0.656313
false
false
false
false
gowansg/firefox-ios
refs/heads/master
Client/Frontend/Browser/TabManager.swift
mpl-2.0
1
/* 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 WebKit protocol TabManagerDelegate: class { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) func tabManager(tabManager: TabManager, didCreateTab tab: Browser) func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int) func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int) } // We can't use a WeakList here because this is a protocol. struct WeakTabManagerDelegate { var value : TabManagerDelegate? init (value: TabManagerDelegate) { self.value = value } func get() -> TabManagerDelegate? { return value } } class TabManager { private var delegates = [WeakTabManagerDelegate]() func addDelegate(delegate: TabManagerDelegate) { assert(NSThread.isMainThread()) delegates.append(WeakTabManagerDelegate(value: delegate)) } func removeDelegate(delegate: TabManagerDelegate) { assert(NSThread.isMainThread()) for var i = 0; i < delegates.count; i++ { var del = delegates[i] if delegate === del.get() { delegates.removeAtIndex(i) return } } } private var tabs: [Browser] = [] private var _selectedIndex = -1 var selectedIndex: Int { return _selectedIndex } private let defaultNewTabRequest: NSURLRequest private var configuration: WKWebViewConfiguration init(defaultNewTabRequest: NSURLRequest) { self.defaultNewTabRequest = defaultNewTabRequest // Create a common webview configuration with a shared process pool. configuration = WKWebViewConfiguration() configuration.processPool = WKProcessPool() } var count: Int { return tabs.count } var selectedTab: Browser? { if !(0..<count ~= _selectedIndex) { return nil } return tabs[_selectedIndex] } func getTab(index: Int) -> Browser { return tabs[index] } func getTab(webView: WKWebView) -> Browser? { for tab in tabs { if tab.webView === webView { return tab } } return nil } func selectTab(tab: Browser?) { assert(NSThread.isMainThread()) if selectedTab === tab { return } let previous = selectedTab _selectedIndex = -1 for i in 0..<count { if tabs[i] === tab { _selectedIndex = i break } } assert(tab === selectedTab, "Expected tab is selected") for delegate in delegates { delegate.get()?.tabManager(self, didSelectedTabChange: tab, previous: previous) } } func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration! = nil) -> Browser { assert(NSThread.isMainThread()) if request == nil { request = defaultNewTabRequest } let tab = Browser(configuration: configuration ?? self.configuration) addTab(tab) tab.loadRequest(request) selectTab(tab) return tab } private func addTab(tab: Browser) { for delegate in delegates { delegate.get()?.tabManager(self, didCreateTab: tab) } tabs.append(tab) for delegate in delegates { delegate.get()?.tabManager(self, didAddTab: tab, atIndex: tabs.count-1) } } func removeTab(tab: Browser) { assert(NSThread.isMainThread()) // If the removed tab was selected, find the new tab to select. if tab === selectedTab { let index = getIndex(tab) if index + 1 < count { selectTab(tabs[index + 1]) } else if index - 1 >= 0 { selectTab(tabs[index - 1]) } else { assert(count == 1, "Removing last tab") selectTab(nil) } } let prevCount = count var index = -1 for i in 0..<count { if tabs[i] === tab { tabs.removeAtIndex(i) index = i break } } assert(count == prevCount - 1, "Tab removed") for delegate in delegates { delegate.get()?.tabManager(self, didRemoveTab: tab, atIndex: index) } } func removeAll() { let tabs = self.tabs for tab in tabs { removeTab(tab) } } func getIndex(tab: Browser) -> Int { for i in 0..<count { if tabs[i] === tab { return i } } assertionFailure("Tab not in tabs list") return -1 } } extension TabManager { func encodeRestorableStateWithCoder(coder: NSCoder) { coder.encodeInteger(count, forKey: "tabCount") coder.encodeInteger(selectedIndex, forKey: "selectedIndex") for i in 0..<count { let tab = tabs[i] coder.encodeObject(tab.url!, forKey: "tab-\(i)-url") } } func decodeRestorableStateWithCoder(coder: NSCoder) { let count: Int = coder.decodeIntegerForKey("tabCount") for i in 0..<count { let url = coder.decodeObjectForKey("tab-\(i)-url") as! NSURL addTab(request: NSURLRequest(URL: url)) } let selectedIndex: Int = coder.decodeIntegerForKey("selectedIndex") self.selectTab(tabs[selectedIndex]) } }
8f1608e4fa7eeee8f2fe9f53be7b7242
27.338235
108
0.574641
false
true
false
false
peaks-cc/iOS11_samplecode
refs/heads/master
chapter_12/HomeKitSample/App/Code/Controller/ServicesViewController.swift
mit
1
// // ServicesViewController.swift // // Created by ToKoRo on 2017-08-21. // import UIKit import HomeKit class ServicesViewController: UITableViewController, ContextHandler { typealias ContextType = ServiceStore @IBInspectable var isSelectMode: Bool = false var store: ServiceStore { return context! } var services: [HMService] { return store.services } var selectedService: HMService? override func viewDidLoad() { super.viewDidLoad() if !isSelectMode && !store.isServiceAddable { navigationItem.rightBarButtonItem = nil } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refresh() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "Service"?: sendContext((selectedService, store), to: segue.destination) case "SelectService"?: let context: ServiceStore = { switch store.serviceStoreKind { case .accessory(let accessory): return accessory.home ?? accessory case .serviceGroup(let serviceGroup): return serviceGroup.home ?? serviceGroup case .home(let home): return home } }() sendContext(context, to: segue.destination) default: break } } func refresh() { DispatchQueue.main.async { self.tableView.reloadData() } } func service(at indexPath: IndexPath) -> HMService? { return services.safe[indexPath.row] } @IBAction func addButtonDidTap(sender: AnyObject) { performSegue(withIdentifier: "SelectService", sender: nil) } @IBAction func cancelButtonDidTap(sender: AnyObject) { dismiss(animated: true) } } // MARK: - UITableViewDataSource extension ServicesViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return services.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Service", for: indexPath) if let service = service(at: indexPath) { cell.textLabel?.text = service.name cell.detailTextLabel?.text = service.localizedDescription } return cell } } // MARK: - UITableViewDelegate extension ServicesViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } self.selectedService = service(at: indexPath) if isSelectMode, let service = selectedService { ResponderChain(from: self).send(service, protocol: ServiceSelector.self) { service, handler in handler.selectService(service) } dismiss(animated: true) } else { performSegue(withIdentifier: "Service", sender: nil) } } } // MARK: - ServiceSelector extension ServicesViewController: ServiceSelector { func selectService(_ service: HMService) { guard case .serviceGroup(let serviceGroup) = store.serviceStoreKind else { return } serviceGroup.addService(service) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } } // MARK: - ServiceActionHandler extension ServicesViewController: ServiceActionHandler { func handleRemove(_ service: HMService) { guard case .serviceGroup(let serviceGroup) = store.serviceStoreKind else { return } serviceGroup.removeService(service) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } }
ff03b4b141001b4ddb7746ad02a6220b
27.767606
109
0.614688
false
false
false
false
jacobwhite/firefox-ios
refs/heads/master
Client/Frontend/AuthenticationManager/PasscodeViews.swift
mpl-2.0
1
/* 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 SnapKit private struct PasscodeUX { static let TitleVerticalSpacing: CGFloat = 32 static let DigitSize: CGFloat = 30 static let TopMargin: CGFloat = 80 static let PasscodeFieldSize: CGSize = CGSize(width: 160, height: 32) } @objc protocol PasscodeInputViewDelegate: class { func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) } /// A custom, keyboard-able view that displays the blank/filled digits when entrering a passcode. class PasscodeInputView: UIView, UIKeyInput { weak var delegate: PasscodeInputViewDelegate? var digitFont: UIFont = UIConstants.PasscodeEntryFont let blankCharacter: Character = "-" let filledCharacter: Character = "•" fileprivate let passcodeSize: Int fileprivate var inputtedCode: String = "" fileprivate var blankDigitString: NSAttributedString { return NSAttributedString(string: "\(blankCharacter)", attributes: [NSAttributedStringKey.font: digitFont]) } fileprivate var filledDigitString: NSAttributedString { return NSAttributedString(string: "\(filledCharacter)", attributes: [NSAttributedStringKey.font: digitFont]) } @objc var keyboardType: UIKeyboardType = .numberPad init(frame: CGRect, passcodeSize: Int) { self.passcodeSize = passcodeSize super.init(frame: frame) isOpaque = false } convenience init(passcodeSize: Int) { self.init(frame: .zero, passcodeSize: passcodeSize) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var canBecomeFirstResponder: Bool { return true } func resetCode() { inputtedCode = "" setNeedsDisplay() } @objc var hasText: Bool { return !inputtedCode.isEmpty } @objc func insertText(_ text: String) { guard inputtedCode.count < passcodeSize else { return } inputtedCode += text setNeedsDisplay() if inputtedCode.count == passcodeSize { delegate?.passcodeInputView(self, didFinishEnteringCode: inputtedCode) } } // Required for implementing UIKeyInput @objc func deleteBackward() { guard !inputtedCode.isEmpty else { return } inputtedCode.remove(at: inputtedCode.index(before: inputtedCode.endIndex)) setNeedsDisplay() } override func draw(_ rect: CGRect) { let circleSize = CGSize(width: 14, height: 14) guard let context = UIGraphicsGetCurrentContext() else { return } context.setLineWidth(1) context.setStrokeColor(UIConstants.PasscodeDotColor.cgColor) context.setFillColor(UIConstants.PasscodeDotColor.cgColor) (0..<passcodeSize).forEach { index in let offset = floor(rect.width / CGFloat(passcodeSize)) var circleRect = CGRect(size: circleSize) circleRect.center = CGPoint(x: (offset * CGFloat(index + 1)) - offset / 2, y: rect.height / 2) if index < inputtedCode.count { context.fillEllipse(in: circleRect) } else { context.strokeEllipse(in: circleRect) } } } } /// A pane that gets displayed inside the PasscodeViewController that displays a title and a passcode input field. class PasscodePane: UIView { let codeInputView: PasscodeInputView var codeViewCenterConstraint: Constraint? var containerCenterConstraint: Constraint? fileprivate lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIConstants.DefaultChromeFont label.isAccessibilityElement = true return label }() fileprivate let centerContainer = UIView() override func accessibilityElementCount() -> Int { return 1 } override func accessibilityElement(at index: Int) -> Any? { switch index { case 0: return titleLabel default: return nil } } init(title: String? = nil, passcodeSize: Int = 4) { codeInputView = PasscodeInputView(passcodeSize: passcodeSize) super.init(frame: .zero) backgroundColor = SettingsUX.TableViewHeaderBackgroundColor titleLabel.text = title centerContainer.addSubview(titleLabel) centerContainer.addSubview(codeInputView) addSubview(centerContainer) centerContainer.snp.makeConstraints { make in make.centerX.equalTo(self) containerCenterConstraint = make.centerY.equalTo(self).constraint } titleLabel.snp.makeConstraints { make in make.centerX.equalTo(centerContainer) make.top.equalTo(centerContainer) make.bottom.equalTo(codeInputView.snp.top).offset(-PasscodeUX.TitleVerticalSpacing) } codeInputView.snp.makeConstraints { make in codeViewCenterConstraint = make.centerX.equalTo(centerContainer).constraint make.bottom.equalTo(centerContainer) make.size.equalTo(PasscodeUX.PasscodeFieldSize) } layoutIfNeeded() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) } func shakePasscode() { UIView.animate(withDuration: 0.1, animations: { self.codeViewCenterConstraint?.update(offset: -10) self.layoutIfNeeded() }, completion: { complete in UIView.animate(withDuration: 0.1, animations: { self.codeViewCenterConstraint?.update(offset: 0) self.layoutIfNeeded() }) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func keyboardWillShow(_ sender: Notification) { guard let keyboardFrame = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else { return } UIView.animate(withDuration: 0.1, animations: { self.containerCenterConstraint?.update(offset: -keyboardFrame.height/2) self.layoutIfNeeded() }) } @objc func keyboardWillHide(_ sender: Notification) { UIView.animate(withDuration: 0.1, animations: { self.containerCenterConstraint?.update(offset: 0) self.layoutIfNeeded() }) } }
39974fac07d4c5895592cf81a3bf6e5d
32.184466
131
0.65828
false
false
false
false
younata/RSSClient
refs/heads/master
TethysKit/Use Cases/ImportUseCase.swift
mit
1
import Muon import Lepton import Result import CBGPromise import FutureHTTP public enum ImportUseCaseItem: Equatable { case none(URL) case webPage(URL, [URL]) case feed(URL, Int) case opml(URL, Int) } public protocol ImportUseCase { func scanForImportable(_ url: URL) -> Future<ImportUseCaseItem> func importItem(_ url: URL) -> Future<Result<Void, TethysError>> } public final class DefaultImportUseCase: ImportUseCase { private let httpClient: HTTPClient private let feedCoordinator: FeedCoordinator private let opmlService: OPMLService private let fileManager: FileManager private let mainQueue: OperationQueue fileprivate enum ImportType { case feed case opml } fileprivate var knownUrls: [URL: ImportType] = [:] public init(httpClient: HTTPClient, feedCoordinator: FeedCoordinator, opmlService: OPMLService, fileManager: FileManager, mainQueue: OperationQueue) { self.httpClient = httpClient self.feedCoordinator = feedCoordinator self.opmlService = opmlService self.fileManager = fileManager self.mainQueue = mainQueue } public func scanForImportable(_ url: URL) -> Future<ImportUseCaseItem> { let promise = Promise<ImportUseCaseItem>() if url.isFileURL { guard !url.absoluteString.contains("default.realm"), let data = try? Data(contentsOf: url) else { promise.resolve(.none(url)) return promise.future } promise.resolve(self.scanDataForItem(data, url: url)) } else { self.httpClient.request(URLRequest(url: url)).map { result in switch result { case .success(let response): self.mainQueue.addOperation { promise.resolve(self.scanDataForItem(response.body, url: url)) } case .failure: self.mainQueue.addOperation { promise.resolve(.none(url)) } } } } return promise.future } public func importItem(_ url: URL) -> Future<Result<Void, TethysError>> { let promise = Promise<Result<Void, TethysError>>() guard let importType = self.knownUrls[url] else { promise.resolve(.failure(.unknown)) return promise.future } switch importType { case .feed: let url = self.canonicalURLForFeedAtURL(url) self.feedCoordinator.subscribe(to: url).then { result in self.mainQueue.addOperation { promise.resolve(result.map { _ in Void() }) } } case .opml: self.opmlService.importOPML(url).then { result in self.mainQueue.addOperation { promise.resolve(result.map { _ in Void() }) } } } return promise.future } private func scanDataForItem(_ data: Data, url: URL) -> ImportUseCaseItem { guard let string = String(data: data, encoding: String.Encoding.utf8) else { return .none(url) } if let feedCount = self.isDataAFeed(string) { self.knownUrls[url] = .feed return .feed(url, feedCount) } else if let opmlCount = self.isDataAnOPML(string) { self.knownUrls[url] = .opml return .opml(url, opmlCount) } else { let feedUrls = self.feedsInWebPage(url, webPage: string) feedUrls.forEach { self.knownUrls[$0] = .feed } return .webPage(url, feedUrls) } } private func isDataAFeed(_ data: String) -> Int? { var ret: Int? let feedParser = FeedParser(string: data) _ = feedParser.success { ret = $0.articles.count } feedParser.start() return ret } private func canonicalURLForFeedAtURL(_ url: URL) -> URL { guard url.isFileURL else { return url } let string = (try? String(contentsOf: url)) ?? "" var ret: URL! = nil FeedParser(string: string).success { ret = $0.link }.start() return ret } private func isDataAnOPML(_ data: String) -> Int? { var ret: Int? let opmlParser = Parser(text: data) _ = opmlParser.success { ret = $0.count } opmlParser.start() return ret } private func feedsInWebPage(_ url: URL, webPage: String) -> [URL] { var ret: [URL] = [] let webPageParser = WebPageParser(string: webPage) { ret = $0.map { URL(string: $0.absoluteString, relativeTo: url)?.absoluteURL ?? $0 as URL } } webPageParser.searchType = .feeds webPageParser.start() return ret } }
82e557a3992825d62316e070d0313b7a
32.261745
109
0.569209
false
false
false
false
iceman201/NZAirQuality
refs/heads/master
NZAirQuality/Model/LocationServices.swift
mit
1
// // LocationServices.swift // NZAirQuality // // Created by Liguo Jiao on 21/07/17. // Copyright © 2017 Liguo Jiao. All rights reserved. // import Foundation import CoreLocation class Location: NSObject, CLLocationManagerDelegate { enum Result <T> { case Success(T) case Failure(Error) } static let shared: Location = Location() typealias Callback = (Result<Location>) -> Void var requests: Array <Callback> = Array <Callback>() var location: CLLocation? { return sharedLocationManager.location } lazy var sharedLocationManager: CLLocationManager = { let newLocationmanager = CLLocationManager() newLocationmanager.delegate = self return newLocationmanager }() // MARK: - Authorization class func authorize() { shared.authorize() } func authorize() { sharedLocationManager.requestWhenInUseAuthorization() } // MARK: - Helpers func locate(callback: @escaping Callback) { self.requests.append(callback) sharedLocationManager.startUpdatingLocation() } func reset() { self.requests = Array <Callback>() sharedLocationManager.stopUpdatingLocation() } // MARK: - Delegate func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { for request in self.requests { request(.Failure(error)) } self.reset() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: Array <CLLocation>) { for request in self.requests { request(.Success(self)) } self.reset() } }
4d04e0397ece364497b98991b2b9a543
26.327869
106
0.64967
false
false
false
false
AboutObjectsTraining/swift-ios-2015-07-kop
refs/heads/master
Coolness/Coolness/CoolViewController.swift
mit
1
import UIKit let AccessoryHeight: CGFloat = 66 class CoolViewController: UIViewController { var textField: UITextField! var coolView: UIView! func addCoolView() { println("\(textField.text)") let newCell = CoolViewCell(frame: CGRect.zeroRect) newCell.text = textField.text newCell.sizeToFit() coolView.addSubview(newCell) } override func loadView() { let bounds = UIScreen.mainScreen().bounds let backgroundView = UIView(frame: bounds) view = backgroundView backgroundView.backgroundColor = UIColor.brownColor() let accessoryView = UIView(frame: CGRect( origin: bounds.origin, size: CGSize( width: bounds.width, height: AccessoryHeight))) backgroundView.addSubview(accessoryView) accessoryView.backgroundColor = UIColor(white: 1.0, alpha: 0.5) coolView = UIView(frame: CGRect( x: bounds.origin.x, y: AccessoryHeight, width: bounds.width, height: bounds.height - AccessoryHeight)) backgroundView.addSubview(coolView) coolView.backgroundColor = UIColor(white: 1.0, alpha: 0.7) coolView.clipsToBounds = true // self.coolView = coolView // Controls textField = UITextField(frame: CGRect(x: 8, y: 28, width: 280, height: 30)) accessoryView.addSubview(textField) textField.borderStyle = .RoundedRect textField.placeholder = "Enter some text" textField.delegate = self let button = UIButton.buttonWithType(.System) as! UIButton button.setTitle("Add", forState: .Normal) button.sizeToFit() accessoryView.addSubview(button) button.frame.offset(dx: 300.0, dy: 28.0) button.addTarget(self, action: Selector("addCoolView"), forControlEvents: .TouchUpInside) // Cool View Cells let cell1 = CoolViewCell(frame: CGRect(x: 20, y: 40, width: 80, height: 30)) coolView.addSubview(cell1) cell1.backgroundColor = UIColor.purpleColor() let cell2 = CoolViewCell(frame: CGRect(x: 60, y: 100, width: 80, height: 30)) coolView.addSubview(cell2) cell2.backgroundColor = UIColor.orangeColor() cell1.text = "The race is to the Swift?" cell2.text = "Hello World!" cell1.sizeToFit() cell2.sizeToFit() } } extension CoolViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
2e70f1be616c7d188720015e1bf0377e
26.892157
97
0.58594
false
false
false
false
swiftsanyue/TestKitchen
refs/heads/master
TestKitchen/TestKitchen/classes/ingredient(食材)/material(食材)/model/IngreMaterial.swift
mit
1
// // IngreMaterial.swift // TestKitchen // // Created by ZL on 16/11/2. // Copyright © 2016年 zl. All rights reserved. // import UIKit import SwiftyJSON class IngreMaterial: NSObject { var code:String? var data:IngreMaterialData? var msg:String? var timestamp:NSNumber? var version:String? class func parseData(data:NSData)-> IngreMaterial{ let json = JSON(data: data) let model = IngreMaterial() model.code = json["code"].string model.data = IngreMaterialData.parse(json["data"]) model.msg = json["msg"].string model.timestamp = json["timestamp"].number model.version = json["version"].string return model } } class IngreMaterialData: NSObject { var data:Array<IngreMaterialType>? var id:NSNumber? var name:String? var text:String? class func parse(json: JSON)-> IngreMaterialData{ let model = IngreMaterialData() var array = Array<IngreMaterialType>() for (_,subJson) in json["data"] { let typeModel = IngreMaterialType.parse(subJson) array.append(typeModel) } model.data = array model.id = json["id"].number model.name = json["name"].string model.text = json["text"].string return model } } class IngreMaterialType : NSObject { var data:Array<IngreMaterialSubtype>? var id:String? var image:String? var text:String? class func parse(json:JSON) -> IngreMaterialType { let model = IngreMaterialType() var array = Array<IngreMaterialSubtype>() for (_,subJson) in json["data"] { let typeModel = IngreMaterialSubtype.parse(subJson) array.append(typeModel) } model.data = array model.id = json["id"].string model.image = json["image"].string model.text = json["text"].string return model } } class IngreMaterialSubtype :NSObject { var id:String? var image:String? var text:String? class func parse(json:JSON) -> IngreMaterialSubtype{ let model = IngreMaterialSubtype() model.id = json["id"].string model.image = json["image"].string model.text = json["text"].string return model } }
63c8b277c6d5847f15e53c42e00a7f87
23.587629
63
0.591195
false
false
false
false
coderCX/PullToBounce
refs/heads/master
PullToBounce/Example/SampleCell.swift
mit
4
// // SampleCell.swift // PullToBounce // // Created by Takuya Okamoto on 2015/08/12. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit class SampleCell: UITableViewCell { let color = UIColor.lightBlue override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) let iconMock = UIView() iconMock.backgroundColor = color iconMock.frame = CGRect(x: 16, y: 16, width: 60, height: 60) iconMock.layer.cornerRadius = 10 self.addSubview(iconMock) let lineLeft:CGFloat = iconMock.frame.right + 16 let lineMargin:CGFloat = 12 let line1 = CGRect(x: lineLeft, y: 12 + lineMargin, width: 100, height: 6) let line2 = CGRect(x: lineLeft, y: line1.bottom + lineMargin, width: 160, height: 5) let line3 = CGRect(x: lineLeft, y: line2.bottom + lineMargin, width: 180, height: 5) addLine(line1) addLine(line2) addLine(line3) let sepalator = UIView() sepalator.frame = CGRect(x: 0, y: 92 - 1, width: frame.width, height: 1) sepalator.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2) self.addSubview(sepalator) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func addLine(frame:CGRect) { let line = UIView(frame:frame) line.layer.cornerRadius = frame.height / 2 line.backgroundColor = color self.addSubview(line) } }
c0af06a115135783aa6f94f3a7d32769
22.602941
92
0.62243
false
false
false
false
Minitour/WWDC-Collaborators
refs/heads/master
Macintosh.playground/Sources/Interface/OSWindow.swift
mit
1
import Foundation import UIKit public class OSWindow: UIView{ var applicationIdentifiers: [String : OSApplicationWindow] = [:] //Other apps var activeApplications: [MacApp]! var desktopApplications: [DesktopApplication]! //The finder app lazy var rootApplication: MacApp = { [weak self] in let finder = Finder() finder.window = self return finder }() var toolBar: OSToolBar?{ get{ for view in subviews{ if view is OSToolBar{ return view as? OSToolBar } } return nil } } convenience public init(withRes res: CGSize) { let rect = CGRect(origin: CGPoint(x: 0, y:0), size: res) self.init(frame: rect) } override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("Sorry m8 there is no coder here") } func setup(){ activeApplications = [MacApp]() desktopApplications = [DesktopApplication]() } /// The applications that appear when clicking the  menu. lazy var osMenus: [MenuAction] = { var menus = [MenuAction]() menus.append(MenuAction(title: "About the Finder...", action: { let newApplicationWindow = self.createApplication(from: self.rootApplication) self.loadApplication(newApplicationWindow) }, subMenus: nil)) menus.append(MenuAction(type: .seperator)) menus.append(MenuAction(title: "Alarm Clock", action: { let applicationWindow = self.createApplication(from: AlarmClock()) self.loadApplication(applicationWindow) }, subMenus: nil)) menus.append(MenuAction(title: "Calculator", action: { let applicationWindow = self.createApplication(from: Calculator()) self.loadApplication(applicationWindow) }, subMenus: nil)) menus.append(MenuAction(title: "Control Panel", enabled: false)) menus.append(MenuAction(title: "Key Caps", action: { let applicationWindow = self.createApplication(from: KeyCaps()) self.loadApplication(applicationWindow) }, subMenus: nil)) menus.append(MenuAction(title: "Note Pad", action: { let applicationWindow = self.createApplication(from: NotePad()) self.loadApplication(applicationWindow) }, subMenus: nil)) menus.append(MenuAction(title: "Puzzle", action: { let applicationWindow = self.createApplication(from: Puzzle()) self.loadApplication(applicationWindow) }, subMenus: nil)) menus.append(MenuAction(title: "Scrapbook", enabled: false)) return menus }() /// A helper function that creates an instance of OSApplicationWindow using an instance of a MacApp. Note however that if the app exists in memory then it will return it. func createApplication(from app: MacApp)->OSApplicationWindow{ let applicationWindow = OSApplicationWindow() applicationWindow.backgroundColor = .white applicationWindow.delegate = self applicationWindow.dataSource = app let nApp: OSApplicationWindow = applicationIdentifiers[(applicationWindow.dataSource?.identifier ?? (applicationWindow.dataSource?.uniqueIdentifier ?? ""))] ?? applicationWindow return nApp } /// Checks if application `MacApp` exists in memory. /// /// - Parameter app: The app that contains an identifier which we want to check. /// - Returns: true if the app exists, else false. func doesApplicationExistInMemory(app: MacApp)->Bool{ if let _ = applicationIdentifiers[(app.identifier ?? (app.uniqueIdentifier ))]{ return true }else{ return false } } /// Load an OSApplicationWindow /// /// - Parameter app: The OSApplicationWindow which we want to load into the OSWindow. open func loadApplication(_ app: OSApplicationWindow){ loadApplication(app, under: toolBar!) } /// Load an OSApplicationWindow under a certain toolbar. /// /// - Parameters: /// - app: The OSApplicationWindow which we want to load into the OSWindow. /// - toolbar: The toolbar which we are loading the application under. open func loadApplication(_ app: OSApplicationWindow,under toolbar: OSToolBar){ let nApp: OSApplicationWindow = applicationIdentifiers[(app.dataSource?.identifier ?? (app.dataSource?.uniqueIdentifier ?? ""))] ?? app nApp.dataSource?.willLaunchApplication(in: self, withApplicationWindow: app) if let identifier: String = app.dataSource?.identifier{ //check if unique id exists already if let applicationWindow = self.applicationIdentifiers[identifier]{ //check if window is already subview if applicationWindow.isDescendant(of: self){ //bring to front bringAppToFront(applicationWindow) return }else{ //add subview toolbar.requestCloseAllMenus() addAppAsSubView(applicationWindow) } }else{ //add application to UI and IDs applicationIdentifiers[identifier] = app toolbar.requestCloseAllMenus() addAppAsSubView(app) } }else{ //add application to ui without adding unique id toolbar.requestCloseAllMenus() addAppAsSubView(app) } nApp.dataSource?.didLaunchApplication(in: self, withApplicationWindow: nApp) } func addAppAsSubView(_ application: OSApplicationWindow){ insertSubview(application, belowSubview: toolBar!) activeApplications.append(application.dataSource!) if application.frame.origin == CGPoint.zero { application.center = center } application.layoutIfNeeded() } func bringAppToFront(_ application: OSApplicationWindow){ let id: String = application.dataSource!.uniqueIdentifier var i = 0 for app in activeApplications{ if app.uniqueIdentifier == id { activeApplications.append(activeApplications.remove(at: i)) break } i += 1 } bringSubview(toFront: application) bringSubview(toFront: toolBar!) } /// The `close` function is a function that is used to terminate a certain application. /// /// - Parameter app: The app which we want to terminate. open func close(app: MacApp){ if let nApp: OSApplicationWindow = applicationIdentifiers[(app.identifier ?? (app.uniqueIdentifier))]{ nApp.close() }else{ } } /// The `add` function allows us to load desktop applications. The placement of the applications will be set automatically based on already existing applications on the desktop. /// /// - Parameter app: The application which we want to display on the desktop. open func add(desktopApp app: DesktopApplication){ let space: CGFloat = 5 let initalHeight: CGFloat = OSToolBar.height + space let initalWidth: CGFloat = SystemSettings.resolution.width - MacAppDesktopView.width - space * 2 var heightCounter: CGFloat = initalHeight var widthCounter: CGFloat = initalWidth for i in 0..<desktopApplications.count{ let app = desktopApplications[i] let height = app.view.frame.height + space * 2 if heightCounter + height > SystemSettings.resolution.height{ //reset height to initial value heightCounter = initalHeight //move left widthCounter -= MacAppDesktopView.width }else{ heightCounter += height } } app.view.frame.origin = CGPoint(x: widthCounter, y: heightCounter) insertSubview(app.view, at: 0) desktopApplications.append(app) } } // MARK: - OSToolBarDataSource extension OSWindow: OSToolBarDataSource{ public func osMenuActions(_ toolBar: OSToolBar) -> [MenuAction] { return self.osMenus } public func menuActions(_ toolBar: OSToolBar) -> [MenuAction] { let topApp: MacApp = /*activeApplications.count > 1 ? activeApplications[activeApplications.count - 1] :*/ rootApplication return topApp.menuActions! } } // MARK: - OSApplicationWindowDelegate extension OSWindow: OSApplicationWindowDelegate{ public func applicationWindow(_ applicationWindow: OSApplicationWindow, didTapWindowPanel panel: WindowPanel, atPoint point: CGPoint) { self.toolBar?.requestCloseAllMenus() bringAppToFront(applicationWindow) } public func applicationWindow(_ application: OSApplicationWindow, canMoveToPoint point: inout CGPoint) -> Bool { let halfHeight = application.bounds.midY let osHeight = self.bounds.height if point.y < OSToolBar.height + halfHeight { point.y = OSToolBar.height + halfHeight return true } else if point.y > osHeight + halfHeight - OSToolBar.height{ point.y = osHeight + halfHeight - OSToolBar.height return true } return true } public func applicationWindow(_ applicationWindow: OSApplicationWindow, willStartDraggingContainer container: UIView){ self.toolBar?.requestCloseAllMenus() bringAppToFront(applicationWindow) } public func applicationWindow(_ applicationWindow: OSApplicationWindow, didFinishDraggingContainer container: UIView){ } public func applicationWindow(_ application: OSApplicationWindow, didCloseWindowWithPanel panel: WindowPanel){ var i = 0 for app in activeApplications{ if app.uniqueIdentifier == application.dataSource?.uniqueIdentifier{ activeApplications.remove(at: i) break } i += 1 } if !(application.dataSource?.keepInMemory ?? true){ application.dataSource?.willTerminateApplication() if let identifier: String = application.dataSource?.identifier{ self.applicationIdentifiers[identifier] = nil }else if let uniqueId: String = application.dataSource?.uniqueIdentifier{ self.applicationIdentifiers[uniqueId] = nil } } //check origin and animate it if let origin = application.windowOrigin?.center{ //create a frame/border window with the same size of the application view let transitionWindowFrame = MovingWindow() transitionWindowFrame.backgroundColor = .clear transitionWindowFrame.borderColor = .lightGray transitionWindowFrame.frame = application.frame //add the frame to the os window addSubview(transitionWindowFrame) //animate it with affine scale transformation and by changing it's center to the origin UIView.animate(withDuration: 0.2, animations: { transitionWindowFrame.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) transitionWindowFrame.center = origin }, //uppon animation end, remove the frame from super view completion: { (completion) in transitionWindowFrame.removeFromSuperview() }) } } } // MARK: - DesktopAppDelegate extension OSWindow: DesktopAppDelegate{ public func didFinishDragging(_ application: DesktopApplication) { } public func willStartDragging(_ application: DesktopApplication) { self.toolBar?.requestCloseAllMenus() } public func didDoubleClick(_ application: DesktopApplication) { toolBar?.requestCloseAllMenus() let applicationWindow = self.createApplication(from: application.app!) if applicationWindow.isDescendant(of: self){ //bring it to front bringAppToFront(applicationWindow) return } applicationWindow.windowOrigin = application.view //create border window let transitionWindowFrame = MovingWindow() transitionWindowFrame.backgroundColor = .clear transitionWindowFrame.borderColor = .lightGray let doesExist = doesApplicationExistInMemory(app: application.app!) if doesExist{ transitionWindowFrame.frame = applicationWindow.frame }else{ transitionWindowFrame.frame = CGRect(x: 0, y: 0, width: application.app!.sizeForWindow().width, height: application.app!.sizeForWindow().height + 20) } //set it's center to match application.center transitionWindowFrame.center = application.view.center //add affine scale transformation of 0.1 transitionWindowFrame.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) addSubview(transitionWindowFrame) //animate it to origin of the application with UIView.animate(withDuration: 0.2, animations: { if doesExist{ transitionWindowFrame.center = applicationWindow.center }else{ transitionWindowFrame.center = self.center } transitionWindowFrame.transform = .identity }) { (completion) in transitionWindowFrame.removeFromSuperview() self.loadApplication(applicationWindow) } } }
86d2865319c7fb693eb0f75657d08153
35.315
181
0.603401
false
false
false
false
jpedrosa/sua_nc
refs/heads/master
Sources/_Sua/sys.swift
apache-2.0
2
import CSua import Glibc public enum FileOperation: Int { case R // Read case W // Write case A // Append } public enum PopenOperation: String { case R = "r" // Read case W = "w" // Write case RE = "re" // ReadWithCloexec case WE = "we" // WriteWithCloexec } public class Signal { // The callback closure must be created directly from a function on the // outer scope so that it does not capture context. As required by Swift for // callbacks to C functions. public static var trap = Glibc.signal public static let INT = SIGINT public static let TERM = SIGTERM public static let ABRT = SIGABRT public static let KILL = SIGKILL public static let HUP = SIGHUP public static let ALRM = SIGALRM public static let CHLD = SIGCHLD } // This alias allows other files like the FileBrowser to declare this type // without having to import Glibc as well. public typealias CDirentPointer = UnsafeMutablePointer<dirent> public typealias CStat = stat public typealias CTimespec = timespec public typealias CTime = tm public typealias CFilePointer = UnsafeMutablePointer<FILE> func statStruct() -> CStat { return stat() } public struct PosixSys { public static let DEFAULT_DIR_MODE = S_IRWXU | S_IRWXG | S_IRWXO public static let DEFAULT_FILE_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH public static let USER_RW_FILE_MODE: UInt32 = S_IRUSR | S_IWUSR public static let SEEK_SET: Int32 = 0 public static let SEEK_CUR: Int32 = 1 public static let SEEK_END: Int32 = 2 public static let STDIN_FD: Int32 = 0 public static let STDOUT_FD: Int32 = 1 public static let STDERR_FD: Int32 = 2 public func open(path: String, flags: Int32, mode: UInt32) -> Int32 { return retry { Glibc.open(path, flags, mode) } } public func openFile(filePath: String, operation: FileOperation = .R, mode: UInt32 = DEFAULT_FILE_MODE) -> Int32 { var flags: Int32 = 0 switch operation { case .R: flags = O_RDONLY case .W: flags = O_RDWR | O_CREAT | O_TRUNC case .A: flags = O_RDWR | O_CREAT | O_APPEND } flags |= O_CLOEXEC return open(filePath, flags: flags, mode: mode) } public func doOpenDir(dirPath: String) -> Int32 { return open(dirPath, flags: O_RDONLY | O_DIRECTORY, mode: 0) } public func mkdir(dirPath: String, mode: UInt32 = DEFAULT_DIR_MODE) -> Int32 { return retry { Glibc.mkdir(dirPath, mode) } } public func read(fd: Int32, address: UnsafeMutablePointer<Void>, length: Int) -> Int { return retry { Glibc.read(fd, address, length) } } public func write(fd: Int32, address: UnsafePointer<Void>, length: Int) -> Int { return retry { Glibc.write(fd, address, length) } } public func writeString(fd: Int32, string: String) -> Int { var a = Array(string.utf8) return write(fd, address: &a, length: a.count) } public func writeBytes(fd: Int32, bytes: [UInt8], maxBytes: Int) -> Int { var a = bytes return write(fd, address: &a, length: maxBytes) } public func close(fd: Int32) -> Int32 { return retry { Glibc.close(fd) } } public func fflush(stream: CFilePointer = nil) -> Int32 { return Glibc.fflush(stream) } public func lseek(fd: Int32, offset: Int, whence: Int32) -> Int { return retry { Glibc.lseek(fd, offset, whence) } } public var pid: Int32 { return Glibc.getpid() } public func rename(oldPath: String, newPath: String) -> Int32 { return Glibc.rename(oldPath, newPath) } public func unlink(path: String) -> Int32 { return Glibc.unlink(path) } public var cwd: String? { var a = [CChar](count:256, repeatedValue: 0) let i = Glibc.getcwd(&a, 255) if i != nil { return String.fromCharCodes(a) } return nil } public func stat(path: String, buffer: UnsafeMutablePointer<CStat>) -> Int32 { return Glibc.stat(path, buffer) } public func lstat(path: String, buffer: UnsafeMutablePointer<CStat>) -> Int32 { return Glibc.lstat(path, buffer) } public func statBuffer() -> CStat { return statStruct() } public func readdir(dirp: COpaquePointer) -> CDirentPointer { return dirp != nil ? Glibc.readdir(dirp) : nil } public func opendir(path: String) -> COpaquePointer { return Glibc.opendir(path) } public func opendir(pathBytes: [UInt8]) -> COpaquePointer { return Glibc.opendir(UnsafePointer<CChar>(pathBytes)) } public func closedir(dirp: COpaquePointer) -> Int32 { return retry { Glibc.closedir(dirp) } } public func fgets(buffer: UnsafeMutablePointer<CChar>, length: Int32, fp: CFilePointer) -> UnsafeMutablePointer<CChar> { return Glibc.fgets(buffer, length, fp) } public func fread(buffer: UnsafeMutablePointer<Void>, size: Int, nmemb: Int, fp: CFilePointer) -> Int { return Glibc.fread(buffer, size, nmemb, fp) } public func fclose(fp: CFilePointer) -> Int32 { return Glibc.fclose(fp) } public func popen(command: String, operation: PopenOperation = .R) -> CFilePointer { return Glibc.popen(command, operation.rawValue) } public func pclose(fp: CFilePointer) -> Int32 { return Glibc.pclose(fp) } public func isatty(fd: Int32) -> Bool { return Glibc.isatty(fd) == 1 } public func strlen(sp: UnsafePointer<CChar>) -> UInt { return Glibc.strlen(sp) } public func sleep(n: UInt32) -> UInt32 { return Glibc.sleep(n) } public func nanosleep(seconds: Int, nanoseconds: Int = 0) -> Int32 { var ts: CTimespec = Glibc.timespec(tv_sec: seconds, tv_nsec: nanoseconds) return retry { Glibc.nanosleep(&ts, nil) } } public func time() -> Int { return Glibc.time(nil) } public func timeBuffer() -> CTime { return Glibc.tm() } public func localtime_r(secondsSinceEpoch: Int, buffer: UnsafeMutablePointer<CTime>) { var n = secondsSinceEpoch Glibc.localtime_r(&n, buffer) } public func gmtime_r(secondsSinceEpoch: Int, buffer: UnsafeMutablePointer<CTime>) { var n = secondsSinceEpoch Glibc.gmtime_r(&n, buffer) } public func abs(n: Int32) -> Int32 { return Glibc.abs(n) } public func abs(n: Int) -> Int { return Glibc.labs(n) } public func round(f: Double) -> Int { return Int(Glibc.round(f)) } public func getenv(name: String) -> String? { let vp = Glibc.getenv(name) return vp != nil ? String.fromCString(vp) : nil } public func setenv(name: String, value: String) -> Int32 { return Glibc.setenv(name, value, 1) } public func unsetenv(name: String) -> Int32 { return Glibc.unsetenv(name) } // The environ variable is made available by the CSua sister project // dependency. public var environment: [String: String] { var env = [String: String]() var i = 0 while true { let nm = (environ + i).memory if nm == nil { break } let np = UnsafePointer<CChar>(nm) if let s = String.fromCString(np) { let (name, value) = s.splitOnce("=") env[name!] = value ?? "" } i += 1 } return env } public func getpwnam(name: String) -> UnsafeMutablePointer<passwd> { return Glibc.getpwnam(name) } public func retry(fn: () -> Int32) -> Int32 { var value = fn() while value == -1 { if errno != EINTR { break } value = fn() } return value } public func retry(fn: () -> Int) -> Int { var value = fn() while value == -1 { if errno != EINTR { break } value = fn() } return value } } public let Sys = PosixSys()
13685ba9eaf3b86cc469f50ac54b7047
23.564516
80
0.645174
false
false
false
false
ikemai/ScaledVisibleCellsCollectionView
refs/heads/master
ScaledVisibleCellsCollectionView/ScaledVisibleCellsCollectionView.swift
mit
1
// // ScaledVisibleCellsCollectionView.swift // ScaledVisibleCellsCollectionView // // Created by Mai Ikeda on 2015/08/22. // Copyright (c) 2015年 mai_ikeda. All rights reserved. // import UIKit public enum SC_ScaledPattern { case HorizontalCenter case HorizontalLeft case HorizontalRight case VerticalCenter case VerticalBottom case VerticalTop } public class ScaledVisibleCellsCollectionView { static let sharedInstance = ScaledVisibleCellsCollectionView() var maxScale: CGFloat = 1.0 var minScale: CGFloat = 0.5 var maxAlpha: CGFloat = 1.0 var minAlpha: CGFloat = 0.5 var scaledPattern: SC_ScaledPattern = .VerticalCenter } extension UICollectionView { /** Please always set */ public func setScaledDesginParam(scaledPattern pattern: SC_ScaledPattern, maxScale: CGFloat, minScale: CGFloat, maxAlpha: CGFloat, minAlpha: CGFloat) { ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern = pattern ScaledVisibleCellsCollectionView.sharedInstance.maxScale = maxScale ScaledVisibleCellsCollectionView.sharedInstance.minScale = minScale ScaledVisibleCellsCollectionView.sharedInstance.maxAlpha = maxAlpha ScaledVisibleCellsCollectionView.sharedInstance.minAlpha = minAlpha } /** Please call at any time */ public func scaledVisibleCells() { switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern { case .HorizontalCenter, .HorizontalLeft, .HorizontalRight: scaleCellsForHorizontalScroll(visibleCells()) break case .VerticalCenter, .VerticalTop, .VerticalBottom: self.scaleCellsForVerticalScroll(visibleCells()) break } } } extension UICollectionView { private func scaleCellsForHorizontalScroll(visibleCells: [UICollectionViewCell]) { let scalingAreaWidth = bounds.width / 2 let maximumScalingAreaWidth = (bounds.width / 2 - scalingAreaWidth) / 2 for cell in visibleCells { var distanceFromMainPosition: CGFloat = 0 switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern { case .HorizontalCenter: distanceFromMainPosition = horizontalCenter(cell) break case .HorizontalLeft: distanceFromMainPosition = abs(cell.frame.midX - contentOffset.x - (cell.bounds.width / 2)) break case .HorizontalRight: distanceFromMainPosition = abs(bounds.width / 2 - (cell.frame.midX - contentOffset.x) + (cell.bounds.width / 2)) break default: return } let preferredAry = scaleCells(distanceFromMainPosition, maximumScalingArea: maximumScalingAreaWidth, scalingArea: scalingAreaWidth) let preferredScale = preferredAry[0] let preferredAlpha = preferredAry[1] cell.transform = CGAffineTransformMakeScale(preferredScale, preferredScale) cell.alpha = preferredAlpha } } private func scaleCellsForVerticalScroll(visibleCells: [UICollectionViewCell]) { let scalingAreaHeight = bounds.height / 2 let maximumScalingAreaHeight = (bounds.height / 2 - scalingAreaHeight) / 2 for cell in visibleCells { var distanceFromMainPosition: CGFloat = 0 switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern { case .VerticalCenter: distanceFromMainPosition = verticalCenter(cell) break case .VerticalBottom: distanceFromMainPosition = abs(bounds.height - (cell.frame.midY - contentOffset.y + (cell.bounds.height / 2))) break case .VerticalTop: distanceFromMainPosition = abs(cell.frame.midY - contentOffset.y - (cell.bounds.height / 2)) break default: return } let preferredAry = scaleCells(distanceFromMainPosition, maximumScalingArea: maximumScalingAreaHeight, scalingArea: scalingAreaHeight) let preferredScale = preferredAry[0] let preferredAlpha = preferredAry[1] cell.transform = CGAffineTransformMakeScale(preferredScale, preferredScale) cell.alpha = preferredAlpha } } private func scaleCells(distanceFromMainPosition: CGFloat, maximumScalingArea: CGFloat, scalingArea: CGFloat) -> [CGFloat] { var preferredScale: CGFloat = 0.0 var preferredAlpha: CGFloat = 0.0 let maxScale = ScaledVisibleCellsCollectionView.sharedInstance.maxScale let minScale = ScaledVisibleCellsCollectionView.sharedInstance.minScale let maxAlpha = ScaledVisibleCellsCollectionView.sharedInstance.maxAlpha let minAlpha = ScaledVisibleCellsCollectionView.sharedInstance.minAlpha if distanceFromMainPosition < maximumScalingArea { // cell in maximum-scaling area preferredScale = maxScale preferredAlpha = maxAlpha } else if distanceFromMainPosition < (maximumScalingArea + scalingArea) { // cell in scaling area let multiplier = abs((distanceFromMainPosition - maximumScalingArea) / scalingArea) preferredScale = maxScale - multiplier * (maxScale - minScale) preferredAlpha = maxAlpha - multiplier * (maxAlpha - minAlpha) } else { // cell in minimum-scaling area preferredScale = minScale preferredAlpha = minAlpha } return [ preferredScale, preferredAlpha ] } } extension UICollectionView { private func horizontalCenter(cell: UICollectionViewCell)-> CGFloat { return abs(bounds.width / 2 - (cell.frame.midX - contentOffset.x)) } private func verticalCenter(cell: UICollectionViewCell)-> CGFloat { return abs(bounds.height / 2 - (cell.frame.midY - contentOffset.y)) } }
da560eb147b0a4c7c88ea8a2cd6e370e
37.893082
155
0.657771
false
false
false
false
AdySan/HomeKit-Demo
refs/heads/master
BetterHomeKit/ActionSetViewController.swift
mit
4
// // ActionSetViewController.swift // BetterHomeKit // // Created by Khaos Tian on 8/6/14. // Copyright (c) 2014 Oltica. All rights reserved. // import UIKit import HomeKit class ActionSetViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var actionsTableView: UITableView! weak var currentActionSet:HMActionSet? var actions = [HMAction]() override func viewDidLoad() { super.viewDidLoad() if let currentActionSet = currentActionSet { self.title = "\(currentActionSet.name)" } updateActions() } func updateActions () { actions.removeAll(keepCapacity: false) if let currentActionSet = currentActionSet { if let cActions = currentActionSet.actions{ var generator = cActions.generate() while let act = generator.next() as? HMAction{ actions.append(act) } } } actionsTableView.reloadData() } @IBAction func executeActionSet(sender: AnyObject) { if let currentHome = Core.sharedInstance.currentHome { currentHome.executeActionSet(currentActionSet) { error in if error != nil { NSLog("Failed executing action set, error:\(error)") } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return actions.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ActionCell", forIndexPath: indexPath) as! UITableViewCell let action = actions[indexPath.row] as! HMCharacteristicWriteAction if let charDesc = HomeKitUUIDs[action.characteristic.characteristicType] { cell.textLabel?.text = charDesc }else{ cell.textLabel?.text = action.characteristic.characteristicType } cell.detailTextLabel?.text = "Accessory: \(action.characteristic.service.accessory.name) | Target Value: \(action.targetValue)" return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let _action = actions[indexPath.row] as! HMCharacteristicWriteAction let object = _action.characteristic var charDesc = object.characteristicType charDesc = HomeKitUUIDs[object.characteristicType] switch (object.metadata.format as NSString) { case HMCharacteristicMetadataFormatBool: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Please choose the target state for this action", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "On", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in _action.updateTargetValue(true) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } })) alert.addAction(UIAlertAction(title: "Off", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in _action.updateTargetValue(false) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } })) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) case HMCharacteristicMetadataFormatInt,HMCharacteristicMetadataFormatFloat,HMCharacteristicMetadataFormatUInt8,HMCharacteristicMetadataFormatUInt16,HMCharacteristicMetadataFormatUInt32,HMCharacteristicMetadataFormatUInt64: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target state for this action from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField let f = NSNumberFormatter() f.numberStyle = NSNumberFormatterStyle.DecimalStyle _action.updateTargetValue(f.numberFromString(textField.text)) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) case HMCharacteristicMetadataFormatString: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target \(charDesc) from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField _action.updateTargetValue(textField.text) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) default: NSLog("Unsupported") } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let action = actions[indexPath.row] self.currentActionSet?.removeAction(action) { [weak self] error in if error != nil { NSLog("Failed removing action from action set, error:\(error)") } else { self?.updateActions() } } } } }
e945150e73f69fed94f9133429ceecb7
43.775401
269
0.582229
false
false
false
false