repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
welbesw/easypost-swift
Pod/Classes/EasyPostCustomsInfo.swift
1
4916
// // EasyPostCustomsInfo.swift // EasyPostApi // // Created by Sachin Vas on 19/04/18. // import Foundation open class EasyPostCustomsInfo { public enum ContentType: String { case other case sample case gift case documents case merchandise case returned_goods } public enum RestrictionType: String { case none case other case quarantine case sanitary_phytosanitary_inspection } public enum NonDeliveryOption: String { case `return` case abandon } open var id: String? open var customsItems: [EasyPostCustomsItem]? open var contentsType: ContentType? open var contentsExplanation: String? open var restrictionType: RestrictionType? open var restrictionComments: String? open var customsCertify: NSNumber? open var customsSigner: String? open var nonDeliveryOption: NonDeliveryOption = .return open var eelPfc: String? open var createdAt: Date? open var updatedAt: Date? public init() { } public init(jsonDictionary: [String: Any]) { //Load the JSON dictionary let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" //2013-04-22T05:40:57Z if let stringValue = jsonDictionary["id"] as? String { id = stringValue } if let arrayValue = jsonDictionary["customs_items"] as? Array<Dictionary<String, Any>> { customsItems = [] for value in arrayValue { customsItems?.append(EasyPostCustomsItem(jsonDictionary: value)) } } if let stringValue = jsonDictionary["contents_type"] as? String { contentsType = ContentType(rawValue: stringValue) } if let stringValue = jsonDictionary["contents_explanation"] as? String { contentsExplanation = stringValue } if let stringValue = jsonDictionary["restriction_type"] as? String { restrictionType = RestrictionType(rawValue: stringValue) } if let stringValue = jsonDictionary["restriction_comments"] as? String { restrictionComments = stringValue } if let boolValue = jsonDictionary["customs_certify"] as? NSNumber { customsCertify = boolValue } if let stringValue = jsonDictionary["customs_signer"] as? String { customsSigner = stringValue } if let stringValue = jsonDictionary["non_delivery_option"] as? String { nonDeliveryOption = NonDeliveryOption(rawValue: stringValue) ?? .return } if let stringValue = jsonDictionary["eel_pfc"] as? String { eelPfc = stringValue } if let stringValue = jsonDictionary["created_at"] as? String { createdAt = dateFormatter.date(from: stringValue) } if let stringValue = jsonDictionary["updated_at"] as? String { updatedAt = dateFormatter.date(from: stringValue) } } open func jsonDict() -> [String: Any] { var dict = [String: Any]() if id != nil { dict.updateValue(id! as AnyObject, forKey: "id") } if let custom_items = customsItems { var jsonDict: [[String: Any]] = [] for custom_item in custom_items { jsonDict.append(custom_item.jsonDict()) } dict.updateValue(jsonDict as AnyObject, forKey: "customs_items") } if contentsType != nil { dict.updateValue(contentsType!.rawValue as AnyObject, forKey: "contents_type") } if contentsExplanation != nil { dict.updateValue(contentsExplanation! as AnyObject, forKey: "contents_explanation") } if restrictionType != nil { dict.updateValue(restrictionType!.rawValue as AnyObject, forKey: "restriction_type") } if restrictionComments != nil { dict.updateValue(restrictionComments! as AnyObject, forKey: "restriction_comments") } if customsCertify != nil { dict.updateValue(customsCertify! as AnyObject, forKey: "customs_certify") } if customsSigner != nil { dict.updateValue(customsSigner! as AnyObject, forKey: "customs_signer") } dict.updateValue(nonDeliveryOption.rawValue as AnyObject, forKey: "non_delivery_option") if eelPfc != nil { dict.updateValue(eelPfc! as AnyObject, forKey: "eel_pfc") } return dict } }
mit
ce15a863861878f16769a1dfe40f40d9
30.312102
96
0.582587
4.88668
false
false
false
false
wusuowei/WTCarouselFlowLayout
Example/WTCarouselFlowLayout/CollectionViewCell.swift
1
621
// // CollectionViewCell.swift // WTCarouselFlowLayout // // Created by 温天恩 on 2017/8/31. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @objc let imageView = UIImageView() @objc var model = MovieModel() { didSet { if !self.subviews.contains(self.imageView) { addSubview(self.imageView) } self.imageView.frame = self.bounds self.imageView.backgroundColor = UIColor.red self.imageView.image = UIImage(named: model.imageName) } } }
mit
fa115ce57ed78b20ccdfb8d44a3c0d13
24.5
66
0.622549
4.25
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Knowledge Detail/Interactor Tests/DefaultKnowledgeDetailSceneInteractorTests.swift
1
5247
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class FakeKnowledgeService: KnowledgeService { func add(_ observer: KnowledgeServiceObserver) { } private var stubbedKnowledgeEntries = [KnowledgeEntryIdentifier: FakeKnowledgeEntry]() func fetchKnowledgeEntry(for identifier: KnowledgeEntryIdentifier, completionHandler: @escaping (KnowledgeEntry) -> Void) { completionHandler(stubbedKnowledgeEntry(for: identifier)) } func fetchImagesForKnowledgeEntry(identifier: KnowledgeEntryIdentifier, completionHandler: @escaping ([Data]) -> Void) { completionHandler(stubbedKnowledgeEntryImages(for: identifier)) } private var stubbedGroups = [KnowledgeGroup]() func fetchKnowledgeGroup(identifier: KnowledgeGroupIdentifier, completionHandler: @escaping (KnowledgeGroup) -> Void) { stubbedGroups.first(where: { $0.identifier == identifier }).let(completionHandler) } } extension FakeKnowledgeService { func stubbedKnowledgeEntry(for identifier: KnowledgeEntryIdentifier) -> FakeKnowledgeEntry { if let entry = stubbedKnowledgeEntries[identifier] { return entry } let randomEntry = FakeKnowledgeEntry.random randomEntry.identifier = identifier stubbedKnowledgeEntries[identifier] = randomEntry return randomEntry } func stub(_ group: KnowledgeGroup) { stubbedGroups.append(group) } func stubbedKnowledgeEntryImages(for identifier: KnowledgeEntryIdentifier) -> [Data] { return [unwrap(identifier.rawValue.data(using: .utf8))] } } class DefaultKnowledgeDetailSceneInteractorTests: XCTestCase { var knowledgeService: FakeKnowledgeService! var renderer: StubMarkdownRenderer! var shareService: CapturingShareService! var interactor: DefaultKnowledgeDetailSceneInteractor! override func setUp() { super.setUp() renderer = StubMarkdownRenderer() knowledgeService = FakeKnowledgeService() shareService = CapturingShareService() interactor = DefaultKnowledgeDetailSceneInteractor(knowledgeService: knowledgeService, renderer: renderer, shareService: shareService) } func testProducingViewModelConvertsKnowledgeEntryContentsViaWikiRenderer() { let entry = FakeKnowledgeEntry.random var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let randomizedEntry = knowledgeService.stubbedKnowledgeEntry(for: entry.identifier) let expected = renderer.stubbedContents(for: randomizedEntry.contents) XCTAssertEqual(expected, viewModel?.contents) } func testProducingViewModelConvertsLinksIntoViewModels() { let entry = FakeKnowledgeEntry.random var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let randomizedEntry = knowledgeService.stubbedKnowledgeEntry(for: entry.identifier) let expected = randomizedEntry.links.map { (link) in return LinkViewModel(name: link.name) } XCTAssertEqual(expected, viewModel?.links) } func testRequestingLinkAtIndexReturnsExpectedLink() { let entry = FakeKnowledgeEntry.random var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let randomizedEntry = knowledgeService.stubbedKnowledgeEntry(for: entry.identifier) let randomLink = randomizedEntry.links.randomElement() let expected = randomLink.element let actual = viewModel?.link(at: randomLink.index) XCTAssertEqual(expected.name, actual?.name) } func testUsesTitlesOfEntryAsTitle() { let entry = FakeKnowledgeEntry.random var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let randomizedEntry = knowledgeService.stubbedKnowledgeEntry(for: entry.identifier) XCTAssertEqual(randomizedEntry.title, viewModel?.title) } func testAdaptsImagesFromService() { let entry = FakeKnowledgeEntry.random var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let expected = knowledgeService.stubbedKnowledgeEntryImages(for: entry.identifier).map(KnowledgeEntryImageViewModel.init) XCTAssertEqual(expected, viewModel?.images) } func testSharingEntrySubmitsURLAndSenderToShareService() { let identifier = KnowledgeEntryIdentifier.random let entry = knowledgeService.stubbedKnowledgeEntry(for: identifier) var viewModel: KnowledgeEntryDetailViewModel? interactor.makeViewModel(for: entry.identifier) { viewModel = $0 } let sender = self viewModel?.shareKnowledgeEntry(sender) XCTAssertEqual(entry.contentURL, shareService.sharedItem as? URL) XCTAssertTrue(sender === (shareService.sharedItemSender as AnyObject)) } }
mit
9acb75bdb5844a257dfd42078dec4d0c
38.75
129
0.719268
5.505771
false
true
false
false
g-ackt/Sampling-Rx
Source/Models/Weather.swift
2
682
// Copyright © 2016 Gavan Chan. All rights reserved. import Argo import Curry import Runes typealias Temperature = Double typealias Percentage = Double struct Weather { let city: City let current: Temperature let cloudiness: Percentage } extension Weather: Decodable { static func decode(_ json: JSON) -> Decoded<Weather> { let city: Decoded<City> = City.decode(json) let current: Decoded<Temperature> = json <| ["main", "temp"] let cloudiness: Decoded<Percentage> = json <| ["clouds", "all"] let initialiser: ((City) -> (Temperature) -> (Percentage) -> Weather) = curry(Weather.init) return initialiser <^> city <*> current <*> cloudiness } }
mit
a7603ba1aa4b88edc8bf5b8138d17118
25.192308
95
0.687225
4.029586
false
false
false
false
gunterhager/AnnotationClustering
AnnotationClustering/Code/ClusterManager.swift
1
6442
// // ClusterManager.swift // AnnotationClustering // // Created by Gunter Hager on 07.06.16. // Copyright © 2016 Gunter Hager. All rights reserved. // import Foundation import MapKit /** * Protocol that the Delegate of the cluster manager needs to implement. */ public protocol ClusterManagerDelegate { /** Provide a cell size factor for the cluster manager. The cell size factor defines the size of the cells that the map uses for clustering. Clusters are grouped into cells. - parameter manager: Manager that wants to know its cell size factor. - returns: A cell size factor fo rthe manager to use. */ func cellSizeFactorForManager(_ manager: ClusterManager) -> CGFloat } /// Class that manages the clustering of the annotations. open class ClusterManager { open var delegate: ClusterManagerDelegate? open var maxZoomLevel = 19 fileprivate var tree = QuadTree() fileprivate var lock = NSRecursiveLock() public init(annotations: [MKAnnotation] = []){ addAnnotations(annotations) } open func setAnnotations(_ annotations:[MKAnnotation]) { lock.lock() tree = QuadTree() addAnnotations(annotations) lock.unlock() } open func addAnnotations(_ annotations:[MKAnnotation]) { lock.lock() for annotation in annotations { tree.addAnnotation(annotation) } lock.unlock() } open func clusteredAnnotationsWithinMapRect(_ rect:MKMapRect, withZoomScale zoomScale:Double) -> [MKAnnotation] { guard !zoomScale.isInfinite else { return [] } let zoomLevel = ClusterManager.zoomScaleToZoomLevel(MKZoomScale(zoomScale)) let cellSize = ClusterManager.cellSizeForZoomLevel(zoomLevel) let scaleFactor:Double = zoomScale / Double(cellSize) let minX = Int(floor(MKMapRectGetMinX(rect) * scaleFactor)) let maxX = Int(floor(MKMapRectGetMaxX(rect) * scaleFactor)) let minY = Int(floor(MKMapRectGetMinY(rect) * scaleFactor)) let maxY = Int(floor(MKMapRectGetMaxY(rect) * scaleFactor)) var clusteredAnnotations = [MKAnnotation]() lock.lock() for i in minX...maxX { for j in minY...maxY { let mapPoint = MKMapPoint(x: Double(i) / scaleFactor, y: Double(j) / scaleFactor) let mapSize = MKMapSize(width: 1.0 / scaleFactor, height: 1.0 / scaleFactor) let mapRect = MKMapRect(origin: mapPoint, size: mapSize) let mapBox = BoundingBox(mapRect: mapRect) var totalLatitude:Double = 0 var totalLongitude:Double = 0 var annotations = [MKAnnotation]() tree.forEachAnnotationInBox(mapBox) { (annotation) in totalLatitude += annotation.coordinate.latitude totalLongitude += annotation.coordinate.longitude annotations.append(annotation) } let count = annotations.count if count == 1 || zoomLevel >= self.maxZoomLevel { clusteredAnnotations += annotations } else if count > 1 { let coordinate = CLLocationCoordinate2D( latitude: CLLocationDegrees(totalLatitude) / CLLocationDegrees(count), longitude: CLLocationDegrees(totalLongitude) / CLLocationDegrees(count) ) let cluster = AnnotationCluster() cluster.coordinate = coordinate cluster.annotations = annotations clusteredAnnotations.append(cluster) } } } lock.unlock() return clusteredAnnotations } open var allAnnotations: [MKAnnotation] { lock.lock() let annotations = tree.allAnnotations lock.unlock() return annotations } open func displayAnnotations(_ annotations: [MKAnnotation], mapView:MKMapView){ DispatchQueue.main.async { let before = NSMutableSet(array: mapView.annotations) before.remove(mapView.userLocation) let after = NSSet(array: annotations) let toKeep = NSMutableSet(set: before) toKeep.intersect(after as Set<NSObject>) let toAdd = NSMutableSet(set: after) toAdd.minus(toKeep as Set<NSObject>) let toRemove = NSMutableSet(set: before) toRemove.minus(after as Set<NSObject>) if let toAddAnnotations = toAdd.allObjects as? [MKAnnotation]{ mapView.addAnnotations(toAddAnnotations) } if let removeAnnotations = toRemove.allObjects as? [MKAnnotation]{ mapView.removeAnnotations(removeAnnotations) } } } open class func zoomScaleToZoomLevel(_ scale: MKZoomScale) -> Int { let totalTilesAtMaxZoom = MKMapSizeWorld.width / 256.0 let zoomLevelAtMaxZoom = Int(log2(totalTilesAtMaxZoom)) let floorLog2ScaleFloat = floor(log2f(Float(scale))) + 0.5 guard !floorLog2ScaleFloat.isInfinite else { return (floorLog2ScaleFloat.sign == .minus) ? 0 : 19 } let sum = zoomLevelAtMaxZoom + Int(floorLog2ScaleFloat) let zoomLevel = max(0, sum) return zoomLevel; } open class func cellSizeForZoomLevel(_ zoomLevel: Int) -> CGFloat { switch (zoomLevel) { case 13: return 64 case 14: return 64 case 15: return 64 case 16: return 32 case 17: return 32 case 18: return 32 case 18 ..< Int.max: return 16 default: // less than 13 zoom level return 88 } } open class func cellSizeForZoomScale(_ zoomScale: MKZoomScale) -> CGFloat { let zoomLevel = ClusterManager.zoomScaleToZoomLevel(zoomScale) return ClusterManager.cellSizeForZoomLevel(zoomLevel) } }
mit
509f0d447268d232805163fd0bd2fcc9
33.079365
174
0.577705
5.296875
false
false
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/DataManager/DataManager+LoadTemplates.swift
1
5332
// // DataManager+LoadTemplates.swift // MoyskladiOSRemapSDK // // Created by Vladislav on 31.08.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation import RxSwift extension DataManager { /** Load print templates for document type. Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#шаблон-печатной-формы) - parameter forDocument: Request metadata type for which templates should be loaded - parameter parameters: container for parameters like auth, offset, search, expanders, filter, stringData, urlParameters - parameter type: Type of Template that should be loaded */ public static func templates(forDocument documentType: MSDocumentType, parameters: UrlRequestParameters, type: MSTemplateType) -> Observable<[MSEntity<MSTemplate>]> { return HttpClient.get(documentType.metadataRequest, auth: parameters.auth, urlPathComponents: [type.rawValue]) .flatMapLatest { result -> Observable<[MSEntity<MSTemplate>]> in guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectTemplateResponse.value)) } let deserialized = result.msArray("rows").map { MSTemplate.from(dict: $0) } let withoutNills = deserialized.removeNils() guard withoutNills.count == deserialized.count else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectTemplateResponse.value)) } return Observable.just(withoutNills) } } /** Load link to created PDF for document from template. Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#печать-документов) - parameter forDocument: Document type for which PDF should be loaded - parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters - parameter meta: Document template metadata - returns: Observable sequence with http link to PDF document */ public static func documentFromTemplate(forDocument documentType: MSDocumentType, parameters: UrlRequestParameters, id: String, meta: MSMeta) -> Observable<String> { let urlPathComponents: [String] = [id, "export"] var body = meta.dictionaryForTemplate() body["extension"] = "pdf" return HttpClient.updateWithHeadersResult(documentType.apiRequest, auth: parameters.auth, urlPathComponents: urlPathComponents, body: body.toJSONType()).flatMapLatest { result -> Observable<String> in guard let result = result else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecDocumentFromTemplateResponse.value)) } guard let res = result["Location"] else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecDocumentFromTemplateResponse.value)) } return Observable.just(res) } } /** Load link to created publication for document from template. Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#публикация-документов) - parameter forDocument: Document type for which publication should be loaded - parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters - parameter meta: Document template metadata - returns: Observable sequence with http link to publication */ public static func publicationFromTemplate(forDocument documentType: MSDocumentType, parameters: UrlRequestParameters, id: String, meta: MSMeta) -> Observable<String> { let urlPathComponents: [String] = [id, "publication"] let body = meta.dictionaryForTemplate() return HttpClient.create(documentType.apiRequest, auth: parameters.auth, urlPathComponents: urlPathComponents, body: body.toJSONType(), contentType: .json).flatMapLatest { result -> Observable<String> in guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecPublicationFromTemplateResponse.value)) } guard let res = result["href"] as? String else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecPublicationFromTemplateResponse.value)) } return Observable.just(res) } } /** Load file disk - parameter url: URL of file that should be loaded - returns: Observable sequence with URL to downloaded file */ public static func downloadDocument(url: URL) -> Observable<URL> { return HttpClient.resultCreateFromData(url).flatMapLatest{ result -> Observable<URL> in guard let result = result else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecDownloadDocumentResponse.value)) } return Observable.just(result) } } }
mit
c81067c717deaf4d15f98ce8d8a7e29b
53.958333
211
0.691243
4.792007
false
false
false
false
ahoppen/swift
test/Serialization/opaque_with_availability_cross_module.swift
3
1455
// RUN: %empty-directory(%t) // RUN: %target-build-swift -target %target-cpu-apple-macosx10.15 -parse-as-library -emit-library -emit-module-path %t/LimitedAvailOpaque.swiftmodule -module-name LimitedAvailOpaque %S/Inputs/opaque_with_limited_availability.swift -o %t/%target-library-name(LimitedAvailOpaque) // RUN: %target-build-swift -target %target-cpu-apple-macosx10.15 -lLimitedAvailOpaque -module-name main -I %t -L %t %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s --color // REQUIRES: OS=macosx && (CPU=x86_64 || CPU=arm64) // REQUIRES: executable_test import LimitedAvailOpaque struct S: P { func hello() { print("Hello from S") } } @available(macOS 100.0.1, *) struct NewS: P { func hello() { print("Hello from NewS") } } public struct Test { @Example var body: some P { // TODO(diagnostics): This is incorrect warning due to `some P` return of `buildWithLimitedAvailability` // expected-warning@+1 {{result builder 'Example' does not implement 'buildLimitedAvailability'; this code may crash on earlier versions of the OS}} if #available(macOS 100.0.1, *) { NewS() } S() } func sayHello() { body.hello() } } let result = LimitedAvailOpaque.test() result.hello() // CHECK: Hello from Empty Test().sayHello() // CHECK: Hello from Empty // CHECK: Hello from Tuple let conditionalR = LimitedAvailOpaque.test_return_from_conditional() conditionalR.hello() // CHECK: Hello from Named
apache-2.0
d1faed70ef81e735850f1b10e5856f04
29.957447
277
0.701031
3.360277
false
true
false
false
TinyCrayon/TinyCrayon-iOS-SDK
TCMask/BrushTool.swift
1
2426
// // RegularBrushTool // TinyCrayon // // Created by Xin Zeng on 6/22/16. // // import UIKit import TCCore class BrushTool : Tool { var imgSize: CGSize! var previousAlpha = [UInt8]() var previousPoint = CGPoint() init(maskView: MaskView, toolManager: ToolManager) { super.init(type: .brush, maskView: maskView, toolManager: toolManager) imgSize = maskView.image.size previousAlpha = [UInt8](repeating: 0, count: maskView.opacity.count) TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count) } override func refresh() { maskView.refresh() } override func invert() { TCCore.invertAlpha(&maskView.opacity, count: maskView.opacity.count) TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count) refresh() } override func endProcessing() { } override func touchBegan(_ location: CGPoint) { notifyWillBeginProcessing() drawCircularGrident(center: location) previousPoint = location; } override func touchMoved(_ previousLocation: CGPoint, _ location: CGPoint) { if (round(previousLocation.x * maskView.scaleFactor) == round(location.x * maskView.scaleFactor) && round(previousLocation.y * maskView.scaleFactor) == round(location.y * maskView.scaleFactor)) { return } drawCircularGrident(center: location) } override func touchEnded(_ previousLocation: CGPoint, _ location: CGPoint) { toolManager.pushLogOfBrush(previousAlpha: previousAlpha, currentAlpha: maskView.opacity) TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count) notifyDidEndProcessing() } func drawCircularGrident(center: CGPoint) { let params = delegate.getToolParams() let endRadius = maskView.lineWidth(scribbleSize: params.brushSize) / 2 let startRadius = endRadius * params.brushHardness var outRect = CGRect() if (TCCore.drawRadialGradient(onAlpha: &maskView.opacity, size: imgSize, center: center * maskView.scaleFactor, startValue: UInt8(params.brushOpacity * params.brushOpacity * 255), startRadius: startRadius, endValue: 0, endRadius: endRadius, outRect: &outRect, add: params.add)) { maskView.refresh(outRect) } } }
mit
b339bc81ceedd9873abc1df33689b3b4
34.676471
285
0.667766
4.517691
false
false
false
false
e78l/swift-corelibs-foundation
TestFoundation/TestIndexSet.swift
1
42456
// 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 // class TestIndexSet : XCTestCase { func test_BasicConstruction() { let set = IndexSet() let set2 = IndexSet(integersIn: 4..<11) XCTAssertEqual(set.count, 0) XCTAssertEqual(set.first, nil) XCTAssertEqual(set.last, nil) XCTAssertEqual(set2.count, 7) XCTAssertEqual(set2.first, 4) XCTAssertEqual(set2.last, 10) let set3 = NSMutableIndexSet() set3.add(2) set3.add(5) set3.add(in: NSRange(location: 4, length: 7)) set3.add(8) XCTAssertEqual(set3.count, 8) XCTAssertEqual(set3.firstIndex, 2) XCTAssertEqual(set3.lastIndex, 10) } func test_copy() { let range: NSRange = NSRange(location: 3, length: 4) let array : [Int] = [1,2,3,4,5,6,7,8,9,10] let indexSet = NSMutableIndexSet() for index in array { indexSet.add(index) } //Test copy operation of NSIndexSet case which is immutable let selfIndexSet: NSIndexSet = NSIndexSet(indexesIn: range) let selfIndexSetCopy = selfIndexSet.copy() as! NSIndexSet XCTAssertTrue(selfIndexSetCopy === selfIndexSet) XCTAssertTrue(selfIndexSetCopy.isEqual(to: selfIndexSet._bridgeToSwift())) //Test copy operation of NSMutableIndexSet case let mutableIndexSet: NSIndexSet = indexSet indexSet.add(11) let mutableIndexSetCopy = mutableIndexSet.copy() as! NSIndexSet XCTAssertFalse(mutableIndexSetCopy === mutableIndexSet) XCTAssertTrue(mutableIndexSetCopy.isEqual(to: mutableIndexSet._bridgeToSwift())) } func test_enumeration() { let set = IndexSet(integersIn: 4..<11) var result = Array<Int>() for idx in set { result.append(idx) } XCTAssertEqual(result, [4, 5, 6, 7, 8, 9, 10]) result = Array<Int>() for idx in IndexSet() { result.append(idx) } XCTAssertEqual(result, []) let disjointSet = NSMutableIndexSet() disjointSet.add(2) disjointSet.add(5) disjointSet.add(8) disjointSet.add(in: NSRange(location: 7, length: 3)) disjointSet.add(11) disjointSet.add(in: NSRange(location: 13, length: 2)) result = Array<Int>() disjointSet.enumerate(options: []) { (idx, _) in result.append(idx) } XCTAssertEqual(result, [2, 5, 7, 8, 9, 11, 13, 14]) } func test_sequenceType() { let set = IndexSet(integersIn: 4..<11) var result = Array<Int>() for idx in set { result.append(idx) } XCTAssertEqual(result, [4, 5, 6, 7, 8, 9, 10]) } func test_removal() { var removalSet = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: 10)) removalSet.remove(0) removalSet.remove(in: NSRange(location: 9, length: 5)) removalSet.remove(in: NSRange(location: 2, length: 4)) XCTAssertEqual(removalSet.count, 4) XCTAssertEqual(removalSet.firstIndex, 1) XCTAssertEqual(removalSet.lastIndex, 8) var expected = IndexSet() expected.insert(1) expected.insert(integersIn: 6..<9) XCTAssertTrue(removalSet.isEqual(to: expected)) // Removing a non-existent element has no effect removalSet.remove(9) XCTAssertTrue(removalSet.isEqual(to: expected)) removalSet.removeAllIndexes() expected = IndexSet() XCTAssertTrue(removalSet.isEqual(to: expected)) // Set removal removalSet = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: 10)) removalSet.remove(IndexSet(integersIn: 8..<11)) removalSet.remove(IndexSet(integersIn: 0..<2)) removalSet.remove(IndexSet(integersIn: 4..<6)) XCTAssertEqual(removalSet.count, 4) XCTAssertEqual(removalSet.firstIndex, 2) XCTAssertEqual(removalSet.lastIndex, 7) expected = IndexSet() expected.insert(integersIn: 2..<4) expected.insert(integersIn: 6..<8) XCTAssertTrue(removalSet.isEqual(to: expected)) // Removing an empty set has no effect removalSet.remove(IndexSet()) XCTAssertTrue(removalSet.isEqual(to: expected)) // Removing non-existent elements has no effect removalSet.remove(IndexSet(integersIn: 0..<2)) XCTAssertTrue(removalSet.isEqual(to: expected)) } func test_addition() { let testSetA = NSMutableIndexSet(index: 0) testSetA.add(5) testSetA.add(6) testSetA.add(7) testSetA.add(8) testSetA.add(42) let testInputA1 = [0,5,6,7,8,42] var i = 0 if testInputA1.count == testSetA.count { testSetA.enumerate(options: []) { (idx, _) in XCTAssertEqual(idx, testInputA1[i]) i += 1 } } else { XCTFail("IndexSet does not contain correct number of indexes") } let testInputA2 = [NSRange(location: 0, length: 1),NSRange(location: 5, length: 4),NSRange(location: 42, length: 1)] i = 0 testSetA.enumerateRanges(options: []) { (range, _) in let testRange = testInputA2[i] XCTAssertEqual(range.location, testRange.location) XCTAssertEqual(range.length, testRange.length) i += 1 } let testSetB = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: 5)) testSetB.add(in: NSRange(location: 42, length: 3)) testSetB.add(in: NSRange(location: 2, length: 2)) testSetB.add(in: NSRange(location: 18, length: 1)) let testInputB1 = [0,1,2,3,4,18,42,43,44] i = 0 if testInputB1.count == testSetB.count { testSetB.enumerate(options: []) { (idx, _) in XCTAssertEqual(idx, testInputB1[i]) i += 1 } } else { XCTFail("IndexSet does not contain correct number of indexes") } let testInputB2 = [NSRange(location: 0, length: 5),NSRange(location: 18, length: 1),NSRange(location: 42, length: 3)] i = 0 testSetB.enumerateRanges(options: []) { (range, _) in let testRange = testInputB2[i] XCTAssertEqual(range.location, testRange.location) XCTAssertEqual(range.length, testRange.length) i += 1 } } func test_setAlgebra() { var is1, is2, expected: IndexSet do { is1 = IndexSet(integersIn: 0..<5) is2 = IndexSet(integersIn: 3..<10) expected = IndexSet(integersIn: 0..<3) expected.insert(integersIn: 5..<10) XCTAssertTrue(expected == is1.symmetricDifference(is2)) XCTAssertTrue(expected == is2.symmetricDifference(is1)) } do { is1 = IndexSet([0, 2]) is2 = IndexSet([0, 1, 2]) XCTAssertTrue(IndexSet(integer: 1) == is1.symmetricDifference(is2)) } do { is1 = IndexSet(integersIn: 0..<5) is2 = IndexSet(integersIn: 4..<10) expected = IndexSet(integer: 4) XCTAssertTrue(expected == is1.intersection(is2)) XCTAssertTrue(expected == is2.intersection(is1)) } do { is1 = IndexSet([0, 2]) is2 = IndexSet([0, 1, 2]) XCTAssertTrue(is1 == is1.intersection(is2)) } } func testEnumeration() { let someIndexes = IndexSet(integersIn: 3...4) let first = someIndexes.startIndex let last = someIndexes.endIndex XCTAssertNotEqual(first, last) var count = 0 var firstValue = 0 var secondValue = 0 for v in someIndexes { if count == 0 { firstValue = v } if count == 1 { secondValue = v } count += 1 } XCTAssertEqual(2, count) XCTAssertEqual(3, firstValue) XCTAssertEqual(4, secondValue) } func testSubsequence() { var someIndexes = IndexSet(integersIn: 1..<3) someIndexes.insert(integersIn: 10..<20) let intersectingRange = someIndexes.indexRange(in: 5..<21) XCTAssertFalse(intersectingRange.isEmpty) let sub = someIndexes[intersectingRange] var count = 0 for i in sub { if count == 0 { XCTAssertEqual(10, i) } if count == 9 { XCTAssertEqual(19, i) } count += 1 } XCTAssertEqual(count, 10) } func testIndexRange() { var someIndexes = IndexSet(integersIn: 1..<3) someIndexes.insert(integersIn: 10..<20) var r : Range<IndexSet.Index> r = someIndexes.indexRange(in: 1..<3) XCTAssertEqual(1, someIndexes[r.lowerBound]) XCTAssertEqual(10, someIndexes[r.upperBound]) r = someIndexes.indexRange(in: 0..<0) XCTAssertEqual(r.lowerBound, r.upperBound) r = someIndexes.indexRange(in: 100..<201) XCTAssertEqual(r.lowerBound, r.upperBound) XCTAssertTrue(r.isEmpty) r = someIndexes.indexRange(in: 0..<100) XCTAssertEqual(r.lowerBound, someIndexes.startIndex) XCTAssertEqual(r.upperBound, someIndexes.endIndex) r = someIndexes.indexRange(in: 1..<11) XCTAssertEqual(1, someIndexes[r.lowerBound]) XCTAssertEqual(11, someIndexes[r.upperBound]) let empty = IndexSet() XCTAssertTrue(empty.indexRange(in: 1..<3).isEmpty) } func testMutation() { var someIndexes = IndexSet(integersIn: 1..<3) someIndexes.insert(3) someIndexes.insert(4) someIndexes.insert(5) someIndexes.insert(10) someIndexes.insert(11) XCTAssertEqual(someIndexes.count, 7) someIndexes.remove(11) XCTAssertEqual(someIndexes.count, 6) someIndexes.insert(integersIn: 100...101) XCTAssertEqual(8, someIndexes.count) XCTAssertEqual(2, someIndexes.count(in: 100...101)) someIndexes.remove(integersIn: 100...101) XCTAssertEqual(6, someIndexes.count) XCTAssertEqual(0, someIndexes.count(in: 100...101)) someIndexes.insert(integersIn: 200..<202) XCTAssertEqual(8, someIndexes.count) XCTAssertEqual(2, someIndexes.count(in: 200..<202)) someIndexes.remove(integersIn: 200..<202) XCTAssertEqual(6, someIndexes.count) XCTAssertEqual(0, someIndexes.count(in: 200..<202)) } func testContainsAndIntersects() { let someIndexes = IndexSet(integersIn: 1..<10) XCTAssertTrue(someIndexes.contains(integersIn: 1..<10)) XCTAssertTrue(someIndexes.contains(integersIn: 1...9)) XCTAssertTrue(someIndexes.contains(integersIn: 2..<10)) XCTAssertTrue(someIndexes.contains(integersIn: 2...9)) XCTAssertTrue(someIndexes.contains(integersIn: 1..<9)) XCTAssertTrue(someIndexes.contains(integersIn: 1...8)) XCTAssertFalse(someIndexes.contains(integersIn: 0..<10)) XCTAssertFalse(someIndexes.contains(integersIn: 0...9)) XCTAssertFalse(someIndexes.contains(integersIn: 2..<11)) XCTAssertFalse(someIndexes.contains(integersIn: 2...10)) XCTAssertFalse(someIndexes.contains(integersIn: 0..<9)) XCTAssertFalse(someIndexes.contains(integersIn: 0...8)) XCTAssertTrue(someIndexes.intersects(integersIn: 1..<10)) XCTAssertTrue(someIndexes.intersects(integersIn: 1...9)) XCTAssertTrue(someIndexes.intersects(integersIn: 2..<10)) XCTAssertTrue(someIndexes.intersects(integersIn: 2...9)) XCTAssertTrue(someIndexes.intersects(integersIn: 1..<9)) XCTAssertTrue(someIndexes.intersects(integersIn: 1...8)) XCTAssertTrue(someIndexes.intersects(integersIn: 0..<10)) XCTAssertTrue(someIndexes.intersects(integersIn: 0...9)) XCTAssertTrue(someIndexes.intersects(integersIn: 2..<11)) XCTAssertTrue(someIndexes.intersects(integersIn: 2...10)) XCTAssertTrue(someIndexes.intersects(integersIn: 0..<9)) XCTAssertTrue(someIndexes.intersects(integersIn: 0...8)) XCTAssertFalse(someIndexes.intersects(integersIn: 0..<0)) XCTAssertFalse(someIndexes.intersects(integersIn: 10...12)) XCTAssertFalse(someIndexes.intersects(integersIn: 10..<12)) } func testContainsIndexSet() { var someIndexes = IndexSet() someIndexes.insert(integersIn: 1..<2) someIndexes.insert(integersIn: 100..<200) someIndexes.insert(integersIn: 1000..<2000) let contained1 = someIndexes let contained2 = IndexSet(integersIn: 120..<150) var contained3 = IndexSet() contained3.insert(integersIn: 100..<200) contained3.insert(integersIn: 1500..<1600) let notContained1 = IndexSet(integer: 9) let notContained2 = IndexSet(integersIn: 150..<300) var notContained3 = IndexSet() notContained3.insert(integersIn: 1..<2) notContained3.insert(integersIn: 100..<200) notContained3.insert(integersIn: 1000..<2000) notContained3.insert(integersIn: 3000..<5000) XCTAssertTrue(someIndexes.contains(integersIn: contained1)) XCTAssertTrue(someIndexes.contains(integersIn: contained2)) XCTAssertTrue(someIndexes.contains(integersIn: contained3)) XCTAssertFalse(someIndexes.contains(integersIn: notContained1)) XCTAssertFalse(someIndexes.contains(integersIn: notContained2)) XCTAssertFalse(someIndexes.contains(integersIn: notContained3)) let emptySet = IndexSet() XCTAssertTrue(emptySet.contains(integersIn: emptySet)) XCTAssertTrue(someIndexes.contains(integersIn: emptySet)) XCTAssertFalse(emptySet.contains(integersIn: someIndexes)) } func testIteration() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) let start = someIndexes.startIndex let end = someIndexes.endIndex // Count forwards var i = start var count = 0 while i != end { count += 1 i = someIndexes.index(after: i) } XCTAssertEqual(8, count) // Count backwards i = end count = 0 while i != start { i = someIndexes.index(before: i) count += 1 } XCTAssertEqual(8, count) // Count using a for loop count = 0 for _ in someIndexes { count += 1 } XCTAssertEqual(8, count) // Go the other way count = 0 for _ in someIndexes.reversed() { count += 1 } XCTAssertEqual(8, count) } func testRangeIteration() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) var count = 0 for r in someIndexes.rangeView { // print("\(r)") count += 1 if count == 3 { XCTAssertEqual(r, 15..<16) } } XCTAssertEqual(3, count) // Backwards count = 0 for r in someIndexes.rangeView.reversed() { // print("\(r)") count += 1 if count == 3 { XCTAssertEqual(r, 1..<5) } } XCTAssertEqual(3, count) } func testSubrangeIteration() { var someIndexes = IndexSet(integersIn: 2..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(integersIn: 15..<20) someIndexes.insert(integersIn: 30..<40) someIndexes.insert(integersIn: 60..<80) var count = 0 for _ in someIndexes.rangeView { count += 1 } XCTAssertEqual(5, count) count = 0 for r in someIndexes.rangeView(of: 9..<35) { if count == 0 { XCTAssertEqual(r, 9..<11) } count += 1 if count == 3 { XCTAssertEqual(r, 30..<35) } } XCTAssertEqual(3, count) count = 0 for r in someIndexes.rangeView(of: 0...34) { if count == 0 { XCTAssertEqual(r, 2..<5) } count += 1 if count == 4 { XCTAssertEqual(r, 30..<35) } } XCTAssertEqual(4, count) // Empty intersection, before start count = 0 for _ in someIndexes.rangeView(of: 0..<1) { count += 1 } XCTAssertEqual(0, count) // Empty range count = 0 for _ in someIndexes.rangeView(of: 0..<0) { count += 1 } XCTAssertEqual(0, count) // Empty intersection, after end count = 0 for _ in someIndexes.rangeView(of: 999..<1000) { count += 1 } XCTAssertEqual(0, count) } func testSlicing() { var someIndexes = IndexSet(integersIn: 2..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(integersIn: 15..<20) someIndexes.insert(integersIn: 30..<40) someIndexes.insert(integersIn: 60..<80) var r : Range<IndexSet.Index> r = someIndexes.indexRange(in: 5..<25) XCTAssertEqual(8, someIndexes[r.lowerBound]) XCTAssertEqual(19, someIndexes[someIndexes.index(before: r.upperBound)]) var count = 0 for _ in someIndexes[r] { count += 1 } XCTAssertEqual(8, someIndexes.count(in: 5..<25)) XCTAssertEqual(8, count) r = someIndexes.indexRange(in: 100...199) XCTAssertTrue(r.isEmpty) let emptySlice = someIndexes[r] XCTAssertEqual(0, emptySlice.count) let boundarySlice = someIndexes[someIndexes.indexRange(in: 2..<3)] XCTAssertEqual(1, boundarySlice.count) let boundarySlice2 = someIndexes[someIndexes.indexRange(in: 79..<80)] XCTAssertEqual(1, boundarySlice2.count) let largeSlice = someIndexes[someIndexes.indexRange(in: 0..<100000)] XCTAssertEqual(someIndexes.count, largeSlice.count) } func testEmptyIteration() { var empty = IndexSet() let start = empty.startIndex let end = empty.endIndex XCTAssertEqual(start, end) var count = 0 for _ in empty { count += 1 } XCTAssertEqual(count, 0) count = 0 for _ in empty.rangeView { count += 1 } XCTAssertEqual(count, 0) empty.insert(5) empty.remove(5) count = 0 for _ in empty { count += 1 } XCTAssertEqual(count, 0) count = 0 for _ in empty.rangeView { count += 1 } XCTAssertEqual(count, 0) } func testSubsequences() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) // Get a subsequence of this IndexSet let range = someIndexes.indexRange(in: 4..<15) let subSet = someIndexes[range] XCTAssertEqual(subSet.count, 4) // Iterate a subset var count = 0 for _ in subSet { count += 1 } XCTAssertEqual(count, 4) // And in reverse count = 0 for _ in subSet.reversed() { count += 1 } XCTAssertEqual(count, 4) } func testFiltering() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) // An array let resultArray = someIndexes.filter { $0 % 2 == 0 } XCTAssertEqual(resultArray.count, 4) let resultSet = someIndexes.filteredIndexSet { $0 % 2 == 0 } XCTAssertEqual(resultSet.count, 4) let resultOutsideRange = someIndexes.filteredIndexSet(in: 20..<30, includeInteger: { _ in return true } ) XCTAssertEqual(resultOutsideRange.count, 0) let resultInRange = someIndexes.filteredIndexSet(in: 0..<16, includeInteger: { _ in return true } ) XCTAssertEqual(resultInRange.count, someIndexes.count) } func testFilteringRanges() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) let resultArray = someIndexes.rangeView.filter { $0.count > 1 } XCTAssertEqual(resultArray.count, 2) } func testShift() { var someIndexes = IndexSet(integersIn: 1..<5) someIndexes.insert(integersIn: 8..<11) someIndexes.insert(15) let lastValue = someIndexes.last! someIndexes.shift(startingAt: 13, by: 1) // Count should not have changed XCTAssertEqual(someIndexes.count, 8) // But the last value should have XCTAssertEqual(lastValue + 1, someIndexes.last!) // Shift starting at something not in the set someIndexes.shift(startingAt: 0, by: 1) // Count should not have changed, again XCTAssertEqual(someIndexes.count, 8) // But the last value should have, again XCTAssertEqual(lastValue + 2, someIndexes.last!) } func testSymmetricDifference() { var is1 : IndexSet var is2 : IndexSet var expected : IndexSet do { is1 = IndexSet() is1.insert(integersIn: 1..<3) is1.insert(integersIn: 4..<11) is1.insert(integersIn: 15..<21) is1.insert(integersIn: 40..<51) is2 = IndexSet() is2.insert(integersIn: 5..<18) is2.insert(integersIn: 45..<61) expected = IndexSet() expected.insert(integersIn: 1..<3) expected.insert(4) expected.insert(integersIn: 11..<15) expected.insert(integersIn: 18..<21) expected.insert(integersIn: 40..<45) expected.insert(integersIn: 51..<61) XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet() is1.insert(integersIn: 5..<18) is1.insert(integersIn: 45..<61) is2 = IndexSet() is2.insert(integersIn: 5..<18) is2.insert(integersIn: 45..<61) expected = IndexSet() XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet(integersIn: 1..<10) is2 = IndexSet(integersIn: 20..<30) expected = IndexSet() expected.insert(integersIn: 1..<10) expected.insert(integersIn: 20..<30) XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet(integersIn: 1..<10) is2 = IndexSet(integersIn: 1..<11) expected = IndexSet(integer: 10) XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet(integer: 42) is2 = IndexSet(integer: 42) XCTAssertEqual(IndexSet(), is1.symmetricDifference(is2)) XCTAssertEqual(IndexSet(), is2.symmetricDifference(is1)) } do { is1 = IndexSet(integer: 1) is1.insert(3) is1.insert(5) is1.insert(7) is2 = IndexSet(integer: 0) is2.insert(2) is2.insert(4) is2.insert(6) expected = IndexSet(integersIn: 0..<8) XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet(integersIn: 0..<5) is2 = IndexSet(integersIn: 3..<10) expected = IndexSet(integersIn: 0..<3) expected.insert(integersIn: 5..<10) XCTAssertEqual(expected, is1.symmetricDifference(is2)) XCTAssertEqual(expected, is2.symmetricDifference(is1)) } do { is1 = IndexSet([0, 2]) is2 = IndexSet([0, 1, 2]) XCTAssertEqual(IndexSet(integer: 1), is1.symmetricDifference(is2)) } } func testIntersection() { var is1 : IndexSet var is2 : IndexSet var expected : IndexSet do { is1 = IndexSet() is1.insert(integersIn: 1..<3) is1.insert(integersIn: 4..<11) is1.insert(integersIn: 15..<21) is1.insert(integersIn: 40..<51) is2 = IndexSet() is2.insert(integersIn: 5..<18) is2.insert(integersIn: 45..<61) expected = IndexSet() expected.insert(integersIn: 5..<11) expected.insert(integersIn: 15..<18) expected.insert(integersIn: 45..<51) XCTAssertEqual(expected, is1.intersection(is2)) XCTAssertEqual(expected, is2.intersection(is1)) } do { is1 = IndexSet() is1.insert(integersIn: 5..<11) is1.insert(integersIn: 20..<31) is2 = IndexSet() is2.insert(integersIn: 11..<20) is2.insert(integersIn: 31..<40) XCTAssertEqual(IndexSet(), is1.intersection(is2)) XCTAssertEqual(IndexSet(), is2.intersection(is1)) } do { is1 = IndexSet(integer: 42) is2 = IndexSet(integer: 42) XCTAssertEqual(IndexSet(integer: 42), is1.intersection(is2)) } do { is1 = IndexSet(integer: 1) is1.insert(3) is1.insert(5) is1.insert(7) is2 = IndexSet(integer: 0) is2.insert(2) is2.insert(4) is2.insert(6) expected = IndexSet() XCTAssertEqual(expected, is1.intersection(is2)) XCTAssertEqual(expected, is2.intersection(is1)) } do { is1 = IndexSet(integersIn: 0..<5) is2 = IndexSet(integersIn: 4..<10) expected = IndexSet(integer: 4) XCTAssertEqual(expected, is1.intersection(is2)) XCTAssertEqual(expected, is2.intersection(is1)) } do { is1 = IndexSet([0, 2]) is2 = IndexSet([0, 1, 2]) XCTAssertEqual(is1, is1.intersection(is2)) } } func testUnion() { var is1 : IndexSet var is2 : IndexSet var expected : IndexSet do { is1 = IndexSet() is1.insert(integersIn: 1..<3) is1.insert(integersIn: 4..<11) is1.insert(integersIn: 15..<21) is1.insert(integersIn: 40..<51) is2 = IndexSet() is2.insert(integersIn: 5..<18) is2.insert(integersIn: 45..<61) expected = IndexSet() expected.insert(integersIn: 1..<3) expected.insert(integersIn: 4..<21) expected.insert(integersIn: 40..<61) let u1 = is1.union(is2) XCTAssertEqual(expected, u1) } do { is1 = IndexSet() is1.insert(integersIn: 5..<11) is1.insert(integersIn: 20..<31) is2 = IndexSet() is2.insert(integersIn: 11..<20) is2.insert(integersIn: 31..<40) expected = IndexSet() expected.insert(integersIn: 5..<11) expected.insert(integersIn: 20..<31) expected.insert(integersIn: 11..<20) expected.insert(integersIn: 31..<40) XCTAssertEqual(expected, is1.union(is2)) XCTAssertEqual(expected, is2.union(is1)) } do { is1 = IndexSet(integer: 42) is2 = IndexSet(integer: 42) let u1 = is1.union(is2) XCTAssertEqual(IndexSet(integer: 42), u1) } do { is1 = IndexSet() is1.insert(integersIn: 5..<10) is1.insert(integersIn: 15..<20) is2 = IndexSet() is2.insert(integersIn: 1..<4) is2.insert(integersIn: 15..<20) expected = IndexSet() expected.insert(integersIn: 1..<4) expected.insert(integersIn: 5..<10) expected.insert(integersIn: 15..<20) XCTAssertEqual(expected, is1.union(is2)) XCTAssertEqual(expected, is2.union(is1)) } XCTAssertEqual(IndexSet(), IndexSet().union(IndexSet())) do { is1 = IndexSet(integer: 1) is1.insert(3) is1.insert(5) is1.insert(7) is2 = IndexSet(integer: 0) is2.insert(2) is2.insert(4) is2.insert(6) expected = IndexSet() XCTAssertEqual(expected, is1.intersection(is2)) XCTAssertEqual(expected, is2.intersection(is1)) } do { is1 = IndexSet(integersIn: 0..<5) is2 = IndexSet(integersIn: 3..<10) expected = IndexSet(integersIn: 0..<10) XCTAssertEqual(expected, is1.union(is2)) XCTAssertEqual(expected, is2.union(is1)) } do { is1 = IndexSet() is1.insert(2) is1.insert(6) is1.insert(21) is1.insert(22) is2 = IndexSet() is2.insert(8) is2.insert(14) is2.insert(21) is2.insert(22) is2.insert(24) expected = IndexSet() expected.insert(2) expected.insert(6) expected.insert(21) expected.insert(22) expected.insert(8) expected.insert(14) expected.insert(21) expected.insert(22) expected.insert(24) let u1 = is1.union(is2) let u2 = is2.union(is1) XCTAssertEqual(expected, u1) XCTAssertEqual(expected, u2) } } func test_findIndex() { var i = IndexSet() // Verify nil result for empty sets XCTAssertEqual(nil, i.first) XCTAssertEqual(nil, i.last) XCTAssertEqual(nil, i.integerGreaterThan(5)) XCTAssertEqual(nil, i.integerLessThan(5)) XCTAssertEqual(nil, i.integerGreaterThanOrEqualTo(5)) XCTAssertEqual(nil, i.integerLessThanOrEqualTo(5)) i.insert(integersIn: 5..<10) i.insert(integersIn: 15..<20) // Verify non-nil result XCTAssertEqual(5, i.first) XCTAssertEqual(19, i.last) XCTAssertEqual(nil, i.integerGreaterThan(19)) XCTAssertEqual(5, i.integerGreaterThan(3)) XCTAssertEqual(nil, i.integerLessThan(5)) XCTAssertEqual(5, i.integerLessThan(6)) XCTAssertEqual(nil, i.integerGreaterThanOrEqualTo(20)) XCTAssertEqual(19, i.integerGreaterThanOrEqualTo(19)) XCTAssertEqual(nil, i.integerLessThanOrEqualTo(4)) XCTAssertEqual(5, i.integerLessThanOrEqualTo(5)) } // MARK: - // MARK: Performance Testing func largeIndexSet() -> IndexSet { var result = IndexSet() for i in 1..<10000 { let start = i * 10 let end = start + 9 result.insert(integersIn: start..<end + 1) } return result } func testIndexingPerformance() { /* let set = largeIndexSet() self.measureBlock { var count = 0 while count < 20 { for _ in set { } count += 1 } } */ } func test_AnyHashableContainingIndexSet() { let values: [IndexSet] = [ IndexSet([0, 1]), IndexSet([0, 1, 2]), IndexSet([0, 1, 2]), ] let anyHashables = values.map(AnyHashable.init) XCTAssert(IndexSet.self == type(of: anyHashables[0].base)) XCTAssert(IndexSet.self == type(of: anyHashables[1].base)) XCTAssert(IndexSet.self == type(of: anyHashables[2].base)) XCTAssertNotEqual(anyHashables[0], anyHashables[1]) XCTAssertEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSIndexSet() { let values: [NSIndexSet] = [ NSIndexSet(index: 0), NSIndexSet(index: 1), NSIndexSet(index: 1), ] let anyHashables = values.map(AnyHashable.init) XCTAssert(IndexSet.self == type(of: anyHashables[0].base)) XCTAssert(IndexSet.self == type(of: anyHashables[1].base)) XCTAssert(IndexSet.self == type(of: anyHashables[2].base)) XCTAssertNotEqual(anyHashables[0], anyHashables[1]) XCTAssertEqual(anyHashables[1], anyHashables[2]) } func test_unconditionallyBridgeFromObjectiveC() { XCTAssertEqual(IndexSet(), IndexSet._unconditionallyBridgeFromObjectiveC(nil)) } func testInsertNonOverlapping() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.insert(200) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<201) expected.insert(integersIn: 1000..<2000) XCTAssertEqual(tested, expected) } func testInsertOverlapping() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.insert(integersIn: 10000..<20000) tested.insert(integersIn: 150..<1500) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<2000) expected.insert(integersIn: 10000..<20000) XCTAssertEqual(tested, expected) } func testInsertOverlappingExtend() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.insert(integersIn: 50..<500) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 50..<500) expected.insert(integersIn: 1000..<2000) XCTAssertEqual(tested, expected) } func testInsertOverlappingMultiple() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.insert(integersIn: 10000..<20000) tested.insert(integersIn: 150..<3000) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<3000) expected.insert(integersIn: 10000..<20000) XCTAssertEqual(tested, expected) } func testRemoveNonOverlapping() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.remove(199) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<199) expected.insert(integersIn: 1000..<2000) XCTAssertEqual(tested, expected) } func testRemoveOverlapping() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.remove(integersIn: 150..<1500) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<150) expected.insert(integersIn: 1500..<2000) XCTAssertEqual(tested, expected) } func testRemoveSplitting() { var tested = IndexSet() tested.insert(integersIn: 1..<2) tested.insert(integersIn: 100..<200) tested.insert(integersIn: 1000..<2000) tested.remove(integersIn: 150..<160) var expected = IndexSet() expected.insert(integersIn: 1..<2) expected.insert(integersIn: 100..<150) expected.insert(integersIn: 160..<200) expected.insert(integersIn: 1000..<2000) XCTAssertEqual(tested, expected) } let fixtures: [TypedFixture<NSIndexSet>] = [ Fixtures.indexSetEmpty, Fixtures.indexSetOneRange, Fixtures.indexSetManyRanges, ] let mutableFixtures: [TypedFixture<NSMutableIndexSet>] = [ Fixtures.mutableIndexSetEmpty, Fixtures.mutableIndexSetOneRange, Fixtures.mutableIndexSetManyRanges, ] func testCodingRoundtrip() throws { for fixture in fixtures { try fixture.assertValueRoundtripsInCoder() } for fixture in mutableFixtures { try fixture.assertValueRoundtripsInCoder() } } func testLoadedValuesMatch() throws { for fixture in fixtures { try fixture.assertLoadedValuesMatch() } for fixture in mutableFixtures { try fixture.assertLoadedValuesMatch() } } static var allTests: [(String, (TestIndexSet) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_enumeration", test_enumeration), ("test_sequenceType", test_sequenceType), ("test_removal", test_removal), ("test_addition", test_addition), ("test_setAlgebra", test_setAlgebra), ("test_copy", test_copy), ("test_BasicConstruction", test_BasicConstruction), ("test_copy", test_copy), ("test_enumeration", test_enumeration), ("test_sequenceType", test_sequenceType), ("test_removal", test_removal), ("test_addition", test_addition), ("test_setAlgebra", test_setAlgebra), ("testEnumeration", testEnumeration), ("testSubsequence", testSubsequence), ("testIndexRange", testIndexRange), ("testMutation", testMutation), ("testContainsAndIntersects", testContainsAndIntersects), ("testContainsIndexSet", testContainsIndexSet), ("testIteration", testIteration), ("testRangeIteration", testRangeIteration), ("testSubrangeIteration", testSubrangeIteration), ("testSlicing", testSlicing), ("testEmptyIteration", testEmptyIteration), ("testSubsequences", testSubsequences), ("testFiltering", testFiltering), ("testFilteringRanges", testFilteringRanges), ("testShift", testShift), ("testSymmetricDifference", testSymmetricDifference), ("testIntersection", testIntersection), ("testUnion", testUnion), ("test_findIndex", test_findIndex), ("testIndexingPerformance", testIndexingPerformance), ("test_AnyHashableContainingIndexSet", test_AnyHashableContainingIndexSet), ("test_AnyHashableCreatedFromNSIndexSet", test_AnyHashableCreatedFromNSIndexSet), ("test_unconditionallyBridgeFromObjectiveC", test_unconditionallyBridgeFromObjectiveC), ("testInsertNonOverlapping", testInsertNonOverlapping), ("testInsertOverlapping", testInsertOverlapping), ("testInsertOverlappingExtend", testInsertOverlappingExtend), ("testInsertOverlappingMultiple", testInsertOverlappingMultiple), ("testRemoveNonOverlapping", testRemoveNonOverlapping), ("testRemoveOverlapping", testRemoveOverlapping), ("testRemoveSplitting", testRemoveSplitting), ("testCodingRoundtrip", testCodingRoundtrip), ("testLoadedValuesMatch", testLoadedValuesMatch), ] } }
apache-2.0
ee19325003348daf015dd27778409db3
31.809892
125
0.55594
4.63089
false
true
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View/QiscusChatVC/QVCCollectionView.swift
1
8982
// // QVCCollectionView.swift // Example // // Created by Ahmad Athaullah on 5/16/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit // MARK: - CollectionView dataSource, delegate, and delegateFlowLayout extension QiscusChatVC: QConversationViewConfigurationDelegate { public func configDelegate(usingTpingCellIndicator collectionView: QConversationCollectionView) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(usingTypingCell: self){ return config } return false } public func configDelegate(userNameLabelColor collectionView:QConversationCollectionView, forUser user:QUser)->UIColor?{ if let config = self.configDelegate{ if let color = config.chatVCConfigDelegate?(userNameLabelColor: self, forUser: user){ return color } } return nil } public func configDelegate(hideLeftAvatarOn collectionView:QConversationCollectionView)->Bool{ if let config = self.configDelegate{ if let hidden = config.chatVCConfigDelegate?(hideLeftAvatarOn: self){ return hidden } } return false } public func configDelegate(hideUserNameLabel collectionView:QConversationCollectionView, forUser user:QUser)->Bool{ if let config = self.configDelegate{ if let hideLabel = config.chatVCConfigDelegate?(hideUserNameLabel: self, forUser: user){ return hideLabel } } return false } public func configDelegate(deletedMessageText collectionView: QConversationCollectionView, selfMessage isSelf: Bool) -> String { if let config = self.configDelegate?.chatVCConfigDelegate?(deletedMessageTextFor: self, selfMessage: isSelf){ return config }else if isSelf { return "🚫 You deleted this message." }else{ return "🚫 This message was deleted." } } public func configDelegate(enableInfoMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableInfoMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableReplyMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableReplyMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableShareMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableShareMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableDeleteMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableDeleteMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableResendMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableResendMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableDeleteForMeMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableDeleteForMeMenuItem: self, forComment: comment) { return config } return true } public func configDelegate(enableForwardMenuItem collectionView: QConversationCollectionView, forComment comment: QComment) -> Bool { if let config = self.configDelegate?.chatVCConfigDelegate?(enableForwardMenuItem: self, forComment: comment) { return config } return true } } extension QiscusChatVC: QConversationViewDelegate { public func viewDelegate(usingSoftDeleteOnView view: QConversationCollectionView) -> Bool { if let softDelete = self.configDelegate?.chatVCConfigDelegate?(usingSoftDeleteOn: self){ return softDelete } return false } public func viewDelegate(enableInfoAction view: QConversationCollectionView) -> Bool { if let delegate = self.delegate { return delegate.chatVC(enableInfoAction: self) }else{ return false } } public func viewDelegate(enableForwardAction view: QConversationCollectionView) -> Bool { if let delegate = self.delegate{ return delegate.chatVC(enableForwardAction: self) } return false } public func viewDelegate(view:QConversationCollectionView, cellForComment comment:QComment, indexPath:IndexPath)->QChatCell?{ if let delegate = self.cellDelegate { if let cell = delegate.chatVC?(viewController:self, cellForComment:comment, indexPath:indexPath){ return cell } } return nil } public func viewDelegate(view:QConversationCollectionView, heightForComment comment:QComment)->QChatCellHeight?{ if let delegate = self.cellDelegate { if let height = delegate.chatVC?(viewController: self, heightForComment: comment){ return height } } return nil } public func viewDelegate(view:QConversationCollectionView, willDisplayCellForComment comment:QComment, cell:QChatCell, indexPath: IndexPath){ } public func viewDelegate(view:QConversationCollectionView, didEndDisplayingCellForComment comment:QComment, cell:QChatCell, indexPath: IndexPath){ } public func viewDelegate(didEndDisplayingLastMessage view:QConversationCollectionView, comment:QComment){ self.bottomButton.isHidden = false if (self.chatRoom?.isInvalidated)!{ return } if self.chatRoom?.unreadCount == 0 { self.unreadIndicator.isHidden = true }else{ self.unreadIndicator.isHidden = true var unreadText = "" if self.chatRoom!.unreadCount > 0 { if self.chatRoom!.unreadCount > 99 { unreadText = "99+" }else{ unreadText = "\(self.chatRoom!.unreadCount)" } } self.unreadIndicator.text = unreadText self.unreadIndicator.isHidden = self.bottomButton.isHidden } } open func viewDelegate(willDisplayLastMessage view:QConversationCollectionView, comment:QComment){ self.bottomButton.isHidden = true if self.isPresence && !self.prefetch { if let room = self.chatRoom { let rid = room.id QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ rts.readAll() } } } } } public func viewDelegate(view:QConversationCollectionView, hideCellWith comment:QComment)->Bool{ if let delegate = self.cellDelegate { if let hide = delegate.chatVC?(viewController: self, hideCellWith: comment) { return hide } } return false } public func viewDelegate(view: QConversationCollectionView, didLoadData messages: [[String]]) { if messages.count > 0 { let delay = 0.8 * Double(NSEC_PER_SEC) let time = DispatchTime.now() + delay / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { self.welcomeView.isHidden = true self.collectionView.isHidden = false self.dismissLoading() if self.firstLoad { self.collectionView.scrollToBottom() self.firstLoad = false } if !self.prefetch && self.isPresence{ if let room = self.chatRoom { let rid = room.id QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ // rts.readAll() } } } } }) }else{ self.welcomeView.isHidden = true self.collectionView.isHidden = true self.dismissLoading() } } }
mit
4df023d83175266fb66258f271c5df1b
39.246637
150
0.626407
5.187861
false
true
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/FAQActions.swift
1
8317
// // FAQActions.swift // WebimClientLibrary // // Created by Nikita Kaberov on 07.02.19. // Copyright © 2019 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** - author: Nikita Kaberov - copyright: 2019 Webim */ class FAQActions { // MARK: - Constants enum Parameter: String { case application = "app" case categoryId = "categoryid" case departmentKey = "department-key" case itemId = "itemid" case language = "lang" case limit = "limit" case open = "open" case platform = "platform" case query = "query" case userId = "userid" } enum ServerPathSuffix: String { case item = "/services/faq/v1/item" case category = "/services/faq/v1/category" case categories = "/webim/api/v1/faq/category" case structure = "/services/faq/v1/structure" case search = "/services/faq/v1/search" case like = "/services/faq/v1/like" case dislike = "/services/faq/v1/dislike" case track = "/services/faq/v1/track" } // MARK: - Properties private let baseURL: String private let faqRequestLoop: FAQRequestLoop private static let deviceID = ClientSideID.generateClientSideID() // MARK: - Initialization init(baseURL: String, faqRequestLoop: FAQRequestLoop) { self.baseURL = baseURL self.faqRequestLoop = faqRequestLoop } // MARK: - Methods func getItem(itemId: String, completion: @escaping (_ faqItem: Data?) throws -> ()) { let dataToPost = [Parameter.itemId.rawValue: itemId, Parameter.userId.rawValue: FAQActions.deviceID] as [String: Any] let urlString = baseURL + ServerPathSuffix.item.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func getCategory(categoryId: String, completion: @escaping (_ faqCategory: Data?) throws -> ()) { let dataToPost = [Parameter.categoryId.rawValue: categoryId, Parameter.userId.rawValue: FAQActions.deviceID] as [String: Any] let urlString = baseURL + ServerPathSuffix.category.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func getCategoriesFor(application: String, language: String, departmentKey: String, completion: @escaping (_ faqCategories: Data?) throws -> ()) { let dataToPost = [Parameter.application.rawValue: application, Parameter.platform.rawValue: "ios", Parameter.language.rawValue: language, Parameter.departmentKey.rawValue: departmentKey] as [String: Any] let urlString = baseURL + ServerPathSuffix.categories.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func getStructure(categoryId: String, completion: @escaping (_ faqStructure: Data?) throws -> ()) { let dataToPost = [Parameter.categoryId.rawValue: categoryId] as [String: Any] let urlString = baseURL + ServerPathSuffix.structure.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func search(query: String, categoryId: String, limit: Int, completion: @escaping (_ data: Data?) throws -> ()) { let dataToPost = [Parameter.categoryId.rawValue: categoryId, Parameter.query.rawValue: query, Parameter.limit.rawValue: limit] as [String: Any] let urlString = baseURL + ServerPathSuffix.search.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func like(itemId: String, completion: @escaping (_ data: Data?) throws -> ()) { let dataToPost = [Parameter.itemId.rawValue: itemId, Parameter.userId.rawValue: FAQActions.deviceID] as [String: Any] let urlString = baseURL + ServerPathSuffix.like.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func dislike(itemId: String, completion: @escaping (_ data: Data?) throws -> ()) { let dataToPost = [Parameter.itemId.rawValue: itemId, Parameter.userId.rawValue: FAQActions.deviceID] as [String: Any] let urlString = baseURL + ServerPathSuffix.dislike.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, baseURLString: urlString, faqCompletionHandler: completion)) } func track(itemId: String, openFrom: FAQItemSource) { let source: String switch openFrom { case .search: source = "search" case .tree: source = "tree" } let dataToPost = [Parameter.itemId.rawValue: itemId, Parameter.open.rawValue: source] as [String: Any] let urlString = baseURL + ServerPathSuffix.track.rawValue faqRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, baseURLString: urlString)) } }
mit
d69e6380dc4c8df2377af63a8b21c95e
42.768421
91
0.54305
5.467456
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/IndustryJobCell.swift
2
4116
// // IndustryJobCell.swift // Neocom // // Created by Artem Shimanski on 11/9/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI import TreeController class IndustryJobCell: RowCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var jobRunsLabel: UILabel! @IBOutlet weak var runsPerCopyLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() let layer = self.progressView.superview?.layer; layer?.borderColor = UIColor(number: 0x3d5866ff).cgColor layer?.borderWidth = 1.0 / UIScreen.main.scale } } extension Prototype { enum IndustryJobCell { static let `default` = Prototype(nib: UINib(nibName: "IndustryJobCell", bundle: nil), reuseIdentifier: "IndustryJobCell") } } extension Tree.Item { class IndustryJobRow: RoutableRow<ESI.Industry.Job> { override var prototype: Prototype? { return Prototype.IndustryJobCell.default } let location: EVELocation? lazy var type: SDEInvType? = Services.sde.viewContext.invType(content.blueprintTypeID) lazy var activity: SDERamActivity? = Services.sde.viewContext.ramActivity(content.activityID) init(_ content: ESI.Industry.Job, location: EVELocation?) { self.location = location super.init(content, route: Router.SDE.invTypeInfo(.typeID(content.blueprintTypeID))) } override func configure(cell: UITableViewCell, treeController: TreeController?) { super.configure(cell: cell, treeController: treeController) guard let cell = cell as? IndustryJobCell else {return} cell.titleLabel.text = type?.typeName ?? NSLocalizedString("Unknown Type", comment: "") cell.subtitleLabel.attributedText = (location ?? .unknown).displayName cell.iconView.image = type?.icon?.image?.image ?? Services.sde.viewContext.eveIcon(.defaultType)?.image?.image let activity = self.activity?.activityName ?? NSLocalizedString("Unknown Activity", comment: "") let t = content.endDate.timeIntervalSinceNow let status = content.currentStatus let s: String switch status { case .active: cell.progressView.progress = 1.0 - Float(t / TimeInterval(content.duration)) s = "\(TimeIntervalFormatter.localizedString(from: max(t, 0), precision: .minutes)) (\(Int(cell.progressView.progress * 100))%)" case .cancelled: s = "\(NSLocalizedString("cancelled", comment: "")) \(DateFormatter.localizedString(from: content.endDate, dateStyle: .short, timeStyle: .short))" cell.progressView.progress = 0 case .delivered: s = "\(NSLocalizedString("delivered", comment: "")) \(DateFormatter.localizedString(from: content.endDate, dateStyle: .short, timeStyle: .short))" cell.progressView.progress = 1 case .paused: s = "\(NSLocalizedString("paused", comment: "")) \(DateFormatter.localizedString(from: content.endDate, dateStyle: .short, timeStyle: .short))" cell.progressView.progress = 0 case .ready: s = "\(NSLocalizedString("ready", comment: "")) \(DateFormatter.localizedString(from: content.endDate, dateStyle: .short, timeStyle: .short))" cell.progressView.progress = 1 case .reverted: s = "\(NSLocalizedString("reverted", comment: "")) \(DateFormatter.localizedString(from: content.endDate, dateStyle: .short, timeStyle: .short))" cell.progressView.progress = 0 } cell.stateLabel.attributedText = "\(activity): " * [NSAttributedString.Key.foregroundColor: UIColor.white] + s * [NSAttributedString.Key.foregroundColor: UIColor.lightText] cell.jobRunsLabel.text = UnitFormatter.localizedString(from: content.runs, unit: .none, style: .long) cell.runsPerCopyLabel.text = UnitFormatter.localizedString(from: content.licensedRuns ?? 0, unit: .none, style: .long) let color = status == .active || status == .ready ? UIColor.white : UIColor.lightText cell.titleLabel.textColor = color cell.jobRunsLabel.textColor = color cell.runsPerCopyLabel.textColor = color } } }
lgpl-2.1
17ef04a4f7d71f766896b26d07d6e459
40.989796
175
0.731956
3.926527
false
true
false
false
michael-yuji/spartanX
Sources/SXClient.swift
2
4243
// Copyright (c) 2016, Yuji // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 6/2/16. // Copyright © 2016 yuuji. All rights reserved. // import struct Foundation.Data import xlibc public struct ClientFunctions<ClientSocketType> { var read: (ClientSocketType, Int) throws -> Data? var write: (ClientSocketType, _ data: Data) throws -> () var clean: ((ClientSocketType) -> ())? } public struct SXClientSocket : ClientSocket { public var readMethod: (SXClientSocket, Int) throws -> Data? public var writeMethod: (SXClientSocket, Data) throws -> () public var sockfd: Int32 public var domain: SocketDomains public var type: SocketTypes public var `protocol`: Int32 public var address: SXSocketAddress? public var recvFlags: Int32 = 0 public var sendFlags: Int32 = 0 internal init(fd: Int32, addrinfo: (addr: sockaddr, len: socklen_t), sockinfo: (type: SocketTypes, `protocol`: Int32), functions: ClientFunctions<SXClientSocket> ) throws { self.address = try SXSocketAddress(addrinfo.addr, socklen: addrinfo.len) self.sockfd = fd switch Int(addrinfo.len) { case MemoryLayout<sockaddr_in>.size: self.domain = .inet case MemoryLayout<sockaddr_in6>.size: self.domain = .inet6 case MemoryLayout<sockaddr_un>.size: self.domain = .unix default: throw SocketError.socket("Unknown domain") } self.type = sockinfo.type self.`protocol` = sockinfo.`protocol` self.readMethod = functions.read self.writeMethod = functions.write } } public extension SXClientSocket { public static let standardIOHandlers: ClientFunctions = ClientFunctions(read: { (client: Socket & Readable, availableCount: Int) throws -> Data? in return client.isBlocking ? try client.recv_block(size: availableCount) : try client.recv_nonblock(size: availableCount) }, write: { (client: Socket & Writable, data: Data) throws -> () in if send(client.sockfd, data.bytes, data.length, 0) == -1 { throw SocketError.send("send: \(String.errno)") } }) { (_ client: SXClientSocket) in } public var addressString: String? { return self.address?.address } public func write(data: Data) throws { try self.writeMethod(self, data) } public func read(size: Int) throws -> Data? { return try self.readMethod(self, size) } public func done() { close(self.sockfd) } }
bsd-2-clause
b48b47a7985bd8d55f2c30fce0eddbab
36.539823
151
0.668553
4.368692
false
false
false
false
suragch/Chimee-iOS
Chimee/FavoriteDataHelper.swift
1
6380
import SQLite class FavoriteDataHelper: DataHelperProtocol { static let FAVORITE_MESSAGE_TABLE_NAME = "favorite" // favorite table static let favoriteMessageTable = Table(FAVORITE_MESSAGE_TABLE_NAME) static let favoriteId = Expression<Int64>("_id") static let favoriteDate = Expression<Int64>("datetime") static let favoriteMessage = Expression<String>("message") typealias T = Message static func createTable() throws { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } // create table do { let _ = try db.run( favoriteMessageTable.create(ifNotExists: false) {t in t.column(favoriteId, primaryKey: true) t.column(favoriteDate) t.column(favoriteMessage) }) } catch _ { // Error throw if table already exists // FIXME: This is relying on throwing an error every time. Perhaps not the best. http://stackoverflow.com/q/37185087 //print("favorite database was already created") return } // insert initial data do { try insertInitialFavoritesData() } catch _ { print("Initialization error") } } static func insertInitialFavoritesData() throws { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } // reverse order that they will appear in // TODO: get better mongol descriptions let data = [ //"ᠲᠦᠯᠬᠢᠭᠡᠳ ᠠᠷᠢᠯᠭᠠᠬᠤ", // Swipe up to delete //"ᠳᠣᠶ᠋ᠢᠭᠠᠳ ᠣᠷᠤᠭᠤᠯᠬᠤ", //Tap to insert "ᠰᠠᠢᠨ ᠪᠠᠢᠨ᠎ᠠ ᠤᠤ?" ] do { // insert initial favorite messages try db.transaction { var extraSeconds = 0 // so that messages will be ordered by time for item in data { let dateTime = Int64(NSDate().timeIntervalSince1970) + extraSeconds let _ = try db.run(favoriteMessageTable.insert(favoriteDate <- dateTime, favoriteMessage <- item)) extraSeconds += 1 } } } catch _ { print("insert error with favorite initialization") throw DataAccessError.insert_Error } } static func insert(_ item: T) throws -> Int64 { // error checking guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } guard let dateToInsert = item.dateTime, let messageToInsert = item.messageText else { throw DataAccessError.nil_In_Data } // do the insert let insert = favoriteMessageTable.insert(favoriteDate <- dateToInsert, favoriteMessage <- messageToInsert) do { let rowId = try db.run(insert) guard rowId > 0 else { throw DataAccessError.insert_Error } return rowId } catch _ { throw DataAccessError.insert_Error } } static func insertMessage(_ messageToInsert: String) throws -> Int64 { // error checking guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } // do the insert let dateToInsert = Int64(NSDate().timeIntervalSince1970) let insert = favoriteMessageTable.insert(favoriteDate <- dateToInsert, favoriteMessage <- messageToInsert) do { let rowId = try db.run(insert) guard rowId > 0 else { throw DataAccessError.insert_Error } return rowId } catch _ { throw DataAccessError.insert_Error } } static func updateTimeForFavorite(_ messageText: String) throws { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } do { try db.transaction { let currentTime = Int64(NSDate().timeIntervalSince1970) let myMessage = favoriteMessageTable.filter(favoriteMessage == messageText) if try db.run(myMessage.update(favoriteDate <- currentTime)) > 0 { //print("updated time") } } } catch _ { print("some sort of error was thrown") throw DataAccessError.insert_Error // is this the best error to throw? } } static func delete(_ item: T) throws -> Void { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } if let id = item.messageId { let query = favoriteMessageTable.filter(favoriteId == id) do { let tmp = try db.run(query.delete()) guard tmp == 1 else { throw DataAccessError.delete_Error } } catch _ { throw DataAccessError.delete_Error } } } static func findAll() throws -> [T]? { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } var retArray = [T]() do { let query = favoriteMessageTable.order(favoriteDate.desc) let items = try db.prepare(query) for item in items { retArray.append(Message(messageId: item[favoriteId], dateTime: item[favoriteDate], messageText: item[favoriteMessage])) } } catch _ { throw DataAccessError.search_Error } return retArray } }
mit
dc44afe76836d54b585874f74723846d
28.810427
135
0.541494
4.808869
false
false
false
false
asbhat/stanford-ios10-apps
Calculator/Calculator/CalculatorBrain.swift
1
9174
// // CalculatorBrain.swift // Calculator // // Created by Aditya Bhat on 6/6/17. // Copyright © 2017 Aditya Bhat. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation struct CalculatorBrain { // structs have no inheritance (classes do) // are passed by value (classes are passed by reference) // automatically initialized (classes need an initializer) // need to mark funcs as 'mutating' if modifies the struct (don't need to in classes) private enum Operation { case constant(Double) case nullaryOperation(() -> Double) case unaryOperation((Double) -> Double) case unaryOperationWithCheck(((Double) -> String?), ((Double) -> Double)) case binaryOperation((Double, Double) -> Double) case binaryOperationWithCheck(((Double) -> String?), ((Double, Double) -> Double)) case equals } private enum SequenceItem { case operand((value: Double, text: String)) case operation(String) case variable(String) } private let descriptionFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 1 return formatter }() // Better way to do constants private struct OperandFormat { static let maximumDecimalPlaces = 6 } private var sequence = [SequenceItem]() private var operations: Dictionary<String, Operation> = [ "π" : Operation.constant(Double.pi), "e" : Operation.constant(M_E), "Rand" : Operation.nullaryOperation({ Double(arc4random()) / Double(UINT32_MAX) }), "√" : Operation.unaryOperationWithCheck({ ErrorChecks.forNegativeRoot(of: $0) }, sqrt), "∛" : Operation.unaryOperation({ pow($0, 1.0/3.0) }), "sin" : Operation.unaryOperation(sin), "cos" : Operation.unaryOperation(cos), "±" : Operation.unaryOperation({ -$0 }), "%" : Operation.unaryOperation({ $0 / 100.0 }), "x²" : Operation.unaryOperation({ pow($0, 2) }), "x³" : Operation.unaryOperation({ pow($0, 3) }), "×" : Operation.binaryOperation({ $0 * $1 }), "÷" : Operation.binaryOperationWithCheck({ ErrorChecks.forDivideByZero(with: $0) }, { $0 / $1 }), "+" : Operation.binaryOperation({ $0 + $1 }), "-" : Operation.binaryOperation({ $0 - $1 }), "=" : Operation.equals ] mutating func performOperation(_ symbol: String) { sequence.append(.operation(symbol)) } mutating func setOperand(_ operand: Double) { descriptionFormatter.maximumFractionDigits = operand.remainder(dividingBy: 1) == 0 ? 0 : OperandFormat.maximumDecimalPlaces sequence.append(.operand((value: operand, text: descriptionFormatter.string(from: NSNumber(value: operand))!))) } mutating func setOperand(variable named: String) { sequence.append(.variable(named)) } func evaluate(using variables: [String : Double]? = nil) -> (result: Double?, isPending: Bool, description: String, errorMessage: String?) { var result: (value: Double?, text: String?) = (0, "0") var description = "" var errorMessage: String? var pendingBinaryOperation: PendingBinaryOperation? var isPending: Bool { return pendingBinaryOperation != nil } func evaluate(_ sequence: [SequenceItem]) { for item in sequence { switch item { case .operand(let (value, text)): result = (value, text) if (!isPending) { description = result.text! } case .operation(let symbol): evaluate(operation: symbol) case .variable(let name): result = (variables?[name] ?? 0, name) } } } func evaluate(operation symbol: String) { if let operation = operations[symbol] { switch operation { case .constant(let value): result = (value, symbol) if (!isPending) { description = result.text! } case .nullaryOperation(let function): result = (function(), "\(symbol)()") if (!isPending) { description = result.text! } case .unaryOperationWithCheck(let check, let function): if let value = result.value { errorMessage = check(value) } evaluate(unary: function, having: symbol) case .unaryOperation(let function): evaluate(unary: function, having: symbol) case .binaryOperationWithCheck(let check, let function): evaluate(binary: function, having: symbol) pendingBinaryOperation?.check = check case .binaryOperation(let function): evaluate(binary: function, having: symbol) case .equals: evaluatePendingBinaryOperation() } } } func evaluate(unary function: ((Double) -> Double), having symbol: String) { if let oldResult = result.value { let oldText = result.text! result = (function(oldResult), "\(symbol)(\(oldText))") if (!isPending) { description = result.text! } else { if description.hasSuffix(oldText) { description = description.replace(ending: oldText, with: result.text!)! } else { description += " \(result.text!)" } } } } func evaluate(binary function: @escaping ((Double, Double) -> Double), having symbol: String) { if result.value != nil { evaluatePendingBinaryOperation() description = "\(result.text!) \(symbol)" pendingBinaryOperation = PendingBinaryOperation(function: function, firstOperand: result.value!, check: nil) result = (nil, nil) } } func evaluatePendingBinaryOperation() { if pendingBinaryOperation != nil && result.value != nil { if !description.hasSuffix(" \(result.text!)") { description += " \(result.text!)" } if let checkFunction = pendingBinaryOperation!.check { errorMessage = checkFunction(result.value!) } result = (pendingBinaryOperation!.evaluate(with: result.value!), description) pendingBinaryOperation = nil } } struct PendingBinaryOperation { let function: (Double, Double) -> Double let firstOperand: Double var check: ((Double) -> String?)? func evaluate(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } evaluate(sequence) return (result.value, isPending, description, errorMessage) } @available(*, deprecated, message: "Please use evaluate().result going forward") var result: Double? { return evaluate().result } @available(*, deprecated, message: "Please use evaluate().isPending going forward") var resultIsPending: Bool { return evaluate().isPending } @available(*, deprecated, message: "Please use evaluate().description going forward") var description: String { return evaluate().description } mutating func clear() { sequence.removeAll() } mutating func undo() { if (sequence.count > 0) { sequence.removeLast() } } } private struct ErrorChecks { static func forNegativeRoot(of operand: Double) -> String? { guard operand < 0 else { return nil } return "Error! root of \(String(operand)) is not \'real\'" } static func forDivideByZero(with divisor: Double) -> String? { guard divisor == 0 else { return nil } return "Error! cannot divide by zero" } } private extension String { func replace(ending: String, with replacement: String) -> String? { guard self.hasSuffix(ending) else { return nil } return String(self.dropLast(ending.count)) + replacement } }
apache-2.0
9dcc14e3ed06e55ebc8d37ae88e60b1a
37.020747
144
0.568591
4.832806
false
false
false
false
slepcat/mint
MINT/MintPort.swift
1
9153
// // MintPort.swift // mint // // Created by NemuNeko on 2015/10/11. // Copyright © 2015年 Taizo A. All rights reserved. // import Foundation import Cocoa class Mint3DPort : MintPort, MintSubject { struct Mesh { var vexes: [Float] = [] var normals: [Float] = [] var colors: [Float] = [] var alphas: [Float] = [] } struct Lines { var vexes: [Float] = [] var normals: [Float] = [] var colors: [Float] = [] var alphas: [Float] = [] } var portid : UInt = 0 var portidlist : [UInt] = [] var obs : [MintObserver] = [] var mesh : Mesh? = nil var lines : Lines? = nil var viewctrl : MintModelViewController? = nil override func write(_ data: SExpr, uid: UInt){ portid = uid // accumulator for polygons var acc: [Double] = [] var acc_normal: [Double] = [] var acc_color: [Float] = [] var acc_alpha: [Float] = [] // accumulator for lines var ln_acc: [Double] = [] var ln_acc_normal: [Double] = [] var ln_acc_color: [Float] = [] var ln_acc_alpha: [Float] = [] let args = delayed_list_of_values(data) for arg in args { let elms = delayed_list_of_values(arg) for elm in elms { if let p = elm as? MPolygon { let vertices = p.value.vertices if vertices.count == 3 { for vertex in vertices { acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z] acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z] acc_color += vertex.color acc_alpha += [vertex.alpha] } } else if vertices.count > 3 { // if polygon is not triangle, split it to triangle polygons //if polygon.checkIfConvex() { let triangles = p.value.triangulationConvex() for tri in triangles { for vertex in tri.vertices { acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z] acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z] acc_color += vertex.color acc_alpha += [vertex.alpha] } } } } else if let l = elm as? MLineSeg { // implement line let ln = l.value ln_acc += [ln.from.pos.x, ln.from.pos.y, ln.from.pos.z, ln.to.pos.x, ln.to.pos.y, ln.to.pos.z] ln_acc_normal += [ln.from.normal.x, ln.from.normal.y, ln.from.normal.z, ln.to.normal.x, ln.to.normal.y, ln.to.normal.z] ln_acc_color += ln.from.color + ln.to.color ln_acc_alpha += [ln.from.alpha, ln.to.alpha] } } } mesh = Mesh(vexes: d2farray(acc), normals: d2farray(acc_normal), colors: acc_color, alphas: acc_alpha) lines = Lines(vexes: d2farray(ln_acc), normals: d2farray(ln_acc_normal), colors: ln_acc_color, alphas: ln_acc_alpha) } override func update() { for o in obs { o.update(self, uid: portid) } viewctrl?.setNeedDisplay() } func mesh_vex() -> [Float] { if let m = mesh { return m.vexes } return [] } func mesh_normal() -> [Float] { if let m = mesh { return m.normals } return [] } func mesh_color() -> [Float] { if let m = mesh { return m.colors } return [] } func mesh_alpha() -> [Float] { if let m = mesh { return m.alphas } return [] } func line_vex() -> [Float] { if let l = lines { return l.vexes } return [] } func line_normal() -> [Float] { if let l = lines { return l.normals } return [] } func line_color() -> [Float] { if let l = lines { return l.colors } return [] } func line_alpha() -> [Float] { if let l = lines { return l.alphas } return [] } func registerObserver(_ observer: MintObserver) { obs.append(observer) } func removeObserver(_ observer: MintObserver) { for i in 0..<obs.count { if obs[i] === observer { obs.remove(at: i) break } } } override func create_port(_ uid: UInt) { //if the portid is arleady exist, exit func. for id in portidlist { if id == uid { return } } if let _mesh = viewctrl?.addMesh(uid), let _lines = viewctrl?.addLines(uid) { registerObserver(_mesh) registerObserver(_lines) portidlist.append(uid) } } override func remove_port(_ uid: UInt) { for i in 0..<portidlist.count { if portidlist[i] == uid { if let mesh = viewctrl?.removeMesh(portidlist[i]), let lines = viewctrl?.removeLines(portidlist[i]) { removeObserver(mesh) removeObserver(lines) } portidlist.remove(at: i) break } } } } class MintErrPort : MintPort, MintSubject { var portid : UInt = 0 var obs : [MintObserver] = [] var err : String = "" override func write(_ data: SExpr, uid: UInt){ if let errmsg = data as? MStr { err = errmsg.value portid = uid } } override func update() { for o in obs { o.update(self, uid: portid) } } func registerObserver(_ observer: MintObserver) { obs.append(observer) } func removeObserver(_ observer: MintObserver) { for i in 0..<obs.count { if obs[i] === observer { obs.remove(at: i) break } } } } class MintImportPort : MintReadPort { override func read(_ path: String, uid: UInt) -> SExpr { if let delegate = NSApplication.shared().delegate as? AppDelegate { if let url = getLibPath(path, docpath: delegate.workspace.fileurl?.deletingLastPathComponent().path) { let coordinator = NSFileCoordinator(filePresenter: delegate.workspace) let error : NSErrorPointer = nil var output = "" coordinator.coordinate(readingItemAt: url, options: .withoutChanges, error: error) { (fileurl: URL) in do { output = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) as String } catch { print("fail to open", terminator:"\n") return } } // load mint file. and unwrap "_pos_" expression let interpreter : MintInterpreter = delegate.controller.interpreter var acc : [SExpr] = [] for exp in interpreter.readfile(fileContent: output) { if let pair = exp as? Pair { let posunwrap = MintPosUnwrapper(expr: pair) acc.append(posunwrap.unwrapped) } else { acc.append(exp) } } return list_from_array(acc) } } return MNull() } private func getLibPath(_ path: String, docpath: String?) -> URL? { if FileManager.default.fileExists(atPath: path) { return URL(fileURLWithPath: path) } else { let bundle = Bundle.main if let libpath = bundle.path(forResource: path, ofType: "mint") { return URL(fileURLWithPath: libpath) } else if let dirpath = docpath { if FileManager.default.fileExists(atPath: dirpath + path) { return URL(fileURLWithPath: dirpath + path) } } } return nil } }
gpl-3.0
508dd5419d6cbdbf82614c54d1e32902
28.326923
124
0.439454
4.568148
false
false
false
false
godenzim/NetKit
NetKit/Common/XML/XMLElement.swift
1
7411
// // XMLElement.swift // NetKit // // Created by Mike Godenzi on 28.09.14. // Copyright (c) 2014 Mike Godenzi. All rights reserved. // import Foundation public protocol XMLInitializable { init?(xml : XMLElement); } public class XMLElement { public final weak var parent : XMLElement? public final let name : String public var text : String? { return nil } public var attributes : [String:String]? { return nil } public var children : [XMLElement]? { return nil } public required init(name : String) { self.name = name } private final class func XMLElementWithElement(element : XMLElement) -> XMLElement { var result : XMLElement? let hasText = element.text != nil && (element.text!).characters.count > 0 let hasChildren = element.children != nil && element.children!.count > 0 let hasAttributes = element.attributes != nil && element.attributes!.count > 0 switch (hasText, hasChildren, hasAttributes) { case (true, false, false): result = XMLLeaf(name: element.name, text: element.text!) case (false, true, false): result = XMLList(name: element.name, children: element.children!) case (false, false, true): result = XMLEmpty(name: element.name, attributes: element.attributes!) default: result = element } return result! } } extension XMLElement { public final func elementAtPath(path : String) -> XMLElement? { var result : XMLElement? = nil let components = path.componentsSeparatedByString(".") let count = components.count var current : Int = 0 let first = components[current] if first.isEmpty || first == self.name { current++ } if current < count { var match : XMLElement? = self repeat { if let _children = match?.children { match = nil for element in _children { if element.name == components[current] { match = element break } } } } while (match != nil && ++current < count) result = match } return result } public final func elementsAtPath(path : String) -> [XMLElement] { var result = [XMLElement]() let components = path.componentsSeparatedByString(".") let count = components.count var current : Int = 0 let first = components[current] if first.isEmpty || first == self.name { current++ } if current < count { var matches = [self] repeat { var tmp = [XMLElement]() for element in matches { if let children = element.children { tmp += children.filter { $0.name == components[current] } } } matches = tmp } while (matches.count > 0 && ++current < count) result += matches } return result } public final func XMLElementWithContentsOfFile(file : String) -> XMLElement? { var result : XMLElement? if let data = NSData(contentsOfFile: file) { do { result = try XMLParser.parse(data) } catch { result = nil } } return result } public subscript(index : Int) -> XMLElement? { get { var result : XMLElement? = nil if let _children = children { if index < _children.count { result = _children[index] } } return result } } public subscript(key : String) -> XMLElement? { get { return elementAtPath(key) } } } extension XMLElement { public final class func XMLElementWithContentsOfFile(path : String) -> XMLElement? { var result : XMLElement? if let data = NSData(contentsOfFile: path) { do { result = try XMLParser.parse(data) } catch { result = nil } } return result } public final class func XMLElementWithData(data : NSData) throws -> XMLElement { return try XMLParser.parse(data) } } extension XMLElement : CustomStringConvertible { public var description : String { get { let attributes = self.attributes?.description ?? "" let text = self.text ?? "" let children = self.children?.description ?? "" return "<\(name) \(attributes)>\(text)</\(name)>\n\(children)" } } } private final class XMLFull : XMLElement { private var _text : String? private override var text : String? { get { return _text; } set { _text = newValue } } private var _attributes : [String:String]? private override var attributes : [String:String]? { get { return _attributes } set { _attributes = newValue } } private var _children : [XMLElement]? = [XMLElement]() private override var children : [XMLElement]? { get { return _children } set { _children = newValue } } private convenience init(name : String, text : String, attributes : [String:String], children : [XMLElement]) { self.init(name: name) self._text = text self._attributes = attributes self._children = children } private func addChild(child : XMLElement) { _children?.append(child) } } private final class XMLLeaf : XMLElement { private var _text : String = "" private override var text : String? { return _text; } private convenience init(name : String, text : String) { self.init(name: name) self._text = text } } private final class XMLEmpty : XMLElement { private var _attributes = [String:String]() private override var attributes : [String:String] { return _attributes } private convenience init(name: String, attributes : [String:String]) { self.init(name: name) self._attributes = attributes } } private final class XMLList : XMLElement { private var _children = [XMLElement]() private override var children : [XMLElement] { return _children } private convenience init(name: String, children : [XMLElement]) { self.init(name: name) self._children = children } private func addChild(child : XMLElement) { _children.append(child) } } public enum XMLParserError : ErrorType { case Unknown } public final class XMLParser : NSObject { private var root : XMLElement? private var current : XMLElement? private var parents = [XMLElement]() private lazy var parser : NKXMLParser = NKXMLParser(delegate: self)! public var error : NSError? { let result : NSError? = self.parser.error return result } public func parse(data : NSData) { self.parser.parse(data) } public func end() -> XMLElement? { self.parser.end() return self.root } public class func parse(data : NSData) throws -> XMLElement { let parser = XMLParser() parser.parse(data) let result = parser.end() if let error = parser.error { throw error } guard let value = result else { throw XMLParserError.Unknown } return value } } extension XMLParser : NKXMLParserDelegate { public func parser(parser: NKXMLParser!, didStartElement name: String!, withAttributes attributes: [NSObject : AnyObject]!) { let current = XMLFull(name: name) current.attributes = attributes as? [String:String] if root != nil { if let current = self.current { parents.append(current) } current.parent = self.current self.current = current } else { root = current self.current = current } } public func parser(parser: NKXMLParser!, didEndElement name: String!, withText text: String!) { if let _current = self.current as? XMLFull { _current.text = text self.current = XMLElement.XMLElementWithElement(_current) if let _parent = _current.parent as? XMLFull { _parent._children?.append(self.current!) self.current!.parent = _parent } } self.current = self.current?.parent if self.parents.count > 0 && self.current != nil { self.parents.removeLast() } } }
mit
b263b04cff12c2a579f5fb02961ba17b
22.087227
126
0.66941
3.510658
false
false
false
false
propellerlabs/PropellerNetwork
Source/QueryStringEncoder.swift
1
1581
// // QueryStringEncoder.swift // PropellerNetwork // // Created by Roy McKenzie on 1/18/17. // Copyright © 2017 Propeller. All rights reserved. // import Foundation public struct QueryStringEncoder: ParameterEncoding { public static var `default`: QueryStringEncoder = QueryStringEncoder() public func encode(_ request: URLRequest, parameters: Parameters) throws -> URLRequest { var request = request var queryItems = parameters.flatMap { URLQueryItem(name: $0.key, value: "\($0.value)") } if let url = request.url { var components = URLComponents(url: url, resolvingAgainstBaseURL: false) let baseString = url.absoluteString if let currentQueryItems = components?.queryItems { queryItems.append(contentsOf: currentQueryItems) } components?.queryItems = queryItems if let queryString = components?.query { let escapedQueryString = escape(queryString) let newUrl = URL(string: "\(baseString)?\(escapedQueryString)") request.url = newUrl } } return request } public func escape(_ string: String) -> String { var allowedCharacters = NSCharacterSet.urlQueryAllowed allowedCharacters.remove(charactersIn: "+@") let newString = string.addingPercentEncoding(withAllowedCharacters: allowedCharacters) return newString ?? string } }
mit
e0b2c6949059644be665376c90d85bf0
31.916667
94
0.605063
5.663082
false
false
false
false
glessard/swift-channels
utilities/shuffle.swift
1
1444
// // shuffle.swift // // Created by Guillaume Lessard on 2014-08-28. // Copyright (c) 2014 Guillaume Lessard. All rights reserved. // import Darwin /** Get a sequence/generator that will return a collection's elements in a random order. The input collection is not modified in any way. */ func shuffle<C: CollectionType>(c: C) -> PermutationGenerator<C, AnySequence<C.Index>> { return PermutationGenerator(elements: c, indices: AnySequence(IndexShuffler(c.indices))) } /** A stepwise implementation of the Knuth Shuffle (a.k.a. Fisher-Yates Shuffle), using a sequence of indices as its input. */ struct IndexShuffler<I: ForwardIndexType>: SequenceType, GeneratorType { private var i: [I] private let count: Int private var step = -1 init<S: SequenceType where S.Generator.Element == I>(_ input: S) { self.init(Array(input)) } init(_ input: Range<I>) { self.init(Array(input)) } init(_ input: Array<I>) { i = input count = input.count } mutating func next() -> I? { step += 1 if step < count { // select a random Index from the rest of the array let j = step + Int(arc4random_uniform(UInt32(count-step))) // swap that Index with the one at the current step in the array swap(&i[j], &i[step]) // return the new random Index. return i[step] } return nil } func generate() -> IndexShuffler { return self } }
mit
5e40bd4ed92a70d5ada735207c4777fe
19.628571
90
0.65097
3.61
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/ConversationList/ZMConversationListTests+Labels.swift
1
3890
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @testable import WireDataModel final class ZMConversationListTests_Labels: ZMBaseManagedObjectTest { var dispatcher: NotificationDispatcher! override func setUp() { super.setUp() dispatcher = NotificationDispatcher(managedObjectContext: uiMOC) } override func tearDown() { dispatcher.tearDown() dispatcher = nil super.tearDown() } func testThatAddingAConversationToFavoritesMovesItToFavoriteConversationList() { // given let favoriteList = uiMOC.conversationListDirectory().favoriteConversations let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.conversationType = .oneOnOne conversation.lastModifiedDate = Date() XCTAssertTrue(uiMOC.saveOrRollback()) XCTAssertEqual(favoriteList.count, 0) // when conversation.isFavorite = true XCTAssertTrue(uiMOC.saveOrRollback()) // then XCTAssertEqual(favoriteList.count, 1) } func testThatRemovingAConversationFromFavoritesRemovesItFromFavoriteConversationList() { // given let favoriteList = uiMOC.conversationListDirectory().favoriteConversations let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.conversationType = .oneOnOne conversation.lastModifiedDate = Date() conversation.isFavorite = true XCTAssertTrue(uiMOC.saveOrRollback()) XCTAssertEqual(favoriteList.count, 1) // when conversation.isFavorite = false XCTAssertTrue(uiMOC.saveOrRollback()) // then XCTAssertEqual(favoriteList.count, 0) } func testThatAddingAConversationToFolderMovesItToFolderConversationList() { // given let folder = uiMOC.conversationListDirectory().createFolder("folder 1")! let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.conversationType = .oneOnOne conversation.lastModifiedDate = Date() XCTAssertTrue(uiMOC.saveOrRollback()) XCTAssertEqual(uiMOC.conversationListDirectory().conversations(by: .folder(folder)).count, 0) // when conversation.moveToFolder(folder) XCTAssertTrue(uiMOC.saveOrRollback()) // then XCTAssertEqual(uiMOC.conversationListDirectory().conversations(by: .folder(folder)).count, 1) } func testThatRemovingAConversationFromAFolderRemovesItFromTheFolderConversationList() { // given let folder = uiMOC.conversationListDirectory().createFolder("folder 1")! let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.conversationType = .oneOnOne conversation.lastModifiedDate = Date() conversation.moveToFolder(folder) XCTAssertTrue(uiMOC.saveOrRollback()) XCTAssertEqual(uiMOC.conversationListDirectory().conversations(by: .folder(folder)).count, 1) // when conversation.removeFromFolder() XCTAssertTrue(uiMOC.saveOrRollback()) // then XCTAssertEqual(uiMOC.conversationListDirectory().conversations(by: .folder(folder)).count, 0) } }
gpl-3.0
a594539b92342eab494deedfbd6f06c9
35.35514
101
0.706941
5.228495
false
true
false
false
hoomazoid/CTSlidingUpPanel
Example/CTSlidingUpPanel/ViewController.swift
1
2055
// // ViewController.swift // CTBottomSlideController // // Created by Gio Andriadze on 6/29/17. // Copyright © 2017 Casatrade Ltd. All rights reserved. // import UIKit import CTSlidingUpPanel class ViewController: UIViewController, CTBottomSlideDelegate{ @IBOutlet weak var bottomView: UIView! var bottomController:CTBottomSlideController?; override func viewDidLoad() { super.viewDidLoad() bottomController = CTBottomSlideController(parent: view, bottomView: bottomView, tabController: self.tabBarController!, navController: self.navigationController, visibleHeight: 64) bottomController?.setAnchorPoint(anchor: 0.7) bottomController?.delegate = self; bottomController?.onPanelExpanded = { print("Panel Expanded in closure") } bottomController?.onPanelCollapsed = { print("Panel Collapsed in closure") } bottomController?.onPanelMoved = { offset in print("Panel moved in closure " + offset.description) } //Uncomment to specify top margin on expanded panel //bottomController?.setExpandedTopMargin(pixels: 100) if bottomController?.currentState == .collapsed { //do anything, i don't care } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) bottomController?.viewWillTransition(to: size, with: coordinator) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didPanelCollapse() { print("Collapsed"); } func didPanelExpand(){ print("Expanded") } func didPanelAnchor(){ print("Anchored") } func didPanelMove(panelOffset: CGFloat) { print(panelOffset); } }
mit
c27ddbbd25a65673f9156e62fbb19c10
25.675325
188
0.639727
5.096774
false
false
false
false
VitoNYang/VTAutoSlideView
VTAutoSlideViewDemo/UseInStoryboardViewController.swift
1
1648
// // UseInStoryboardViewController.swift // VTAutoSlideViewDemo // // Created by hao on 2017/2/7. // Copyright © 2017年 Vito. All rights reserved. // import UIKit import VTAutoSlideView class UseInStoryboardViewController: UIViewController { @IBOutlet weak var slideView: VTAutoSlideView! @IBOutlet weak var pageControl: UIPageControl! lazy var imageList = { (1...4).compactMap { UIImage(named: "0\($0)") } }() override func viewDidLoad() { super.viewDidLoad() func setupSlideView() { slideView.register(nib: UINib(nibName: "DisplayImageCell", bundle: nibBundle)) slideView.dataSource = self slideView.delegate = self slideView.dataList = imageList slideView.autoChangeTime = 1 } func setupPageControl() { pageControl.numberOfPages = imageList.count pageControl.currentPage = 0 } setupSlideView() setupPageControl() } } extension UseInStoryboardViewController: VTAutoSlideViewDataSource { func configuration(cell: UICollectionViewCell, for index: Int) { guard let cell = cell as? DisplayImageCell else { return } cell.imageView.image = imageList[index] } } extension UseInStoryboardViewController: VTAutoSlideViewDelegate { func slideView(_ slideView: VTAutoSlideView, didSelectItemAt currentIndex: Int) { print("click > \(currentIndex)") } func slideView(_ slideView: VTAutoSlideView, currentIndex: Int) { pageControl.currentPage = currentIndex } }
mit
05eb2c32fbb4006ce863b1cc5882c463
26.416667
90
0.645593
4.838235
false
false
false
false
melsomino/unified-ios
Unified/Library/UIKitExtensions.swift
1
2895
// // Created by Власов М.Ю. on 08.06.16. // Copyright (c) 2016 Tensor. All rights reserved. // import Foundation import UIKit extension UIViewController { public var wrapper: UIViewController { if let split = splitViewController { return split } if let navigation = navigationController { return navigation } return self } public func unwrap<T>() -> T { switch self { case let target as T: return target case let navigation as UINavigationController: return navigation.topViewController!.unwrap() as T case let split as UISplitViewController: return split.childViewControllers[0].unwrap() as T default: fatalError("can not unwrap controller to \(String(T.self))") } } } public class SplitControllerFix: UISplitViewControllerDelegate { @objc public func splitViewController(svc: UISplitViewController, shouldHideViewController vc: UIViewController, inOrientation orientation: UIInterfaceOrientation) -> Bool { //TODO: Бага в режиме SplitView на iPad Air 2, iPad Pro на iOS 9. Не показывает Master у SplitView в режиме 3:1. return false } @objc public func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return true } else { return false } } } private let splitControllerFix = SplitControllerFix() extension UIStoryboard { public static func createInitialControllerInStoryboard<Controller: UIViewController>(name: String, forClass: AnyClass, dependency: DependencyResolver) -> Controller { let storyboard = UIStoryboard(name: name, bundle: NSBundle(forClass: forClass)) let controller = storyboard.instantiateInitialViewController()! let target = controller.unwrap() as Controller dependency.resolve(target as! DependentObject) if let split = controller as? UISplitViewController { split.preferredDisplayMode = .AllVisible split.delegate = splitControllerFix } return target } } extension UIView { func nearestSuperview<Superview>() -> Superview? { var test = superview while test != nil { if let found = test as? Superview { return found } test = test!.superview } return nil } } extension UIImage { func resizedToFitSize(bounds: CGSize) -> UIImage { let ratio = max(bounds.width / size.width, bounds.height / size.height) let thumbnailSize = CGSizeMake(size.width * ratio, size.height * ratio) UIGraphicsBeginImageContextWithOptions(thumbnailSize, false, UIScreen.mainScreen().scale); drawInRect(CGRectMake(0, 0, thumbnailSize.width, thumbnailSize.height)) let thumbnail = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return thumbnail } }
mit
5091e15358e507e257df75636ef1cae2
26.699029
234
0.756311
4.340944
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Video/VideoPlayer.swift
1
7597
// // VideoPlayer.swift // MusicApp // // Created by Hưng Đỗ on 7/4/17. // Copyright © 2017 HungDo. All rights reserved. // import AVFoundation import RxSwift import NSObject_Rx protocol VideoPlayer: class { var player: AVPlayer? { get } weak var delegate: VideoPlayerDelegate? { get set } var currentTime: Int { get } var duration: Int { get } func load(_ url: String) func reload(_ url: String) func play() func play(url: String) func seek(_ time: Int) func pause() func stop() } class MAVideoPlayer: NSObject, VideoPlayer { var player: AVPlayer? weak var delegate: VideoPlayerDelegate? // MARK: Play Controls func load(_ url: String) { let url = URL(string: url)! player = AVPlayer(url: url) delegate?.videoPlayerWillLoad(self) play() } func reload(_ url: String) { stop() load(url) } func play() { registerObservers() player?.play() fadeInVolume() delegate?.videoPlayerDidPlay(self) } func play(url: String) { if player != nil { play() } else { reload(url) } } func seek(_ time: Int) { delegate?.videoPlayer(self, willSeekToTime: time) player?.seek(to: CMTimeMake(Int64(time), 1), completionHandler: { [weak self] success in guard let this = self else { return } if success { this.delegate?.videoPlayer(this, didSeekToTime: time) } else { this.delegate?.videoPlayer(this, failSeekToTime: time) } }) } func pause() { unregisterObservers() self.delegate?.videoPlayerWillPause(self) fadeInSubscription?.dispose() fadeOutVolume { self.player?.pause() self.delegate?.videoPlayerDidPause(self) } } func stop() { unregisterObservers() player?.pause() player?.replaceCurrentItem(with: nil) player = nil delegate?.videoPlayerDidStop(self) } // MARK: De Initialization deinit { unregisterObservers() stop() } // MARK: Register/Unregister Observers private var isObserving: Bool = false private var currentTimeObserverToken: Any? private var durationObserverToken: Any? private func registerObservers() { if isObserving { return } addAVPlayerItemDidPlayToEndTimeNotification(player?.currentItem) addPeriodicTimeObservers() isObserving = true } private func unregisterObservers() { if !isObserving { return } removeAVPlayerItemDidPlayToEndTimeNotification(player?.currentItem) removePeriodicTimeObservers() isObserving = false } // MARK: Notification private func addAVPlayerItemDidPlayToEndTimeNotification(_ playerItem: AVPlayerItem?) { NotificationCenter.default.addObserver( self, selector: #selector(playerItemDidReachEnd), name: .AVPlayerItemDidPlayToEndTime, object: playerItem ) } private func removeAVPlayerItemDidPlayToEndTimeNotification(_ playerItem: AVPlayerItem?) { NotificationCenter.default.removeObserver( self, name: .AVPlayerItemDidPlayToEndTime, object: playerItem ) } func playerItemDidReachEnd(_ notification: Notification) { pause() } // MARK: Time Observing var currentTime: Int = 0 { didSet { delegate?.videoPlayer(self, didGetCurrentTime: currentTime) } } var duration: Int = 0 { didSet { delegate?.videoPlayer(self, didGetDuration: duration) } } private func addPeriodicTimeObservers() { let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)) durationObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in guard let this = self else { return } guard let duration = this.player?.currentItem?.duration, duration.isValid && !duration.indefinite else { return } let seconds = CMTimeGetSeconds(duration) self?.duration = Int(seconds) if let durationToken = self?.durationObserverToken { this.player?.removeTimeObserver(durationToken) self?.durationObserverToken = nil } } currentTimeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in guard let this = self else { return } guard let currentTime = this.player?.currentTime(), currentTime.isValid && !currentTime.indefinite else { return } let seconds = CMTimeGetSeconds(currentTime) self?.currentTime = Int(seconds) } } private func removePeriodicTimeObservers() { if currentTimeObserverToken != nil { player?.removeTimeObserver(currentTimeObserverToken!) } if durationObserverToken != nil { player?.removeTimeObserver(durationObserverToken!) } } // MARK: Fade in/Fade out volume private var fadeInSubscription: Disposable? private var fadeOutSubscription: Disposable? private func fadeInVolume(completion: (() -> Void)? = nil) { guard let player = self.player else { return } fadeInSubscription = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance) .take(10) .filter { _ in Double(player.volume) < 1.0 } .subscribe( onNext: { _ in player.volume += 0.1 }, onError: nil, onCompleted: { completion?() }, onDisposed: nil ) fadeInSubscription?.addDisposableTo(rx_disposeBag) } private func fadeOutVolume(completion: (() -> Void)? = nil) { guard let player = self.player else { return } fadeOutSubscription = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance) .take(10) .filter { _ in Double(player.volume) > 0.0 } .subscribe( onNext: { _ in player.volume -= 0.1 }, onError: nil, onCompleted: { completion?() }, onDisposed: nil ) fadeOutSubscription?.addDisposableTo(rx_disposeBag) } } protocol VideoPlayerDelegate: class { func videoPlayer(_ player: VideoPlayer, didGetCurrentTime currentTime: Int) func videoPlayer(_ player: VideoPlayer, didGetDuration duration: Int) func videoPlayerWillLoad(_ player: VideoPlayer) func videoPlayerDidPlay(_ player: VideoPlayer) func videoPlayerWillPause(_ player: VideoPlayer) func videoPlayerDidPause(_ player: VideoPlayer) func videoPlayerDidStop(_ player: VideoPlayer) func videoPlayer(_ player: VideoPlayer, willSeekToTime time: Int) func videoPlayer(_ player: VideoPlayer, failSeekToTime time: Int) func videoPlayer(_ player: VideoPlayer, didSeekToTime time: Int) }
mit
cde480cb60f6bae499f5541bd675b3ee
27.649057
126
0.582323
5.312806
false
false
false
false
goldensuneur/BatteryChecker
Battery Checker/AppDelegate.swift
1
2120
import Cocoa import CoreFoundation import IOKit.ps @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { override init() { super.init() setupBatteryWatcher() } func setupBatteryWatcher() { CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, { (_, _, _, _, _) in struct Holder { static var shouldSendNotification = false } let blobUnmanaged :Unmanaged<CFTypeRef>! = IOPSCopyPowerSourcesInfo() let blob = blobUnmanaged.takeRetainedValue() let sourcesUnmanaged : Unmanaged<CFArray>! = IOPSCopyPowerSourcesList(blob) let sources = sourcesUnmanaged.takeRetainedValue() let source : CFTypeRef = Unmanaged.fromOpaque(CFArrayGetValueAtIndex(sources, 0)).takeUnretainedValue() let sourceDescUnmanaged : Unmanaged<CFDictionary>! = IOPSGetPowerSourceDescription(blob, source) let sourceDesc = sourceDescUnmanaged.takeUnretainedValue() as Dictionary for (key, val) in sourceDesc { if ((key as! String == kIOPSPowerSourceStateKey) && (val as! String == kIOPSACPowerValue)) { Holder.shouldSendNotification = true; } else if ((key as! String == kIOPSIsFinishingChargeKey) && (val as! Bool == true)) { if (Holder.shouldSendNotification) { let note = NSUserNotification.init() note.title = "Battery checker" note.subtitle = "Battery is fully charged" note.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(note) Holder.shouldSendNotification = false } } } }, kIOPSNotifyAnyPowerSource as CFString!, nil, CFNotificationSuspensionBehavior.drop) } }
unlicense
f103f056ee7b45011b0569cf78044e8d
40.568627
115
0.578774
5.84022
false
false
false
false
panadaW/MyNews
MyWb完善首页数据/MyWb/Class/Controllers/Finder/FinderTableViewController.swift
2
3427
// // FinderTableViewController.swift // MyWb // // Created by 王明申 on 15/10/8. // Copyright © 2015年 晨曦的Mac. All rights reserved. // import UIKit class FinderTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() visitorview?.changViewInfo(false, imagename: "visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
eb32bb9b5f44dfec7ab7244966e61872
33.958333
157
0.690107
5.335453
false
false
false
false
ryanfowler/SwiftQL
Tests/SQPoolTests.swift
1
19953
// // SQPoolTests.swift // // Copyright (c) 2015 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import SwiftQL class SQPoolTests: XCTestCase { override func setUp() { super.setUp() let db = SQDatabase() db.open() let success = db.updateMany(["DROP TABLE IF EXISTS test", "CREATE TABLE test (id INT PRIMARY KEY, name TEXT, age INT)"]) XCTAssertTrue(success, "table should have been created") db.close() } func testWrite() { let pool = SQPool() pool.write({ db in var success = db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [1, "Ryan", 24]) XCTAssertTrue(success, "row should have been inserted") }) } func testRead() { let pool = SQPool() pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") XCTAssertFalse(cursor!.next(), "cursor should not contain any rows") }) } func testConcurrentWrites() { let pool = SQPool() let dGroup = dispatch_group_create() var success1 = false var success2 = false var success3 = false dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 0; i < 1000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } success1 = db.commitTransaction() }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 1000; i < 2000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } success2 = db.commitTransaction() }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 2000; i < 3000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } success3 = db.commitTransaction() }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) XCTAssertTrue(success1, "transaction from write1 should successfully commit") XCTAssertTrue(success2, "transaction from write2 should successfully commit") XCTAssertTrue(success3, "transaction from write3 should successfully commit") var idArr: [Int] = [] var nameArr: [String] = [] var ageArr: [Int] = [] pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr.append(cursor.intForColumnIndex(0)!) nameArr.append(cursor.stringForColumnIndex(1)!) ageArr.append(cursor.intForColumnIndex(2)!) } } }) XCTAssertEqual(idArr.count, 3000, "id array should ahve 3000 rows") XCTAssertEqual(nameArr.count, 3000, "name array should ahve 3000 rows") XCTAssertEqual(ageArr.count, 3000, "age array should ahve 3000 rows") } func testConcurrentReads() { let pool = SQPool() var success = pool.transaction({ db in for var i = 0; i < 1000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } return true }) XCTAssertTrue(success, "inserts should succeed in transaction") let dGroup = dispatch_group_create() var idArr1: [Int] = [] var nameArr1: [String] = [] var ageArr1: [Int] = [] var idArr2: [Int] = [] var nameArr2: [String] = [] var ageArr2: [Int] = [] var idArr3: [Int] = [] var nameArr3: [String] = [] var ageArr3: [Int] = [] dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr1.append(cursor.intForColumnIndex(0)!) nameArr1.append(cursor.stringForColumnIndex(1)!) ageArr1.append(cursor.intForColumnIndex(2)!) } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr2.append(cursor.intForColumnIndex(0)!) nameArr2.append(cursor.stringForColumnIndex(1)!) ageArr2.append(cursor.intForColumnIndex(2)!) } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr3.append(cursor.intForColumnIndex(0)!) nameArr3.append(cursor.stringForColumnIndex(1)!) ageArr3.append(cursor.intForColumnIndex(2)!) } } }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) XCTAssertEqual(idArr1.count, 1000, "read1 ids shoudl be 1000") XCTAssertEqual(nameArr1.count, 1000, "read1 names shoudl be 1000") XCTAssertEqual(ageArr1.count, 1000, "read1 ages shoudl be 1000") XCTAssertEqual(idArr2.count, 1000, "read2 ids shoudl be 1000") XCTAssertEqual(nameArr2.count, 1000, "read2 names shoudl be 1000") XCTAssertEqual(ageArr2.count, 1000, "read2 ages shoudl be 1000") XCTAssertEqual(idArr3.count, 1000, "read3 ids shoudl be 1000") XCTAssertEqual(nameArr3.count, 1000, "read3 names shoudl be 1000") XCTAssertEqual(ageArr3.count, 1000, "read3 ages shoudl be 1000") } func testConcurrentReadWrites() { let pool = SQPool() let dGroup = dispatch_group_create() dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 0; i < 1000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } let success = db.commitTransaction() XCTAssertTrue(success, "transaction should successfully commit") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 1000; i < 2000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } let success = db.commitTransaction() XCTAssertTrue(success, "transaction should successfully commit") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) var idArr: [Int] = [] var nameArr: [String] = [] var ageArr: [Int] = [] pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr.append(cursor.intForColumnIndex(0)!) nameArr.append(cursor.stringForColumnIndex(1)!) ageArr.append(cursor.intForColumnIndex(0)!) } } }) XCTAssertEqual(idArr.count, 2000, "id array should have 2000 values") XCTAssertEqual(nameArr.count, 2000, "name array should have 2000 values") XCTAssertEqual(ageArr.count, 2000, "age array should have 2000 values") } func testConcurrentWriteReads() { let pool = SQPool() let dGroup = dispatch_group_create() dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 0; i < 1000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } let success = db.commitTransaction() XCTAssertTrue(success, "transaction should successfully commit") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in db.beginTransaction() for var i = 1000; i < 2000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } let success = db.commitTransaction() XCTAssertTrue(success, "transaction should successfully commit") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) var idArr: [Int] = [] var nameArr: [String] = [] var ageArr: [Int] = [] pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr.append(cursor.intForColumnIndex(0)!) nameArr.append(cursor.stringForColumnIndex(1)!) ageArr.append(cursor.intForColumnIndex(0)!) } } }) XCTAssertEqual(idArr.count, 2000, "id array should have 2000 values") XCTAssertEqual(nameArr.count, 2000, "name array should have 2000 values") XCTAssertEqual(ageArr.count, 2000, "age array should have 2000 values") } func testMaxSustainedConnectionLimit() { let pool = SQPool() let dGroup = dispatch_group_create() dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) XCTAssertLessThan(pool.numberOfFreeConnections(), pool.maxSustainedConnections + 1, "should be less than the max sustained connections") } func testManyAsyncOperations() { let pool = SQPool() let dGroup = dispatch_group_create() dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in for var i = 0; i < 1000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") if cursor != nil { while cursor!.next() { cursor!.intForColumn("id") cursor!.stringForColumn("name") cursor!.intForColumn("age") } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in for var i = 1000; i < 2000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") if cursor != nil { while cursor!.next() { cursor!.intForColumn("id") cursor!.stringForColumn("name") cursor!.intForColumn("age") } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in for var i = 2000; i < 3000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") if cursor != nil { while cursor!.next() { cursor!.intForColumn("id") cursor!.stringForColumn("name") cursor!.intForColumn("age") } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in for var i = 3000; i < 4000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") if cursor != nil { while cursor!.next() { cursor!.intForColumn("id") cursor!.stringForColumn("name") cursor!.intForColumn("age") } } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.write({ db in for var i = 4000; i < 5000; i++ { db.update("INSERT INTO test VALUES (?, ?, ?)", withObjects: [i, "Ryan", 24]) } }) }) dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { pool.read({ db in let cursor = db.query("SELECT * FROM test") XCTAssertNotNil(cursor, "cursor should not be nil") if cursor != nil { while cursor!.next() { cursor!.intForColumn("id") cursor!.stringForColumn("name") cursor!.intForColumn("age") } } }) }) dispatch_group_wait(dGroup, DISPATCH_TIME_FOREVER) var idArr: [Int] = [] var nameArr: [String] = [] var ageArr: [Int] = [] pool.read({ db in if let cursor = db.query("SELECT * FROM test") { while cursor.next() { idArr.append(cursor.intForColumnIndex(0)!) nameArr.append(cursor.stringForColumnIndex(1)!) ageArr.append(cursor.intForColumnIndex(2)!) } } }) XCTAssertEqual(idArr.count, 5000, "id array should have 5000 values") XCTAssertEqual(nameArr.count, 5000, "name array should have 5000 values") XCTAssertEqual(ageArr.count, 5000, "age array should have 5000 values") } }
mit
34df3960eecbf423dbb98ccbfd792325
38.432806
144
0.504435
4.586897
false
true
false
false
carolight/sample-code
swift/06-Texturing/Texturing/ViewController.swift
1
3020
// // ViewController.swift // Texturing // // Created by Caroline Begbie on 2/01/2016. // Copyright © 2016 Caroline Begbie. All rights reserved. // import MetalKit import AudioToolbox class ViewController: UIViewController { let kVelocityScale:CGFloat = 0.01 let kRotationDamping:CGFloat = 0.05 let kMooSpinThreshold:CGFloat = 30 let kMooDuration:CFAbsoluteTime = 3 var metalView:MTKView { return view as! MTKView } var renderer: MBERenderer? var mooSound: SystemSoundID = 0 var lastMooTime:CFAbsoluteTime = 0 var angularVelocity:CGPoint = .zero var angle:CGPoint = .zero override func viewDidLoad() { super.viewDidLoad() metalView.device = MTLCreateSystemDefaultDevice() renderer = MBERenderer(device: metalView.device) metalView.delegate = self let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(ViewController.gestureDidRecognize(_:))) metalView.addGestureRecognizer(panGesture) loadResources() } override var prefersStatusBarHidden: Bool { return true } private func loadResources() { if let mooURL = Bundle.main.url(forResource: "moo", withExtension: "aiff") { let result = AudioServicesCreateSystemSoundID(mooURL, &mooSound) if result != noErr { print("Error when loading sound effect. Error code: \(result)") } } else { print("Could not find sound effect file in main bundle") } } func gestureDidRecognize(_ gesture: UIPanGestureRecognizer) { let velocity = gesture.velocity(in: view) angularVelocity = CGPoint(x:velocity.x * kVelocityScale, y:velocity.y * kVelocityScale) } } extension ViewController: MTKViewDelegate { private func updateMotionWithTimestep(_ duration:CGFloat) { if duration > 0 { // Update the rotation angles according to the current velocity and time step angle = CGPoint(x: angle.x + angularVelocity.x * duration, y: angle.y + angularVelocity.y * duration) // Apply damping by removing some proportion of the angular velocity each frame angularVelocity = CGPoint(x: angularVelocity.x * (1 - kRotationDamping), y: angularVelocity.y * (1 - kRotationDamping)) let spinSpeed = hypot(angularVelocity.x, angularVelocity.y) // If we're spinning fast and haven't mooed in a while, trigger the moo sound effect let frameTime = CFAbsoluteTimeGetCurrent() if spinSpeed > kMooSpinThreshold && frameTime > (lastMooTime + kMooDuration) { AudioServicesPlaySystemSound(mooSound) lastMooTime = frameTime } } } func draw(in view: MTKView) { updateMotionWithTimestep(1.0 / CGFloat(view.preferredFramesPerSecond)) renderer?.rotationX = Float(-angle.y) renderer?.rotationY = Float(-angle.x) renderer?.draw(in: view) } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } }
mit
1d682473d22b54acaf4f111a5a7f3257
28.891089
121
0.67837
4.388081
false
false
false
false
hrscy/TodayNews
News/News/Classes/Video/View/RelatedVideoFooterView.swift
1
3071
// // RelatedVideoFooterView.swift // News // // Created by 杨蒙 on 2018/1/21. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import IBAnimatable import Kingfisher class RelatedVideoFooterView: UIView, NibLoadable { var ad = AD() { didSet { if ad.app.ad_id != 0 { titleLabel.text = ad.app.title nameLabel.text = ad.app.app_name downloadButton.setTitle(ad.app.button_text, for: .normal) if let urlList = ad.app.image.url_list.first { thumbImageView.kf.setImage(with: URL(string: urlList.url)!) } } else if ad.mixed.id != 0 { titleLabel.text = ad.mixed.title nameLabel.text = ad.mixed.source_name if ad.mixed.image != "" { thumbImageView.kf.setImage(with: URL(string: ad.mixed.image)!) } else if ad.mixed.image_list.count != 0 { if let image = ad.mixed.image_list.first { if let urlList = image.url_list.first { thumbImageView.kf.setImage(with: URL(string: urlList.url)!) } } } downloadButton.setTitle(ad.mixed.button_text, for: .normal) } else { // 没有广告 bgView.isHidden = true } } } override func layoutSubviews() { super.layoutSubviews() width = screenWidth // 没有广告 if ad.app.ad_id == 0 && ad.mixed.id == 0 { height = moreButton.isSelected ? 0 : 40 } else { height = bgView.frame.maxY + 5 } } /// 标题 @IBOutlet weak var titleLabel: UILabel! /// 查看更多 @IBOutlet weak var moreButton: UIButton! @IBOutlet weak var moreButtonHeight: NSLayoutConstraint! /// 缩略图 @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var thumbAspect: NSLayoutConstraint! /// app 名称 @IBOutlet weak var nameLabel: UILabel! /// 立即下载 @IBOutlet weak var downloadButton: AnimatableButton! @IBOutlet weak var separatorView: UIView! @IBOutlet weak var bgView: UIView! override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.separatorViewColor" bgView.theme_backgroundColor = "colors.cellBackgroundColor" separatorView.theme_backgroundColor = "colors.separatorViewColor" moreButton.theme_setImage("images.arrow_down_16_16x14_", forState: .normal) titleLabel.theme_textColor = "colors.black" } /// 查看更多点击 @IBAction func moreButtonClicked(_ sender: UIButton) { moreButtonHeight.constant = 0 height = 300 UIView.animate(withDuration: 0.25) { self.layoutIfNeeded() } sender.isHidden = true } /// 关闭按钮点击 @IBAction func closeButtonClicked(_ sender: UIButton) { } }
mit
96cb579916c0a7dab252e6845d4760b5
31.543478
92
0.567802
4.495495
false
false
false
false
omnypay/omnypay-sdk-ios
ExampleApp/OmnyPayAllSdkDemo/Pods/Starscream/Source/SSLSecurity.swift
2
8687
////////////////////////////////////////////////////////////////////////////////////////////////// // // SSLSecurity.swift // Starscream // // Created by Dalton Cherry on 5/16/15. // Copyright (c) 2014-2015 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import Security public class SSLCert { var certData: Data? var key: SecKey? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ public init(data: Data) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ public init(key: SecKey) { self.key = key } } public class SSLSecurity { public var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [Data]? //the certificates var pubKeys: [SecKey]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public convenience init(usePublicKeys: Bool = false) { let paths = Bundle.main.paths(forResourcesOfType: "cer", inDirectory: ".") let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in var certs = certs if let data = NSData(contentsOfFile: path) { certs.append(SSLCert(data: data as Data)) } return certs } self.init(certs: certs, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public init(certs: [SSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { DispatchQueue.global(qos: .default).async { let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in var pubKeys = pubKeys if let data = cert.certData, cert.key == nil { cert.key = self.extractPublicKey(data) } if let key = cert.key { pubKeys.append(key) } return pubKeys } self.pubKeys = pubKeys self.isReady = true } } else { let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in var certificates = certificates if let data = cert.certData { certificates.append(data) } return certificates } self.certificates = certificates self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ public func isValid(_ trust: SecTrust, domain: String?) -> Bool { var tries = 0 while !self.isReady { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicy if self.validatedDN { policy = SecPolicyCreateSSL(true, domain as NSString?) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { let serverPubKeys = publicKeyChain(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { return true } } } } } else if let certs = self.certificates { let serverCerts = certificateChain(trust) var collect = [SecCertificate]() for cert in certs { collect.append(SecCertificateCreateWithData(nil,cert as CFData)!) } SecTrustSetAnchorCertificates(trust,collect as NSArray) var result: SecTrustResultType = .unspecified SecTrustEvaluate(trust,&result) if result == .unspecified || result == .proceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount += 1 break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(_ data: Data) -> SecKey? { guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil } return extractPublicKey(cert, policy: SecPolicyCreateBasicX509()) } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? { var possibleTrust: SecTrust? SecTrustCreateWithCertificates(cert, policy, &possibleTrust) guard let trust = possibleTrust else { return nil } var result: SecTrustResultType = .unspecified SecTrustEvaluate(trust, &result) return SecTrustCopyPublicKey(trust) } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChain(_ trust: SecTrust) -> [Data] { let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([Data]()) { (certificates: [Data], index: Int) -> [Data] in var certificates = certificates let cert = SecTrustGetCertificateAtIndex(trust, index) certificates.append(SecCertificateCopyData(cert!) as Data) return certificates } return certificates } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChain(_ trust: SecTrust) -> [SecKey] { let policy = SecPolicyCreateBasicX509() let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [SecKey] in var keys = keys let cert = SecTrustGetCertificateAtIndex(trust, index) if let key = extractPublicKey(cert!, policy: policy) { keys.append(key) } return keys } return keys } }
apache-2.0
9f33c807d8ad29271a8691a0ff843cc7
32.801556
134
0.554507
5.422597
false
false
false
false
ddki/my_study_project
language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/tunnel_server/main.swift
1
1484
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the main code for the SimpleTunnel server. */ import Foundation /// Dispatch source to catch and handle SIGINT let interruptSignalSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, UInt(SIGINT), 0, dispatch_get_main_queue()) /// Dispatch source to catch and handle SIGTERM let termSignalSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, UInt(SIGTERM), 0, dispatch_get_main_queue()) /// Basic sanity check of the parameters. if Process.arguments.count < 3 { print("Usage: \(Process.arguments[0]) <port> <config-file>") exit(1) } func ignore(_: Int32) { } signal(SIGTERM, ignore) signal(SIGINT, ignore) let portString = Process.arguments[1] let configurationPath = Process.arguments[2] let networkService: NSNetService // Initialize the server. if !ServerTunnel.initializeWithConfigurationFile(configurationPath) { exit(1) } if let portNumber = Int(portString) { networkService = ServerTunnel.startListeningOnPort(Int32(portNumber)) } else { print("Invalid port: \(portString)") exit(1) } // Set up signal handling. dispatch_source_set_event_handler(interruptSignalSource) { networkService.stop() return } dispatch_resume(interruptSignalSource) dispatch_source_set_event_handler(termSignalSource) { networkService.stop() return } dispatch_resume(termSignalSource) NSRunLoop.mainRunLoop().run()
mit
b46bc20d459df952de6ee4e7621602c4
23.716667
123
0.767206
3.462617
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadDataKit/Data/WalletPersistence.swift
1
4128
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import KeychainKit import ToolKit import WalletPayloadKit /// An object responsible for observing changes from `WalletStorage` and persisting them. final class WalletRepoPersistence: WalletRepoPersistenceAPI { enum KeychainAccessKey { static let walletState = "wallet-repo-state" } private let repo: WalletRepoAPI private let keychainAccess: KeychainAccessAPI private let persistenceQueue: DispatchQueue private let encoder: WalletRepoStateEncoding private let decoder: WalletRepoStateDecoding init( repo: WalletRepoAPI, keychainAccess: KeychainAccessAPI, queue: DispatchQueue, encoder: @escaping WalletRepoStateEncoding = walletRepoStateEncoder, decoder: @escaping WalletRepoStateDecoding = walletRepoStateDecoder ) { self.repo = repo self.keychainAccess = keychainAccess self.encoder = encoder self.decoder = decoder persistenceQueue = queue } func beginPersisting() -> AnyPublisher<Void, WalletRepoPersistenceError> { repo .stream() .removeDuplicates() .setFailureType(to: WalletRepoPersistenceError.self) .receive(on: persistenceQueue) .flatMap { [encoder] state in encoder(state) .publisher .mapError(WalletRepoPersistenceError.decodingFailed) } .flatMap { [keychainAccess] data in keychainAccess .write(value: data, for: KeychainAccessKey.walletState) .publisher .mapError(WalletRepoPersistenceError.keychainFailure) .eraseToAnyPublisher() } .eraseToAnyPublisher() } func retrieve() -> AnyPublisher<WalletRepoState, WalletRepoPersistenceError> { keychainAccess.read(for: KeychainAccessKey.walletState) .mapError(WalletRepoPersistenceError.keychainFailure) .publisher .receive(on: persistenceQueue) .flatMap { [decoder] data -> AnyPublisher<WalletRepoState, WalletRepoPersistenceError> in decoder(data) .mapError(WalletRepoPersistenceError.decodingFailed) .publisher .eraseToAnyPublisher() } .eraseToAnyPublisher() } func delete() -> AnyPublisher<Void, WalletRepoPersistenceError> { Deferred { [keychainAccess] in Future { promise in let removalResult = keychainAccess.remove(for: KeychainAccessKey.walletState) switch removalResult { case .success: promise(.success(())) case .failure(let error): promise(.failure(WalletRepoPersistenceError.keychainFailure(error))) } } } .eraseToAnyPublisher() } } // MARK: - Global Retrieval Method /// Retrieves the `WalletStorageState` from the `Keychain` /// - Returns: A previously stored `WalletStorageState` or an default empty state func retrieveWalletRepoState( keychainAccess: KeychainAccessAPI, decoder: WalletRepoStateDecoding = walletRepoStateDecoder ) -> WalletRepoState? { let readResult = keychainAccess.read(for: WalletRepoPersistence.KeychainAccessKey.walletState) guard case .success(let data) = readResult else { return nil } guard case .success(let state) = decoder(data) else { return nil } return state } func walletRepoStateEncoder( _ value: WalletRepoState ) -> Result<Data, WalletRepoStateCodingError> { Result { try JSONEncoder().encode(value) } .mapError(WalletRepoStateCodingError.encodingFailed) } func walletRepoStateDecoder( _ data: Data ) -> Result<WalletRepoState, WalletRepoStateCodingError> { Result { try JSONDecoder().decode(WalletRepoState.self, from: data) } .mapError(WalletRepoStateCodingError.decodingFailed) }
lgpl-3.0
2cdcc032e9f8b9f03bcf288aa5712e96
33.391667
101
0.647444
5.088779
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationPublic.swift
1
6864
// // AnimationPublic.swift // lottie-swift // // Created by Brandon Withrow on 2/5/19. // import Foundation import CoreGraphics public extension Animation { // MARK: Animation (Loading) /** Loads an animation model from a bundle by its name. Returns `nil` if an animation is not found. - Parameter name: The name of the json file without the json extension. EG "StarAnimation" - Parameter bundle: The bundle in which the animation is located. Defaults to `Bundle.main` - Parameter subdirectory: A subdirectory in the bundle in which the animation is located. Optional. - Parameter animationCache: A cache for holding loaded animations. Optional. - Returns: Deserialized `Animation`. Optional. */ static func named(_ name: String, bundle: Bundle = Bundle.main, subdirectory: String? = nil, animationCache: AnimationCacheProvider? = nil) -> Animation? { /// Create a cache key for the animation. let cacheKey = bundle.bundlePath + (subdirectory ?? "") + "/" + name /// Check cache for animation if let animationCache = animationCache, let animation = animationCache.animation(forKey: cacheKey) { /// If found, return the animation. return animation } /// Make sure the bundle has a file at the path provided. guard let url = bundle.url(forResource: name, withExtension: "json", subdirectory: subdirectory) else { return nil } do { /// Decode animation. let json = try Data(contentsOf: url) let animation = try JSONDecoder().decode(Animation.self, from: json) animationCache?.setAnimation(animation, forKey: cacheKey) return animation } catch { /// Decoding error. print(error) return nil } } /** Loads an animation from a specific filepath. - Parameter filepath: The absolute filepath of the animation to load. EG "/User/Me/starAnimation.json" - Parameter animationCache: A cache for holding loaded animations. Optional. - Returns: Deserialized `Animation`. Optional. */ static func filepath(_ filepath: String, animationCache: AnimationCacheProvider? = nil) -> Animation? { /// Check cache for animation if let animationCache = animationCache, let animation = animationCache.animation(forKey: filepath) { return animation } do { /// Decode the animation. let json = try Data(contentsOf: URL(fileURLWithPath: filepath)) let animation = try JSONDecoder().decode(Animation.self, from: json) animationCache?.setAnimation(animation, forKey: filepath) return animation } catch { /// Decoding Error. return nil } } /// A closure for an Animation download. The closure is passed `nil` if there was an error. typealias DownloadClosure = (Animation?) -> Void /** Loads a Lottie animation asynchronously from the URL. - Parameter url: The url to load the animation from. - Parameter closure: A closure to be called when the animation has loaded. - Parameter animationCache: A cache for holding loaded animations. */ static func loadedFrom(url: URL, closure: @escaping Animation.DownloadClosure, animationCache: AnimationCacheProvider?) { if let animationCache = animationCache, let animation = animationCache.animation(forKey: url.absoluteString) { closure(animation) } else { let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard error == nil, let jsonData = data else { DispatchQueue.main.async { closure(nil) } return } do { let animation = try JSONDecoder().decode(Animation.self, from: jsonData) DispatchQueue.main.async { animationCache?.setAnimation(animation, forKey: url.absoluteString) closure(animation) } } catch { DispatchQueue.main.async { closure(nil) } } } task.resume() } } // MARK: Animation (Helpers) /** Markers are a way to describe a point in time by a key name. Markers are encoded into animation JSON. By using markers a designer can mark playback points for a developer to use without having to worry about keeping track of animation frames. If the animation file is updated, the developer does not need to update playback code. Returns the Progress Time for the marker named. Returns nil if no marker found. */ func progressTime(forMarker named: String) -> AnimationProgressTime? { guard let markers = markerMap, let marker = markers[named] else { return nil } return progressTime(forFrame: marker.frameTime) } /** Markers are a way to describe a point in time by a key name. Markers are encoded into animation JSON. By using markers a designer can mark playback points for a developer to use without having to worry about keeping track of animation frames. If the animation file is updated, the developer does not need to update playback code. Returns the Frame Time for the marker named. Returns nil if no marker found. */ func frameTime(forMarker named: String) -> AnimationFrameTime? { guard let markers = markerMap, let marker = markers[named] else { return nil } return marker.frameTime } /// Converts Frame Time (Seconds * Framerate) into Progress Time (0 to 1). func progressTime(forFrame frameTime: AnimationFrameTime) -> AnimationProgressTime { return ((frameTime - startFrame) / (endFrame - startFrame)).clamp(0, 1) } /// Converts Progress Time (0 to 1) into Frame Time (Seconds * Framerate) func frameTime(forProgress progressTime: AnimationProgressTime) -> AnimationFrameTime { return ((endFrame - startFrame) * progressTime) + startFrame } /// Converts Frame Time (Seconds * Framerate) into Time (Seconds) func time(forFrame frameTime: AnimationFrameTime) -> TimeInterval { return Double(frameTime - startFrame) / framerate } /// Converts Time (Seconds) into Frame Time (Seconds * Framerate) func frameTime(forTime time: TimeInterval) -> AnimationFrameTime { return CGFloat(time * framerate) + startFrame } /// The duration in seconds of the animation. var duration: TimeInterval { return Double(endFrame - startFrame) / framerate } /// The natural bounds in points of the animation. var bounds: CGRect { return CGRect(x: 0, y: 0, width: width, height: height) } /// The natural size in points of the animation. var size: CGSize { return CGSize(width: width, height: height) } }
mit
bb5bd3f8a016a8f2079969d1cba7ee2f
34.020408
114
0.660693
4.730531
false
false
false
false
oarrabi/Guaka-Generator
Sources/Swiftline/Args.swift
1
1891
// // Args.swift // Swiftline // // Created by Omar Abdelhafith on 25/11/2015. // Copyright © 2015 Omar Abdelhafith. All rights reserved. // /// Return the command line arguments passed to the script public class Args { /// Return the list of arguments passed to the script public static var all: [String] { return CommandLine.arguments } static var cachedResults: ParsedArgs? /// Return a parsed list of arguments containing the flags and the parameters passed to the scripts /// The flags are recognized as short flags `-f` or long flags `--force` /// The flag value will be the argument that follows the flag /// `--` is used to mark the terminatin of the flags public static var parsed: ParsedArgs { let result = parse(argumens: all, cachedResults: cachedResults) cachedResults = result return result } static func parse(argumens: [String], cachedResults: ParsedArgs?) -> ParsedArgs { if let result = cachedResults { return result } var parsedFlags = [String: String]() let parsedArgs = ArgsParser.parseFlags(argumens) parsedArgs.0.forEach { parsedFlags[$0.argument.name] = $0.value ?? "" } var arguments = parsedArgs.1 // the first argument is always the executable's name var commandName = "" if let firstArgument = arguments.first { // just in case! commandName = firstArgument arguments.removeFirst(1) } return ParsedArgs(command: commandName, flags: parsedFlags, parameters: arguments) } } public struct ParsedArgs { /// The name of the executable that was invoked from the command line public let command: String /// Parsed flags will be prepred in a dictionary, the key is the flag and the value is the flag value public let flags: [String: String] /// List of parameters passed to the script public let parameters: [String] }
mit
5300fcc6d47ef80c38e9502ef7c36d27
27.636364
103
0.694709
4.285714
false
false
false
false
skylib/SnapOnboarding-iOS
SnapOnboarding-iOS/Snapshot_tests/LoginViewControllerWelcomeBackSnapshots.swift
2
1024
import SnapFBSnapshotBase @testable import SnapOnboarding_iOS class LoginViewControllerWelcomeBackSnapshots: SnapFBSnapshotBase { var vc: SnapOnboardingViewController! override func setUp() { vc = getSnapOnboardingViewController() let delegate = mockSnapOnboardingDelegate() let configuration = SnapOnboardingConfiguration(delegate: delegate, viewModel: viewModel) vc.applyConfiguration(configuration) sutBackingViewController = vc sut = vc.view // vc.viewWillAppear(false) UIApplication.shared.keyWindow?.rootViewController = vc UIApplication.shared.keyWindow?.rootViewController = nil // Setup the loaded view currentPage = 3 let userViewModel = mockUserViewModel() vc.applyFormerAuthorizationService(.facebook, userViewModel: userViewModel) super.setUp() recordMode = recordAll || false } override func tearDown() { vc = nil super.tearDown() } }
bsd-3-clause
1659438e6902403649935b3e2c78a02f
25.947368
97
0.685547
5.535135
false
true
false
false
yramanchuk/gitTest
SmartFeed/UI/ReadFeed/SFFeedDetailListController.swift
1
5496
// // SFFeedDetailListController.swift // SmartFeed // // Created by Yury Ramanchuk on 3/24/16. // Copyright © 2016 Yury Ramanchuk. All rights reserved. // import UIKit import DGElasticPullToRefresh //import SafariServices class SFFeedDetailListController: UITableViewController { var selectedFeed: SFFeedProtocol? { didSet { // self.tableView.reloadData() self.title = selectedFeed?.title } } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem?.accessibilityLabel = "back" // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() let loadingView = DGElasticPullToRefreshLoadingViewCircle() loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0) tableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in SFNetworkManager.sharedInstance.feelFeedRss((self?.selectedFeed?.link)!, completionHandler: { (result, error) in if error == nil { self?.selectedFeed = result self?.tableView.reloadData() self?.tableView.dg_stopLoading() } }) }, loadingView: loadingView) tableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0)) tableView.dg_setPullToRefreshBackgroundColor(tableView.backgroundColor!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selectedFeed?.articles.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FeedCell", forIndexPath: indexPath) as! SFFeedDetailListCell if let cellArticle = selectedFeed?.articles[indexPath.row] { cell.lblTitle.text = cellArticle.title cell.btnNew.hidden = !cellArticle.isNew } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // let object = selectedFeed?.articles[indexPath.row] // let controller = SFSafariViewController.init(URL: NSURL(string: (object?.linkURL)!)!, entersReaderIfAvailable: true) // self.navigationController?.pushViewController(controller, animated: true) // } // 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?) { if segue.identifier == "showArticle" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = selectedFeed?.articles[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! SFArticleDetailController controller.article = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) } } } deinit { self.tableView.dg_removePullToRefresh() } }
mit
41ed165133324862fcfae3dd0ee8e1e9
37.697183
157
0.669154
5.473108
false
false
false
false
weiyanwu84/MLSwiftBasic
MLSwiftBasic/Classes/Base/MBBaseViewController.swift
1
4683
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // MBBaseViewController.swift // MakeBolo // // Created by 张磊 on 15/6/14. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit class MBBaseViewController: UIViewController,MBNavigationBarViewDelegate { var isBack:Bool{ set{ self.navBar.back = newValue; } get{ return self.navBar.back } } lazy var navBar:MBNavigationBarView = { if self.view.viewWithTag(10000001) == nil { println(self) var navBar = MBNavigationBarView() navBar.tag = 10000001 navBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, TOP_Y) navBar.delegate = self navBar.backgroundColor = NAV_BG_COLOR navBar.title = self.titleStr() navBar.leftStr = self.leftStr() navBar.rightStr = self.rightStr() if (self.rightTitles().count > 0) { navBar.rightTitles = self.rightTitles() } if (self.rightImgs().count > 0) { navBar.rightImgs = self.rightImgs() } self.view.insertSubview(navBar, atIndex: 0) if self.leftImg().isEmpty == false { navBar.leftImage = self.leftImg() navBar.leftButton.setImage(UIImage(named: self.leftImg()), forState: .Normal) } if self.titleImg().isEmpty == false { navBar.titleImage = self.titleImg() navBar.titleButton.setImage(UIImage(named: self.titleImg()), forState: .Normal) } if self.rightImg().isEmpty == false { navBar.rightImage = self.rightImg() navBar.rightButton.setImage(UIImage(named: self.rightImg()), forState: .Normal) } return navBar } return self.view.viewWithTag(10000001) as! MBNavigationBarView }() func setTitleStr(title:String!){ if var str:String = title{ self.navBar.title = str } } func titleStr() -> String{ return "" } func leftStr() -> String { return ""; } func rightStr() -> String { return ""; } func titleImg() -> String { return ""; } func leftImg() -> String { return ""; } func rightImg() -> String { return ""; } func rightImgs() -> NSArray { return [] } func rightTitles() -> NSArray { return [] } func rightItemWidth() -> CGFloat { return NAV_ITEM_RIGHT_W } func leftItemWidth() -> CGFloat { return NAV_ITEM_LEFT_W } // <#navigationNavBarView Delegate> func goBack() { self.navigationController?.popViewControllerAnimated(true) } func rightClickAtIndexBtn(button:UIButton){ } func titleClick() { } func leftClick(){ } func rightClick(){ } func setNavBarViewBackgroundColor(color :UIColor){ self.navBar.backgroundColor = color } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.removeFromSuperview() self.view.backgroundColor = BG_COLOR self.setupMenuClickEvent() self.setupNavItemWidthOrHeight() } func setupMenuClickEvent(){ self.navBar.titleButton.addTarget(self, action: "titleClick", forControlEvents: .TouchUpInside) self.navBar.leftButton.addTarget(self, action:"leftClick", forControlEvents: .TouchUpInside) self.navBar.rightButton.addTarget(self, action:"rightClick", forControlEvents: .TouchUpInside) for (var i = 0; i < self.navBar.rightTitles.count; i++){ self.navBar.rightTitles[i].addTarget(self, action: "rightClickAtIndexBtn:", forControlEvents: .TouchUpInside) } } func setupNavItemWidthOrHeight(){ self.navBar.rightItemWidth = self.rightItemWidth() self.navBar.leftItemWidth = self.leftItemWidth() } func addBottomLineView(view :UIView) -> UIView { let lineView = UIView(frame: CGRectMake(0, CGRectGetMaxY(view.frame) - 1, view.frame.width, 1)) lineView.backgroundColor = UIColor(red: 230.0/256.0, green: 230.0/256.0, blue: 230.0/256.0, alpha: 1.0) view.addSubview(lineView) return lineView } }
mit
202ad8b088651137de8d0372b8eaf8a8
26.674556
121
0.56083
4.55848
false
false
false
false
KarlWarfel/nutshell-ios
Pods/CryptoSwift/Sources/CryptoSwift/HashProtocol.swift
1
953
// // HashProtocol.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 17/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // internal protocol HashProtocol { var message: Array<UInt8> { get } /** Common part for hash calculation. Prepare header data. */ func prepare(len:Int) -> Array<UInt8> } extension HashProtocol { func prepare(len:Int) -> Array<UInt8> { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array<UInt8>(count: counter, repeatedValue: 0) return tmpMessage } }
bsd-2-clause
80d9c8554d95a1ff7fa47c9ba11b3b89
25.416667
81
0.592008
4.226667
false
false
false
false
ello/ello-ios
Specs/Model/CoderSpec.swift
1
3902
@testable import Ello import Quick import Nimble class CoderSpec: QuickSpec { override func spec() { var filePath = "" if let url = URL(string: FileManager.ElloDocumentsDir()) { filePath = url.appendingPathComponent("DecoderSpec").absoluteString } afterEach { do { try FileManager.default.removeItem(atPath: filePath) } catch { } } describe("Coder") { it("encodes and decodes required properties") { let obj = CoderSpecFake( stringProperty: "prop1", intProperty: 123, boolProperty: true ) NSKeyedArchiver.archiveRootObject(obj, toFile: filePath) let unArchivedObject = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! CoderSpecFake expect(unArchivedObject.stringProperty) == "prop1" expect(unArchivedObject.intProperty) == 123 expect(unArchivedObject.boolProperty) == true expect(unArchivedObject.optionalStringProperty).to(beNil()) expect(unArchivedObject.optionalIntProperty).to(beNil()) expect(unArchivedObject.optionalBoolProperty).to(beNil()) } it("encodes and decodes optional properties") { let obj = CoderSpecFake( stringProperty: "prop1", intProperty: 123, boolProperty: true ) obj.optionalStringProperty = "optionalString" obj.optionalIntProperty = 666 obj.optionalBoolProperty = true NSKeyedArchiver.archiveRootObject(obj, toFile: filePath) let unArchivedObject = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! CoderSpecFake expect(unArchivedObject.stringProperty) == "prop1" expect(unArchivedObject.intProperty) == 123 expect(unArchivedObject.boolProperty) == true expect(unArchivedObject.optionalStringProperty) == "optionalString" expect(unArchivedObject.optionalIntProperty) == 666 expect(unArchivedObject.optionalBoolProperty) == true } } } } @objc class CoderSpecFake: NSObject, NSCoding { let stringProperty: String let intProperty: Int let boolProperty: Bool var optionalStringProperty: String? var optionalIntProperty: Int? var optionalBoolProperty: Bool? init(stringProperty: String, intProperty: Int, boolProperty: Bool) { self.stringProperty = stringProperty self.intProperty = intProperty self.boolProperty = boolProperty } func encode(with encoder: NSCoder) { let coder = Coder(encoder) coder.encodeObject(stringProperty, forKey: "stringProperty") coder.encodeObject(intProperty, forKey: "intProperty") coder.encodeObject(boolProperty, forKey: "boolProperty") coder.encodeObject(optionalStringProperty, forKey: "optionalStringProperty") coder.encodeObject(optionalIntProperty, forKey: "optionalIntProperty") coder.encodeObject(optionalBoolProperty, forKey: "optionalBoolProperty") } required init(coder: NSCoder) { let decoder = Coder(coder) self.stringProperty = decoder.decodeKey("stringProperty") self.intProperty = decoder.decodeKey("intProperty") self.boolProperty = decoder.decodeKey("boolProperty") self.optionalStringProperty = decoder.decodeOptionalKey("optionalStringProperty") self.optionalIntProperty = decoder.decodeOptionalKey("optionalIntProperty") self.optionalBoolProperty = decoder.decodeOptionalKey("optionalBoolProperty") } }
mit
5132efc7f1eac1e4408b14fbd0da218d
38.816327
92
0.625833
5.404432
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/Register/RegisterPickMobileViewController.swift
1
5989
// // RegisterPickMobileViewController.swift // Yep // // Created by NIX on 15/3/17. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit import YepNetworking import Ruler import RxSwift import RxCocoa final class RegisterPickMobileViewController: SegueViewController { var mobile: String? var areaCode: String? private lazy var disposeBag = DisposeBag() @IBOutlet private weak var pickMobileNumberPromptLabel: UILabel! @IBOutlet private weak var pickMobileNumberPromptLabelTopConstraint: NSLayoutConstraint! @IBOutlet weak var areaCodeTextField: BorderTextField! @IBOutlet weak var areaCodeTextFieldWidthConstraint: NSLayoutConstraint! @IBOutlet weak var mobileNumberTextField: BorderTextField! @IBOutlet private weak var mobileNumberTextFieldTopConstraint: NSLayoutConstraint! private lazy var nextButton: UIBarButtonItem = { let button = UIBarButtonItem() button.title = NSLocalizedString("Next", comment: "") button.rx_tap .subscribeNext({ [weak self] in self?.tryShowRegisterVerifyMobile() }) .addDisposableTo(self.disposeBag) return button }() deinit { println("deinit RegisterPickMobile") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yepViewBackgroundColor() navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: "")) navigationItem.rightBarButtonItem = nextButton pickMobileNumberPromptLabel.text = NSLocalizedString("What's your number?", comment: "") areaCodeTextField.text = areaCode ?? NSTimeZone.areaCode areaCodeTextField.backgroundColor = UIColor.whiteColor() areaCodeTextField.delegate = self areaCodeTextField.rx_text .subscribeNext({ [weak self] _ in self?.adjustAreaCodeTextFieldWidth() }) .addDisposableTo(disposeBag) //mobileNumberTextField.placeholder = "" mobileNumberTextField.text = mobile mobileNumberTextField.backgroundColor = UIColor.whiteColor() mobileNumberTextField.textColor = UIColor.yepInputTextColor() mobileNumberTextField.delegate = self Observable.combineLatest(areaCodeTextField.rx_text, mobileNumberTextField.rx_text) { !$0.isEmpty && !$1.isEmpty } .bindTo(nextButton.rx_enabled) .addDisposableTo(disposeBag) pickMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value mobileNumberTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value if mobile == nil { nextButton.enabled = false } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) mobileNumberTextField.becomeFirstResponder() } // MARK: Actions func tryShowRegisterVerifyMobile() { view.endEditing(true) guard let mobile = mobileNumberTextField.text, areaCode = areaCodeTextField.text else { return } YepHUD.showActivityIndicator() validateMobile(mobile, withAreaCode: areaCode, failureHandler: { (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) YepHUD.hideActivityIndicator() }, completion: { (available, message) in if available, let nickname = YepUserDefaults.nickname.value { println("ValidateMobile: available") registerMobile(mobile, withAreaCode: areaCode, nickname: nickname, failureHandler: { (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) YepHUD.hideActivityIndicator() if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) } }, completion: { created in YepHUD.hideActivityIndicator() if created { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.performSegueWithIdentifier("showRegisterVerifyMobile", sender: ["mobile" : mobile, "areaCode": areaCode]) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.nextButton.enabled = false YepAlert.alertSorry(message: "registerMobile failed", inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) }) } }) } else { println("ValidateMobile: \(message)") YepHUD.hideActivityIndicator() SafeDispatch.async { self.nextButton.enabled = false YepAlert.alertSorry(message: message, inViewController: self, withDismissAction: { [weak self] in self?.mobileNumberTextField.becomeFirstResponder() }) } } }) } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showRegisterVerifyMobile" { if let info = sender as? [String: String] { let vc = segue.destinationViewController as! RegisterVerifyMobileViewController vc.mobile = info["mobile"] vc.areaCode = info["areaCode"] } } } }
mit
2ff231a63bb02af0c8299b558be24a6d
34.011696
141
0.617505
5.767823
false
false
false
false
carabina/ZTDropDownTextField
ZTDropDownTextField/ViewController.swift
1
3310
// // ViewController.swift // Example // // Created by Ziyang Tan on 7/30/15. // Copyright (c) 2015 Ziyang Tan. All rights reserved. // import UIKit import MapKit import AddressBookUI import ZTDropDownTextField class ViewController: UIViewController { // MARK: Instance Variables let geocoder = CLGeocoder() let region = CLCircularRegion(center: CLLocationCoordinate2DMake(37.7577, -122.4376), radius: 1000, identifier: "region") var placemarkList: [CLPlacemark] = [] // Mark: Outlet @IBOutlet weak var fullAddressTextField: ZTDropDownTextField! @IBOutlet weak var addressSummaryTextView: UITextView! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() fullAddressTextField.dataSourceDelegate = self fullAddressTextField.animationStyle = .Expand fullAddressTextField.addTarget(self, action: "fullAddressTextDidChanged:", forControlEvents:.EditingChanged) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Address Helper Mehtods func fullAddressTextDidChanged(textField: UITextField) { if textField.text.isEmpty { placemarkList.removeAll(keepCapacity: false) fullAddressTextField.dropDownTableView.reloadData() return } geocoder.geocodeAddressString(textField.text, inRegion: region, completionHandler: { (placemarks, error) -> Void in if error != nil { println(error) } else { self.placemarkList.removeAll(keepCapacity: false) self.placemarkList = placemarks as! [CLPlacemark] self.fullAddressTextField.dropDownTableView.reloadData() } }) } private func formateedFullAddress(placemark: CLPlacemark) -> String { let lines = ABCreateStringWithAddressDictionary(placemark.addressDictionary, false) let addressString = lines.stringByReplacingOccurrencesOfString("\n", withString: ", ", options: .LiteralSearch, range: nil) return addressString } } extension ViewController: ZTDropDownTextFieldDataSourceDelegate { func dropDownTextField(dropDownTextField: ZTDropDownTextField, numberOfRowsInSection section: Int) -> Int { return placemarkList.count } func dropDownTextField(dropDownTextField: ZTDropDownTextField, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = dropDownTextField.dropDownTableView.dequeueReusableCellWithIdentifier("addressCell") as? UITableViewCell if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "addressCell") } cell!.textLabel!.text = formateedFullAddress(placemarkList[indexPath.row]) cell!.textLabel?.numberOfLines = 0 return cell! } func dropDownTextField(dropdownTextField: ZTDropDownTextField, didSelectRowAtIndexPath indexPath: NSIndexPath) { fullAddressTextField.text = formateedFullAddress(placemarkList[indexPath.row]) addressSummaryTextView.text = formateedFullAddress(placemarkList[indexPath.row]) } }
mit
1bdc68fc4bf9427957e760ad672deac9
36.191011
133
0.688822
5.262321
false
false
false
false
carabina/HiBeacons
HiBeacons/NATAdvertisingOperation.swift
3
5306
// // NATAdvertising.swift // HiBeacons // // Created by Nick Toumpelis on 2015-07-26. // Copyright (c) 2015 Nick Toumpelis. // // 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 CoreLocation import CoreBluetooth /// Lists the methods that an advertising delegate should implement to be notified for all advertising operation events. protocol NATAdvertisingOperationDelegate { /** Triggered when the advertising operation has started successfully. */ func advertisingOperationDidStartSuccessfully() /** Triggered by the advertising operation when it has stopped successfully. */ func advertisingOperationDidStopSuccessfully() /** Triggered when the advertising operation has failed to start. */ func advertisingOperationDidFailToStart() } /// NATAdvertisingOperation contains all the process logic required to successfully advertising the presence of a /// a specific beacon (and region) to nearby devices. class NATAdvertisingOperation: NATOperation { /// The delegate for an advertising operation. var delegate: NATAdvertisingOperationDelegate? /// An instance of a CBPeripheralManager, which is used for advertising a beacon to nearby devices. var peripheralManager = CBPeripheralManager(delegate: nil, queue: nil, options: nil) /** Starts the beacon advertising process. */ func startAdvertisingBeacon() { println("Turning on advertising...") if peripheralManager?.state != .PoweredOn { println("Peripheral manager is off.") delegate?.advertisingOperationDidFailToStart() return } activatePeripheralManagerNotifications(); turnOnAdvertising() } /** Turns on advertising (after all the checks have been passed). */ func turnOnAdvertising() { let major: CLBeaconMajorValue = CLBeaconMajorValue(arc4random_uniform(5000)) let minor: CLBeaconMinorValue = CLBeaconMajorValue(arc4random_uniform(5000)) var region: CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconRegion.proximityUUID, major: major, minor: minor, identifier: beaconRegion.identifier) var beaconPeripheralData: NSMutableDictionary = region.peripheralDataWithMeasuredPower(nil) peripheralManager?.startAdvertising(beaconPeripheralData as [NSObject : AnyObject]) println("Turning on advertising for region: \(region).") } /** Stops the monitoring process. */ func stopAdvertisingBeacon() { peripheralManager?.stopAdvertising() deactivatePeripheralManagerNotifications(); println("Turned off advertising.") delegate?.advertisingOperationDidStopSuccessfully() } /** Sets the peripheral manager delegate to self. It is called when an instance is ready to process peripheral manager delegate calls. */ func activatePeripheralManagerNotifications() { peripheralManager.delegate = self; } /** Sets the peripheral manager delegate to nil. It is called when an instance is ready to stop processing peripheral manager delegate calls. */ func deactivatePeripheralManagerNotifications() { peripheralManager.delegate = nil; } } // MARK: - CBPeripheralManagerDelegate methods extension NATAdvertisingOperation: CBPeripheralManagerDelegate { func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager!, error: NSError!) { if error != nil { println("Couldn't turn on advertising: \(error)") delegate?.advertisingOperationDidFailToStart() } if peripheralManager!.isAdvertising { println("Turned on advertising.") delegate?.advertisingOperationDidStartSuccessfully() } } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) { if peripheralManager?.state == .PoweredOff { println("Peripheral manager is off.") delegate?.advertisingOperationDidFailToStart() } else if peripheralManager.state == .PoweredOn { println("Peripheral manager is on.") turnOnAdvertising() } } }
mit
e1bd23fffa2620430fdbe36492c0c1d3
36.104895
159
0.708443
5.414286
false
false
false
false
cnoon/swift-compiler-crashes
crashes-duplicates/03157-swift-typechecker-resolvetypeincontext.swift
11
359
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol P { typealias e : Array<e>() -> { func b<T where A.E == " let t: C { var b { } } class B<T where S.E == " class d<d where H.b = compose() -> { } class B : d where S.e : A: P func f
mit
619740d85f309cc32c1d555dbab3ce2a
21.4375
87
0.651811
3.042373
false
true
false
false
Erez-Panda/LiveBankSDK
Pod/Classes/DocumentView.swift
1
28478
// // CallNewViewController.swift // Panda4doctor // // Created by Erez Haim on 2/6/15. // Copyright (c) 2015 Erez. All rights reserved. // import UIKit class DocumentView: UIView, UIGestureRecognizerDelegate, UIScrollViewDelegate{ var user: String? @IBOutlet weak var presentaionImage: UIImageView? // @IBOutlet weak var drawingView: PassiveLinearInterpView! @IBOutlet weak var scrollView: UIScrollView? var isDragging = false var isFirstLoad = true var currentImage: UIImage? var currentImageUrl: String? var showIncoming = true var signView: SignDocumentPanelView? var signedImageView: UIImageView? var controlPanelView: ControlPanelView? var controlPanelTimer: NSTimer? var okPanelView: OkCancelView? var preLoadedImages: Array<Dictionary<Int, UIImage?>> = [] var signatureBoxes:Dictionary<Int, Array<Dictionary<String, AnyObject>>> = [:] var currentDocument: Int? var currentPage: Int? var currentBox: Int? var oldPreLoadedImages: Dictionary<String, UIImage?> = [:] var modifiedImages: Dictionary<String, UIImage?> = [:] var lastSignatureData: Dictionary<String, AnyObject>? var currentOrientation: UIDeviceOrientation? override func awakeFromNib() { if (isFirstLoad){ self.addGestureRecognizer(UITapGestureRecognizer(target: self, action:"tap:")) let swipeRight = UISwipeGestureRecognizer(target: self, action: "swipeRight") swipeRight.direction = UISwipeGestureRecognizerDirection.Right swipeRight.cancelsTouchesInView = false self.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipeLeft") swipeLeft.direction = UISwipeGestureRecognizerDirection.Left swipeLeft.cancelsTouchesInView = false self.addGestureRecognizer(swipeLeft) if ((currentImage) != nil){ presentaionImage?.image = currentImage } scrollView?.delegate = self addControlPanel() registerForMessages() isFirstLoad = false } // Do any additional setup after loading the view. } func attachToView(view: UIView){ view.addSubview(self) self.addConstraintsToSuperview(view, top: 0, left: 0, bottom: 0, right: 0) } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return presentaionImage } func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { if scale == 1 { scrollView.scrollEnabled = false } else { scrollView.scrollEnabled = true } } func onSignViewClose(sender: UIView){ okPanelView?.removeFromSuperview() okPanelView = nil signView?.removeFromSuperview() self.signView = nil if scrollView?.zoomScale > 1{ scrollView?.scrollEnabled = true } } func randomAlphaNumericString(length: Int) -> String { let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" for _ in (0..<length) { let randomNum = Int(arc4random_uniform(allowedCharsCount)) let newCharacter = allowedChars[allowedChars.startIndex.advancedBy(randomNum)] randomString += String(newCharacter) } return randomString } func sendSignaturePoints(signatureView: LinearInterpView, origin: CGPoint, imgSize: CGSize, scaleRatio: CGFloat, zoom: CGFloat){ var user = "USER-ID" if self.user != nil { user = self.user! } else if let creator = Session.sharedInstance.currentCall?["callee"] as? String{ user = creator } var data = [ // TODO: add the actucal userId "creator": user, "width": signatureView.frame.width, "height": signatureView.frame.height, "left": origin.x/imgSize.width, "top": origin.y/imgSize.height, "image_width": imgSize.width*(zoom/scaleRatio), "image_height": imgSize.height*(zoom/scaleRatio), "call": Session.sharedInstance.currentCall!["id"] as! Int, "page_number": self.currentPage!, "document_id": self.currentDocument!, "tracking": randomAlphaNumericString(6), "type": "signature", "tag": self.signatureBoxes[currentPage!]![currentBox!]["data"] as! String ] as Dictionary<String, AnyObject> // var pointsStr = "width=\()&height=\(signatureView.frame.height)&originX=\(origin.x/imgSize.width)&originY=\(origin.y/imgSize.height)&screenWidth=\(imgSize.width/scaleRatio)&screenHeight=\(imgSize.height/scaleRatio)&zoom=\(zoom)&points=" var pointsStr = "" for line in signatureView.points { for point in line{ pointsStr += "\(NSString(format: "%.3f",max(point.x,0))),\(NSString(format: "%.3f",max(point.y,0)))-" } pointsStr += "***" } data["points"] = pointsStr Session.sharedInstance.sendMessage("signature_points", data: data) } func addSignatureToImage(){ if (presentaionImage == nil && presentaionImage!.image == nil){ return } if let data = lastSignatureData{ let scaledSignView = data["scaledSignView"] as! PassiveLinearInterpView let X = data["X"] as! CGFloat let Y = data["Y"] as! CGFloat if nil != currentBox { self.signatureBoxes[currentPage!]![currentBox!]["originaltype"] = self.signatureBoxes[currentPage!]![currentBox!]["type"] self.signatureBoxes[currentPage!]![currentBox!]["type"] = self.signatureBoxes[currentPage!]![currentBox!]["type"] as! String + "-signed" } let screen = UIScreen.mainScreen().bounds let document = presentaionImage!.image! let scaleRatio = max(document.size.width/screen.width, document.size.height/screen.height) //One of these has to be 0 let heightDiff = (screen.height*scaleRatio) - document.size.height let widthDiff = (screen.width*scaleRatio) - document.size.width let scaledSignImage = takeScreenshot(scaledSignView) UIGraphicsBeginImageContext(document.size) document.drawInRect(CGRectMake(0,0,document.size.width, document.size.height)) scaledSignImage.drawInRect(CGRectMake((X*scaleRatio)-widthDiff/2,(Y*scaleRatio)-heightDiff/2,scaledSignView.frame.width, scaledSignView.frame.height)) let signedDoc = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let image: UIImage = signedDoc self.presentaionImage?.image = image if currentImageUrl != nil { modifiedImages[currentImageUrl!] = image } if currentPage != nil && currentDocument != nil { setImageAtIndex(image, document: currentDocument!, page: currentPage!) } self.signView?.removeFromSuperview() self.signView = nil scrollView?.scrollEnabled = false self.scrollView?.setZoomScale(1, animated: false) } } func addTextToImage(data: Dictionary<String, AnyObject>){ if (presentaionImage == nil && presentaionImage!.image == nil){ return } let document = presentaionImage!.image! let screenWidth = data["image_width"] as! CGFloat let screenHeight = data["image_height"] as! CGFloat let width = data["width"] as! CGFloat let height = data["height"] as! CGFloat //Image is aspect fit, scale factor will be the biggest change on image let x = data["left"] as! CGFloat// * (screen.width-widthDiff) let y = data["top"] as! CGFloat// * (screen.height-heightDiff) let originalScaling = max(document.size.width/screenWidth, document.size.height/screenHeight) let remoteTextView = UITextField(frame: CGRectMake(0,0,width*originalScaling,height*originalScaling)) let fontSize = data["font_size"] as! CGFloat remoteTextView.text = data["text"] as? String remoteTextView.font = remoteTextView.font!.fontWithSize(fontSize*originalScaling) let scaledTextImage = takeScreenshot(remoteTextView) UIGraphicsBeginImageContext(document.size) document.drawInRect(CGRectMake(0,0,document.size.width, document.size.height)) scaledTextImage.drawInRect(CGRectMake((x*document.size.width),(y*document.size.height),remoteTextView.frame.width, remoteTextView.frame.height)) let signedDoc = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let image: UIImage = signedDoc self.presentaionImage?.image = image if currentImageUrl != nil { modifiedImages[currentImageUrl!] = image } if currentPage != nil && currentDocument != nil { setImageAtIndex(image, document: currentDocument!, page: currentPage!) } scrollView?.scrollEnabled = false self.scrollView?.setZoomScale(1, animated: false) } func onSignViewSign(signatureView: LinearInterpView, origin: CGPoint){ if (presentaionImage == nil && presentaionImage!.image == nil){ return } let screen = UIScreen.mainScreen().bounds let zoom = scrollView!.zoomScale //let offset = scrollView!.contentOffset let document = presentaionImage!.image! //Image is aspect fit, scale factor will be the biggest change on image let scaleRatio = max(document.size.width/screen.width, document.size.height/screen.height) let X = (origin.x+scrollView!.contentOffset.x)/zoom let Y = (origin.y+scrollView!.contentOffset.y)/zoom let scaledSignView = PassiveLinearInterpView(frame: CGRectMake(0,0,signatureView.frame.width*scaleRatio/zoom, signatureView.frame.height*scaleRatio/zoom)) //scaledSignView.path?.lineWidth *= scaleRatio/zoom for line in signatureView.points { for i in 0 ..< line.count{ if i==0 { scaledSignView.moveToPoint(CGPoint(x: line[i].x*scaleRatio/zoom , y: line[i].y*scaleRatio/zoom)) } else { scaledSignView.addPoint(CGPoint(x: line[i].x*scaleRatio/zoom , y: line[i].y*scaleRatio/zoom)) } } } //One of these has to be 0 let heightDiff = (screen.height*scaleRatio) - document.size.height let widthDiff = (screen.width*scaleRatio) - document.size.width sendSignaturePoints(signatureView, origin:CGPointMake((X*scaleRatio)-widthDiff/2,(Y*scaleRatio)-heightDiff/2), imgSize:CGSizeMake( document.size.width, document.size.height), scaleRatio: scaleRatio, zoom:zoom) lastSignatureData = [ "scaledSignView": scaledSignView, "X": X, "Y": Y ] } func takeScreenshot(view: UIView) -> UIImage{ UIGraphicsBeginImageContext(view.frame.size) view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func closeOpenPanels(){ okPanelView?.removeFromSuperview() okPanelView = nil signView?.removeFromSuperview() signView = nil if scrollView?.zoomScale > 1{ scrollView?.scrollEnabled = true } } func setBoxPosition(box: Dictionary<String, AnyObject>?){ if (presentaionImage == nil && presentaionImage!.image == nil){ return } if signView != nil && box != nil { dispatch_async(dispatch_get_main_queue()) { self.scrollView?.scrollEnabled = false var bounds = UIScreen.mainScreen().bounds.size if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){ bounds = CGSizeMake(max(bounds.height, bounds.width), min(bounds.height, bounds.width)) } if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){ bounds = CGSizeMake(min(bounds.height, bounds.width), max(bounds.height, bounds.width)) } //let h: CGFloat = 120 let w: CGFloat = 0.8*bounds.width let document = self.presentaionImage!.image! let top = box!["top"] as! CGFloat*document.size.height let left = (box!["left"] as! CGFloat)*document.size.width let width = box!["width"] as! CGFloat*document.size.width let height = box!["height"] as! CGFloat*document.size.height let scale = w/width //Image is aspect fit, scale factor will be the biggest change on image let scaleRatio = max(document.size.width/bounds.width, document.size.height/bounds.height) self.scrollView?.setZoomScale(scaleRatio*scale, animated: false) //One of these has to be 0 let heightDiff = (bounds.height*scaleRatio*scale - document.size.height*scale)/2 let widthDiff = (bounds.width*scaleRatio*scale - document.size.width*scale)/2 let h = w/2//min(height*scale, bounds.height*0.8) let topOffset = max(0, height*scale - w/2) let X = left*scale+widthDiff-((bounds.width-w)/2) let Y = top*scale+heightDiff-((bounds.height-(h+2*topOffset))/2) self.scrollView?.contentOffset = CGPointMake(X, Y) self.signView?.frame = CGRectMake(0.5*(bounds.width-w), 0.5*(bounds.height-h), w, h) } } } override func layoutSubviews() { super.layoutSubviews() if currentOrientation != UIDevice.currentDevice().orientation{ currentOrientation = UIDevice.currentDevice().orientation if (nil != self.currentBox){ setBoxPosition(self.signatureBoxes[self.currentPage!]?[self.currentBox!]) } } } func onPanelOk(){ if let sv = signView{ if !sv.isEmpty(){ sv.disable() onSignViewSign(sv.signView, origin: sv.frame.origin) okPanelView?.removeFromSuperview() } } } func onPanelCancel(){ closeOpenPanels() Session.sharedInstance.sendMessage("box_closed", data: ["error": "User canceled signature"]) } func onPanelClean(){ signView?.clean() } func signDocument(box: Dictionary<String, AnyObject>? = nil){ if (nil != box){ closeOpenPanels() signView = NSBundle(forClass: LiveSign.self).loadNibNamed("SignDocumentPanelView", owner: self, options: nil)[0] as? SignDocumentPanelView signView?.onClose = onSignViewClose // signView?.onSign = onSignViewSign setBoxPosition(box) self.addSubview(signView!) okPanelView = NSBundle(forClass: LiveSign.self).loadNibNamed("OkCancelView", owner: self, options: nil)[0] as? OkCancelView okPanelView?.onClean = onPanelClean okPanelView?.onOk = onPanelOk okPanelView?.onCancel = onPanelCancel okPanelView?.attachToView(signView!, superView: self) } } func tap(sender: UITapGestureRecognizer) { if signView != nil { } else if nil != controlPanelView && controlPanelView!.isVisible(){ controlPanelView?.hide() controlPanelTimer?.invalidate() } else { controlPanelView?.show() controlPanelTimer?.invalidate() controlPanelTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: Selector("hideControlPanel"), userInfo: AnyObject?(), repeats: false) } } func hideControlPanel(){ controlPanelView?.hide() } func openNextBox(){ self.signDocument(self.getNextBox()) } func requestNextBox(){ Session.sharedInstance.sendMessage("request_next_box", data: [:]) } func closeView(){ self.fadeOut(duration: 0.325, remove: true) Session.sharedInstance.disconnect() } func addControlPanel(){ controlPanelView = NSBundle(forClass: LiveSign.self).loadNibNamed("ControlPanelView", owner: self, options: nil)[0] as? ControlPanelView controlPanelView?.onLeft = swipeRight controlPanelView?.onRight = swipeLeft controlPanelView?.onSign = requestNextBox controlPanelView?.onClose = closeView controlPanelView?.attachToView(self) controlPanelTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: Selector("hideControlPanel"), userInfo: AnyObject?(), repeats: false) } func requestForCurrentSlide(){ Session.sharedInstance.sendMessage("send_current_res", data: [:]) } func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in completion(data: data) }.resume() } func swipeRight(){ if signView==nil && self.currentPage != nil && self.currentPage > 0{ selectPage(self.currentPage!-1) } } func swipeLeft(){ if signView==nil && self.currentPage != nil && self.currentPage < preLoadedImages[self.currentDocument!].count-1{ selectPage(self.currentPage!+1) } } func animateImageView(image: UIImage, toRight: Bool) { CATransaction.begin() CATransaction.setAnimationDuration(0.25) let transition = CATransition() // transition.type = kCATransitionFade transition.type = kCATransitionPush if toRight{ transition.subtype = kCATransitionFromRight } else { transition.subtype = kCATransitionFromLeft } self.presentaionImage?.layer.addAnimation(transition, forKey: kCATransition) self.presentaionImage?.image = image CATransaction.commit() } func selectPage(index: Int){ if (index != self.currentPage){ Session.sharedInstance.sendMessage("page_changed", data: ["index": index]) self.signedImageView?.removeFromSuperview() self.signedImageView = nil self.scrollView?.setZoomScale(1.0, animated: false) scrollView?.scrollEnabled = false let prevIndex = currentPage self.currentPage = index if let image = self.getImageAtIndex(self.currentDocument!, page: self.currentPage!){ if nil != self.presentaionImage { dispatch_async(dispatch_get_main_queue()){ //pImg.image = image self.animateImageView(image, toRight: prevIndex<index) } } else { self.currentImage = image } } } } func duplicateBoxes(pagesMetaData: Array<Array<Dictionary<String, AnyObject>>>){ for i in 0..<pagesMetaData.count{ self.signatureBoxes[i] = pagesMetaData[i] } } func registerForMessages(){ Session.sharedInstance.onMessage("load_res_with_index") { (message) -> Void in if (self.signView != nil){ return } self.signedImageView?.removeFromSuperview() self.signedImageView = nil self.scrollView?.setZoomScale(1.0, animated: false) self.scrollView?.scrollEnabled = false if let data = message { self.currentDocument = data["document"] as? Int self.currentPage = data["page"] as? Int if let metaData = data["metaData"] as? Array<Dictionary<String, AnyObject>>{ if nil == self.signatureBoxes[self.currentPage!]{ self.signatureBoxes[self.currentPage!] = metaData } } if let image = self.getImageAtIndex(self.currentDocument!, page: self.currentPage!){ if let pImg = self.presentaionImage { dispatch_async(dispatch_get_main_queue()){ pImg.image = image } } else { self.currentImage = image } } else { self.setImageAtIndex(data["url"] as! String, document: self.currentDocument!, page: self.currentPage!, completion: { (result) -> Void in if let pImg = self.presentaionImage { dispatch_async(dispatch_get_main_queue()){ pImg.image = result } } else { self.currentImage = result } }) } } } Session.sharedInstance.onMessage("preload_res_with_index") { (message) -> Void in if let data = message{ if let metaData = data["metaData"] as? Array<Dictionary<String, AnyObject>>{ if nil == self.signatureBoxes[data["page"] as! Int]{ self.signatureBoxes[data["page"] as! Int] = metaData } } if nil == self.getImageAtIndex(data["document"] as! Int, page: data["page"] as! Int){ self.setImageAtIndex(data["url"] as! String, document: data["document"] as! Int, page: data["page"] as! Int, completion: nil) } } } Session.sharedInstance.onMessage("zoom_scale") { (message) -> Void in if let data = message{ self.scrollView?.setZoomScale(data["scale"] as! CGFloat, animated: false) let x = data["x"] as! CGFloat let y = data["y"] as! CGFloat if let size = self.scrollView?.contentSize { self.scrollView?.contentOffset = CGPoint(x: CGFloat(x) * size.width ,y: CGFloat(y) * size.height) } } } Session.sharedInstance.onMessage("open_next_box") { (message) -> Void in if let data = message{ if let box = self.getNextBox(data["guid"] as? String){ self.signDocument(box) } else { Session.sharedInstance.sendMessage("open_next_box", data: ["error": "No available signatures"]) } } } Session.sharedInstance.onMessage("connection_created") { (message) -> Void in if nil != message { if let firstTime = message!["firstTime"] as? Bool{ if firstTime{ Session.sharedInstance.sendMessage("connection_created", data: ["firstTime": false]) } } } } Session.sharedInstance.onMessage("signature_accepted") { (message) -> Void in if let data = message{ if let success = data["success"] as? Bool{ if success{ self.addSignatureToImage() //self.signDocument(self.getNextBox()) } else{ if nil != data["retry"] as? Bool{ self.closeOpenPanels() self.signDocument(self.signatureBoxes[self.currentPage!]?[self.currentBox!]) } else { self.closeOpenPanels() self.scrollView?.setZoomScale(1, animated: false) self.scrollView?.scrollEnabled = false } } } } } Session.sharedInstance.onMessage("duplicate_boxes") { (message) -> Void in if let boxes = message?["boxes"] as? Array<Array<Dictionary<String, AnyObject>>>{ self.duplicateBoxes(boxes) //self.signDocument(self.getNextBox()) } } Session.sharedInstance.onMessage("add_text") { (message) -> Void in if let data = message{ self.addTextToImage(data) } } Session.sharedInstance.onMessage("translate_and_scale") { (message) -> Void in if (self.signView != nil){ return } if let data = message{ let scale = data["scale"] as! CGFloat self.scrollView?.setZoomScale(scale, animated: false) if scale >= 1 { self.scrollView?.scrollEnabled = false } else { self.scrollView?.scrollEnabled = true } } } Session.sharedInstance.onMessage("close_session") { (message) -> Void in self.closeView() } } func getNextBox(page: Int, data:String? = nil) -> Dictionary<String, AnyObject>?{ if nil != self.signatureBoxes[page]{ for index in 0..<self.signatureBoxes[page]!.count{ if nil != data && data != ""{ if (self.signatureBoxes[page]![index]["data"] as! String).containsString(data!){ currentBox = index return self.signatureBoxes[page]![index] } } if data == "" && !(self.signatureBoxes[page]![index]["type"] as! String).containsString("-signed"){ currentBox = index return self.signatureBoxes[page]![index] } } return nil } return nil } func getNextBox(data:String? = nil) -> Dictionary<String, AnyObject>?{ var index = 0 while index < preLoadedImages.count{ let box = getNextBox(index, data: data) if nil != box { selectPage(index) return box } else { index++ } } return nil } func setImageAtIndex(url: String, document: Int, page: Int, completion: ((result: UIImage) -> Void)?) -> Void{ while preLoadedImages.count < document+1{ preLoadedImages.append([:]) } if let url = NSURL(string: url.stringByReplacingOccurrencesOfString("10.0.2.2", withString: "127.0.0.1")){ self.getDataFromUrl(url) { data in if nil != data{ if let image = UIImage(data: data!){ self.preLoadedImages[document][page] = image completion?(result: image) } } } } } func setImageAtIndex(image: UIImage, document: Int, page: Int){ while preLoadedImages.count < document+1{ preLoadedImages.append([:]) } self.preLoadedImages[document][page] = image } func getImageAtIndex(document: Int, page: Int) -> UIImage?{ if preLoadedImages.count > document{ if let value = self.preLoadedImages[document][page]{ return value } } return nil } }
mit
fbe1afc971ae6610bcbe6c1a0534e552
39.624822
246
0.570195
4.971718
false
false
false
false
yuByte/HackingWithSwift
project23/Project23/GameScene.swift
24
2909
// // GameScene.swift // Project23 // // Created by Hudzilla on 16/09/2015. // Copyright (c) 2015 Paul Hudson. All rights reserved. // import GameplayKit import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var starfield: SKEmitterNode! var player: SKSpriteNode! var possibleEnemies = ["ball", "hammer", "tv"] var gameTimer: NSTimer! var gameOver = false var scoreLabel: SKLabelNode! var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } override func didMoveToView(view: SKView) { backgroundColor = UIColor.blackColor() starfield = SKEmitterNode(fileNamed: "Starfield.sks")! starfield.position = CGPoint(x: 1024, y: 384) starfield.advanceSimulationTime(10) addChild(starfield) starfield.zPosition = -1 player = SKSpriteNode(imageNamed: "player") player.position = CGPoint(x: 100, y: 384) player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size) player.physicsBody!.contactTestBitMask = 1 addChild(player) scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.position = CGPoint(x: 16, y: 16) scoreLabel.horizontalAlignmentMode = .Left addChild(scoreLabel) score = 0 physicsWorld.gravity = CGVector(dx: 0, dy: 0) physicsWorld.contactDelegate = self gameTimer = NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: "createEnemy", userInfo: nil, repeats: true) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { } override func update(currentTime: CFTimeInterval) { for node in children { if node.position.x < -300 { node.removeFromParent() } } if !gameOver { score += 1 } } func createEnemy() { possibleEnemies = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(possibleEnemies) as! [String] let randomDistribution = GKRandomDistribution(lowestValue: 50, highestValue: 736) let sprite = SKSpriteNode(imageNamed: possibleEnemies[0]) sprite.position = CGPoint(x: 1200, y: randomDistribution.nextInt()) addChild(sprite) sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size) sprite.physicsBody?.categoryBitMask = 1 sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0) sprite.physicsBody?.angularVelocity = 5 sprite.physicsBody?.linearDamping = 0 sprite.physicsBody?.angularDamping = 0 } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { guard let touch = touches.first else { return } var location = touch.locationInNode(self) if location.y < 100 { location.y = 100 } else if location.y > 668 { location.y = 668 } player.position = location } func didBeginContact(contact: SKPhysicsContact) { let explosion = SKEmitterNode(fileNamed: "explosion.sks")! explosion.position = player.position addChild(explosion) player.removeFromParent() gameOver = true } }
unlicense
9619cead9ecaa9f43f007f317b803e8d
25.445455
127
0.725335
3.792699
false
false
false
false
tutsplus/iOSFromScratch-ShoppingList-2
Shopping List/AppDelegate.swift
2
3831
// // AppDelegate.swift // Shopping List // // Created by Bart Jacobs on 12/12/15. // Copyright © 2015 Envato Tuts+. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Seed Items seedItems() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - // MARK: Helper Methods private func seedItems() { let ud = NSUserDefaults.standardUserDefaults() if !ud.boolForKey("UserDefaultsSeedItems") { if let filePath = NSBundle.mainBundle().pathForResource("seed", ofType: "plist"), let seedItems = NSArray(contentsOfFile: filePath) { // Items var items = [Item]() // Create List of Items for seedItem in seedItems { if let name = seedItem["name"] as? String, let price = seedItem["price"] as? Float { print("\(name) - \(price)") // Create Item let item = Item(name: name, price: price) // Add Item items.append(item) } } print(items) if let itemsPath = pathForItems() { // Write to File if NSKeyedArchiver.archiveRootObject(items, toFile: itemsPath) { ud.setBool(true, forKey: "UserDefaultsSeedItems") } } } } } private func pathForItems() -> String? { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) if let documents = paths.first, let documentsURL = NSURL(string: documents) { return documentsURL.URLByAppendingPathComponent("items").path } return nil } }
bsd-2-clause
989362945713895de1986a19f6c97369
40.630435
285
0.622193
5.768072
false
false
false
false
AFSR/RettApp
RettApp/AppDelegate.swift
1
5880
// // AppDelegate.swift // RettApp // // Created by Julien Fieschi on 04/04/2020. // Copyright © 2020 AFSR. All rights reserved. // import UIKit import CoreData import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: alreadyParticipation Init var alreadyParticipating:Bool { get{ return UserDefaults.standard.bool(forKey: "UserHasConsentedKey") } set{ UserDefaults.standard.set(newValue, forKey: "UserHasConsentedKey") UserDefaults.standard.synchronize() } } func getPlist(withName name: String) -> [String]? { if let path = Bundle.main.path(forResource: name, ofType: "plist"), let xml = FileManager.default.contents(atPath: path) { return (try? PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: nil)) as? [String] } return nil } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if UserDefaults.standard.value(forKey: "Device_uuid") == nil { UserDefaults.standard.set(UUID().uuidString, forKey: "Device_uuid") } print("UUID de l'appareil: ", UserDefaults.standard.value(forKey: "Device_uuid") as! String ) if let path = Bundle.main.path(forResource: "AFSR_Credentials", ofType: "plist"), let dict_Credentials = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { // use swift dictionary as normal let configuration = ParseClientConfiguration { $0.applicationId = dict_Credentials["appId"] as! String $0.clientKey = dict_Credentials["clientKey"] as! String $0.server = dict_Credentials["server"] as! String } Parse.initialize(with: configuration) } let gameScore = PFObject(className:"GameScore") gameScore["score"] = 1337 gameScore["playerName"] = "Sean Plott" gameScore["cheatMode"] = false gameScore.saveInBackground { (succeeded, error) in if (succeeded) { // The object has been saved. print("Success!") } else { // There was a problem, check error.description print("Failed!") } } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentCloudKitContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentCloudKitContainer(name: "RettApp") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
0825954e33dfcae502a8c95cee63bb4d
41.912409
199
0.628508
5.443519
false
true
false
false
lieonCX/Uber
UberRider/UberRider/ViewModel/Chat/ChatViewModel.swift
1
2723
// // ChatViewModel.swift // UberRider // // Created by lieon on 2017/4/4. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import Foundation import FirebaseDatabase import FirebaseStorage class ChatViewModel { func sendMessage(senderID: String, senderName: String, text: String) { let message: [String: Any] = [Constants.senderID: senderID, Constants.senderName: senderName, Constants.text: text] DBProvider.shared.messageRef.childByAutoId().setValue(message) } func sendMediaMessage(senderID: String, senderName: String, image: Data?, video: URL?) { if let imageData = image { DBProvider.shared.imgaeStorageRef.put(imageData, metadata: nil, completion: { (metaData: FIRStorageMetadata?, error: Error?) in if let error = error { print("upload image failed:\(error.localizedDescription)") return } if let metaData = metaData, let downloadURL = metaData.downloadURL() { let data: [String: Any] = [Constants.senderID: senderID, Constants.senderName: senderName, Constants.URL: String(describing: downloadURL)] DBProvider.shared.mediaMessageRef.childByAutoId().setValue(data) } }) } if let video = video { DBProvider.shared.videoStorageRef.putFile(video, metadata: nil, completion: { (metaData: FIRStorageMetadata?, error: Error?) in if let error = error { print("upload video failed:\(error.localizedDescription)") return } if let metaData = metaData, let downloadURL = metaData.downloadURL() { let data: [String: Any] = [Constants.senderID: senderID, Constants.senderName: senderName, Constants.URL: "\(String(describing: downloadURL))"] DBProvider.shared.mediaMessageRef.childByAutoId().setValue(data) } }) } } func observeTextMessage(callback: @escaping (_ message: [String: Any]) -> Void) { DBProvider.shared.messageRef.observe(.childAdded, with: {snapshot in if let message = snapshot.value as? [String: Any] { callback(message) } }) } func oberserMediaMessage(callback: @escaping(_ message: [String: Any]) -> Void) { DBProvider.shared.mediaMessageRef.observe(.childAdded, with: { snapshot in if let message = snapshot.value as? [String: Any] { callback(message) } }) } }
mit
9f7a04c87406429ace2a74827f969654
42.174603
163
0.5875
4.900901
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Graphics/DrawingDocument.swift
1
5732
// // DrawingDocument.swift // LispKit // // Created by Matthias Zenger on 01/07/2018. // Copyright © 2018 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import CoreGraphics #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(macOS) import AppKit #endif /// /// A `DrawingDocument` object represents a document whose pages consist of drawings. /// For now, the main purpose of creating a `DrawingDocument` object is to save it into /// a PDF document. /// public final class DrawingDocument { /// The title of the collection. public var title: String? /// The author of the collection. public var author: String? /// The creator of the collection. public var creator: String? /// The subject of the collection. public var subject: String? /// Keywords describing the collection public var keywords: String? /// The owner's password public var ownerPassword: String? /// A user password public var userPassword: String? /// Can this collection be printed? public var allowsPrinting: Bool = true /// Can this collection be copied (copy/pasted)? public var allowsCopying: Bool = true /// Internal representation of the various pages of the drawing collection. public private(set) var pages: [Page] /// Initializer public init (title: String? = nil, author: String? = nil, creator: String? = nil, subject: String? = nil, keywords: String? = nil) { self.pages = [] self.title = title self.author = author self.creator = creator self.subject = subject self.keywords = keywords } /// Append a new drawing to the collection. public func append(_ drawing: Drawing, flipped: Bool = false, width: Int, height: Int) { self.pages.append(Page(drawing: drawing, flipped: flipped, width: width, height: height)) } /// Save the collection as a PDF file to URL `url`. public func saveAsPDF(url: URL) -> Bool { // First check if we can write to the URL var dir: ObjCBool = false let parent = url.deletingLastPathComponent().path guard FileManager.default.fileExists(atPath: parent, isDirectory: &dir) && dir.boolValue else { return false } guard FileManager.default.isWritableFile(atPath: parent) else { return false } // Define PDF document information let pdfInfo: NSMutableDictionary = [ kCGPDFContextAllowsPrinting: (self.allowsPrinting ? kCFBooleanTrue : kCFBooleanFalse) as Any, kCGPDFContextAllowsCopying : (self.allowsCopying ? kCFBooleanTrue : kCFBooleanFalse) as Any ] if let title = self.title { pdfInfo[kCGPDFContextTitle] = title } if let author = self.author { pdfInfo[kCGPDFContextAuthor] = author } if let creator = self.creator { pdfInfo[kCGPDFContextCreator] = creator } if let subject = self.subject { pdfInfo[kCGPDFContextSubject] = subject } if let keywords = self.keywords { pdfInfo[kCGPDFContextKeywords] = keywords } if let password = self.ownerPassword { pdfInfo[kCGPDFContextOwnerPassword] = password } if let password = self.userPassword { pdfInfo[kCGPDFContextUserPassword] = password } // Default media box (will be overwritten on a page by page basis) var mediaBox = CGRect(x: 0, y: 0, width: Double(200), height: Double(200)) // Create a core graphics context suitable for creating PDF files guard let cgc = CGContext(url as CFURL, mediaBox: &mediaBox, pdfInfo as CFDictionary) else { return false } #if os(macOS) let previous = NSGraphicsContext.current defer { NSGraphicsContext.current = previous } #endif for page in self.pages { page.createPDFPage(in: cgc) } cgc.closePDF() return true } /// Representation of a page. public struct Page { public let drawing: Drawing public let flipped: Bool public let width: Int public let height: Int fileprivate func createPDFPage(in cgc: CGContext) { var mediaBox = CGRect(x: 0, y: 0, width: Double(self.width), height: Double(self.height)) let pageInfo: NSDictionary = [ kCGPDFContextMediaBox : NSData(bytes: &mediaBox, length: MemoryLayout.size(ofValue: mediaBox)) ] // Create a graphics context for drawing into the PDF page #if os(iOS) || os(watchOS) || os(tvOS) UIGraphicsPushContext(cgc) defer { UIGraphicsPopContext() } #elseif os(macOS) NSGraphicsContext.current = NSGraphicsContext(cgContext: cgc, flipped: self.flipped) #endif // Create a new PDF page cgc.beginPDFPage(pageInfo as CFDictionary) cgc.saveGState() // Flip graphics if required if self.flipped { cgc.translateBy(x: 0.0, y: CGFloat(self.height)) cgc.scaleBy(x: 1.0, y: -1.0) } // Draw the image self.drawing.draw() cgc.restoreGState() // Close PDF page and document cgc.endPDFPage() } } }
apache-2.0
456e9e9dc072438b2c40dd98d4f74d72
30.662983
99
0.65486
4.283259
false
false
false
false
Alberto-Vega/SwiftCodeChallenges
IntegerToWords.playground/Sources/Assertion.swift
1
2712
import Foundation import UIKit public func assertEqual(_ actual: String, _ expected: String) -> String { let result = actual == expected ? "✅" : "⛔️ \"\(actual)\" does not match the expected value of \"\(expected)\"" return result } public enum Assertion: CustomPlaygroundQuickLookable { case success case failure(actual: String, expected: String) public init(actual: String, expected: String) { if actual == expected { self = .success } else { print("⛔️ \"\(actual)\" != \"\(expected)\"") self = .failure(actual: actual, expected: expected) } } public var customPlaygroundQuickLook: PlaygroundQuickLook { switch self { case .success: return .attributedString(NSAttributedString(string: "✅ Success!", attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 30)])) case .failure(let actual, let expected): return .attributedString(failureMessage(actual: actual, expected: expected)) } } func failureMessage(actual: String, expected: String) -> NSAttributedString { let labelAttributes = [NSFontAttributeName : UIFont.italicSystemFont(ofSize: 12), NSForegroundColorAttributeName : UIColor.lightGray] let contentAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 16)]//(name: "Menlo-Regular", size: 16)] let result = NSMutableAttributedString(string: "⛔️", attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 30)]) result.append(NSAttributedString(string: "\nactual:\n", attributes: labelAttributes)) result.append(NSAttributedString(string: actual, attributes: contentAttributes)) result.append(NSAttributedString(string: "\nexpected:\n", attributes: labelAttributes)) result.append(NSAttributedString(string: expected, attributes: contentAttributes)) return result } } func assert(_ actual: String, _ expected: String) -> NSAttributedString { if actual == expected { return NSAttributedString(string: "✅ Success!") } else { print("⛔️ \"\(actual)\" != \"\(expected)\"") let labelAttributes = [NSFontAttributeName : UIFont.italicSystemFont(ofSize: 12), NSForegroundColorAttributeName : UIColor.lightGray] let contentAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 16)]//(name: "Menlo-Regular", size: 16)] let result = NSMutableAttributedString(string: "⛔️\n") result.append(NSAttributedString(string: "actual:\n", attributes: labelAttributes)) result.append(NSAttributedString(string: actual, attributes: contentAttributes)) result.append(NSAttributedString(string: "\nexpected:\n", attributes: labelAttributes)) result.append(NSAttributedString(string: expected, attributes: contentAttributes)) return result } }
mit
f107babc5f4d840797d202dd84b780ac
43.766667
136
0.72971
4.403279
false
false
false
false
slavapestov/swift
validation-test/compiler_crashers_fixed/01185-swift-parser-parsetypeidentifier.swift
3
1132
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b<c { enum b { func b var _ = b func k<q { enum k { } } class x { } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v } protocol y { } struct D : y { func y<v k r { } class y<D> { } } func l<c>(m: (l, c) -> c) -> (l, c) -> c { f { i }, k) class l { class func m { b let k: String = { }() struct q<q : n, p: n where p.q == q.q> { } o q: n = { m, i j l { k m p<i) { } } } }lass func c() } s} class a<f : b, : b where f.d == g> { } struct j<l : o> { } func a<l>() -> [j<l>] { } func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { } class l: f{ class func n {} func a<i>() { b b { } } class a<f : b, l : b m f.l == l> { } protocol b { } struct j<n : b> : b { } enum e<b> : d { func c<b>() -> b { } } protocol d { } enum A : String { } if c == .b { } struct c<f : h> { var b: [c<f>] { g []e f() { } } protocol c : b { func b class j { func y((Any, j))(v: (Any, AnyObject)) { }
apache-2.0
c944e1c65333f5ffab23674231786e3e
11.172043
87
0.493816
2.092421
false
false
false
false
kstaring/swift
test/PlaygroundTransform/high_performance.swift
5
958
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -playground-high-performance -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] $builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log[='0'] // CHECK-NEXT: [{{.*}}] $builtin_log[='1'] // CHECK-NEXT: [{{.*}}] $builtin_log[='2'] var b = true for i in 0..<3 { i continue } // CHECK-NEXT: [{{.*}}] $builtin_log[b='true'] // CHECK-NEXT: [{{.*}}] $builtin_log[='0'] // CHECK-NEXT: [{{.*}}] $builtin_log[='1'] // CHECK-NEXT: [{{.*}}] $builtin_log[='2'] var c = true for i in 0..<3 { i break } // CHECK-NEXT: [{{.*}}] $builtin_log[c='true'] // CHECK-NEXT: [{{.*}}] $builtin_log[='0']
apache-2.0
eec4de866e8667c3a684dabcc30c61fe
22.95
179
0.549061
2.85119
false
false
false
false
kstaring/swift
test/Parse/c_function_pointers.swift
7
2972
// RUN: %target-swift-frontend -parse -verify -module-name main %s func global() -> Int { return 0 } struct S { static func staticMethod() -> Int { return 0 } } class C { static func staticMethod() -> Int { return 0 } class func classMethod() -> Int { return 0 } } if true { var x = 0 func local() -> Int { return 0 } func localWithContext() -> Int { return x } let a: @convention(c) () -> Int = global let a2: @convention(c) () -> Int = main.global let b: @convention(c) () -> Int = { 0 } let c: @convention(c) () -> Int = local // Can't convert a closure with context to a C function pointer let d: @convention(c) () -> Int = { x } // expected-error{{cannot be formed from a closure that captures context}} let d2: @convention(c) () -> Int = { [x] in x } // expected-error{{cannot be formed from a closure that captures context}} let e: @convention(c) () -> Int = localWithContext // expected-error{{cannot be formed from a local function that captures context}} // Can't convert a closure value to a C function pointer let global2 = global let f: @convention(c) () -> Int = global2 // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} let globalBlock: @convention(block) () -> Int = global let g: @convention(c) () -> Int = globalBlock // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} // Can convert a function pointer to a block or closure, or assign to another // C function pointer let h: @convention(c) () -> Int = a let i: @convention(block) () -> Int = a let j: () -> Int = a // Can't convert a C function pointer from a method. // TODO: Could handle static methods. let k: @convention(c) () -> Int = S.staticMethod // expected-error{{}} let m: @convention(c) () -> Int = C.staticMethod // expected-error{{}} let n: @convention(c) () -> Int = C.classMethod // expected-error{{}} // <rdar://problem/22181714> Crash when typing "signal" let iuo_global: (() -> Int)! = global let p: (@convention(c) () -> Int)! = iuo_global // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} func handler(_ callback: (@convention(c) () -> Int)!) {} handler(iuo_global) // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} } class Generic<X : C> { func f<Y : C>(_ y: Y) { let _: @convention(c) () -> Int = { return 0 } let _: @convention(c) () -> Int = { return X.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} let _: @convention(c) () -> Int = { return Y.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} } } func genericFunc<T>(_ t: T) -> T { return t } let f: @convention(c) (Int) -> Int = genericFunc // expected-error{{cannot be formed from a reference to a generic function}}
apache-2.0
cd1e3219c7270e29e8a28c0907c6265a
45.4375
160
0.64502
3.62439
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCodeTests/AppStateTests.swift
1
957
// // AppStateTests.swift // StemCodeTests // // Created by David Evans on 05/09/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import XCTest @testable import StemKit class AppStateTests: XCTestCase { override func setUp() { UserDefaults(suiteName: AppState.suiteName)?.removeObject(forKey: AppState.defaultsKey) } func testFirstInit() { let state = AppState.shared XCTAssertEqual(state.setupVersion, 0) } func testSaveAndLoad() { var state = AppState.shared state.setupVersion = 9876 state.saveToDefaults() // this time loads from disk do { guard let data = UserDefaults(suiteName: AppState.suiteName)?.object(forKey: AppState.defaultsKey) as? Data else { XCTFail("Couldn't load data") return } let state = try PropertyListDecoder().decode(AppState.self, from: data) XCTAssertEqual(state.setupVersion, 9876) } catch { XCTFail(error.localizedDescription) } } }
mit
1dfedafca0cd2759ba5249433fbef692
20.244444
117
0.709205
3.69112
false
true
false
false
practicalswift/swift
test/Constraints/tuple.swift
4
7431
// RUN: %target-typecheck-verify-swift // Test various tuple constraints. func f0(x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y: Float, rest: Int...) {} func f2(_: (_ x: Int, _ y: Int) -> Int) {} func f2xy(x: Int, y: Int) -> Int {} func f2ab(a: Int, b: Int) -> Int {} func f2yx(y: Int, x: Int) -> Int {} func f3(_ x: (_ x: Int, _ y: Int) -> ()) {} func f3a(_ x: Int, y: Int) {} func f3b(_: Int) {} func f4(_ rest: Int...) {} func f5(_ x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}} typealias Interval = (a:Int, b:Int) func takeInterval(_ x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // expected-error {{cannot create a single-element tuple with an element label}} // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' has no member '1'}} // expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} any = (5.0, 6.0) as (Float, Float) _ = (any as! (Float, Float)).1 // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : Comparable & PosixErrorReturn> (_ f: @escaping (A) -> T) -> (_ args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(_ name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(_ c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(_ k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, Error?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(_ a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} // expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (Int, Int), (Int16, Int16), (Int32, Int32), (Int64, Int64), (Int8, Int8), (Self, Self.Scalar), (Self.Scalar, Self), (UInt, UInt), (UInt16, UInt16), (UInt32, UInt32), (UInt64, UInt64), (UInt8, UInt8)}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom>(_ king: K) where K.King == General {} // expected-note {{where 'General' = '(x: Int, y: Int)', 'K.King' = '(Int, Int)'}} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> { return Victory(magify(pair)) // expected-error {{initializer 'init(_:)' requires the types '(x: Int, y: Int)' and '(Int, Int)' be equivalent}} } // https://bugs.swift.org/browse/SR-596 // Compiler crashes when accessing a non-existent property of a closure parameter func call(_ f: (C) -> Void) {} func makeRequest() { call { obj in print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}} } } // <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure struct r25271859<T> { } extension r25271859 { func map<U>(f: (T) -> U) -> r25271859<U> { } func andThen<U>(f: (T) -> r25271859<U>) { } } func f(a : r25271859<(Float, Int)>) { a.map { $0.0 } .andThen { _ in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{18-18=-> r25271859<String> }} print("hello") // comment this out and it runs, leave any form of print in and it doesn't return r25271859<String>() } } // LValue to rvalue conversions. func takesRValue(_: (Int, (Int, Int))) {} func takesAny(_: Any) {} var x = 0 var y = 0 let _ = (x, (y, 0)) takesRValue((x, (y, 0))) takesAny((x, (y, 0))) // SR-2600 - Closure cannot infer tuple parameter names typealias Closure<A, B> = ((a: A, b: B)) -> String func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) { print(closure((a, b))) } invoke(a: 1, b: "B") { $0.b } invoke(a: 1, b: "B") { $0.1 } invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in return c.b } invoke(a: 1, b: "B") { c in return c.b } // Crash with one-element tuple with labeled element class Dinner {} func microwave() -> Dinner? { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}} } func microwave() -> Dinner { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}} } // Tuple conversion with an optional func f(b: Bool) -> (a: Int, b: String)? { let x = 3 let y = "" return b ? (x, y) : nil } // Single element tuple expressions func singleElementTuple() { let _ = (label: 123) // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = (label: 123).label // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = ((label: 123)) // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} let _ = ((label: 123)).label // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} }
apache-2.0
21037266e49041f2763bf21afffa9b1a
27.362595
296
0.619163
3.097541
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Cells/MyCoRightsCell.swift
1
2563
// // MyCoRightsCell.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // struct GirdRightsItem { let imageName: String let title: String let selectorName: String private static let imageNames = [ "discount", "integral", "breakfast", "checkout" ] private static let coTitles = [ "8.8折优惠", "2倍积分", "1份早餐", "14:00退房", ] private static let memberTitles = [ "房费8.8折", "免费早餐", "2倍积分", ] static var coItems: [GirdRightsItem] { return zip(imageNames, coTitles).map { GirdRightsItem(imageName: "ic_my_co_rights_\($0.0)", title: $0.1, selectorName: "coRightsStyle") } } static var memberItems: [GirdRightsItem] { return zip(imageNames, memberTitles).map { GirdRightsItem(imageName: "ic_my_co_rights_\($0.0)", title: $0.1, selectorName: "memberRightsStyle") } } } class MyCoRightsCell: UITableViewCell, Updatable { private lazy var descLabel: UILabel = { let descLabel = UILabel() descLabel.textColor = UIColor(hex: 0x4A4A4A) descLabel.font = UIFontMake(14) descLabel.text = "华住金会员权益" return descLabel }() private lazy var girdView: GirdView<CoRightsGirdViewCell> = { let girdView = GirdView<CoRightsGirdViewCell>(items: GirdRightsItem.coItems) return girdView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none let dummyView = UIView() contentView.addSubview(dummyView) dummyView.snp.makeConstraints { (make) in make.height.equalTo(187).priority(.high) make.edges.equalToSuperview() } contentView.addSubview(descLabel) descLabel.snp.makeConstraints { (make) in make.top.equalTo(27) make.centerX.equalToSuperview() } contentView.addSubview(girdView) girdView.snp.makeConstraints { (make) in make.leading.trailing.equalToSuperview() make.top.equalTo(descLabel.snp.bottom).offset(30) make.bottom.equalTo(-32) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bc39401dc6080a4f960762f4b30ff2ff
26.384615
112
0.599117
3.924409
false
false
false
false
nnianhou-/M-Vapor
Sources/App/Models/RcToken.swift
1
3243
// // RcToken.swift // M-Vapor // // Created by N年後 on 2017/9/3. // // import Vapor import FluentProvider import HTTP final class RcToken:Model{ static let idKey = "id" static let accountKey = "account" static let tokenKey = "token" static let openidKey = "openid" static let rctokenKey = "rctoken" var account: String var token: String var openid: String var rctoken: String let storage = Storage() /// 常规的构造器 init(account: String,token:String,openid:String,rctoken:String) { self.account = account self.token = token self.openid = openid self.rctoken = rctoken } // MARK: Fluent 序列化构造器 /// 通过这个构造器你可以使用数据库中的一行生成一个对应的对象 init(row: Row) throws { account = try row.get(RcToken.accountKey) token = try row.get(RcToken.tokenKey) openid = try row.get(RcToken.openidKey) rctoken = try row.get(RcToken.rctokenKey) } // 把一个对象存储到数据库当中 func makeRow() throws -> Row { var row = Row() try row.set(RcToken.accountKey, account) try row.set(RcToken.tokenKey, token) try row.set(RcToken.openidKey, openid) try row.set(RcToken.rctokenKey, rctoken) return row } } extension RcToken:Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { RcTokens in RcTokens.id() RcTokens.string(RcToken.accountKey) RcTokens.string(RcToken.tokenKey) RcTokens.string(RcToken.openidKey) RcTokens.string(RcToken.rctokenKey) }) } static func revert(_ database: Database) throws { try database.delete(self) } } extension RcToken: JSONRepresentable { convenience init(json: JSON) throws { try self.init( account:json.get(RcToken.accountKey), token:json.get(RcToken.tokenKey), openid:json.get(RcToken.openidKey), rctoken:json.get(RcToken.rctokenKey) ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(RcToken.idKey, id) try json.set(RcToken.accountKey, account) try json.set(RcToken.tokenKey, token) try json.set(RcToken.openidKey, openid) try json.set(RcToken.rctokenKey, rctoken) return json } } extension RcToken: Updateable { public static var updateableKeys: [UpdateableKey<RcToken>] { return [ UpdateableKey(RcToken.accountKey, String.self) { RcToken, account in RcToken.account = account }, UpdateableKey(RcToken.tokenKey, String.self) { RcToken, token in RcToken.token = token }, UpdateableKey(RcToken.openidKey, String.self) { RcToken, openid in RcToken.openid = openid }, UpdateableKey(RcToken.rctokenKey, String.self) { RcToken, rctoken in RcToken.rctoken = rctoken } ] } } extension RcToken: ResponseRepresentable { }
mit
29105a29b3b60146c0a30ddbe72f2005
25.108333
80
0.599106
3.681551
false
false
false
false
realami/Msic
weekTwo/weekTwo/Controllers/ContactViewController.swift
1
3863
// // ContactViewController.swift // weekTwo // // Created by Cyan on 28/10/2017. // Copyright © 2017 Cyan. All rights reserved. // import UIKit import SnapKit import Then class ContactViewController: UIViewController { var data: Dictionary<String, String>! private var icon: UIImageView! private var name: UILabel! private var nameText: UILabel! private var phone: UILabel! private var phoneText: UILabel! private var email: UILabel! private var emailText: UILabel! private var notes: UILabel! private var notesText: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "Infomation" view.backgroundColor = .white icon = UIImageView().then { $0.contentMode = .scaleAspectFill $0.image = UIImage(named: data["icon"]!) } view.addSubview(icon) icon.snp.makeConstraints{ $0.width.height.equalTo(100) $0.top.equalTo(view.snp.top).offset(84) $0.left.equalTo(view.snp.left).offset(21) } name = UILabel().then { $0.text = "Name" $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = .blue } view.addSubview(name) name.snp.makeConstraints { $0.top.equalTo(icon.snp.bottom).offset(30) $0.left.equalTo(icon.snp.left) } nameText = UILabel().then { $0.textColor = .black $0.text = data["name"] $0.font = UIFont.systemFont(ofSize: 25) } view.addSubview(nameText) nameText.snp.makeConstraints { $0.top.equalTo(name.snp.bottom).offset(10) $0.left.equalTo(name) } phone = UILabel().then { $0.text = "Mobile" $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = .blue } view.addSubview(phone) phone.snp.makeConstraints { $0.top.equalTo(nameText.snp.bottom).offset(30) $0.left.equalTo(nameText) } phoneText = UILabel().then { $0.text = data["phone"] $0.textColor = .black $0.font = UIFont.systemFont(ofSize: 25) } view.addSubview(phoneText) phoneText.snp.makeConstraints { $0.left.equalTo(phone) $0.top.equalTo(phone.snp.bottom).offset(10) } email = UILabel().then { $0.text = "Email" $0.textColor = .blue $0.font = UIFont.systemFont(ofSize: 15) } view.addSubview(email) email.snp.makeConstraints { $0.left.equalTo(phoneText) $0.top.equalTo(phoneText.snp.bottom).offset(30) } emailText = UILabel().then { $0.text = data["email"] $0.textColor = .black $0.font = UIFont.systemFont(ofSize: 25) } view.addSubview(emailText) emailText.snp.makeConstraints { $0.left.equalTo(email) $0.top.equalTo(email.snp.bottom).offset(10) } notes = UILabel().then { $0.text = "Notes" $0.textColor = .blue $0.font = UIFont.systemFont(ofSize: 15) } view.addSubview(notes) notes.snp.makeConstraints { $0.left.equalTo(emailText) $0.top.equalTo(emailText.snp.bottom).offset(30) } notesText = UILabel().then { $0.text = data["notes"] $0.textColor = .black $0.font = UIFont.systemFont(ofSize: 25) } view.addSubview(notesText) notesText.snp.makeConstraints { $0.left.equalTo(notes) $0.top.equalTo(notes.snp.bottom).offset(10) } } }
mit
c560c7b04e8a8c771036e8a49c6a14b7
27.189781
59
0.532367
4.060988
false
false
false
false
QQLS/YouTobe
YouTube/AppDelegate/AppDelegate.swift
1
4750
// // AppDelegate.swift // YouTube // // Created by xiupai on 2017/3/15. // Copyright © 2017年 QQLS. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. if #available(iOS 10.0, *) { self.saveContext() } else { // Fallback on earlier versions } } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "YouTube") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support @available(iOS 10.0, *) func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
6e4fe42a78ce7ee5af71fc845811b18e
46.949495
285
0.677059
5.726176
false
false
false
false
lfaoro/Cast
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/FlatMap.swift
1
5936
// // FlatMap.swift // RxSwift // // Created by Krunoslav Zaher on 6/11/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // It's value is one because initial source subscription is always in CompositeDisposable let FlatMapNoIterators = 1 class FlatMapSinkIter<SourceType, O: ObserverType> : ObserverType { typealias Parent = FlatMapSink<SourceType, O> typealias DisposeKey = CompositeDisposable.DisposeKey typealias E = O.E let parent: Parent let disposeKey: DisposeKey init(parent: Parent, disposeKey: DisposeKey) { self.parent = parent self.disposeKey = disposeKey } func on(event: Event<E>) { switch event { case .Next(let value): parent.lock.performLocked { parent.observer?.on(.Next(value)) } case .Error(let error): parent.lock.performLocked { parent.observer?.on(.Error(error)) self.parent.dispose() } case .Completed: parent.group.removeDisposable(disposeKey) // If this has returned true that means that `Completed` should be sent. // In case there is a race who will sent first completed, // lock will sort it out. When first Completed message is sent // it will set observer to nil, and thus prevent further complete messages // to be sent, and thus preserving the sequence grammar. if parent.stopped && parent.group.count == FlatMapNoIterators { parent.lock.performLocked { parent.observer?.on(.Completed) self.parent.dispose() } } } } } class FlatMapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType { typealias ResultType = O.E typealias Element = SourceType typealias Parent = FlatMap<SourceType, ResultType> let parent: Parent let lock = NSRecursiveLock() let group = CompositeDisposable() let sourceSubscription = SingleAssignmentDisposable() var stopped = false init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func performMap(element: SourceType) throws -> Observable<ResultType> { return abstractMethod() } func on(event: Event<SourceType>) { let observer = super.observer switch event { case .Next(let element): do { let value = try performMap(element) subscribeInner(value) } catch let e { observer?.on(.Error(e)) self.dispose() } case .Error(let error): lock.performLocked { observer?.on(.Error(error)) self.dispose() } case .Completed: lock.performLocked { final() } } } func final() { stopped = true if group.count == FlatMapNoIterators { lock.performLocked { observer?.on(.Completed) dispose() } } else { self.sourceSubscription.dispose() } } func subscribeInner(source: Observable<O.E>) { let iterDisposable = SingleAssignmentDisposable() if let disposeKey = group.addDisposable(iterDisposable) { let iter = FlatMapSinkIter(parent: self, disposeKey: disposeKey) let subscription = source.subscribeSafe(iter) iterDisposable.disposable = subscription } } func run() -> Disposable { group.addDisposable(sourceSubscription) let subscription = self.parent.source.subscribeSafe(self) sourceSubscription.disposable = subscription return group } } class FlatMapSink1<SourceType, O : ObserverType> : FlatMapSink<SourceType, O> { override init(parent: Parent, observer: O, cancel: Disposable) { super.init(parent: parent, observer: observer, cancel: cancel) } override func performMap(element: SourceType) throws -> Observable<O.E> { return try self.parent.selector1!(element) } } class FlatMapSink2<SourceType, O : ObserverType> : FlatMapSink<SourceType, O> { var index = 0 override init(parent: Parent, observer: O, cancel: Disposable) { super.init(parent: parent, observer: observer, cancel: cancel) } override func performMap(element: SourceType) throws -> Observable<O.E> { return try self.parent.selector2!(element, index++) } } class FlatMap<SourceType, ResultType>: Producer<ResultType> { typealias Selector1 = (SourceType) throws -> Observable<ResultType> typealias Selector2 = (SourceType, Int) throws -> Observable<ResultType> let source: Observable<SourceType> let selector1: Selector1? let selector2: Selector2? init(source: Observable<SourceType>, selector: Selector1) { self.source = source self.selector1 = selector self.selector2 = nil } init(source: Observable<SourceType>, selector: Selector2) { self.source = source self.selector2 = selector self.selector1 = nil } override func run<O: ObserverType where O.E == ResultType>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { if let _ = self.selector1 { let sink = FlatMapSink1(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } else { let sink = FlatMapSink2(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } } }
mit
71e4d1b1b18b30ca6c4dddb5f2977bb6
30.247368
142
0.594677
4.841762
false
false
false
false
thedistance/TheDistanceForms
TheDistanceFormsThemed/ThemedClasses/TKTextViewStack.swift
1
2699
// // TKTextViewStack.swift // TheDistanceForms // // Created by Josh Campion on 27/04/2016. // Copyright © 2016 The Distance. All rights reserved. // import Foundation import TheDistanceForms import ThemeKitCore /** `TextViewStack` whose views are ThemeKit equivalents. - `textView` is a `TKTextView` configured as `.Body1`, `.Text` text colour, and `.SecondaryText` placeholder text colour. - `placeholderLabel` is a `TKLabel` with `.Caption` font and `.SecondaryText` colour. - `errorLabel` is a `TKLabel` with `.Caption` font and `.Accent` colour. - `errorImageView` is a `TKImageView` with `.Accent` tint colour and `.ScaleAspectFit` contentMode. - `iconImageView` is a `TKImageView` with no tint colour and `.ScaleAspectFit` contentMode. - `underline` is a `TKView` which is `.Accent` alpha 1.0 when `textView.isFirstResponder` is `true`, `.SecondaryText` when `textView.isFirstResponder` is `false` but `textView.enabled`, and invisible when `textView.enabled` is `false`. */ public class TKTextViewStack: TextViewStack { /// Default initialiser. Creates and styles the components. init() { let textView = TKTextView() textView.textStyle = .body1 textView.textColourStyle = .text let placeholder = TKLabel() placeholder.textStyle = .caption placeholder.textColourStyle = .secondaryText let errorLabel = TKLabel() errorLabel.textStyle = .caption errorLabel.textColourStyle = .accent let errorImageView = TKImageView() errorImageView.tintColourStyle = .accent errorImageView.contentMode = .scaleAspectFit let iconImageView = TKImageView() iconImageView.contentMode = .scaleAspectFit let underline = TKView() super.init(textView: textView, placeholderLabel: placeholder, errorLabel: errorLabel, errorImageView: errorImageView, iconImageView: iconImageView, underline: underline) placeholderTextColour = TKThemeVendor.defaultColour(.secondaryText) } /// Configures the `underline` to be `.Accent` when the view is active and `hidden` public override func configureUnderline() { guard let underline = self.underline as? TKView else { return } if textView.isFirstResponder { underline.backgroundColourStyle = .accent underline.alpha = 1.0 } else { underline.backgroundColourStyle = .secondaryText underline.alpha = enabled ? 1.0 : 0.0 } } }
mit
31f3b77e421ae685e8eec11390834008
34.973333
236
0.644922
4.878843
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/Demo/Modules/Demos/Components/QDToastListViewController.swift
1
4381
// // QDToastListViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/5/4. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit class QDToastListViewController: QDCommonListViewController { override func initDataSource() { dataSource = ["Loading", "Loading With Text", "Tips For Succeed", "Tips For Error", "Tips For Info", "Custom TintColor", "Custom BackgroundView Style", "Custom Animator", "Custom Content View"] } override func didSelectCell(_ title: String) { guard let parentView = navigationController?.view else { return } if title == "Loading" { // 如果不需要修改contentView的样式,可以直接使用下面这个工具方法 // QMUITips *tips = [QMUITips showLoadingInView:parentView hideAfterDelay:2]; // 展示如何修改自定义的样式 let tips = QMUITips.createTips(to: parentView) let contentView = tips.contentView as? QMUIToastContentView contentView?.minimumSize = CGSize(width: 90, height: 90) tips.willShowClosure = { (showInView, animated) in print("tips calling willShowClosure") } tips.didShowClosure = { (showInView, animated) in print("tips calling didShowClosure") } tips.willHideClosure = { (showInView, animated) in print("tips calling willHideClosure") } tips.didHideClosure = { (showInView, animated) in print("tips calling didHideClosure") } tips.showLoading(hideAfterDelay: 2) } else if title == "Loading With Text" { QMUITips.showLoading(text: "加载中...", in: parentView, hideAfterDelay: 2) } else if title == "Tips For Succeed" { QMUITips.showSucceed(text: "加载成功", in: parentView, hideAfterDelay: 2) } else if title == "Tips For Error" { QMUITips.showError(text: "加载失败,请检查网络情况", in: parentView, hideAfterDelay: 2) } else if title == "Tips For Info" { QMUITips.showInfo(text: "活动已经结束", detailText: "本次活动时间为2月1号-2月15号", in: parentView, hideAfterDelay: 2) } else if title == "Custom TintColor" { let tips = QMUITips.showInfo(text: "活动已经结束", detailText: "本次活动时间为2月1号-2月15号", in: parentView, hideAfterDelay: 2) tips.tintColor = UIColorBlue } else if title == "Custom BackgroundView Style" { let tips = QMUITips.showInfo(text: "活动已经结束", detailText: "本次活动时间为2月1号-2月15号", in: parentView, hideAfterDelay: 2) if let backgroundView = tips.backgroundView as? QMUIToastBackgroundView { backgroundView.showldBlurBackgroundView = true backgroundView.styleColor = UIColor(r: 232, g: 232, b: 232, a: 0.8) tips.tintColor = UIColorBlack } } else if title == "Custom Content View" { let tips = QMUITips.createTips(to: parentView) tips.toastPosition = .bottom let customAnimator = QDCustomToastAnimator(toastView: tips) tips.toastAnimator = customAnimator let customContentView = QDCustomToastContentView() customContentView.render(with: UIImageMake("image0"), text: "什么是QMUIToastView", detailText: "QMUIToastView用于临时显示某些信息,并且会在数秒后自动消失。这些信息通常是轻量级操作的成功信息。") tips.contentView = customContentView tips.show(true) tips.hide(true, afterDelay: 4) } else if title == "Custom Animator" { let tips = QMUITips.createTips(to: parentView) let customAnimator = QDCustomToastAnimator(toastView: tips) tips.toastAnimator = customAnimator tips.showInfo(text: "活动已经结束", detailText: "本次活动时间为2月1号-2月15号", hideAfterDelay: 2) } tableView.qmui_clearsSelection() } }
mit
8efa031407f1f222504c56b1df196694
44.863636
161
0.592418
4.474501
false
false
false
false
PureSwift/SwiftFoundation
Sources/SwiftFoundation/Date.swift
1
9458
// // Date.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 6/28/15. // Copyright © 2015 PureSwift. All rights reserved. // /// `Date` structs represent a single point in time. public struct Date: Equatable, Hashable { // MARK: - Static Properties and Methods /// The number of seconds from 1 January 1970 to the reference date, 1 January 2001. public static var timeIntervalBetween1970AndReferenceDate: SwiftFoundation.TimeInterval { return 978307200.0 } /** Creates and returns a Date value representing a date in the distant future. The distant future is in terms of centuries. */ public static var distantFuture: SwiftFoundation.Date { return Date(timeIntervalSinceReferenceDate: 63113904000.0) } /** Creates and returns a Date value representing a date in the distant past. The distant past is in terms of centuries. */ public static var distantPast: SwiftFoundation.Date { return Date(timeIntervalSinceReferenceDate: -63114076800.0) } /// The interval between 00:00:00 UTC on 1 January 2001 and the current date and time. public static var timeIntervalSinceReferenceDate: TimeInterval { return self.timeIntervalSince1970 - self.timeIntervalBetween1970AndReferenceDate } // MARK: - Properties /// The time interval between the date and the reference date (1 January 2001, GMT). public var timeIntervalSinceReferenceDate: TimeInterval /** The time interval between the date and the current date and time. If the date is earlier than the current date and time, the this property’s value is negative. - SeeAlso: `timeIntervalSince(_:)` - SeeAlso: `timeIntervalSince1970` - SeeAlso: `timeIntervalSinceReferenceDate` */ public var timeIntervalSinceNow: TimeInterval { return timeIntervalSinceReferenceDate - Date.timeIntervalSinceReferenceDate } /** The interval between the date object and 00:00:00 UTC on 1 January 1970. This property’s value is negative if the date object is earlier than 00:00:00 UTC on 1 January 1970. - SeeAlso: `timeIntervalSince(_:)` - SeeAlso: `timeIntervalSinceNow` - SeeAlso: `timeIntervalSinceReferenceDate` */ public var timeIntervalSince1970: TimeInterval { return timeIntervalSinceReferenceDate + Date.timeIntervalBetween1970AndReferenceDate } // MARK: - Initialization /// Returns a `Date` initialized to the current date and time. public init() { self.init(timeIntervalSinceReferenceDate: Date.timeIntervalSinceReferenceDate) } /// Returns an `Date` initialized relative to 00:00:00 UTC on 1 January 2001 by a given number of seconds. public init(timeIntervalSinceReferenceDate timeInterval: TimeInterval) { self.timeIntervalSinceReferenceDate = timeInterval } /// Returns a `Date` initialized relative to the current date and time by a given number of seconds. public init(timeIntervalSinceNow: TimeInterval) { self.timeIntervalSinceReferenceDate = timeIntervalSinceNow + Date.timeIntervalSinceReferenceDate } /// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds. public init(timeIntervalSince1970: TimeInterval) { self.timeIntervalSinceReferenceDate = timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate } /** Returns a `Date` initialized relative to another given date by a given number of seconds. - Parameter timeInterval: The number of seconds to add to `date`. A negative value means the receiver will be earlier than `date`. - Parameter date: The reference date. */ public init(timeInterval: SwiftFoundation.TimeInterval, since date: SwiftFoundation.Date) { self.timeIntervalSinceReferenceDate = date.timeIntervalSinceReferenceDate + timeInterval } // MARK: - Methods /** Returns the interval between the receiver and another given date. - Parameter another: The date with which to compare the receiver. - Returns: The interval between the receiver and the `another` parameter. If the receiver is earlier than `anotherDate`, the return value is negative. If `anotherDate` is `nil`, the results are undefined. - SeeAlso: `timeIntervalSince1970` - SeeAlso: `timeIntervalSinceNow` - SeeAlso: `timeIntervalSinceReferenceDate` */ public func timeIntervalSince(_ date: SwiftFoundation.Date) -> SwiftFoundation.TimeInterval { return timeIntervalSinceReferenceDate - date.timeIntervalSinceReferenceDate } /// Return a new `Date` by adding a `TimeInterval` to this `Date`. /// /// - parameter timeInterval: The value to add, in seconds. /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public func addingTimeInterval(_ timeInterval: TimeInterval) -> Date { return self + timeInterval } /// Add a `TimeInterval` to this `Date`. /// /// - parameter timeInterval: The value to add, in seconds. /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. public mutating func addTimeInterval(_ timeInterval: TimeInterval) { self += timeInterval } } // MARK: - CustomStringConvertible extension SwiftFoundation.Date: CustomStringConvertible { public var description: String { // TODO: Custom date printing return timeIntervalSinceReferenceDate.description } } // MARK: - CustomDebugStringConvertible extension SwiftFoundation.Date: CustomDebugStringConvertible { public var debugDescription: String { return description } } // MARK: - Comparable extension SwiftFoundation.Date: Comparable { public static func < (lhs: SwiftFoundation.Date, rhs: SwiftFoundation.Date) -> Bool { return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate } public static func > (lhs: SwiftFoundation.Date, rhs: SwiftFoundation.Date) -> Bool { return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate } } // MARK: - Operators public extension SwiftFoundation.Date { /// Returns a `Date` with a specified amount of time added to it. static func +(lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate + rhs) } /// Returns a `Date` with a specified amount of time subtracted from it. static func -(lhs: Date, rhs: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate - rhs) } /// Add a `TimeInterval` to a `Date`. /// /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. static func +=(lhs: inout Date, rhs: TimeInterval) { lhs = lhs + rhs } /// Subtract a `TimeInterval` from a `Date`. /// /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. static func -=(lhs: inout Date, rhs: TimeInterval) { lhs = lhs - rhs } typealias Stride = TimeInterval /// Returns the `TimeInterval` between this `Date` and another given date. /// /// - returns: The interval between the receiver and the another parameter. If the receiver is earlier than `other`, the return value is negative. func distance(to other: Date) -> TimeInterval { return other.timeIntervalSince(self) } /// Creates a new date value by adding a `TimeInterval` to this `Date`. /// /// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more. func advanced(by n: TimeInterval) -> Date { return self.addingTimeInterval(n) } } // MARK: - Codable extension Date: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let timestamp = try container.decode(Double.self) self.init(timeIntervalSinceReferenceDate: timestamp) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.timeIntervalSinceReferenceDate) } } // MARK: - Supporting Types /// Time interval difference between two dates, in seconds. public typealias TimeInterval = Double
mit
51922286f726646493346e08a6155c7a
40.460526
269
0.706019
5.174056
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Platform/BRKVStorePlugin.swift
1
10819
// // BRKVStorePlugin.swift // BreadWallet // // Created by Samuel Sutch on 8/18/16. // Copyright © 2016 breawallet LLC. All rights reserved. // import Foundation // swiftlint:disable cyclomatic_complexity /// Provides KV Store access to the HTML5 platform @objc class BRKVStorePlugin: NSObject, BRHTTPRouterPlugin { let client: BRAPIClient init(client: BRAPIClient) { self.client = client } func transformErrorToResponse(_ request: BRHTTPRequest, err: Error?) -> BRHTTPResponse? { switch err { case nil: return nil case let e as BRReplicatedKVStoreError: switch e { case .notFound: return BRHTTPResponse(request: request, code: 404) case .conflict: return BRHTTPResponse(request: request, code: 409) case .invalidKey: print("[BRHTTPStorePlugin]: invalid key!") return BRHTTPResponse(request: request, code: 400) default: break } default: break } print("[BRHTTPStorePlugin]: unexpected error: \(String(describing: err))") return BRHTTPResponse(request: request, code: 500) } func getKey(_ s: String) -> String { return "plat-\(s)" } func decorateResponse(version: UInt64, date: Date, response: BRHTTPResponse) -> BRHTTPResponse { let headers = [ "Cache-Control": ["max-age=0, must-revalidate"], "ETag": ["\(version)"], "Last-Modified": [date.RFC1123String() ?? ""] ] return BRHTTPResponse(request: response.request, statusCode: response.statusCode, statusReason: response.statusReason, headers: headers, body: response.body) } func hook(_ router: BRHTTPRouter) { // GET /_kv/(key) // // Retrieve a value from a key. If it exists, the most recent version will be returned as JSON. The ETag header // will be set with the most recent version ID. The Last-Modified header will be set with the most recent // version's date // // If the key was removed the caller will receive a 410 Gone response, with the most recent ETag and // Last-Modified header set appropriately. // // If you are retrieving a key that was replaced after having deleted it, you may have to instruct your client // to ignore its cache (using Pragma: no-cache and Cache-Control: no-cache headers) router.get("/_kv/(key)") { (request, match) -> BRHTTPResponse in guard let key = match["key"], key.count == 1 else { print("[BRKVStorePlugin] missing key argument") return BRHTTPResponse(request: request, code: 400) } guard let kv = self.client.kv else { print("[BRKVStorePlugin] kv store is not yet set up on client") return BRHTTPResponse(request: request, code: 500) } var ver: UInt64 = 0 var date: Date = Date() var del: Bool var bytes: [UInt8] var json: Any var uncompressedBytes: [UInt8] do { (ver, date, del, bytes) = try kv.get(self.getKey(key[0])) if del { return self.decorateResponse(version: ver, date: date, response: BRHTTPResponse(request: request, code: 404)) } let data = Data(bzCompressedData: Data(bytes: &bytes, count: bytes.count)) ?? Data() json = try JSONSerialization.jsonObject(with: data, options: []) // ensure valid json let jsonData = try JSONSerialization.data(withJSONObject: json, options: []) uncompressedBytes = [UInt8](repeating: 0, count: jsonData.count) (jsonData as NSData).getBytes(&uncompressedBytes, length: jsonData.count) } catch let e { if let resp = self.transformErrorToResponse(request, err: e) { if resp.statusCode == 500 { // the data is most probably corrupted.. just delete it and return a 404 let (newVer, newDate) = (try? kv.del(self.getKey(key[0]), localVer: ver)) ?? (0, Date()) return self.decorateResponse(version: newVer, date: newDate, response: BRHTTPResponse(request: request, code: 404)) } return self.decorateResponse(version: ver, date: date, response: resp) } return BRHTTPResponse(request: request, code: 500) // no idea what happened... } if del { let headers: [String: [String]] = [ "ETag": ["\(ver)"], "Cache-Control": ["max-age=0, must-revalidate"], "Last-Modified": [date.RFC1123String() ?? ""] ] return BRHTTPResponse( request: request, statusCode: 410, statusReason: "Gone", headers: headers, body: nil ) } let headers: [String: [String]] = [ "ETag": ["\(ver)"], "Cache-Control": ["max-age=0, must-revalidate"], "Last-Modified": [date.RFC1123String() ?? ""], "Content-Type": ["application/json"] ] return BRHTTPResponse( request: request, statusCode: 200, statusReason: "OK", headers: headers, body: uncompressedBytes ) } // PUT /_kv/(key) // // Save a JSON value under a key. If it's a new key, then pass 0 as the If-None-Match header // Otherwise you must pass the current version in the database (which may be retrieved with GET /_kv/(key) // If the version in the If-None-Match header doesn't match the one in the database the caller // will receive a 409 Conflict response. // // The request body MUST be encoded as application/json and the encoded body MUST not exceed 500kb // // Successful response is a 204 no content with the ETag set to the new version and Last-Modified header // set to that version's date router.put("/_kv/(key)") { (request, match) -> BRHTTPResponse in guard let key = match["key"], key.count == 1 else { print("[BRKVStorePlugin] missing key argument") return BRHTTPResponse(request: request, code: 400) } guard let kv = self.client.kv else { print("[BRKVStorePlugin] kv store is not yet set up on client") return BRHTTPResponse(request: request, code: 500) } guard let ct = request.headers["content-type"], ct.count == 1 && ct[0] == "application/json" else { print("[BRKVStorePlugin] can only set application/json request bodies") return BRHTTPResponse(request: request, code: 400) } guard let vs = request.headers["if-none-match"], vs.count == 1 && Int(vs[0]) != nil else { print("[BRKVStorePlugin] missing If-None-Match header, set to `0` if creating a new key") return BRHTTPResponse(request: request, code: 400) } guard let body = request.body(), let compressedBody = body.bzCompressedData else { print("[BRKVStorePlugin] missing request body") return BRHTTPResponse(request: request, code: 400) } var bodyBytes = [UInt8](repeating: 0, count: compressedBody.count) (compressedBody as NSData).getBytes(&bodyBytes, length: compressedBody.count) var ver: UInt64 = 0 var date: Date = Date() do { (ver, date) = try kv.set(self.getKey(key[0]), value: bodyBytes, localVer: UInt64(Int(vs[0])!)) } catch let e { if let resp = self.transformErrorToResponse(request, err: e) { return self.decorateResponse(version: ver, date: date, response: resp) } return BRHTTPResponse(request: request, code: 500) // no idea what happened... } let headers: [String: [String]] = [ "ETag": ["\(ver)"], "Cache-Control": ["max-age=0, must-revalidate"], "Last-Modified": [date.RFC1123String() ?? ""] ] return BRHTTPResponse( request: request, statusCode: 204, statusReason: "No Content", headers: headers, body: nil ) } // DELETE /_kv/(key) // // Mark a key as deleted in the KV store. The If-None-Match header MUST be the current version stored in the // database (which may retrieved with GET /_kv/(key) otherwise the caller will receive a 409 Conflict resposne // // Keys may not actually be removed from the database, and can be restored by PUTing a new version. This is // called a tombstone and is used to replicate deletes to other databases router.delete("/_kv/(key)") { (request, match) -> BRHTTPResponse in guard let key = match["key"], key.count == 1 else { print("[BRKVStorePlugin] missing key argument") return BRHTTPResponse(request: request, code: 400) } guard let kv = self.client.kv else { print("[BRKVStorePlugin] kv store is not yet set up on client") return BRHTTPResponse(request: request, code: 500) } guard let vs = request.headers["if-none-match"], vs.count == 1 && Int(vs[0]) != nil else { print("[BRKVStorePlugin] missing If-None-Match header") return BRHTTPResponse(request: request, code: 400) } var ver: UInt64 = 0 var date: Date = Date() do { (ver, date) = try kv.del(self.getKey(key[0]), localVer: UInt64(Int(vs[0])!)) } catch let e { if let resp = self.transformErrorToResponse(request, err: e) { return self.decorateResponse(version: ver, date: date, response: resp) } return BRHTTPResponse(request: request, code: 500) // no idea what happened... } let headers: [String: [String]] = [ "ETag": ["\(ver)"], "Cache-Control": ["max-age=0, must-revalidate"], "Last-Modified": [date.RFC1123String() ?? ""] ] return BRHTTPResponse( request: request, statusCode: 204, statusReason: "No Content", headers: headers, body: nil ) } } }
mit
0f89174a1e2bcdad60dcb97591ba5f62
48.39726
139
0.556572
4.623077
false
false
false
false
ccrazy88/activity-kit
Sources/ActivityKit/Extensions/UIImage.swift
1
4967
// // UIImage.swift // ActivityKit // // Created by Chrisna Aing on 6/14/16. // Copyright © 2016 Chrisna. All rights reserved. // import UIKit // Source/Inspiration: // https://github.com/marcoarment/FCUtilities/blob/master/FCUtilities/FCOpenInSafariActivity.m extension UIImage { // MARK: - Activity Images @objc(cka_openInSafariActivityImageForWidth:scale:) static func openInSafariActivityImage(sideLength length: CGFloat, scale: CGFloat) -> UIImage? { let size = CGSize(width: length, height: length) UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } let origin = CGPoint.zero let rectangle = CGRect(origin: origin, size: size) let constants = OpenInSafariActivityConstants(sideLength: length, scale: scale) drawOpenInSafariGradient(context: context, rectangle: rectangle, constants: constants) drawOpenInSafariTickLines(context: context, constants: constants) drawOpenInSafariTriangles(context: context, constants: constants) let image = UIGraphicsGetImageFromCurrentImageContext() return image } // MARK: - Helpers private static func drawOpenInSafariGradient(context: CGContext, rectangle: CGRect, constants: OpenInSafariActivityConstants) { context.saveGState() defer { context.restoreGState() } context.addEllipse(in: rectangle) context.clip() guard let gradient = constants.gradient else { return } context.drawLinearGradient( gradient, start: CGPoint(x: constants.halfLength, y: 0.0), end: CGPoint(x: constants.halfLength, y: constants.length), options: [] ) } private static func drawOpenInSafariTickLines(context: CGContext, constants: OpenInSafariActivityConstants) { let tickLineColor = UIColor(white: 0.0, alpha: 0.5) tickLineColor.setStroke() (0 ..< constants.tickLineCount).forEach { index in context.saveGState() defer { context.restoreGState() } context.setBlendMode(.clear) context.translateBy(x: constants.halfLength, y: constants.halfLength) context.rotate(by: constants.angleForTickLineIndex(index: index)) context.translateBy(x: -constants.halfLength, y: -constants.halfLength) let tickLine = UIBezierPath() let tickLineStart = CGPoint( x: constants.halfLength - constants.tickMarkHalfWidth, y: constants.tickMarkToCircleGap ) let tickLineEnd = CGPoint( x: constants.halfLength - constants.tickMarkHalfWidth, y: constants.tickMarkToCircleGap + constants.lengthForTickLineIndex(index: index) ) tickLine.move(to: tickLineStart) tickLine.addLine(to: tickLineEnd) tickLine.lineWidth = constants.tickMarkWidth tickLine.stroke() } } private static func drawOpenInSafariTriangles(context: CGContext, constants: OpenInSafariActivityConstants) { context.saveGState() defer { context.restoreGState() } context.translateBy(x: constants.halfLength, y: constants.halfLength) context.rotate(by: .pi + .pi / 4.0) context.translateBy(x: -constants.halfLength, y: -constants.halfLength) let triangleColor = UIColor.black triangleColor.setFill() let triangleLeftBasePoint = CGPoint( x: constants.halfLength - constants.triangleBaseHalfLength, y: constants.halfLength ) let triangleRightBasePoint = CGPoint( x: constants.halfLength + constants.triangleBaseHalfLength, y: constants.halfLength ) let topTriangle = UIBezierPath() let topTriangleStart = CGPoint(x: constants.halfLength, y: constants.triangleTipToCircleGap) topTriangle.move(to: topTriangleStart) topTriangle.addLine(to: triangleLeftBasePoint) topTriangle.addLine(to: triangleRightBasePoint) topTriangle.close() context.setBlendMode(.clear) topTriangle.fill() let bottomTriangle = UIBezierPath() let bottomTriangleStart = CGPoint(x: constants.halfLength, y: constants.length - constants.triangleTipToCircleGap) bottomTriangle.move(to: bottomTriangleStart) bottomTriangle.addLine(to: triangleLeftBasePoint) bottomTriangle.addLine(to: triangleRightBasePoint) bottomTriangle.close() context.setBlendMode(.normal) bottomTriangle.fill() } }
mit
25dcf116595a42dd9a51efa522b82ab7
36.908397
100
0.633508
4.830739
false
false
false
false
thorfroelich/TaylorSource
Sources/Base/Basic.swift
2
5394
// // Basic.swift // TaylorSource // // Created by Daniel Thorpe on 29/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** Simple wrapper for a Datasource. TaylorSource is designed for composing Datasources inside custom classes, referred to as *datasource providers*. There are Table View and Collection View data source generators which accept datasource providers. Therefore, if you absolutely don't want your own custom class to act as the datasource provider, this structure is available to easily wrap any DatasourceType. e.g. let datasource: UITableViewDataSourceProvider<BasicDatasourceProvider<StaticDatasource>> tableView.dataSource = datasource.tableViewDataSource */ public struct BasicDatasourceProvider<Datasource: DatasourceType>: DatasourceProviderType { /// The wrapped Datasource public let datasource: Datasource public let editor = NoEditor() public init(_ d: Datasource) { datasource = d } } /** A concrete implementation of DatasourceType for simple immutable arrays of objects. The static datasource is initalized with the model items to display. They all are in the same section. The cell and supplementary index types are both NSIndexPath, which means using a BasicFactory. This means that the configure block for cells and supplementary views will receive an NSIndexPath as their index argument. */ public final class StaticDatasource< Factory where Factory: _FactoryType, Factory.CellIndexType == NSIndexPath, Factory.SupplementaryIndexType == NSIndexPath>: DatasourceType, SequenceType, CollectionType { public typealias FactoryType = Factory public let factory: Factory public let identifier: String public var title: String? = .None private var items: [Factory.ItemType] /** The initializer. - parameter id: a String identifier - parameter factory: a Factory whose CellIndexType and SupplementaryIndexType must be NSIndexPath, such as BasicFactory. - parameter items: an array of Factory.ItemType instances. */ public init(id: String, factory f: Factory, items i: [Factory.ItemType]) { identifier = id factory = f items = i } /// The number of section, always 1 for a static datasource public var numberOfSections: Int { return 1 } /// The number of items in a section, always the item count for a static datasource public func numberOfItemsInSection(sectionIndex: Int) -> Int { return items.count } /** The item at an indexPath. Will ignore the section property of the NSIndexPath. Will also return .None if the indexPath item index is out of bounds of the array of items. - parameter indexPath: an NSIndexPath - returns: an optional Factory.ItemType */ public func itemAtIndexPath(indexPath: NSIndexPath) -> Factory.ItemType? { if items.startIndex <= indexPath.item && indexPath.item < items.endIndex { return items[indexPath.item] } return .None } /** Will return a cell. The cell is configured with the item at the index path first. Note, that the itemAtIndexPath method will gracefully return a .None if the indexPath is out of range. Here, we fatalError which will deliberately crash the app. - parameter view: the view instance. - parameter indexPath: an NSIndexPath - returns: a dequeued and configured Factory.CellType */ public func cellForItemInView(view: Factory.ViewType, atIndexPath indexPath: NSIndexPath) -> Factory.CellType { if let item = itemAtIndexPath(indexPath) { return factory.cellForItem(item, inView: view, atIndex: indexPath) } fatalError("No item available at index path: \(indexPath)") } /** Will return a supplementary view. This is the result of running any registered closure from the factory for this supplementary element kind. - parameter view: the view instance. - parameter kind" the SupplementaryElementKind of the supplementary view. - returns: a dequeued and configured Factory.SupplementaryViewType */ public func viewForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.SupplementaryViewType? { return factory.supplementaryViewForKind(kind, inView: view, atIndex: indexPath) } /** Will return an optional text for the supplementary kind - parameter view: the View which should dequeue the cell. - parameter kind: the kind of the supplementary element. See SupplementaryElementKind - parameter indexPath: the NSIndexPath of the item. - returns: a TextType? */ public func textForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.TextType? { return factory.supplementaryTextForKind(kind, atIndex: indexPath) } // SequenceType public func generate() -> Array<Factory.ItemType>.Generator { return items.generate() } // CollectionType public var startIndex: Int { return items.startIndex } public var endIndex: Int { return items.endIndex } public subscript(i: Int) -> Factory.ItemType { return items[i] } }
mit
bb139ebd699803c3486024bcb33f3205
32.924528
177
0.718391
4.999073
false
false
false
false
yarshure/Surf
Surf/SFRuleHelper.swift
1
10309
// // SFRuleHelper.swift // Surf // // Created by networkextension on 16/5/4. // Copyright © 2016年 yarshure. All rights reserved. // import Foundation import Foundation //import SQLite class SFRuleHelper{ static let shared = SFRuleHelper() var db:Connection? func testimport(){ let p = Bundle.main.path(forResource:"rules_public.conf", ofType: nil) open("rule8.db", readonly: false) if let path = p { let content = try! NSString.init(contentsOfFile: path, encoding: NSUTF8StringEncoding) let x = content.components(separatedBy: "\n") for item in x { let r = SFRuler() if item.hasPrefix("DOMAIN-KEYWORD"){ //print("Keyword rule") r.type = .DOMAINKEYWORD let x2 = item.components(separatedBy: ",") r.name = x2[1].trimmingCharacters(in: .whitespacesAndNewlines) r.proxyName = x2[2].trimmingCharacters(in: .whitespacesAndNewlines) }else if item.hasPrefix("DOMAIN-SUFFIX") || item.hasPrefix("DOMAIN"){ //print(" DOMAIN Keyword rule") let x2 = item.components(separatedBy: ",") r.name = x2[1].trimmingCharacters(in: .whitespacesAndNewlines) r.proxyName = x2[2].trimmingCharacters(in: .whitespacesAndNewlines) r.type = .DOMAINSUFFIX }else if item.hasPrefix("GEOIP"){ //print("GEOIP Keyword rule") r.type = .GEOIP let x2 = item.components(separatedBy: ",") r.name = x2[1].trimmingCharacters(in: .whitespacesAndNewlines) r.proxyName = x2[2].trimmingCharacters(in: .whitespacesAndNewlines) }else if item.hasPrefix("IP-CIDR"){ //print(" IP-CIDR Keyword rule") r.type = .IPCIDR let x2 = item.components(separatedBy: ",") r.name = x2[1].trimmingCharacters(in: .whitespacesAndNewlines) r.proxyName = x2[2].trimmingCharacters(in: .whitespacesAndNewlines) }else if item.hasPrefix("FINAL"){ //print("Final Keyword rule") r.type = .FINAL let x2 = item.components(separatedBy: ",") r.name = FINAL//x2[1].stringByTrimmingCharactersInSet( //NSCharacterSet.whitespaceAndNewlineCharacterSet()) r.proxyName = x2[1].trimmingCharacters(in: .whitespacesAndNewlines) } if !r.name.isEmpty && !r.proxyName.isEmpty{ print("RULE: " + r.name + " \(r.type.description) " + r.proxyName) saveRuler(r) } } } } func open(path:String,readonly:Bool){ // if let d = db { // //db. // } // let t = NSDate().timeIntervalSince1970 // var fn:String // if path.isEmpty { // fn = String.init(format:"%.0f.sqlite", t) // }else { // fn = path // } //let url0 = applicationDocumentsDirectory.appendingPathComponent(fn) let url = groupContainerURL().appendingPathComponent(path) // do{ // try fm.copyItemAtURL(url0, toURL: url) // }catch let e as NSError{ // print(e) // } if let p = url.path { do { db = try Connection(p,readonly: readonly) //initDatabase(db!) }catch let e as NSError{ logStream.write("open db error \(e.description)") } } } func initDatabase(db:Connection) { let bId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String if bId == "com.yarshure.Surf" { // let rules = Table("rules") // // let name = Expression<String>("name")//domain or IP/mask // // let type = Expression<Int64>("type") // let policy = Expression<Int64>("policy") // // let proxyName = Expression<String>("proxyName") do { try db.run(rules.create { t in t.column(id, primaryKey: .Autoincrement) t.column(name,unique: true)//, t.column(type) t.column(policy) t.column(proxyName) }) }catch let e as NSError { print(e.description) } }else { debugLog("don't need init db") } } func saveRuler(ruler:SFRuler) { if ruler.name.isEmpty { return } if let d = db { do { let rules = Table("rules") //let id = Expression<Int64>("id") // let name = Expression<String>("name")//domain or IP/mask // // let type = Expression<Int64>("type") // let policy = Expression<Int64>("policy") // let proxyName = Expression<String>("proxyName") try d.run( rules.insert( name <- ruler.name, type <- ruler.typeId, policy <- ruler.policyId, proxyName <- ruler.proxyName ) //"INSERT OR REPLACE INTO rules (name, type, policy) " + //"VALUES (?, ?, ?)", ruler.name, ruler.typeId, ruler.policyId ) } catch let _ as NSError { AxLogger.log("insert error ") } }else { //logStream.write("open db error \(e.description)") AxLogger.log("insert error no db") } } func openForApp(){ var fns:[String] = [] //if db == nil { let p = groupContainerURL().path let files = try! FileManager.default.contentsOfDirectoryAtPath(p!) for file in files { if file.containsString(".sqlite") { // let url = groupContainerURL.appendingPathComponent(file) // fns.append(url.path!) fns.append(file) } // let url = groupContainerURL.appendingPathComponent("Log/"+file) // let att = try! fm.attributesOfItemAtPath(url.path!) // let d = att["NSFileCreationDate"] as! NSDate // let size = att["NSFileSize"]! as! NSNumber // let fn = SFFILE.init(n: file, d: d,size:size.longLongValue) // self!.fileList.append(fn) // self!.fileList.sortInPlace({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending }) } //} let x = fns.removeLast() if !x.isEmpty { open(x,readonly: true) } for fx in fns { let url = groupContainerURL().appendingPathComponent(fx) let destURL = applicationDocumentsDirectory.appendingPathComponent(fx) do { try fm.moveItemAtURL(url, toURL: destURL) }catch let e as NSError { print(e.description) } } } func query(t:Int64,nameFilter:String) -> [SFRuler] { var result:[SFRuler] = [] var dbx:Connection! if let db = db { dbx = db }else { return result } do { //requests.order([start.asc]) //rules.filter(type == 1) var query:AnySequence<Row> //= try dbx.prepare(rules.filter(type == t)) if nameFilter.isEmpty { query = try dbx.prepare(rules.filter(type == t)) }else { query = try dbx.prepare(rules.filter(type == t).filter( name == nameFilter)) } for row in query { let req = SFRuler() req.name = row[name] //print(row[url]) //print(row[url]) if let t = SFRulerType(rawValue:Int(row[type])) { req.type = t } req.pWith(row[policy]) req.proxyName = row[proxyName] AxLogger.log("###### host:\(req.name) ip:\(req.proxyName) \(req.type.description) \(nameFilter)") result.append(req) } }catch let e as NSError{ print(e) } return result } func query(domainName:String) -> [SFRuler] { var result:[SFRuler] = [] // let rules = Table("rules") // let name = Expression<String>("name")//domain or IP/mask // // let type = Expression<Int64>("type") // let policy = Expression<Int64>("policy") var dbx:Connection! if let db = db { dbx = db }else { return result } do { //requests.order([start.asc]) //rules.filter(type == 1) let query = try dbx.prepare(rules.filter(type == 2).filter( name == domainName)) for row in query { let req = SFRuler() req.name = row[name] //print(row[url]) //print(row[url]) if let t = SFRulerType(rawValue:Int(row[type])) { req.type = t } req.pWith(row[policy]) print("###### \(req.name) \(req.proxyName) \(req.type.description)") result.append(req) } }catch let e as NSError{ print(e) } return result } }
bsd-3-clause
02772a3b1ab1f3b0b2af737b70948125
33.583893
126
0.458568
4.693078
false
false
false
false
daaavid/TIY-Assignments
32--Global-Time/Global Time/Global Time/ClockView.swift
1
8009
// // ClockView.swift // Clock // // Created by david on 11/17/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit let borderWidth: CGFloat = 2 let borderAlpha: CGFloat = 1 let digitOffset: CGFloat = 15 @IBDesignable class ClockView: UIView { var animationTimer: CADisplayLink? //core animation display link //timer object that allows your application to synchronize its drawing to the refresh rate of the display var clockBGColor = UIColor.whiteColor() var borderColor = UIColor.blackColor() var digitColor = UIColor.blackColor() var secondHandColor = UIColor.redColor() var colorHasBeenSet = false var timezone: NSTimeZone? { didSet //anytime timezone has been set (also can willSet) { animationTimer = CADisplayLink(target: self, selector: "timerFired:") animationTimer!.frameInterval = 8 //8 frame interval. how many frames before this will fire again let currentLoop = NSRunLoop.currentRunLoop() animationTimer!.addToRunLoop(currentLoop, forMode: NSRunLoopCommonModes) } } var time: NSDate? var seconds = 0 var minutes = 0 var hours = 0 var boundsCenter: CGPoint var digitFont: UIFont override init(frame: CGRect) { digitFont = UIFont() boundsCenter = CGPoint() super.init(frame: frame) let fontSize = 8 + frame.size.width/50 digitFont = UIFont.systemFontOfSize(fontSize) boundsCenter = CGPoint(x: bounds.width / 2, y: bounds.height / 2) self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { digitFont = UIFont() boundsCenter = CGPoint() super.init(coder: aDecoder) let fontSize = 8 + frame.size.width/50 digitFont = UIFont.systemFontOfSize(fontSize) boundsCenter = CGPoint(x: bounds.width / 2, y: bounds.height / 2) self.backgroundColor = UIColor.clearColor() } override func drawRect(rect: CGRect) { //clock face let cxt = UIGraphicsGetCurrentContext() //gets current canvas space CGContextAddEllipseInRect(cxt, rect) //rect being the current rectangle CGContextSetFillColorWithColor(cxt, clockBGColor.CGColor) CGContextFillPath(cxt) //clock center var radius: CGFloat = 6.0 let center2 = CGRect(x: boundsCenter.x - radius, y: boundsCenter.y - radius, width: 2 * radius, height: 2 * radius) CGContextAddEllipseInRect(cxt, center2) CGContextSetFillColorWithColor(cxt, digitColor.CGColor) CGContextFillPath(cxt) //clock border CGContextAddEllipseInRect(cxt, CGRect(x: rect.origin.x + borderWidth/2, y: rect.origin.y + borderWidth/2, width: rect.size.width - borderWidth, height: rect.size.height - borderWidth)) CGContextSetStrokeColorWithColor(cxt, borderColor.CGColor) CGContextSetLineWidth(cxt, borderWidth) CGContextStrokePath(cxt) //numerals let center = CGPoint(x: rect.size.width / 2.0, y: rect.size.height / 2.0) let markingDistanceFromCenter = rect.size.width / 2.0 - digitFont.lineHeight / 4.0 - 15 + digitOffset let offset = 4 for digit in 0..<12 { let hourString: String if digit + 1 < 10 { hourString = " " + String(digit + 1) } else { hourString = String(digit + 1) } let labelX = center.x + (markingDistanceFromCenter - digitFont.lineHeight / 2.0) * CGFloat(cos((M_PI / 180) * Double(digit + offset) * 30 + M_PI)) let labelY = center.y - 1 * (markingDistanceFromCenter - digitFont.lineHeight / 2.0) * CGFloat(sin((M_PI / 180) * Double(digit + offset) * 30)) hourString.drawInRect(CGRect(x: labelX - digitFont.lineHeight / 2.0, y: labelY - digitFont.lineHeight / 2.0, width: digitFont.lineHeight, height: digitFont.lineHeight), withAttributes: [NSForegroundColorAttributeName: digitColor, NSFontAttributeName: digitFont]) } //minute hand let minHandPos = minutesHandPosition() CGContextSetStrokeColorWithColor(cxt, digitColor.CGColor) CGContextBeginPath(cxt) CGContextMoveToPoint(cxt, boundsCenter.x, boundsCenter.y) CGContextSetLineWidth(cxt, 3.0) CGContextAddLineToPoint(cxt, minHandPos.x, minHandPos.y) CGContextStrokePath(cxt) //hour hand let hourHandPos = hoursHandPosition() CGContextSetStrokeColorWithColor(cxt, digitColor.CGColor) CGContextBeginPath(cxt) CGContextMoveToPoint(cxt, boundsCenter.x, boundsCenter.y) CGContextSetLineWidth(cxt, 3.0) CGContextAddLineToPoint(cxt, hourHandPos.x, hourHandPos.y) CGContextStrokePath(cxt) //second hand let secHandPos = secondsHandPosition() CGContextSetStrokeColorWithColor(cxt, secondHandColor.CGColor) CGContextBeginPath(cxt) CGContextMoveToPoint(cxt, boundsCenter.x, boundsCenter.y) CGContextSetLineWidth(cxt, 1.0) CGContextAddLineToPoint(cxt, secHandPos.x, secHandPos.y) CGContextStrokePath(cxt) // second hand's center radius = 3.0 let center3 = CGRect(x: boundsCenter.x - radius, y: boundsCenter.y - radius, width: 2 * radius, height: 2 * radius) CGContextAddEllipseInRect(cxt, center3) CGContextSetFillColorWithColor(cxt, secondHandColor.CGColor) CGContextFillPath(cxt) } func secondsHandPosition() -> CGPoint { let secondsAsRadians = Float(Double(seconds) / 60.0 * 2.0 * M_PI - M_PI_2) let handRadius = CGFloat(frame.size.width / 3.2) return CGPoint(x: handRadius*CGFloat(cosf(secondsAsRadians)) + boundsCenter.x, y: handRadius*CGFloat(sinf(secondsAsRadians)) + boundsCenter.y) } func minutesHandPosition() -> CGPoint { let minutesAsRadians = Float(Double(minutes) / 60.0 * 2.0 * M_PI - M_PI_2) let handRadius = CGFloat(frame.size.width / 3.4) return CGPoint(x: handRadius*CGFloat(cosf(minutesAsRadians)) + boundsCenter.x, y: handRadius*CGFloat(sinf(minutesAsRadians)) + boundsCenter.y) } func hoursHandPosition() -> CGPoint { let halfClock = Double(hours) + Double(minutes) / 60.0 let hoursAsRadians = Float(halfClock / 12.0 * 2.0 * M_PI - M_PI_2) let handRadius = CGFloat(frame.size.width / 3.8) return CGPoint(x: handRadius*CGFloat(cosf(hoursAsRadians)) + boundsCenter.x, y: handRadius*CGFloat(sinf(hoursAsRadians)) + boundsCenter.y) } func timerFired(sender: AnyObject) { time = NSDate() let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! calendar.timeZone = self.timezone! let timeComponents = calendar.components([.Hour, .Minute, .Second], fromDate: time!) hours = timeComponents.hour minutes = timeComponents.minute seconds = timeComponents.second if !colorHasBeenSet { setBGColors() colorHasBeenSet = true } setNeedsDisplay() //reload view data } func setBGColors() { print("color set.") let day = isDay(hours) if !day { clockBGColor = UIColor.blackColor() borderColor = UIColor.whiteColor() digitColor = UIColor.whiteColor() secondHandColor = UIColor.cyanColor() } } func isDay(hour: Int) -> Bool { var isDay: Bool print(hour) switch hour { case 5...19: isDay = true default: isDay = false } return isDay } }
cc0-1.0
29b526bcf905b20fe2eea688a3fa568e
35.56621
274
0.624875
4.421866
false
false
false
false
sanjubhatt2010/CarCollection
CarCollection/CarCollection/GenericFunction.swift
1
935
// // PrivateFunction.swift // CarCollection // // Created by Appinventiv on 17/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit extension UIView{ //for getting the table view cell var getTableCell : UITableViewCell? { var subview = self while !(subview is UITableViewCell) { guard let given = subview.superview else { return nil } subview = given } return subview as? UITableViewCell } //for getting the collection view cell var getCollectionCell : UICollectionViewCell? { var subview = self while !(subview is UICollectionViewCell) { guard let given = subview.superview else { return nil } subview = given } return subview as? UICollectionViewCell } }
mit
29af8e2cced9d47533598f607c526cde
22.948718
72
0.555675
5.526627
false
false
false
false
ihak/iHAKTableRefresh
iHAKTableRefresh/iHAKTableRefresh.swift
1
23478
// // iHAKTableRefresh.swift // iHAKTableRefresh // // Created by Hassan Ahmed on 10/18/16. // Copyright © 2016 Hassan Ahmed. All rights reserved. // import Foundation import UIKit enum RefreshType { case Top, Bottom, TopAndBottom } @objc enum RefreshState: Int { case Normal, Pulled, Loading } class iHAKTableRefresh: NSObject, UITableViewDelegate { var topViewHeight = CGFloat(60.0) var bottomViewHeight = CGFloat(40.0) var defaultContentOffset = CGFloat(0.0) var topViewEnabled = true var bottomViewEnabled = true var topRefreshState = RefreshState.Normal { didSet { updateTopView() if oldValue != topRefreshState { self.didChangeTopRefreshState() } } } var bottomRefreshState = RefreshState.Normal { didSet { updateBottomView() if oldValue != bottomRefreshState { self.didChangeBottomRefreshState() } } } var refreshType = RefreshType.TopAndBottom weak var tableView: UITableView! weak var delegate: iHAKTableRefreshDelegate! weak var dataSource: iHAKTableRefreshDataSource! var topView: UIView? var bottomView: UIView? private var topLabel: UILabel? private var bottomLabel: UILabel? private var topActivityIndicator: UIActivityIndicatorView? private var bottomActivityIndicator: UIActivityIndicatorView? private var bottomViewConstriant: NSLayoutConstraint? private var lastUpdated: NSDate? // MARK: - Initializers /// Default initializer. Initializes the instance with given tableview and delegate. /// By default sets refresh type to .TopAndBottom i.e boht top and bottom refresh are enabled. /// /// - parameter tableView: UITableView instance you want to add refresh control to. /// - parameter delegate: An instance that implements iHAKTableRefreshDelegate. init(tableView: UITableView, delegate: iHAKTableRefreshDelegate) { super.init() self.tableView = tableView self.tableView.delegate = self self.delegate = delegate } /// Convenience initializer that takes and object that implements /// iHAKTableRefreshDataSource as well along with iHAKTableRefreshDelegate. /// /// Use this method if you want to use your custom top and bottom views. /// /// - parameter tableView: UITableView instance you want to add refresh control to. /// - parameter delegate: An instance that implements iHAKTableRefreshDelegate. /// - parameter dataSource: An instance that implements iHAKTableRefreshDataSource. convenience init(tableView: UITableView, delegate: iHAKTableRefreshDelegate, dataSource: iHAKTableRefreshDataSource?) { self.init(tableView: tableView, delegate: delegate) self.dataSource = dataSource } /// Convenience initializer that allows you to choose the refresh type (Top|Bottom|TopAndBottom), /// define delegate and datasource. /// Use this method if you want to choose from the available RereshType(s). Implement iHAKTableRefreshDataSource /// if you want to provide your custom top or bottom views. /// /// - parameter tableView: UITableView instance you want to add refresh control to. /// - parameter refreshType: Choose from top, bottom or top and bottom refresh types. /// - parameter delegate: An instance that implements iHAKTableRefreshDelgate. /// - parameter dataSource: An instance that implements iHAKTableRefreshDataSource. convenience init(tableView: UITableView, refreshType: RefreshType, delegate: iHAKTableRefreshDelegate, dataSource: iHAKTableRefreshDataSource?) { self.init(tableView: tableView, delegate: delegate, dataSource: dataSource) self.refreshType = refreshType topViewEnabled = false bottomViewEnabled = false switch refreshType { case .Top: topViewEnabled = true addTopView() case .Bottom: bottomViewEnabled = true addBottomView() case .TopAndBottom: topViewEnabled = true bottomViewEnabled = true addTopView() addBottomView() } if refreshType == .Bottom || refreshType == .TopAndBottom { self.tableView.addObserver(self, forKeyPath: #keyPath(UITableView.contentSize), options: .new, context: nil) } } deinit { self.tableView.removeObserver(self, forKeyPath: #keyPath(UITableView.contentSize)) } // MARK: - Top and bottom views /// Adds bottom view to the tableview. private func addTopView() { let topView = getTopView() topView.translatesAutoresizingMaskIntoConstraints = false self.tableView.addSubview(topView) self.tableView.addConstraint(NSLayoutConstraint(item: topView, attribute: .width, relatedBy: .equal, toItem: self.tableView, attribute: .width, multiplier: 1.0, constant: 0.0)) self.tableView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[topView]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["topView":topView])) self.tableView.addConstraint(NSLayoutConstraint(item: topView, attribute: .bottom, relatedBy: .equal, toItem: self.tableView, attribute: .top, multiplier: 1.0, constant: 0.0)) } /// Gets a top view either by using datasource method or by creating a default one. /// - returns: The created UIView private func getTopView() -> UIView { if let topViewHeight = self.dataSource?.iHAKTableRefreshHeightForTopView?(refreshView: self) { self.topViewHeight = CGFloat(topViewHeight) } var view: UIView if let topView = self.dataSource?.iHAKTableRefreshTopView?(refreshView: self) { view = topView self.topView = view } else { view = createTopView() } return view } /// Creates and return the default top view. /// - returns: The created UIView private func createTopView() -> UIView { let topView = UIView() topView.backgroundColor = UIColor.clear topView.translatesAutoresizingMaskIntoConstraints = false topView.addConstraint(NSLayoutConstraint(item: topView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: topViewHeight)) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSLocalizedString("Pull to Refresh", comment: "") label.font = UIFont.systemFont(ofSize: 14.0, weight: UIFontWeightLight) topView.addSubview(label) topView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) topView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.translatesAutoresizingMaskIntoConstraints = false activityIndicator.hidesWhenStopped = true topView.addSubview(activityIndicator) topView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) topView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.topLabel = label self.topView = topView self.topActivityIndicator = activityIndicator return self.topView! } /// Adds bottom view to the tableview. private func addBottomView() { let bottomView = getBottomView() self.tableView.addSubview(bottomView) self.tableView.addConstraint(NSLayoutConstraint(item: bottomView, attribute: .width, relatedBy: .equal, toItem: self.tableView, attribute: .width, multiplier: 1.0, constant: 0.0)) self.tableView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[bottomView]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["bottomView":bottomView])) self.bottomViewConstriant = NSLayoutConstraint(item: bottomView, attribute: .top, relatedBy: .equal, toItem: self.tableView, attribute: .bottom, multiplier: 1.0, constant: tableView.contentSize.height) self.tableView.addConstraint(self.bottomViewConstriant!) } /// Gets a bottom view either by using datasource method or by creating a default one. /// - returns: The created UIView private func getBottomView() -> UIView { if let bottomViewHeight = self.dataSource?.iHAKTableRefreshHeightForBottomView?(refreshView: self) { self.bottomViewHeight = CGFloat(bottomViewHeight) } var view: UIView if let bottomView = self.dataSource?.iHAKTableRefreshBottomView?(refreshView: self) { view = bottomView self.bottomView = view } else { view = createBottomView() } return view } /// Creates and return the default bottom view. /// - returns: The created UIView private func createBottomView() -> UIView { let bottomView = UIView() bottomView.translatesAutoresizingMaskIntoConstraints = false bottomView.addConstraint(NSLayoutConstraint(item: bottomView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: bottomViewHeight)) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSLocalizedString("Load More Data", comment: "") label.font = UIFont.systemFont(ofSize: 14.0, weight: UIFontWeightLight) bottomView.addSubview(label) bottomView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: bottomView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) bottomView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: bottomView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.translatesAutoresizingMaskIntoConstraints = false activityIndicator.hidesWhenStopped = true bottomView.addSubview(activityIndicator) bottomView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .right, relatedBy: .equal, toItem: label, attribute: .left, multiplier: 1.0, constant: -10.0)) bottomView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerY, relatedBy: .equal, toItem: label, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.bottomLabel = label self.bottomView = bottomView self.bottomActivityIndicator = activityIndicator return self.bottomView! } //MARK: - Update methods private func updateTopRefreshState(state: RefreshState) { topRefreshState = state switch state { case .Loading: // print("Top refresh state: Loading") animateScrollView(insets: UIEdgeInsetsMake(topViewHeight-defaultContentOffset, 0.0, 0.0, 0.0), duration: 0.2) break case .Normal: // print("Top refresh state: Normal") break case .Pulled: // print("Top refresh state: Pulled") break } } private func updateBottomRefreshState(state: RefreshState) { bottomRefreshState = state switch state { case .Loading: // print("Bottom refresh state: Loading") animateScrollView(insets: UIEdgeInsetsMake(0.0, 0.0, bottomViewHeight, 0.0), duration: 0.2) break case .Normal: // print("Bottom refresh state: Normal") break case .Pulled: // print("Bottom refresh state: Pulled") break } } private func updateTopView() { if topRefreshState == .Pulled { self.topLabel?.text = NSLocalizedString("Release to Refresh", comment: "") } else if topRefreshState == .Normal { if let updatedAt = formattedLastUpdate() { self.topLabel?.text = String.init(format: NSLocalizedString("Last updated on %@", comment: ""), updatedAt) } else { self.topLabel?.text = NSLocalizedString("Pull to Refresh", comment: "") } topActivityIndicator?.stopAnimating() self.topLabel?.isHidden = false if !self.tableView.isDragging { animateScrollView(insets: UIEdgeInsetsMake(-defaultContentOffset, 0.0, 0.0, 0.0), duration: 0.2) } } else if topRefreshState == .Loading { self.topLabel?.isHidden = true topActivityIndicator?.startAnimating() } } private func updateBottomView() { if let bottomLabel = self.bottomLabel { if bottomRefreshState == .Normal { bottomLabel.text = NSLocalizedString("Load More Data", comment: "") bottomActivityIndicator?.stopAnimating() } else if bottomRefreshState == .Loading { bottomLabel.text = NSLocalizedString("Loading", comment: "") bottomActivityIndicator?.startAnimating() } } } //MARK: - Bottom view /// This method permanantly disables the bottom view. /// it sets refreshtype to top only, sets bottom refrsh state to normal, removes bottom view and disables it. func disableBottomRefresh() { self.refreshType = .Top self.bottomView?.removeFromSuperview() self.bottomViewEnabled = false self.bottomRefreshState = .Normal } /// Hides bottom refresh view. Call this method when you don't have more data to load. /// Or you can call it at the start when the tableview is empty. func hideBottomRefresh() { self.bottomView?.isHidden = true } /// Shows the bottom refresh view. Call this method when you have data to load. func showBottomRefresh() { self.bottomView?.isHidden = false } /// Call this method to manually trigger top refresh. This method /// don't take into account topViewEnabled property. Nor it trigger the delegate /// shouldPerformTopRefresh. func triggerTopRefresh() { // Scroll the view down to show top view self.tableView.setContentOffset(CGPoint.init(x: 0.0, y: topViewHeight * -1.0), animated: true) // Trigger the delegate and change state to loading self.delegate.iHAKTableRefreshWillPerformTopRefresh(refreshView: self) updateTopRefreshState(state: .Loading) } private func didChangeTopRefreshState() { self.delegate?.iHAKTableRefreshDidChangeTopRefreshState?(refreshView: self, state: self.topRefreshState) } private func didChangeBottomRefreshState() { self.delegate?.iHAKTableRefreshDidChangeBottomRefreshState?(refreshView: self, state: self.bottomRefreshState) } /// Call this method to finish refreshing the table view. /// /// - parameter success: A bool that tells if the refresh action was successful or not. func finishRefresh(success: Bool) { if success && self.topRefreshState == .Loading { lastUpdated = NSDate() } if self.topRefreshState == .Loading { self.delegate?.iHAKTableRefreshDidCompleteTopRefresh?(refreshView: self) } if self.bottomRefreshState == .Loading { self.delegate?.iHAKTableRefreshDidCompleteBottomRefresh?(refreshView: self) } self.topRefreshState = .Normal self.bottomRefreshState = .Normal } private func shouldPerformTopRefresh() -> Bool { if let returnValue = delegate.iHAKTableRefreshShouldPerformTopRefresh?(refreshView: self) { return returnValue } return true } private func shouldPerformBottomRefresh() -> Bool { if let returnValue = delegate.iHAKTableRefreshShouldPerformBottomRefresh?(refreshView: self) { return returnValue } return true } private func animateScrollView(insets: UIEdgeInsets, duration:TimeInterval) { UIView.animate(withDuration: duration) { self.tableView.contentInset = insets } } private func formattedLastUpdate() -> String? { if let date = lastUpdated { let df = DateFormatter() df.dateFormat = "dd MMM hh:mm a" return df.string(from: date as Date) } return nil } //MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.iHAKTableRefreshTable?(tableview: tableView, didSelectRow: indexPath) } //MARK: - UIScrollViewDelegate @objc func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollView.isDragging else { return } // print("frame height: \(scrollView.frame.height)), content height: \(scrollView.contentSize.height), content offset: \(scrollView.contentOffset.y)") if topRefreshState != .Loading && topViewEnabled { if (scrollView.contentOffset.y-defaultContentOffset) <= -topViewHeight { updateTopRefreshState(state: .Pulled) } else { updateTopRefreshState(state: .Normal) } } if bottomRefreshState != .Loading && bottomViewEnabled { // If content is less than the scrollview frame if scrollView.contentSize.height <= scrollView.frame.height { // print("\((scrollView.contentOffset.y-defaultContentOffset)) >= \(bottomViewHeight))") if (scrollView.contentOffset.y-defaultContentOffset) >= bottomViewHeight { updateBottomRefreshState(state: .Pulled) } else { updateBottomRefreshState(state: .Normal) } } else if scrollView.contentSize.height > scrollView.frame.height { if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.height) + bottomViewHeight { updateBottomRefreshState(state: .Pulled) } else { updateBottomRefreshState(state: .Normal) } } } } @objc func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if topRefreshState == .Pulled && topViewEnabled { if shouldPerformTopRefresh() { self.delegate.iHAKTableRefreshWillPerformTopRefresh(refreshView: self) updateTopRefreshState(state: .Loading) } } if bottomRefreshState == .Pulled && bottomViewEnabled { if shouldPerformBottomRefresh() { self.delegate.iHAKTableRefreshWillPerformBottomRefresh(refreshView: self) updateBottomRefreshState(state: .Loading) } } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { self.bottomViewConstriant?.constant = self.tableView.contentSize.height } } @objc protocol iHAKTableRefreshDelegate { /** Implement this method if you want to control when to refresh your view. Return false if you don't want top refresh. This method is not get called if the property topViewEnabled is false. */ @objc optional func iHAKTableRefreshShouldPerformTopRefresh(refreshView: iHAKTableRefresh) -> Bool /** Implement this method if you want to control when to refresh your view. Return false if you don't want bottom refresh. This method is not get called if the property bottomViewEnabled is false. */ @objc optional func iHAKTableRefreshShouldPerformBottomRefresh(refreshView: iHAKTableRefresh) -> Bool /** Implement this method to perform any data refresh on the tableview in case of top refresh. */ func iHAKTableRefreshWillPerformTopRefresh(refreshView: iHAKTableRefresh) /** Implement this method to perform any data refresh on tableview in case of bottom refresh. */ func iHAKTableRefreshWillPerformBottomRefresh(refreshView: iHAKTableRefresh) /** Implement this method if you are interested in the state of the top view. iHAKTableRefresh has three states (Normal, Pulled and Loading) denoted by RefreshState enum. */ @objc optional func iHAKTableRefreshDidChangeTopRefreshState(refreshView: iHAKTableRefresh, state: RefreshState) /** Implement this method if you are interested in the state of the bottom view. iHAKTableRefresh has three states (Normal, Pulled and Loading) denoted by RefreshState enum. */ @objc optional func iHAKTableRefreshDidChangeBottomRefreshState(refreshView: iHAKTableRefresh, state: RefreshState) /** Implement this method to do extra work at the end of top refresh. */ @objc optional func iHAKTableRefreshDidCompleteTopRefresh(refreshView: iHAKTableRefresh) /** Implement this method to do extra work at the end of bottom refresh. */ @objc optional func iHAKTableRefreshDidCompleteBottomRefresh(refreshView: iHAKTableRefresh) /** Implement this method if you want to get UITableViewDelegate's didSelectRow method */ @objc optional func iHAKTableRefreshTable(tableview: UITableView, didSelectRow atIndex: IndexPath) } @objc protocol iHAKTableRefreshDataSource { /** Implement this method to provide a custom top view height. */ @objc optional func iHAKTableRefreshHeightForTopView(refreshView: iHAKTableRefresh) -> Double /** Implement this method to provide a custom top view. */ @objc optional func iHAKTableRefreshTopView(refreshView: iHAKTableRefresh) -> UIView /** Implement this method to provide a custom bottom view height. */ @objc optional func iHAKTableRefreshHeightForBottomView(refreshView: iHAKTableRefresh) -> Double /** Implement this mehtod to provide a custom bottom view. */ @objc optional func iHAKTableRefreshBottomView(refreshView: iHAKTableRefresh) -> UIView }
mit
780c33f45e46fa58ff3a93f3b612e6e6
40.187719
209
0.654683
5.160914
false
false
false
false
lemberg/connfa-ios
Connfa/Stores/Firebase/FirebaseModels/PinModel.swift
1
682
// // PinModel.swift // Connfa // // Created by Marian Fedyk on 12/27/17. // Copyright © 2017 Lemberg Solution. All rights reserved. // import Foundation import Firebase class Pin: Equatable { var pinId: String var displayName: String? var actionTitle: String { return ("\(displayName ?? "") (\(pinId))") } static func ==(lhs: Pin, rhs: Pin) -> Bool { return lhs.pinId == rhs.pinId } init(dictionary: SnapshotDictionary, key: String) { self.pinId = key self.displayName = dictionary?[Keys.displayName] as? String } init(pinId: String, displayName: String? = nil) { self.pinId = pinId self.displayName = displayName } }
apache-2.0
f482a084fcc7d71c28340d536be57392
19.636364
63
0.64464
3.565445
false
false
false
false
leoMehlig/Charts
Charts/Classes/Renderers/PieChartRenderer.swift
3
27684
// // PieChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class PieChartRenderer: ChartDataRendererBase { public weak var chart: PieChartView? public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } public override func drawData(context context: CGContext) { guard let chart = chart else { return } let pieData = chart.data if (pieData != nil) { for set in pieData!.dataSets as! [IPieChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } } public func calculateMinimumRadiusForSpacedSlice( center center: CGPoint, radius: CGFloat, angle: CGFloat, arcStartPointX: CGFloat, arcStartPointY: CGFloat, startAngle: CGFloat, sweepAngle: CGFloat) -> CGFloat { let angleMiddle = startAngle + sweepAngle / 2.0 // Other point of the arc let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) // Middle point on the arc let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) // This is the base of the contained triangle let basePointsDistance = sqrt( pow(arcEndPointX - arcStartPointX, 2) + pow(arcEndPointY - arcStartPointY, 2)) // After reducing space from both sides of the "slice", // the angle of the contained triangle should stay the same. // So let's find out the height of that triangle. let containedTriangleHeight = (basePointsDistance / 2.0 * tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD)) // Now we subtract that from the radius var spacedRadius = radius - containedTriangleHeight // And now subtract the height of the arc that's between the triangle and the outer circle spacedRadius -= sqrt( pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) + pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2)) return spacedRadius } public func drawDataSet(context context: CGContext, dataSet: IPieChartDataSet) { guard let chart = chart, data = chart.data, animator = animator else {return } var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle let phaseX = animator.phaseX let phaseY = animator.phaseY let entryCount = dataSet.entryCount var drawAngles = chart.drawAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 var visibleAngleCount = 0 for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount++; } } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace CGContextSaveGState(context) for (var j = 0; j < entryCount; j++) { let sliceAngle = drawAngles[j] var innerRadius = userInnerRadius guard let e = dataSet.entryForIndex(j) else { continue } // draw only if the value is greater than zero if ((abs(e.value) > 0.000001)) { if (!chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: data.indexOfDataSet(dataSet))) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD) let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD) let path = CGPathCreateMutable() CGPathMoveToPoint( path, nil, arcStartPointX, arcStartPointY) CGPathAddRelativeArc( path, nil, center.x, center.y, radius, startAngleOuter * ChartUtils.Math.FDEG2RAD, sweepAngleOuter * ChartUtils.Math.FDEG2RAD) if drawInnerArc && (innerRadius > 0.0 || sliceSpace > 0.0) { if sliceSpace > 0.0 { var minSpacedRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = max(innerRadius, minSpacedRadius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner CGPathAddLineToPoint( path, nil, center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, innerRadius, endAngleInner * ChartUtils.Math.FDEG2RAD, -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { if sliceSpace > 0.0 { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let sliceSpaceOffset = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) CGPathAddLineToPoint( path, nil, arcEndPointX, arcEndPointY) } else { CGPathAddLineToPoint( path, nil, center.x, center.y) } } CGPathCloseSubpath(path) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextEOFillPath(context) } } angle += sliceAngle * phaseX } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let chart = chart, data = chart.data, animator = animator else { return } let center = chart.centerCircleBox // get whole the radius var r = chart.radius let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let phaseX = animator.phaseX let phaseY = animator.phaseY var off = r / 10.0 * 3.0 if chart.drawHoleEnabled { off = (r - (r * chart.holeRadiusPercent)) / 2.0 } r -= off; // offset to keep things inside the chart var dataSets = data.dataSets let yValueSum = (data as! PieChartData).yValueSum let drawXVals = chart.isDrawSliceTextEnabled let usePercentValuesEnabled = chart.usePercentValuesEnabled var angle: CGFloat = 0.0 var xIndex = 0 for (var i = 0; i < dataSets.count; i++) { guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue } let drawYVals = dataSet.isDrawValuesEnabled if (!drawYVals && !drawXVals) { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } for (var j = 0, entryCount = dataSet.entryCount; j < entryCount; j++) { if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil)) { continue } guard let e = dataSet.entryForIndex(j) else { continue } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceAngle = drawAngles[xIndex] let sliceSpace = dataSet.sliceSpace let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * r) // offset needed to center the drawn text in the slice let offset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0 angle = angle + offset // calculate the text position let x = r * cos((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD) + center.x var y = r * sin((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD) + center.y let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value let val = formatter.stringFromNumber(value)! let lineHeight = valueFont.lineHeight y -= lineHeight // draw everything, depending on settings if (drawXVals && drawYVals) { ChartUtils.drawText( context: context, text: val, point: CGPoint(x: x, y: y), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) if (j < data.xValCount && data.xVals[j] != nil) { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } else if (drawXVals) { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } else if (drawYVals) { ChartUtils.drawText( context: context, text: val, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } xIndex++ } } } public override func drawExtras(context context: CGContext) { drawHole(context: context) drawCenterText(context: context) } /// draws the hole in the center of the chart and the transparent circle / hole private func drawHole(context context: CGContext) { guard let chart = chart, animator = animator else { return } if (chart.drawHoleEnabled) { CGContextSaveGState(context) let radius = chart.radius let holeRadius = radius * chart.holeRadiusPercent let center = chart.centerCircleBox if let holeColor = chart.holeColor { if holeColor != NSUIColor.clearColor() { // draw the hole-circle CGContextSetFillColorWithColor(context, chart.holeColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) } } // only draw the circle if it can be seen (not covered by the hole) if let transparentCircleColor = chart.transparentCircleColor { if transparentCircleColor != NSUIColor.clearColor() && chart.transparentCircleRadiusPercent > chart.holeRadiusPercent { let alpha = animator.phaseX * animator.phaseY let secondHoleRadius = radius * chart.transparentCircleRadiusPercent // make transparent CGContextSetAlpha(context, alpha); CGContextSetFillColorWithColor(context, transparentCircleColor.CGColor) // draw the transparent-circle CGContextBeginPath(context) CGContextAddEllipseInRect(context, CGRect( x: center.x - secondHoleRadius, y: center.y - secondHoleRadius, width: secondHoleRadius * 2.0, height: secondHoleRadius * 2.0)) CGContextAddEllipseInRect(context, CGRect( x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) CGContextEOFillPath(context) } } CGContextRestoreGState(context) } } /// draws the description text in the center of the pie chart makes most sense when center-hole is enabled private func drawCenterText(context context: CGContext) { guard let chart = chart, centerAttributedText = chart.centerAttributedText else { return } if chart.drawCenterTextEnabled && centerAttributedText.length > 0 { let center = chart.centerCircleBox let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0) var boundingRect = holeRect if (chart.centerTextRadiusPercent > 0.0) { boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0) } let textBounds = centerAttributedText.boundingRectWithSize(boundingRect.size, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil) var drawingRect = boundingRect drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0 drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0 drawingRect.size = textBounds.size CGContextSaveGState(context) let clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil) CGContextBeginPath(context) CGContextAddPath(context, clippingPath) CGContextClip(context) centerAttributedText.drawWithRect(drawingRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil) CGContextRestoreGState(context) } } public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let chart = chart, data = chart.data, animator = animator else { return } CGContextSaveGState(context) let phaseX = animator.phaseX let phaseY = animator.phaseY var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 for (var i = 0; i < indices.count; i++) { // get the index to highlight let xIndex = indices[i].xIndex if (xIndex >= drawAngles.count) { continue } guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue } if !set.isHighlightEnabled { continue } let entryCount = set.entryCount var visibleAngleCount = 0 for (var j = 0; j < entryCount; j++) { guard let e = set.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount++; } } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace let sliceAngle = drawAngles[xIndex] var innerRadius = userInnerRadius let shift = set.selectionShift let highlightedRadius = radius + shift CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let sliceSpaceAngleShifted = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius) let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY if (sweepAngleShifted < 0.0) { sweepAngleShifted = 0.0 } let path = CGPathCreateMutable() CGPathMoveToPoint( path, nil, center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD), center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, highlightedRadius, startAngleShifted * ChartUtils.Math.FDEG2RAD, sweepAngleShifted * ChartUtils.Math.FDEG2RAD) var sliceSpaceRadius: CGFloat = 0.0 if sliceSpace > 0.0 { sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD), arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD), startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) } if drawInnerArc && (innerRadius > 0.0 || sliceSpace > 0.0) { if sliceSpace > 0.0 { var minSpacedRadius = sliceSpaceRadius if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = max(innerRadius, minSpacedRadius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner CGPathAddLineToPoint( path, nil, center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, innerRadius, endAngleInner * ChartUtils.Math.FDEG2RAD, -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { if sliceSpace > 0.0 { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) CGPathAddLineToPoint( path, nil, arcEndPointX, arcEndPointY) } else { CGPathAddLineToPoint( path, nil, center.x, center.y) } } CGPathCloseSubpath(path) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextEOFillPath(context) } CGContextRestoreGState(context) } }
apache-2.0
130d76daa89a7ef72265cb8aaa2d4e74
38.268085
220
0.482589
5.859048
false
false
false
false
peterlafferty/LuasLife
LuasLifeKit/Line.swift
1
748
// // Route.swift // LuasLife // // Created by Peter Lafferty on 29/02/2016. // Copyright © 2016 Peter Lafferty. All rights reserved. // import Foundation import Decodable /** A luas route. Names: - GREEN - RED */ public struct Line { public let id: Int public let name: String public let numberOfRoutes: Int public init(id: Int, name: String, numberOfRoutes: Int = 0) { self.id = id self.name = name self.numberOfRoutes = numberOfRoutes } } extension Line: Decodable { public static func decode(_ j: Any) throws -> Line { return try Line( id: j => "id", name: j => "name", numberOfRoutes: j => "numberOfRoutes" ) } }
mit
2b949ef3f1453d67ece7cdac056cf08d
18.153846
65
0.576975
3.716418
false
false
false
false
nathawes/swift
test/type/opaque.swift
5
15590
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify %s protocol P { func paul() mutating func priscilla() } protocol Q { func quinn() } extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } class C {} class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {} } let property: some P = 1 let deflessLet: some P // expected-error{{has no initializer}} {{educational-notes=opaque-type-inference}} var deflessVar: some P // expected-error{{has no initializer}} struct GenericProperty<T: P> { var x: T var property: some P { return x } } let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}} var computedProperty: some P { get { return 1 } set { _ = newValue + 1 } // expected-error{{cannot convert value of type 'some P' to expected argument type 'Int'}} } struct SubscriptTest { subscript(_ x: Int) -> some P { return x } } func bar() -> some P { return 1 } func bas() -> some P & Q { return 1 } func zim() -> some C { return D() } func zang() -> some C & P & Q { return D() } func zung() -> some AnyObject { return D() } func zoop() -> some Any { return D() } func zup() -> some Any & P { return D() } func zip() -> some AnyObject & P { return D() } func zorp() -> some Any & C & P { return D() } func zlop() -> some C & AnyObject & P { return D() } // Don't allow opaque types to propagate by inference into other global decls' // types struct Test { let inferredOpaque = bar() // expected-error{{inferred type}} let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}} let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}} } //let zingle = {() -> some P in 1 } // FIXME ex/pected-error{{'some' types are only implemented}} // Invalid positions typealias Foo = some P // expected-error{{'some' types are only implemented}} func blibble(blobble: some P) {} // expected-error{{'some' types are only implemented}} let blubble: () -> some P = { 1 } // expected-error{{'some' types are only implemented}} func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}} func blab() -> (P, some Q) { return (1, 2) } // expected-error{{'some' types are only implemented}} func blob() -> (some P) -> P { return { $0 } } // expected-error{{'some' types are only implemented}} func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only implemented}} func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only implemented}} expected-error{{cannot convert}} protocol OP: some P {} // expected-error{{'some' types are only implemented}} func foo() -> some P { let x = (some P).self // expected-error*{{}} return 1 } // Invalid constraints let zug: some Int = 1 // FIXME expected-error{{must specify only}} let zwang: some () = () // FIXME expected-error{{must specify only}} let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}} // Type-checking of expressions of opaque type func alice() -> some P { return 1 } func bob() -> some P { return 1 } func grace<T: P>(_ x: T) -> some P { return x } func typeIdentity() { do { var a = alice() a = alice() a = bob() // expected-error{{}} a = grace(1) // expected-error{{}} a = grace("two") // expected-error{{}} } do { var af = alice af = alice af = bob // expected-error{{}} af = grace // expected-error{{generic parameter 'T' could not be inferred}} // expected-error@-1 {{cannot assign value of type '(T) -> some P' to type '() -> some P'}} } do { var b = bob() b = alice() // expected-error{{}} b = bob() b = grace(1) // expected-error{{}} b = grace("two") // expected-error{{}} } do { var gi = grace(1) gi = alice() // expected-error{{}} gi = bob() // expected-error{{}} gi = grace(2) gi = grace("three") // expected-error{{}} } do { var gs = grace("one") gs = alice() // expected-error{{}} gs = bob() // expected-error{{}} gs = grace(2) // expected-error{{}} gs = grace("three") } // The opaque type should conform to its constraining protocols do { let gs = grace("one") var ggs = grace(gs) ggs = grace(gs) } // The opaque type should expose the members implied by its protocol // constraints do { var a = alice() a.paul() a.priscilla() } } func recursion(x: Int) -> some P { if x == 0 { return 0 } return recursion(x: x - 1) } func noReturnStmts() -> some P {} // expected-error {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} {{educational-notes=opaque-type-inference}} func returnUninhabited() -> some P { // expected-note {{opaque return type declared here}} fatalError() // expected-error{{return type of global function 'returnUninhabited()' requires that 'Never' conform to 'P'}} } func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}} {{educational-notes=opaque-type-inference}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}} if true { return 0 // expected-note{{underlying type 'Int'}} } else { return "" // expected-note{{underlying type 'String'}} } } struct MismatchedReturnTypesSubscript { subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } } func jan() -> some P { return [marcia(), marcia(), marcia()] } func marcia() -> some P { return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}} {{educational-notes=opaque-type-inference}} } protocol R { associatedtype S: P, Q // expected-note*{{}} func r_out() -> S func r_in(_: S) } extension Int: R { func r_out() -> String { return "" } func r_in(_: String) {} } func candace() -> some R { return 0 } func doug() -> some R { return 0 } func gary<T: R>(_ x: T) -> some R { return x } func sameType<T>(_: T, _: T) {} func associatedTypeIdentity() { let c = candace() let d = doug() var cr = c.r_out() cr = candace().r_out() cr = doug().r_out() // expected-error{{}} var dr = d.r_out() dr = candace().r_out() // expected-error{{}} dr = doug().r_out() c.r_in(cr) c.r_in(c.r_out()) c.r_in(dr) // expected-error{{}} c.r_in(d.r_out()) // expected-error{{}} d.r_in(cr) // expected-error{{}} d.r_in(c.r_out()) // expected-error{{}} d.r_in(dr) d.r_in(d.r_out()) cr.paul() cr.priscilla() cr.quinn() dr.paul() dr.priscilla() dr.quinn() sameType(cr, c.r_out()) sameType(dr, d.r_out()) sameType(cr, dr) // expected-error {{conflicting arguments to generic parameter 'T' ('(some R).S' (associated type of protocol 'R') vs. '(some R).S' (associated type of protocol 'R'))}} sameType(gary(candace()).r_out(), gary(candace()).r_out()) sameType(gary(doug()).r_out(), gary(doug()).r_out()) // TODO(diagnostics): This is not great but the problem comes from the way solver discovers and attempts bindings, if we could detect that // `(some R).S` from first reference to `gary()` in incosistent with the second one based on the parent type of `S` it would be much easier to diagnose. sameType(gary(doug()).r_out(), gary(candace()).r_out()) // expected-error@-1:3 {{conflicting arguments to generic parameter 'T' ('(some R).S' (associated type of protocol 'R') vs. '(some R).S' (associated type of protocol 'R'))}} // expected-error@-2:12 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} // expected-error@-3:34 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} } func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } func redeclaration() -> Any { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} struct RedeclarationTest { func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some P { return 0 } // expected-note 2{{previously declared}} subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some Q { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> P { return 0 } } func diagnose_requirement_failures() { struct S { var foo: some P { return S() } // expected-note {{declared here}} // expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}} subscript(_: Int) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}} } func bar() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}} } static func baz(x: String) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}} } } func fn() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}} } } func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}} return 42 as Double // expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}} } func recursive_func_is_invalid_opaque() { func rec(x: Int) -> some P { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} if x == 0 { return rec(x: 0) } return rec(x: x - 1) } } func closure() -> some P { _ = { return "test" } return 42 } protocol HasAssocType { associatedtype Assoc func assoc() -> Assoc } struct GenericWithOpaqueAssoc<T>: HasAssocType { func assoc() -> some Any { return 0 } } struct OtherGeneric<X, Y, Z> { var x: GenericWithOpaqueAssoc<X>.Assoc var y: GenericWithOpaqueAssoc<Y>.Assoc var z: GenericWithOpaqueAssoc<Z>.Assoc } protocol P_51641323 { associatedtype T var foo: Self.T { get } } func rdar_51641323() { struct Foo: P_51641323 { var foo: some P_51641323 { // expected-note {{required by opaque return type of property 'foo'}} {} // expected-error {{type '() -> ()' cannot conform to 'P_51641323'; only concrete types such as structs, enums and classes can conform to protocols}} } } } // Protocol requirements cannot have opaque return types protocol OpaqueProtocolRequirement { // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{20-26=<#AssocType#>}} func method() -> some P // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{13-19=<#AssocType#>}} var prop: some P { get } // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{18-24=<#AssocType#>}} subscript() -> some P { get } } func testCoercionDiagnostics() { var opaque = foo() opaque = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaque = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} opaque = computedProperty // expected-error {{cannot assign value of type 'some P' (type of 'computedProperty') to type 'some P' (result of 'foo()')}} {{none}} opaque = SubscriptTest()[0] // expected-error {{cannot assign value of type 'some P' (result of 'SubscriptTest.subscript(_:)') to type 'some P' (result of 'foo()')}} {{none}} var opaqueOpt: Optional = opaque opaqueOpt = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaqueOpt = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} } var globalVar: some P = 17 let globalLet: some P = 38 struct Foo { static var staticVar: some P = 17 static let staticLet: some P = 38 var instanceVar: some P = 17 let instanceLet: some P = 38 } protocol P_52528543 { init() associatedtype A: Q_52528543 var a: A { get } } protocol Q_52528543 { associatedtype B // expected-note 2 {{associated type 'B'}} var b: B { get } } extension P_52528543 { func frob(a_b: A.B) -> some P_52528543 { return self } } func foo<T: P_52528543>(x: T) -> some P_52528543 { return x .frob(a_b: x.a.b) .frob(a_b: x.a.b) // expected-error {{cannot convert}} } struct GenericFoo<T: P_52528543, U: P_52528543> { let x: some P_52528543 = T() let y: some P_52528543 = U() mutating func bump() { var xab = f_52528543(x: x) xab = f_52528543(x: y) // expected-error{{cannot assign}} } } func f_52528543<T: P_52528543>(x: T) -> T.A.B { return x.a.b } func opaque_52528543<T: P_52528543>(x: T) -> some P_52528543 { return x } func invoke_52528543<T: P_52528543, U: P_52528543>(x: T, y: U) { let x2 = opaque_52528543(x: x) let y2 = opaque_52528543(x: y) var xab = f_52528543(x: x2) xab = f_52528543(x: y2) // expected-error{{cannot assign}} } protocol Proto {} struct I : Proto {} dynamic func foo<S>(_ s: S) -> some Proto { return I() } @_dynamicReplacement(for: foo) func foo_repl<S>(_ s: S) -> some Proto { return I() } protocol SomeProtocolA {} protocol SomeProtocolB {} struct SomeStructC: SomeProtocolA, SomeProtocolB {} let someProperty: SomeProtocolA & some SomeProtocolB = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{35-40=}}{{19-19=some }}
apache-2.0
9d7d0d1c8d5e8bb1d10659eb8992a3b1
31.01232
220
0.636818
3.390605
false
false
false
false
BitGo/keytool-ios
KeyTool/KeyTool/KeyInfo.swift
1
1820
// // KeyInfo.swift // KeyTool // // Created by Huang Yu on 7/29/15. // Copyright (c) 2015 BitGo, Inc. All rights reserved. // import UIKit class KeyInfo: NSObject { var mnemonic: BTCMnemonic? var publicKey: NSString! = "" var privateKey: NSString! = "" func mnemonicString() -> String { if let mn = self.mnemonic { var array = mn.words as! [String] return " ".join(array) } return "" } override init() { super.init() } init(mnemonic: BTCMnemonic!, publicKey: NSString, privateKey: NSString) { self.mnemonic = mnemonic self.publicKey = publicKey self.privateKey = privateKey super.init() } convenience init(data mnData: NSData) { self.init( mnemonic: BTCMnemonic( entropy: mnData, password: "", wordListType: BTCMnemonicWordListType.English ) ) } convenience init(words mnWords: [String]) { self.init( mnemonic: BTCMnemonic( words: mnWords, password: "", wordListType: BTCMnemonicWordListType.English ) ) } convenience init(mnemonic: BTCMnemonic?) { var publicKey: String var privateKey: String if let mn = mnemonic { var keychain = mn.keychain publicKey = keychain.extendedPublicKey privateKey = keychain.extendedPrivateKey } else { publicKey = "Invalid Key Recovery Phrase" privateKey = "Invalid Key Recovery Phrase" } self.init( mnemonic: mnemonic, publicKey: publicKey, privateKey: privateKey ) } }
apache-2.0
a0864195999c97591863919fd38717b5
23.931507
77
0.532418
4.751958
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/OptionalContentGroup.swift
1
3438
/** * OptionalContentGroup.swift * Copyright 2020 Innovatics Inc. 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 /// /// Container for drawable objects that can be drawn on a page as part of Optional Content Group. /// Please see the PDF specification and Example_30 for more details. /// /// @author Mark Paxton /// public class OptionalContentGroup { var name: String? var ocgNumber = 0 var objNumber = 0 var visible: Bool? var printable: Bool? var exportable: Bool? private var components = [Drawable]() public init(_ name: String) { self.name = name } public func add(_ drawable: Drawable) { components.append(drawable) } public func setVisible(_ visible: Bool) { self.visible = visible } public func setPrintable(_ printable: Bool) { self.printable = printable } public func setExportable(_ exportable: Bool) { self.exportable = exportable } public func drawOn(_ page: Page) { if !components.isEmpty { page.pdf!.groups.append(self) ocgNumber = page.pdf!.groups.count page.pdf!.newobj() page.pdf!.append("<<\n") page.pdf!.append("/Type /OCG\n") page.pdf!.append("/Name (" + name! + ")\n") page.pdf!.append("/Usage <<\n") if visible != nil { page.pdf!.append("/View << /ViewState /ON >>\n") } else { page.pdf!.append("/View << /ViewState /OFF >>\n") } if printable != nil { page.pdf!.append("/Print << /PrintState /ON >>\n") } else { page.pdf!.append("/Print << /PrintState /OFF >>\n") } if exportable != nil { page.pdf!.append("/Export << /ExportState /ON >>\n") } else { page.pdf!.append("/Export << /ExportState /OFF >>\n") } page.pdf!.append(">>\n") page.pdf!.append(">>\n") page.pdf!.endobj() objNumber = page.pdf!.getObjNumber() page.append("/OC /OC") page.append(ocgNumber) page.append(" BDC\n") for component in components { component.drawOn(page) } page.append("\nEMC\n") } } } // End of OptionalContentGroup.swift
mit
db4b01e585d3cd063b557a6ec7f1119f
30.541284
97
0.600349
4.357414
false
false
false
false
RxSwiftCommunity/RxMKMapView
Sources/Diff.swift
1
1833
// // Diff.swift // RxMKMapView // // Created by Mikko Välimäki on 08/08/2017. // Copyright © 2017 RxSwiftCommunity. All rights reserved. // import Foundation import MapKit public struct Diff<T: NSObjectProtocol> { public let removed: [T] public let added: [T] } private struct BoxedHashable<T: NSObjectProtocol>: Hashable { public let value: T public init(_ value: T) { self.value = value } public func hash(into hasher: inout Hasher) { hasher.combine(value.hash) } public static func == (lhs: BoxedHashable, rhs: BoxedHashable) -> Bool { return lhs.value.isEqual(rhs.value) } } private struct Entry<T> { public var prev: T? public var next: T? func isRemoval() -> Bool { return prev != nil && next == nil } func isAddition() -> Bool { return prev == nil && next != nil } func value() -> T { return (prev ?? next)! } } public extension Diff { static func calculateFrom(previous: [T], next: [T]) -> Diff<T> { var entries = [BoxedHashable<T>: Entry<T>]() for item in previous { var entry = entries[BoxedHashable(item)] ?? Entry() entry.prev = item entries[BoxedHashable(item)] = entry } for item in next { var entry = entries[BoxedHashable(item)] ?? Entry() entry.next = item entries[BoxedHashable(item)] = entry } var removed: [T] = [] var added: [T] = [] for (_, value) in entries { if value.isAddition() { added.append(value.value()) } else if value.isRemoval() { removed.append(value.value()) } // else no change } return Diff(removed: removed, added: added) } }
mit
e282ca13a1ae7957886cc0eefed9d6c0
22.164557
76
0.554098
3.978261
false
false
false
false
silt-lang/silt
Sources/OuterCore/ParseGIR.swift
1
14965
/// ParseGIR.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere import Crust import Seismography import Moho import Mantle public final class GIRParser { struct ParserScope { let name: String } let parser: Parser var module: GIRModule private var _activeScope: ParserScope? fileprivate var continuationsByName: [Name: Continuation] = [:] fileprivate var undefinedContinuation: [Continuation: TokenSyntax] = [:] fileprivate var localValues: [String: Value] = [:] fileprivate var forwardRefLocalValues: [String: TokenSyntax] = [:] private let tc: TypeChecker<CheckPhaseState> var currentScope: ParserScope { guard let scope = self._activeScope else { fatalError("Attempted to request current scope without pushing a scope.") } return scope } public init(_ parser: Parser) { self.parser = parser self.tc = TypeChecker<CheckPhaseState>(CheckPhaseState(), parser.engine) self.module = GIRModule(parent: nil, tc: TypeConverter(self.tc)) } @discardableResult func withScope<T>(named name: String, _ actions: () throws -> T) rethrows -> T { let prevScope = self._activeScope let prevLocals = localValues let prevForwardRefLocals = forwardRefLocalValues self._activeScope = ParserScope(name: name) defer { self._activeScope = prevScope self.localValues = prevLocals self.forwardRefLocalValues = prevForwardRefLocals } return try actions() } func namedContinuation(_ B: GIRBuilder, _ name: Name) -> Continuation { // If there was no name specified for this block, just create a new one. if name.description.isEmpty { return B.buildContinuation(name: QualifiedName(name: name)) } // If the block has never been named yet, just create it. guard let cont = self.continuationsByName[name] else { let cont = B.buildContinuation(name: QualifiedName(name: name)) self.continuationsByName[name] = cont return cont } if undefinedContinuation.removeValue(forKey: cont) == nil { // If we have a redefinition, return a new BB to avoid inserting // instructions after the terminator. fatalError("Redefinition of Basic Block") } return cont } func getReferencedContinuation( _ B: GIRBuilder, _ syntax: TokenSyntax) -> Continuation { assert(syntax.render.starts(with: "@")) let noAtNode = syntax.withKind( .identifier(String(syntax.render.dropFirst()))) let name = Name(name: noAtNode) // If the block has already been created, use it. guard let cont = self.continuationsByName[name] else { // Otherwise, create it and remember that this is a forward reference so // that we can diagnose use without definition problems. let cont = B.buildContinuation(name: QualifiedName(name: name)) self.continuationsByName[name] = cont self.undefinedContinuation[cont] = syntax return cont } return cont } func getLocalValue(_ name: TokenSyntax) -> Value { // Check to see if this is already defined. guard let entry = self.localValues[name.render] else { // Otherwise, this is a forward reference. Create a dummy node to // represent it until we see a real definition. self.forwardRefLocalValues[name.render] = name let entry = NoOp() self.localValues[name.render] = entry return entry } return entry } func setLocalValue(_ value: Value, _ name: String) { // If this value was already defined, it is either a redefinition, or a // specification for a forward referenced value. guard let entry = self.localValues[name] else { // Otherwise, just store it in our map. self.localValues[name] = value return } guard self.forwardRefLocalValues.removeValue(forKey: name) != nil else { fatalError("Redefinition of named value \(name) by \(value)") } // Forward references only live here if they have a single result. entry.replaceAllUsesWith(value) } } extension GIRParser { public func parseTopLevelModule() -> GIRModule { do { _ = try self.parser.consume(.moduleKeyword) let moduleId = try self.parser.parseQualifiedName().render _ = try self.parser.consume(.whereKeyword) let mod = GIRModule(name: moduleId, parent: nil, tc: TypeConverter(self.tc)) self.module = mod let builder = GIRBuilder(module: mod) try self.parseDecls(builder) assert(self.parser.currentToken?.tokenKind == .eof) return mod } catch _ { return self.module } } func parseDecls(_ B: GIRBuilder) throws { while self.parser.peek() != .rightBrace && self.parser.peek() != .eof { _ = try parseDecl(B) } } func parseDecl(_ B: GIRBuilder) throws -> Bool { guard case let .identifier(identStr) = parser.peek(), identStr.starts(with: "@") else { throw self.parser.unexpectedToken() } let ident = try self.parser.parseIdentifierToken() _ = try self.parser.consume(.colon) _ = try self.parser.parseGIRTypeExpr() _ = try self.parser.consume(.leftBrace) return try self.withScope(named: ident.render) { repeat { guard try self.parseGIRBasicBlock(B) else { return false } } while self.parser.peek() != .rightBrace && self.parser.peek() != .eof _ = try self.parser.consume(.rightBrace) return true } } func parseGIRBasicBlock(_ B: GIRBuilder) throws -> Bool { var ident = try self.parser.parseIdentifierToken() if ident.render.hasSuffix(":") { ident = ident.withKind(.identifier(String(ident.render.dropLast()))) } let cont = self.namedContinuation(B, Name(name: ident)) // If there is a basic block argument list, process it. if try self.parser.consumeIf(.leftParen) != nil { repeat { let name = try self.parser.parseIdentifierToken().render _ = try self.parser.consume(.colon) let typeRepr = try self.parser.parseGIRTypeExpr() let arg = cont.appendParameter(type: GIRExprType(typeRepr)) self.setLocalValue(arg, name) } while try self.parser.consumeIf(.semicolon) != nil _ = try self.parser.consume(.rightParen) _ = try self.parser.consume(.colon) } repeat { guard try parseGIRInstruction(B, in: cont) else { return true } } while isStartOfGIRPrimop() return true } func isStartOfGIRPrimop() -> Bool { guard case .identifier(_) = self.parser.peek() else { return false } return true } // swiftlint:disable function_body_length func parseGIRInstruction( _ B: GIRBuilder, in cont: Continuation) throws -> Bool { guard self.parser.peekToken()!.leadingTrivia.containsNewline else { fatalError("Instruction must begin on a new line") } guard case .identifier(_) = self.parser.peek() else { return false } let resultName = tryParseGIRValueName() if resultName != nil { _ = try self.parser.consume(.equals) } guard let opcode = parseGIRPrimOpcode() else { return false } var resultValue: Value? switch opcode { case .dataExtract: fatalError("unimplemented") case .forceEffects: fatalError("unimplemented") case .tuple: fatalError("unimplemented") case .tupleElementAddress: fatalError("unimplemented") case .thicken: fatalError("unimplemented") case .noop: fatalError("noop cannot be spelled") case .alloca: let typeRepr = try self.parser.parseGIRTypeExpr() let type = GIRExprType(typeRepr) resultValue = B.createAlloca(type) case .allocBox: let typeRepr = try self.parser.parseGIRTypeExpr() let type = GIRExprType(typeRepr) resultValue = B.createAllocBox(type) case .apply: guard let fnName = tryParseGIRValueToken() else { return false } let fnVal = self.getLocalValue(fnName) _ = try self.parser.consume(.leftParen) var argNames = [TokenSyntax]() if self.parser.peek() != .rightParen { repeat { guard let arg = self.tryParseGIRValueToken() else { return false } argNames.append(arg) } while try self.parser.consumeIf(.semicolon) != nil } _ = try self.parser.consume(.rightParen) _ = try self.parser.consume(.colon) _ = try self.parser.parseGIRTypeExpr() var args = [Value]() for argName in argNames { let argVal = self.getLocalValue(argName) args.append(argVal) } _ = B.createApply(cont, fnVal, args) case .copyValue: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() resultValue = B.createCopyValue(self.getLocalValue(valueName)) case .copyAddress: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consume(.identifier("to")) guard let addressName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() resultValue = B.createCopyAddress(self.getLocalValue(valueName), to: self.getLocalValue(addressName)) case .dealloca: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() cont.appendCleanupOp(B.createDealloca(self.getLocalValue(valueName))) case .deallocBox: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() cont.appendCleanupOp(B.createDeallocBox(self.getLocalValue(valueName))) case .destroyValue: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() cont.appendCleanupOp(B.createDestroyValue(self.getLocalValue(valueName))) case .destroyAddress: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() cont.appendCleanupOp( B.createDestroyAddress(self.getLocalValue(valueName))) case .switchConstr: guard let val = self.tryParseGIRValueToken() else { return false } let srcVal = self.getLocalValue(val) _ = try self.parser.consume(.colon) _ = try self.parser.parseGIRTypeExpr() var caseConts = [(String, FunctionRefOp)]() while case .semicolon = self.parser.peek() { _ = try self.parser.consume(.semicolon) guard case let .identifier(ident) = self.parser.peek(), ident == "case" else { return false } _ = try self.parser.parseIdentifierToken() let caseName = try self.parser.parseQualifiedName() _ = try self.parser.consume(.colon) guard let arg = self.tryParseGIRValueToken() else { return false } // swiftlint:disable force_cast let fnVal = self.getLocalValue(arg) as! FunctionRefOp caseConts.append((caseName.render, fnVal)) } _ = B.createSwitchConstr(cont, srcVal, caseConts) case .functionRef: guard case let .identifier(refName) = parser.peek(), refName.starts(with: "@") else { return false } let ident = try self.parser.parseIdentifierToken() let resultFn = getReferencedContinuation(B, ident) resultValue = B.createFunctionRef(resultFn) case .dataInit: let typeRepr = try self.parser.parseGIRTypeExpr() _ = try self.parser.consume(.semicolon) let ident = try self.parser.parseQualifiedName() let type = GIRExprType(typeRepr) var args = [Value]() while case .semicolon = self.parser.peek() { _ = try self.parser.consume(.semicolon) guard let arg = self.tryParseGIRValueToken() else { return false } let argVal = self.getLocalValue(arg) _ = try self.parser.consume(.colon) _ = try self.parser.parseGIRTypeExpr() args.append(argVal) } resultValue = B.createDataInit(ident.render, type, nil) case .projectBox: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) let typeRepr = try self.parser.parseGIRTypeExpr() resultValue = B.createProjectBox(self.getLocalValue(valueName), type: GIRExprType(typeRepr)) case .load: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() resultValue = B.createLoad(self.getLocalValue(valueName), .copy) case .store: guard let valueName = tryParseGIRValueToken() else { return false } _ = try self.parser.consume(.identifier("to")) guard let addressName = tryParseGIRValueToken() else { return false } _ = try self.parser.consumeIf(.colon) _ = try self.parser.parseGIRTypeExpr() _ = B.createStore(self.getLocalValue(valueName), to: self.getLocalValue(addressName)) case .unreachable: resultValue = B.createUnreachable(cont) } guard let resName = resultName, let resValue = resultValue else { return true } self.setLocalValue(resValue, resName) return true } func tryParseGIRValueName() -> String? { return tryParseGIRValueToken()?.render } func tryParseGIRValueToken() -> TokenSyntax? { guard let result = self.parser.peekToken() else { return nil } guard case let .identifier(ident) = result.tokenKind else { return nil } guard ident.starts(with: "%") else { return nil } self.parser.advance() return result } func parseGIRPrimOpcode() -> PrimOp.Code? { guard case let .identifier(ident) = self.parser.peek() else { return nil } guard let opCode = PrimOp.Code(rawValue: ident) else { return nil } _ = self.parser.advance() return opCode } } extension TokenSyntax { var render: String { return self.triviaFreeSourceText } } extension QualifiedNameSyntax { var render: String { var result = "" for component in self { result += component.triviaFreeSourceText } return result } }
mit
7937daf834154c272eec941b10510beb
30.307531
80
0.643502
4.165043
false
false
false
false
Moya/Moya
Sources/CombineMoya/AnyPublisher+Response.swift
1
4439
#if canImport(Combine) import Foundation import Combine import Moya #if canImport(UIKit) import UIKit.UIImage #elseif canImport(AppKit) import AppKit.NSImage #endif /// Extension for processing raw NSData generated by network access. @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public extension AnyPublisher where Output == Response, Failure == MoyaError { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. func filter<R: RangeExpression>(statusCodes: R) -> AnyPublisher<Response, MoyaError> where R.Bound == Int { return unwrapThrowable { response in try response.filter(statusCodes: statusCodes) } } /// Filters out responses that has the specified `statusCode`. func filter(statusCode: Int) -> AnyPublisher<Response, MoyaError> { return unwrapThrowable { response in try response.filter(statusCode: statusCode) } } /// Filters out responses where `statusCode` falls within the range 200 - 299. func filterSuccessfulStatusCodes() -> AnyPublisher<Response, MoyaError> { return unwrapThrowable { response in try response.filterSuccessfulStatusCodes() } } /// Filters out responses where `statusCode` falls within the range 200 - 399 func filterSuccessfulStatusAndRedirectCodes() -> AnyPublisher<Response, MoyaError> { return unwrapThrowable { response in try response.filterSuccessfulStatusAndRedirectCodes() } } /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. func mapImage() -> AnyPublisher<Image, MoyaError> { return unwrapThrowable { response in try response.mapImage() } } /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. func mapJSON(failsOnEmptyData: Bool = true) -> AnyPublisher<Any, MoyaError> { return unwrapThrowable { response in try response.mapJSON(failsOnEmptyData: failsOnEmptyData) } } /// Maps received data at key path into a String. If the conversion fails, the signal errors. func mapString(atKeyPath keyPath: String? = nil) -> AnyPublisher<String, MoyaError> { return unwrapThrowable { response in try response.mapString(atKeyPath: keyPath) } } /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. func map<D: Decodable>(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> AnyPublisher<D, MoyaError> { return unwrapThrowable { response in try response.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData) } } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public extension AnyPublisher where Output == ProgressResponse, Failure == MoyaError { /** Filter completed progress response and maps to actual response - returns: response associated with ProgressResponse object */ func filterCompleted() -> AnyPublisher<Response, MoyaError> { return self .compactMap { $0.response } .eraseToAnyPublisher() } /** Filter progress events of current ProgressResponse - returns: observable of progress events */ func filterProgress() -> AnyPublisher<Double, MoyaError> { return self .filter { !$0.completed } .map { $0.progress } .eraseToAnyPublisher() } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension AnyPublisher where Failure == MoyaError { // Workaround for a lot of things, actually. We don't have Publishers.Once, flatMap // that can throw and a lot more. So this monster was created because of that. Sorry. private func unwrapThrowable<T>(throwable: @escaping (Output) throws -> T) -> AnyPublisher<T, MoyaError> { self.tryMap { element in try throwable(element) } .mapError { error -> MoyaError in if let moyaError = error as? MoyaError { return moyaError } else { return .underlying(error, nil) } } .eraseToAnyPublisher() } } #endif
mit
8c1918289514d6d7adce9ec6cf2338d6
35.68595
183
0.661861
4.894157
false
false
false
false
hoddez/MusicTheoryKit
MusicTheoryKit/MelodicInterval.swift
1
2508
// // MelodicInterval.swift // MusicKit // // Created by Thomas Hoddes on 2014-10-07. // Copyright (c) 2014 Thomas Hoddes. All rights reserved. // public struct MelodicInterval : Equatable, ForwardIndexType, Hashable { public let steps: Int public init(steps: Int) { self.steps = steps } public init(_ interval: Interval, _ direction: Direction) { self.steps = interval.size * direction.rawValue } } public extension MelodicInterval { public var interval: Interval { return Interval(size: abs(steps)) } public var direction: Direction { switch self.steps { case let d where d > 0: return .Ascending case let d where d < 0: return .Descending default: return .Flat } } public static func allIntervals(intervals: Set<Interval>, directions: Set<Direction>) -> Set<MelodicInterval> { var allIntervals: Set<MelodicInterval> = [] let intervalsExceptPerfectUnison = intervals.filter { return $0 != .PerfectUnison } let directionsExceptFlat = directions.filter { return $0 != .Flat } for direction in directionsExceptFlat { allIntervals.unionInPlace(intervalsExceptPerfectUnison.map { MelodicInterval($0, direction) }) } if intervals.contains(Interval.PerfectUnison) || directions.contains(Direction.Flat) { allIntervals.insert(MelodicInterval(.PerfectUnison,.Flat)) } return allIntervals } public var description: String { return "\(interval.description) \(direction.description)" } } //ForwardIndexType public extension MelodicInterval { public func successor() -> MelodicInterval { return MelodicInterval(steps: steps + 1) } } //Equatable public func == (left: MelodicInterval, right: MelodicInterval) -> Bool { return (left.interval == right.interval) && (left.direction == right.direction) } //Hashable public extension MelodicInterval { var hashValue: Int { return steps } } public func < (left: MelodicInterval, right: MelodicInterval) -> Bool { return left.steps < right.steps } public func + (left: MelodicInterval, right: MelodicInterval) -> MelodicInterval { return MelodicInterval(steps: left.steps + right.steps) } public func - (left: MelodicInterval, right: MelodicInterval) -> MelodicInterval { return MelodicInterval(steps: left.steps - right.steps) }
mit
12bd59c3c5843a55ac8eae6d0e440e82
28.869048
115
0.656699
4.084691
false
false
false
false
Zhendeshede/weiboBySwift
新浪微博/新浪微博/WelcomeViewController.swift
1
4613
// // WelcomeViewController.swift // 新浪微博 // // Created by 李旭飞 on 15/10/14. // Copyright © 2015年 lee. All rights reserved. // import UIKit class WelcomeViewController: UIViewController { //MARK:- 懒加载头像,昵称 private lazy var backgroudImgView:UIImageView=UIImageView(image: UIImage(named: "ad_background")) private lazy var iconView:UIImageView={ let icon=UIImageView(image: UIImage(named: "avatar_default_big")) icon.layer.masksToBounds=true icon.layer.cornerRadius=45 return icon }() private lazy var label:UILabel={ let lab=UILabel() lab.text=UserAccess.loadUserAccount!.name lab.sizeToFit() return lab }() private var iconBottomC : NSLayoutConstraint? private func prepareForView(){ view.addSubview(backgroudImgView) view.addSubview(iconView) view.addSubview(label) backgroudImgView.translatesAutoresizingMaskIntoConstraints=false view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":backgroudImgView])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":backgroudImgView])) //头像约束 iconView.translatesAutoresizingMaskIntoConstraints=false view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 90)) view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 90)) view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 150)) iconBottomC=view.constraints.last label.translatesAutoresizingMaskIntoConstraints=false view.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 10)) view.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) } override func viewDidLoad() { super.viewDidLoad() prepareForView() if let urlString = UserAccess.loadUserAccount?.avatar_large{ NSURLSession.sharedSession().downloadTaskWithURL(NSURL(string: urlString)!, completionHandler: { (location, _, error) -> Void in if error != nil{ //网络不给力 return } if let data=NSData(contentsOfURL: location!){ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.iconView.image=UIImage(data: data) self.label.text = UserAccess.loadUserAccount!.name }) } }).resume() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) iconBottomC?.constant=UIScreen.mainScreen().bounds.height-iconBottomC!.constant - 100 UIView.animateWithDuration(1.2, delay: 0.2, usingSpringWithDamping: 0.8, initialSpringVelocity: 5.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.view.layoutIfNeeded() },completion: {(_) -> Void in NSNotificationCenter.defaultCenter().postNotificationName(SwitchMainInterfaceNotification, object: true) }) } }
mit
b11eec863b920589254c64ea778f6aa9
36.393443
218
0.639193
5.405213
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/Browser/NoImageModeHelper.swift
1
1798
/* 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 import Shared struct NoImageModePrefsKey { static let NoImageModeStatus = PrefsKeys.KeyNoImageModeStatus } class NoImageModeHelper: TabHelper { fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab if let path = Bundle.main.path(forResource: "NoImageModeHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } static func name() -> String { return "NoImageMode" } func scriptMessageHandlerName() -> String? { return "NoImageMode" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // Do nothing. } static func isNoImageModeAvailable() -> Bool { return AppConstants.MOZ_NO_IMAGE_MODE } static func isActivated(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NoImageModePrefsKey.NoImageModeStatus) ?? false } static func toggle(profile: Profile, tabManager: TabManager) { let enabled = isActivated(profile.prefs) profile.prefs.setBool(!enabled, forKey: PrefsKeys.KeyNoImageModeStatus) tabManager.tabs.forEach { $0.setNoImageMode(!enabled, force: true) } tabManager.selectedTab?.reload() } }
mpl-2.0
ca511d839638c2418827adeff3b3ed79
34.254902
189
0.702447
4.744063
false
false
false
false
kopto/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorShape.swift
1
11307
// // KRActivityIndicatorShape.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017. Updated for Swift 4. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa enum KRActivityIndicatorShape { case circle case circleSemi case ring case ringTwoHalfVertical case ringTwoHalfHorizontal case ringThirdFour case rectangle case triangle case line case pacman func layerWith(size: CGSize, color: NSColor) -> CALayer { let layer: CAShapeLayer = CAShapeLayer() var path: NSBezierPath = NSBezierPath() let lineWidth: CGFloat = 2 // NOTE: NSBezierPath.appendArc(...) accepts ANGLES and NOT RADIANS! // in iOS, the arc function accetps radians and not angles. switch self { case .circle: path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: 360, clockwise: false); layer.fillColor = color.cgColor case .circleSemi: /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: CGFloat(-M_PI / 6), endAngle: CGFloat(-5 * M_PI / 6), clockwise: false)*/ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: -30, endAngle: -150, clockwise: true) path.close() layer.fillColor = color.cgColor case .ring: /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false);*/ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: 0, endAngle: 360, clockwise: false); layer.fillColor = nil layer.strokeColor = color.cgColor layer.lineWidth = lineWidth case .ringTwoHalfVertical: /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-3 * M_PI_4), endAngle:CGFloat(-M_PI_4), clockwise:true)*/ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:-135, endAngle:-45, clockwise:false) path.move( to: CGPoint(x: size.width / 2 - size.width / 2 * CGFloat(cos(Float.pi/4)), y: size.height / 2 + size.height / 2 * CGFloat(sin(Float.pi/4))) ) /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-5 * M_PI_4), endAngle:CGFloat(-7 * M_PI_4), clockwise:false)*/ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:-225, endAngle:-315, clockwise:true) layer.fillColor = nil layer.strokeColor = color.cgColor layer.lineWidth = lineWidth case .ringTwoHalfHorizontal: /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(3 * M_PI_4), endAngle:CGFloat(5 * M_PI_4), clockwise:true) */ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:135, endAngle:225, clockwise:false) path.move( to: CGPoint(x: size.width / 2 + size.width / 2 * CGFloat(cos(Float.pi/4)), y: size.height / 2 - size.height / 2 * CGFloat(sin(Float.pi/4))) ) /*path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:CGFloat(-M_PI_4), endAngle:CGFloat(M_PI_4), clockwise:true)*/ path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius:size.width / 2, startAngle:-45, endAngle:45, clockwise:true) layer.fillColor = nil layer.strokeColor = color.cgColor layer.lineWidth = lineWidth case .ringThirdFour: path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 2, startAngle: -45, endAngle: -135, clockwise: false) layer.fillColor = nil layer.strokeColor = color.cgColor layer.lineWidth = 2 case .rectangle: path.move(to: CGPoint(x: 0, y: 0)) path.line(to: CGPoint(x: size.width, y: 0)) path.line(to: CGPoint(x: size.width, y: size.height)) path.line(to: CGPoint(x: 0, y: size.height)) /*path.appendLine(to: CGPoint(x: size.width, y: 0)) path.appendLine(to: CGPoint(x: size.width, y: size.height)) path.appendLine(to: CGPoint(x: 0, y: size.height))*/ layer.fillColor = color.cgColor case .triangle: let offsetY = size.height / 4 /*path.move(to: CGPoint(x: 0, y: size.height - offsetY)) path.addLine(to: CGPoint(x: size.width / 2, y: size.height / 2 - offsetY)) path.addLine(to: CGPoint(x: size.width, y: size.height - offsetY))*/ path.move(to: CGPoint(x: 0, y: size.height - offsetY)) path.line(to: CGPoint(x: size.width / 2, y: size.height / 2 - offsetY)) path.line(to: CGPoint(x: size.width, y: size.height - offsetY)) path.close() layer.fillColor = color.cgColor case .line: path = NSBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height), xRadius: size.width / 2, yRadius: size.width / 2) layer.fillColor = color.cgColor case .pacman: path.appendArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2), radius: size.width / 4, startAngle: 360, endAngle: 0, clockwise: true); layer.fillColor = nil layer.strokeColor = color.cgColor layer.lineWidth = size.width / 2 } layer.backgroundColor = nil layer.path = CGPathFromNSBezierPath(nsPath: path) layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) return layer } func CGPathFromNSBezierPath(nsPath: NSBezierPath) -> CGPath! { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< nsPath.elementCount { let type = nsPath.element(at: i, associatedPoints: &points) switch type { case .moveToBezierPathElement: path.move(to: CGPoint(x: points[0].x, y: points[0].y) ) case .lineToBezierPathElement: path.addLine(to: CGPoint(x: points[0].x, y: points[0].y) ) case .curveToBezierPathElement: path.addCurve(to: CGPoint(x: points[2].x, y: points[2].y), control1: CGPoint(x: points[0].x, y: points[0].y), control2: CGPoint(x: points[1].x, y: points[1].y) ) case .closePathBezierPathElement: path.closeSubpath() } } return path // Create path /*let path = CGMutablePath() let points = UnsafeMutablePointer<NSPoint>.allocate(capacity: 3) let numElements = nsPath.elementCount let cgPoint1 = CGPoint(x: points[0].x, y: points[0].y) let cgPoint2 = CGPoint(x: points[1].x, y: points[1].y) let cgPoint3 = CGPoint(x: points[2].x, y: points[2].y) if numElements > 0 { var didClosePath = true for index in 0..<numElements { let pathType = nsPath.element(at: index, associatedPoints: points) switch pathType { case .moveToBezierPathElement : path.move(to: cgPoint1) case .lineToBezierPathElement : path.addLine(to: cgPoint1) didClosePath = false case .curveToBezierPathElement : path.addCurve(to: cgPoint1, control1: cgPoint2, control2: cgPoint3) didClosePath = false case .closePathBezierPathElement: path.closeSubpath() didClosePath = true } } if !didClosePath { path.closeSubpath() } } points.deallocate(capacity: 3) return path*/ } }
mit
ae2ea607f02aac4dcda8303720e8f386
44.963415
115
0.514902
4.57588
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EmojiScreenEffect.swift
1
18272
// // EmojiScreenEffect.swift // Telegram // // Created by Mikhail Filimonov on 14.09.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import SwiftSignalKit import TelegramCore import Postbox import AppKit final class EmojiScreenEffect { fileprivate let context: AccountContext fileprivate let takeTableItem:(MessageId)->ChatRowItem? fileprivate(set) var scrollUpdater: TableScrollListener! private let dataDisposable: DisposableDict<MessageId> = DisposableDict() private let reactionDataDisposable: DisposableDict<MessageId> = DisposableDict() private let limit: Int = 5 struct Key : Hashable { enum Mode : Equatable, Hashable { case effect(Bool) case reaction(MessageReaction.Reaction) } let messageId: MessageId let timestamp: TimeInterval let isIncoming: Bool let mode: Mode var screenMode: ChatRowView.ScreenEffectMode { switch self.mode { case let .reaction(value): return .reaction(value) case .effect: return .effect } } } struct Value { let view: WeakReference<EmojiAnimationEffectView> let index: Int let messageId: MessageId let emoji: String? let reaction: MessageReaction.Reaction? let mirror: Bool let key: Key } private var animations:[Key: Value] = [:] private var enqueuedToServer:[Value] = [] private var enqueuedToEnjoy:[Value] = [] private var enjoyTimer: SwiftSignalKit.Timer? private var timers:[MessageId : SwiftSignalKit.Timer] = [:] init(context: AccountContext, takeTableItem:@escaping(MessageId)->ChatRowItem?) { self.context = context self.takeTableItem = takeTableItem self.scrollUpdater = .init(dispatchWhenVisibleRangeUpdated: false, { [weak self] position in self?.updateScroll(transition: .immediate) }) } private func checkItem(_ item: TableRowItem, _ messageId: MessageId, with emoji: String) -> Bool { if let item = item as? ChatRowItem, item.message?.text == emoji { if messageId.peerId.namespace == Namespaces.Peer.CloudUser { return context.sharedContext.baseSettings.bigEmoji } } return false } private func updateScroll(transition: ContainedViewLayoutTransition) { var outOfBounds: Set<Key> = Set() for (key, animation) in animations { var success: Bool = false if let animationView = animation.view.value { if let item = takeTableItem(key.messageId), let view = item.view as? ChatRowView { if let contentView = view.getScreenEffectView(key.screenMode) { var point = contentView.convert(CGPoint.zero, to: animationView) let subSize = animationView.animationSize - contentView.frame.size switch key.mode { case let .effect(isPremium): if !animation.mirror { point.x-=subSize.width } point.y-=subSize.height/2 if isPremium { if !animation.mirror { point.x += 18 } else { point.x -= 18 } point.y -= 2 } case .reaction: point.x-=subSize.width/2 point.y-=subSize.height/2 } animationView.updatePoint(point, transition: transition) if contentView.visibleRect != .zero { success = true } } } } if !success { outOfBounds.insert(key) } } for key in outOfBounds { self.deinitAnimation(key: key, animated: true) } } deinit { dataDisposable.dispose() reactionDataDisposable.dispose() let animations = self.animations for animation in animations { deinitAnimation(key: animation.key, animated: false) } } private func isLimitExceed(_ messageId: MessageId) -> Bool { let onair = animations.filter { $0.key.messageId == messageId } let last = onair.max(by: { $0.key.timestamp < $1.key.timestamp }) if let last = last { if Date().timeIntervalSince1970 - last.key.timestamp < 0.2 { return true } } return onair.count >= limit } func addAnimation(_ emoji: String, index: Int?, mirror: Bool, isIncoming: Bool, messageId: MessageId, animationSize: NSSize, viewFrame: NSRect, for parentView: NSView) { if !isLimitExceed(messageId), let item = takeTableItem(messageId), checkItem(item, messageId, with: emoji) { let signal: Signal<LottieAnimation?, NoError> = context.diceCache.animationEffect(for: emoji.emojiUnmodified) |> map { value -> LottieAnimation? in if let random = value.randomElement(), let data = random.1 { return LottieAnimation(compressed: data, key: .init(key: .bundle("_effect_\(emoji)_\(random.2.fileId)"), size: animationSize, backingScale: Int(System.backingScale), mirror: mirror), cachePurpose: .temporaryLZ4(.effect), playPolicy: .onceEnd) } else { return nil } } |> deliverOnMainQueue dataDisposable.set(signal.start(next: { [weak self, weak parentView] animation in if let animation = animation, let parentView = parentView { self?.initAnimation(.builtin(animation), mode: .effect(false), emoji: emoji, reaction: nil, mirror: mirror, isIncoming: isIncoming, messageId: messageId, animationSize: animationSize, viewFrame: viewFrame, parentView: parentView) } }), forKey: messageId) } else { dataDisposable.set(nil, forKey: messageId) } } func addPremiumEffect(mirror: Bool, isIncoming: Bool, messageId: MessageId, viewFrame: NSRect, for parentView: NSView) { let context = self.context let onair = animations.filter { $0.key.messageId == messageId } if onair.isEmpty, let item = takeTableItem(messageId) { let animationSize = NSMakeSize(item.contentSize.width * 1.5, item.contentSize.height * 1.5) let signal: Signal<(LottieAnimation, String)?, NoError> = context.account.postbox.messageAtId(messageId) |> mapToSignal { message in if let message = message, let file = message.effectiveMedia as? TelegramMediaFile { if let effect = file.premiumEffect { return context.account.postbox.mediaBox.resourceData(effect.resource) |> filter { $0.complete } |> take(1) |> map { data in if data.complete, let data = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { return (LottieAnimation(compressed: data, key: .init(key: .bundle("_prem_effect_\(file.fileId.id)"), size: animationSize, backingScale: Int(System.backingScale), mirror: mirror), cachePurpose: .temporaryLZ4(.effect), playPolicy: .onceEnd), file.stickerText ?? "") } else { return nil } } } } return .single(nil) } |> deliverOnMainQueue dataDisposable.set(signal.start(next: { [weak self, weak parentView] values in if let animation = values?.0, let emoji = values?.1, let parentView = parentView { self?.initAnimation(.builtin(animation), mode: .effect(true), emoji: emoji, reaction: nil, mirror: mirror, isIncoming: isIncoming, messageId: messageId, animationSize: animationSize, viewFrame: viewFrame, parentView: parentView) } }), forKey: messageId) } else { dataDisposable.set(nil, forKey: messageId) } } func addReactionAnimation(_ value: MessageReaction.Reaction, index: Int?, messageId: MessageId, animationSize: NSSize, viewFrame: NSRect, for parentView: NSView) { let context = self.context switch value { case let .custom(fileId): let signal: Signal<LottieAnimation?, NoError> = combineLatest(context.reactions.stateValue |> take(1), context.inlinePacksContext.load(fileId: fileId)) |> map { state, file in return state?.reactions.first(where: { $0.value.string == file?.customEmojiText }) } |> mapToSignal { reaction -> Signal<MediaResourceData?, NoError> in if let file = reaction?.aroundAnimation { return context.account.postbox.mediaBox.resourceData(file.resource) |> map { $0.complete ? $0 : nil } |> take(1) } else { return .single(nil) } } |> map { resource in if let resource = resource, let data = try? Data(contentsOf: URL(fileURLWithPath: resource.path)) { return LottieAnimation(compressed: data, key: .init(key: .bundle("_reaction_e_\(value)"), size: animationSize, backingScale: Int(System.backingScale), mirror: false), cachePurpose: .temporaryLZ4(.effect), playPolicy: .onceEnd) } else { return nil } } |> deliverOnMainQueue reactionDataDisposable.set(signal.start(next: { [weak self, weak parentView] animation in if let parentView = parentView { if let animation = animation { self?.initAnimation(.builtin(animation), mode: .reaction(value), emoji: nil, reaction: value, mirror: false, isIncoming: false, messageId: messageId, animationSize: animationSize, viewFrame: viewFrame, parentView: parentView) } else { let animationSize = NSMakeSize(animationSize.width * 2, animationSize.height * 2) let rect = NSMakeSize(animationSize.width, animationSize.height).bounds let view = CustomReactionEffectView(frame: rect, context: context, fileId: fileId) self?.initAnimation(.custom(view), mode: .reaction(value), emoji: nil, reaction: value, mirror: false, isIncoming: false, messageId: messageId, animationSize: animationSize, viewFrame: viewFrame, parentView: parentView) } } }), forKey: messageId) case .builtin: let signal: Signal<LottieAnimation?, NoError> = context.reactions.stateValue |> take(1) |> map { return $0?.reactions.first(where: { $0.value == value }) } |> filter { $0 != nil} |> map { $0! } |> mapToSignal { reaction -> Signal<MediaResourceData, NoError> in if let file = reaction.aroundAnimation { return context.account.postbox.mediaBox.resourceData(file.resource) |> filter { $0.complete } |> take(1) } else { return .complete() } } |> map { data in if let data = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { return LottieAnimation(compressed: data, key: .init(key: .bundle("_reaction_e_\(value)"), size: animationSize, backingScale: Int(System.backingScale), mirror: false), cachePurpose: .temporaryLZ4(.effect), playPolicy: .onceEnd) } else { return nil } } |> deliverOnMainQueue reactionDataDisposable.set(signal.start(next: { [weak self, weak parentView] animation in if let animation = animation, let parentView = parentView { self?.initAnimation(.builtin(animation), mode: .reaction(value), emoji: nil, reaction: value, mirror: false, isIncoming: false, messageId: messageId, animationSize: animationSize, viewFrame: viewFrame, parentView: parentView) } }), forKey: messageId) } } private func deinitAnimation(key: Key, animated: Bool) { let view = animations.removeValue(forKey: key)?.view.value if let view = view { performSubviewRemoval(view, animated: animated) } enqueuedToServer.removeAll(where: { $0.key == key }) enqueuedToEnjoy.removeAll(where: { $0.key == key }) } func removeAll() { let animations = self.animations for animation in animations { deinitAnimation(key: animation.key, animated: false) } } private func initAnimation(_ animation: EmojiAnimationEffectView.Source, mode: EmojiScreenEffect.Key.Mode, emoji: String?, reaction: MessageReaction.Reaction?, mirror: Bool, isIncoming: Bool, messageId: MessageId, animationSize: NSSize, viewFrame: NSRect, parentView: NSView) { let mediaView = (takeTableItem(messageId)?.view as? ChatMediaView)?.contentNode as? MediaAnimatedStickerView mediaView?.playAgain() let key: Key = .init(messageId: messageId, timestamp: Date().timeIntervalSince1970, isIncoming: isIncoming, mode: mode) switch animation { case let .builtin(animation): animation.triggerOn = (LottiePlayerTriggerFrame.last, { [weak self] in self?.deinitAnimation(key: key, animated: true) }, {}) case let .custom(animation): animation.triggerOnFinish = { [weak self] in self?.deinitAnimation(key: key, animated: true) } } let view = EmojiAnimationEffectView(animation: animation, animationSize: animationSize, animationPoint: .zero, frameRect: viewFrame) parentView.addSubview(view) let value: Value = .init(view: .init(value: view), index: 1, messageId: messageId, emoji: emoji, reaction: reaction, mirror: mirror, key: key) animations[key] = value updateScroll(transition: .immediate) if !isIncoming { self.enqueuedToServer.append(value) } else { self.enqueuedToEnjoy.append(value) } self.enqueueToServer() self.enqueueToEnjoy() } private func enqueueToEnjoy() { if enjoyTimer == nil, !enqueuedToEnjoy.isEmpty { enjoyTimer = .init(timeout: 1.0, repeat: false, completion: { [weak self] in self?.performEnjoyAction() }, queue: .mainQueue()) enjoyTimer?.start() } } private func performEnjoyAction() { self.enjoyTimer = nil var exists:Set<MessageId> = Set() for value in enqueuedToEnjoy { if !exists.contains(value.key.messageId), let emoji = value.emoji { context.account.updateLocalInputActivity(peerId: PeerActivitySpace(peerId: value.key.messageId.peerId, category: .global), activity: .seeingEmojiInteraction(emoticon: emoji), isPresent: true) exists.insert(value.key.messageId) } } self.enqueuedToEnjoy.removeAll() } private func enqueueToServer() { let outgoing = self.enqueuedToServer let msgIds:[MessageId] = outgoing.map { $0.key.messageId }.uniqueElements for msgId in msgIds { if self.timers[msgId] == nil { self.timers[msgId] = .init(timeout: 1, repeat: false, completion: { [weak self] in self?.performServerActions(for: msgId) }, queue: .mainQueue()) self.timers[msgId]?.start() } } } private func performServerActions(for msgId: MessageId) { let values = self.enqueuedToServer.filter { $0.key.messageId == msgId } self.enqueuedToServer.removeAll(where: { $0.key.messageId == msgId }) self.timers.removeValue(forKey: msgId) if !values.isEmpty { let value = values.min(by: { $0.key.timestamp < $1.key.timestamp })! let animations:[EmojiInteraction.Animation] = values.map { current -> EmojiInteraction.Animation in .init(index: current.index, timeOffset: Float((current.key.timestamp - value.key.timestamp))) }.sorted(by: { $0.timeOffset < $1.timeOffset }) if let emoji = value.emoji { context.account.updateLocalInputActivity(peerId: PeerActivitySpace(peerId: msgId.peerId, category: .global), activity: .interactingWithEmoji(emoticon: emoji, messageId: msgId, interaction: EmojiInteraction(animations: animations)), isPresent: true) } } } func updateLayout(rect: CGRect, transition: ContainedViewLayoutTransition) { for (_ , animation) in animations { if let value = animation.view.value { transition.updateFrame(view: value, frame: rect) value.updateLayout(size: rect.size, transition: transition) } } } }
gpl-2.0
5fc063e2c2ecb8200a05aaec8f848fd1
43.781863
295
0.56483
5.018127
false
false
false
false
RyanMacG/poppins
Poppins/Controllers/CascadeController.swift
3
1977
import Foundation import Runes class CascadeController { private let imageFetcher: ImageFetcher private let observer: ManagedObjectContextObserver private let imageStore: ImageStore private let syncEngine: SyncEngine var viewModel: CascadeViewModel init(syncClient: SyncClient) { let dataStore = Store() imageStore = ImageStore(store: dataStore) observer = dataStore.managedObjectContextObserver imageFetcher = ImageFetcher() syncEngine = SyncEngine(imageStore: imageStore, syncClient: syncClient) viewModel = CascadeViewModel(images: []) } var hasPasteboardImage: Bool { return Pasteboard.hasImageData } func syncWithTHECLOUD() { syncEngine.runSync() } func fetchImages() { viewModel = CascadeViewModel(images: imageStore.cachedImages() ?? []) } func registerForChanges(callback: ([NSIndexPath], [NSIndexPath], [NSIndexPath]) -> ()) { observer.callback = { inserted, updated, deleted in let d = deleted.map(self.createIndexPathFromImage) let u = updated.map(self.createIndexPathFromImage) self.fetchImages() let i = inserted.map(self.createIndexPathFromImage) callback(compact(i), compact(u), compact(d)) } } private func createIndexPathFromImage(image: CachedImage) -> NSIndexPath? { return find(viewModel.images.map { $0.path }, image.path) >>- { NSIndexPath(forRow: $0, inSection: 0) } } func cellControllerForIndexPath(indexPath: NSIndexPath) -> PoppinsCellController? { let path = viewModel.imagePathForIndexPath(indexPath) return PoppinsCellController(imageFetcher: imageFetcher, path: path ?? "") } func importController() -> ImportController? { return Pasteboard.fetchImageData().map { ImportController(imageData: $0.data, imageType: $0.type, store: imageStore, client: syncEngine.client) } } }
mit
ce6f2ce8d7ff2d4a94b04cff1e900feb
35.611111
153
0.680324
4.845588
false
false
false
false
Google-IO-Extended-Grand-Rapids/conference_ios
ConferenceApp/ConferenceApp/EventDetailsViewController.swift
1
5410
// // EventDetailsViewController.swift // ConferenceApp // // Created by Dan McCracken on 3/7/15. // Copyright (c) 2015 GR OpenSource. All rights reserved. // import UIKit class EventDetailsViewController: UITableViewController { var detailItem: Conference? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. // if let detail: Conference = self.detailItem { // if let label = self.eventNameLabel { // self.eventNameLabel.text = detail.name // self.eventDateLabel.text = "put the date here" // } // } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowSchedule" { NSLog("showing schedule") (segue.destinationViewController as! ScheduleViewController).detailItem = detailItem } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 1 } else { return 3 } } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if (indexPath.section == 0) { return 200 } else { return UITableViewAutomaticDimension } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if (indexPath.section == 0) { return 200 } else { return UITableViewAutomaticDimension } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EventDetailCell", forIndexPath: indexPath) as! UITableViewCell let object = detailItem as Conference! if (indexPath.section == 0) { let cell = tableView.dequeueReusableCellWithIdentifier("BackgroundImageCell", forIndexPath: indexPath) as! BackgroundImageCell if object.id! % 2 == 0 { cell.backgroundImage.image = UIImage(named: "GRDark.jpg") } else { cell.backgroundImage.image = UIImage(named: "GRLight.jpg") } } else { if (indexPath.row == 0) { let cell = tableView.dequeueReusableCellWithIdentifier("EventDetailCell", forIndexPath: indexPath) as! EventDetailCell cell.detailLabel.text = object.fullDesc cell.scheduleButton.addTarget(self, action: "scheduleButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) cell.scheduleButton.backgroundColor = UIColor(red: 40.0/255.0, green: 154.0/255.0, blue: 214.0/255.0, alpha: 1) cell.scheduleButton.layer.cornerRadius = 5 return cell } else if (indexPath.row == 1) { let cell = tableView.dequeueReusableCellWithIdentifier("SponsorsCell", forIndexPath: indexPath) as! SponsorsCell return cell } else if (indexPath.row == 2) { } } return cell } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if (section == 1) { return 70 } else { return 0 } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() let object = detailItem as Conference! let formatter = NSDateFormatter() formatter.dateStyle = NSDateFormatterStyle.MediumStyle let eventLabel = UILabel(frame: CGRectMake(12, 6, 588, 30)) eventLabel.text = object.name eventLabel.textColor = UIColor .whiteColor() eventLabel.font = UIFont .boldSystemFontOfSize(18) headerView .addSubview(eventLabel) let durationLabel = UILabel(frame: CGRectMake(12, 30, 588, 30)) durationLabel.text = String(format: "%@ to %@",formatter.stringFromDate(object.startDate!),formatter.stringFromDate(object.endDate!)) durationLabel.textColor = UIColor .whiteColor() durationLabel.font = UIFont .boldSystemFontOfSize(12) headerView .addSubview(durationLabel) headerView.backgroundColor = UIColor(red: 99.0/255.0, green: 119.0/255.0, blue: 198.0/255.0, alpha: 1) if (section == 1) { return headerView } else { return nil } } func scheduleButtonPressed(sender: UIButton){ NSLog("touched button") } }
apache-2.0
1084044ba558a48773b1e8cc560ab958
34.359477
141
0.60536
5.298727
false
false
false
false
stevebrambilla/autolayout-expressions
Sources/LayoutExpressions/Core/Expressions/SingleAxisEdgesExpression.swift
2
6247
// Copyright (c) 2019 Steve Brambilla. All rights reserved. #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #else #error("Requires either UIKit or AppKit") #endif // Supports pinning edges in a single dimension: // subview.anchors.verticalEdges == container.anchors.verticalEdges // // Supports insets using the '-' operator: // subview.anchors.verticalEdges == container.anchors.verticalEdges - 10 // // The '+' operator defines outsets: // subview.anchors.verticalEdges == container.anchors.verticalEdges + 10 // MARK: - Axis Edge public protocol AxisEdgesProtocol { associatedtype AnchorType: AnyObject var firstAnchor: NSLayoutAnchor<AnchorType> { get } var secondAnchor: NSLayoutAnchor<AnchorType> { get } } public struct XAxisEdges: AxisEdgesProtocol { public let firstAnchor: NSLayoutAnchor<NSLayoutXAxisAnchor> public let secondAnchor: NSLayoutAnchor<NSLayoutXAxisAnchor> internal init(leading: NSLayoutAnchor<NSLayoutXAxisAnchor>, trailing: NSLayoutAnchor<NSLayoutXAxisAnchor>) { self.firstAnchor = leading self.secondAnchor = trailing } } public struct YAxisEdges: AxisEdgesProtocol { public let firstAnchor: NSLayoutAnchor<NSLayoutYAxisAnchor> public let secondAnchor: NSLayoutAnchor<NSLayoutYAxisAnchor> internal init(top: NSLayoutAnchor<NSLayoutYAxisAnchor>, bottom: NSLayoutAnchor<NSLayoutYAxisAnchor>) { self.firstAnchor = top self.secondAnchor = bottom } } // MARK: - Single Axis Edges Expression public struct SingleAxisEdgesExpression<Axis: AxisEdgesProtocol, Inset: ConstantProtocol>: ExpressionProtocol { fileprivate let lhs: SingleAxisEdgesAnchor<Axis, NoConstant> fileprivate let relation: Relation fileprivate let rhs: SingleAxisEdgesAnchor<Axis, Inset> fileprivate let priority: Priority? fileprivate init(lhs: SingleAxisEdgesAnchor<Axis, NoConstant>, relation: Relation, rhs: SingleAxisEdgesAnchor<Axis, Inset>, priority: Priority? = nil) { self.lhs = lhs self.relation = relation self.rhs = rhs self.priority = priority } public func update(priority: Priority) -> SingleAxisEdgesExpression { assert(priority.isValid) return SingleAxisEdgesExpression(lhs: lhs, relation: relation, rhs: rhs, priority: priority) } public func evaluateAll() -> [Constraint] { let inset = rhs.inset.value ?? 0 // top, leading let firstConstraint = AnchorConstraints.constraintForRelation(relation: relation, lhsAnchor: lhs.firstAnchor, rhsAnchor: rhs.firstAnchor, constant: -inset) // bottom, trailing let secondConstraint = AnchorConstraints.constraintForRelation(relation: relation, lhsAnchor: lhs.secondAnchor, rhsAnchor: rhs.secondAnchor, constant: inset) if let priority = priority { firstConstraint.priority = priority.layoutPriority secondConstraint.priority = priority.layoutPriority } return [firstConstraint, secondConstraint] } } // MARK: - Single Axis Edges Anchor public struct SingleAxisEdgesAnchor<Axis: AxisEdgesProtocol, Inset: ConstantProtocol> { fileprivate let axis: Axis public let inset: Inset internal init(axis: Axis, inset: Inset) { self.axis = axis self.inset = inset } fileprivate var firstAnchor: NSLayoutAnchor<Axis.AnchorType> { axis.firstAnchor } fileprivate var secondAnchor: NSLayoutAnchor<Axis.AnchorType> { axis.secondAnchor } fileprivate func update<NextInset>(inset: NextInset) -> SingleAxisEdgesAnchor<Axis, NextInset> { SingleAxisEdgesAnchor<Axis, NextInset>(axis: axis, inset: inset) } fileprivate var withoutModifiers: SingleAxisEdgesAnchor<Axis, NoConstant> { SingleAxisEdgesAnchor<Axis, NoConstant>(axis: axis, inset: NoConstant()) } } // MARK: - Arithmetic Operators // CGFloat Insets / Outsets public func - <Axis>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, inset: CGFloat) -> SingleAxisEdgesAnchor<Axis, ValueConstant> { return lhs.update(inset: ValueConstant(value: -inset)) } public func + <Axis>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, outset: CGFloat) -> SingleAxisEdgesAnchor<Axis, ValueConstant> { return lhs.update(inset: ValueConstant(value: outset)) } // Int Insets / Outsets public func - <Axis>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, inset: Int) -> SingleAxisEdgesAnchor<Axis, ValueConstant> { lhs - CGFloat(inset) } public func + <Axis>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, outset: Int) -> SingleAxisEdgesAnchor<Axis, ValueConstant> { lhs + CGFloat(outset) } // MARK: - Comparison Operators public func == <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, NoConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs, relation: .equal, rhs: rhs) } public func == <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs.withoutModifiers, relation: .equal, rhs: rhs) } public func <= <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, NoConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs, relation: .lessThanOrEqual, rhs: rhs) } public func <= <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs.withoutModifiers, relation: .lessThanOrEqual, rhs: rhs) } public func >= <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, NoConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs, relation: .greaterThanOrEqual, rhs: rhs) } public func >= <Axis, Inset>(lhs: SingleAxisEdgesAnchor<Axis, UndefinedConstant>, rhs: SingleAxisEdgesAnchor<Axis, Inset>) -> SingleAxisEdgesExpression<Axis, Inset> { SingleAxisEdgesExpression(lhs: lhs.withoutModifiers, relation: .greaterThanOrEqual, rhs: rhs) }
mit
59968dad25af38018678846e32ec276d
38.537975
166
0.738755
4.186997
false
false
false
false
alessiobrozzi/firefox-ios
Storage/PageMetadata.swift
1
3330
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import WebImage enum MetadataKeys: String { case imageURL = "image_url" case imageDataURI = "image_data_uri" case pageURL = "url" case title = "title" case description = "description" case type = "type" case provider = "provider" } /* * Value types representing a page's metadata */ public struct PageMetadata { public let id: Int? public let siteURL: String public let mediaURL: String? public let title: String? public let description: String? public let type: String? public let providerName: String? public init(id: Int?, siteURL: String, mediaURL: String?, title: String?, description: String?, type: String?, providerName: String?, mediaDataURI: String?, cacheImages: Bool = true) { self.id = id self.siteURL = siteURL self.mediaURL = mediaURL self.title = title self.description = description self.type = type self.providerName = providerName if cacheImages { self.cacheImage(fromDataURI: mediaDataURI, forURL: mediaURL) } } public static func fromDictionary(_ dict: [String: Any]) -> PageMetadata? { guard let siteURL = dict[MetadataKeys.pageURL.rawValue] as? String else { return nil } return PageMetadata(id: nil, siteURL: siteURL, mediaURL: dict[MetadataKeys.imageURL.rawValue] as? String, title: dict[MetadataKeys.title.rawValue] as? String, description: dict[MetadataKeys.description.rawValue] as? String, type: dict[MetadataKeys.type.rawValue] as? String, providerName: dict[MetadataKeys.provider.rawValue] as? String, mediaDataURI: dict[MetadataKeys.imageDataURI.rawValue] as? String) } fileprivate func cacheImage(fromDataURI dataURI: String?, forURL urlString: String?) { if let urlString = urlString, let url = URL(string: urlString) { if let dataURI = dataURI, let dataURL = URL(string: dataURI), !SDWebImageManager.shared().cachedImageExists(for: dataURL), let data = try? Data(contentsOf: dataURL), let image = UIImage(data: data) { self.cache(image: image, forURL: url) } else if !SDWebImageManager.shared().cachedImageExists(for: url) { // download image direct from URL self.downloadAndCache(fromURL: url) } } } fileprivate func downloadAndCache(fromURL webUrl: URL) { let imageManager = SDWebImageManager.shared() let _ = imageManager?.downloadImage(with: webUrl, options: SDWebImageOptions.continueInBackground, progress: nil) { (image, error, cacheType, success, url) in guard let image = image else { return } self.cache(image: image, forURL: webUrl) } } fileprivate func cache(image: UIImage, forURL url: URL) { let imageManager = SDWebImageManager.shared() imageManager?.saveImage(toCache: image, for: url) } }
mpl-2.0
4ba0d1fbfcb3785ad7a03562ee3a73dc
37.72093
208
0.636637
4.625
false
false
false
false
n-studio/BetterKeyboardSDK
Pod/Classes/UIViewController+extension.swift
1
876
// // UIViewController+extension.swift // betterkeyboard // // Created by Lidner on 10/26/15. // Copyright © 2015 Solfanto. All rights reserved. // import UIKit extension UIViewController { public func bk_getKeyboardView() -> UIView? { for window in UIApplication.shared.windows { if NSStringFromClass(type(of: window)) == "UIRemoteKeyboardWindow" { for subView in window.subviews { if NSStringFromClass(type(of: subView)) == "UIInputSetContainerView" { for subsubView in subView.subviews { if NSStringFromClass(type(of: subsubView)) == "UIInputSetHostView" { return subsubView } } } } } } return nil } }
mit
b65d6c81b9013f4d3206c24cb14eda6d
30.25
96
0.517714
5.087209
false
false
false
false
apple/swift-numerics
Sources/ComplexModule/Complex+IntegerLiteral.swift
1
698
//===--- Complex+IntegerLiteral.swift -------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // // Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// extension Complex: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = RealType.IntegerLiteralType @inlinable public init(integerLiteral value: IntegerLiteralType) { self.init(RealType(integerLiteral: value)) } }
apache-2.0
af97ae1b73edcf26b0572ab0d26f1c3a
35.736842
80
0.631805
5.453125
false
false
false
false
LYM-mg/MGDYZB
MGDYZB/MGDYZB/Class/Live/ViewModel/AllListViewModel.swift
1
1925
// // AllListViewModel.swift // MGDYZB // // Created by ming on 16/10/30. // Copyright © 2016年 ming. All rights reserved. import UIKit class AllListViewModel: NSObject { // 用于上下拉刷新 var currentPage = 0 var rooms: [RoomModel] = [] fileprivate let tagID: String = "0" } extension AllListViewModel { func loadAllListData(_ finishedCallback: @escaping () -> ()) { let parameters:[String : Any] = ["offset": 20*currentPage, "limit": 20, "time": String(format: "%.0f", Date().timeIntervalSince1970)] let url = "http://capi.douyucdn.cn/api/v1/live/" + "\(tagID)?" NetWorkTools.requestData(type: .get, urlString: url,parameters: parameters, succeed: { (result, err) in // 1.获取到数据 guard let resultDict = result as? [String: Any] else { return } guard let dataArray = resultDict["data"] as? [[String: Any]] else { return } // debugPrint(dataArray) // 2.字典转模型 for dict in dataArray { self.rooms.append(RoomModel(dict: dict)) } // 3.完成回调 finishedCallback() }) { (err) in finishedCallback() } NetWorkTools.requestData(type: .get, urlString: "http://www.douyu.com/api/v1/live/directory",parameters: nil, succeed: { (result, err) in // 1.获取到数据 guard let resultDict = result as? [String: Any] else { return } guard let dataArray = resultDict["data"] as? [[String: Any]] else { return } debugPrint(dataArray) // 2.字典转模型 for dict in dataArray { self.rooms.append(RoomModel(dict: dict)) } // 3.完成回调 finishedCallback() }) { (err) in finishedCallback() } } }
mit
a714e188f72317a075238b9415b868e2
32.672727
145
0.544276
4.228311
false
false
false
false
a2/MessagePack.swift
Sources/MessagePack/Unpack.swift
1
10778
import Foundation /// Joins bytes to form an integer. /// /// - parameter data: The input data to unpack. /// - parameter size: The size of the integer. /// /// - returns: An integer representation of `size` bytes of data and the not-unpacked remaining data. func unpackInteger(_ data: Subdata, count: Int) throws -> (value: UInt64, remainder: Subdata) { guard count > 0 else { throw MessagePackError.invalidArgument } guard data.count >= count else { throw MessagePackError.insufficientData } var value: UInt64 = 0 for i in 0 ..< count { let byte = data[i] value = value << 8 | UInt64(byte) } return (value, data[count ..< data.count]) } /// Joins bytes to form a string. /// /// - parameter data: The input data to unpack. /// - parameter length: The length of the string. /// /// - returns: A string representation of `size` bytes of data and the not-unpacked remaining data. func unpackString(_ data: Subdata, count: Int) throws -> (value: String, remainder: Subdata) { guard count > 0 else { return ("", data) } guard data.count >= count else { throw MessagePackError.insufficientData } let subdata = data[0 ..< count] guard let result = String(data: subdata.data, encoding: .utf8) else { throw MessagePackError.invalidData } return (result, data[count ..< data.count]) } /// Joins bytes to form a data object. /// /// - parameter data: The input data to unpack. /// - parameter length: The length of the data. /// /// - returns: A subsection of data representing `size` bytes and the not-unpacked remaining data. func unpackData(_ data: Subdata, count: Int) throws -> (value: Subdata, remainder: Subdata) { guard data.count >= count else { throw MessagePackError.insufficientData } return (data[0 ..< count], data[count ..< data.count]) } /// Joins bytes to form an array of `MessagePackValue` values. /// /// - parameter data: The input data to unpack. /// - parameter count: The number of elements to unpack. /// - parameter compatibility: When true, unpacks strings as binary data. /// /// - returns: An array of `count` elements and the not-unpacked remaining data. func unpackArray(_ data: Subdata, count: Int, compatibility: Bool) throws -> (value: [MessagePackValue], remainder: Subdata) { var values = [MessagePackValue]() var remainder = data var newValue: MessagePackValue for _ in 0 ..< count { (newValue, remainder) = try unpack(remainder, compatibility: compatibility) values.append(newValue) } return (values, remainder) } /// Joins bytes to form a dictionary with `MessagePackValue` key/value entries. /// /// - parameter data: The input data to unpack. /// - parameter count: The number of elements to unpack. /// - parameter compatibility: When true, unpacks strings as binary data. /// /// - returns: An dictionary of `count` entries and the not-unpacked remaining data. func unpackMap(_ data: Subdata, count: Int, compatibility: Bool) throws -> (value: [MessagePackValue: MessagePackValue], remainder: Subdata) { var dict = [MessagePackValue: MessagePackValue](minimumCapacity: count) var lastKey: MessagePackValue? = nil let (array, remainder) = try unpackArray(data, count: 2 * count, compatibility: compatibility) for item in array { if let key = lastKey { dict[key] = item lastKey = nil } else { lastKey = item } } return (dict, remainder) } /// Unpacks data into a MessagePackValue and returns the remaining data. /// /// - parameter data: The input data to unpack. /// - parameter compatibility: When true, unpacks strings as binary data. /// /// - returns: A `MessagePackValue`and the not-unpacked remaining data. public func unpack(_ data: Subdata, compatibility: Bool = false) throws -> (value: MessagePackValue, remainder: Subdata) { guard !data.isEmpty else { throw MessagePackError.insufficientData } let value = data[0] let data = data[1 ..< data.endIndex] switch value { // positive fixint case 0x00 ... 0x7f: return (.uint(UInt64(value)), data) // fixmap case 0x80 ... 0x8f: let count = Int(value - 0x80) let (dict, remainder) = try unpackMap(data, count: count, compatibility: compatibility) return (.map(dict), remainder) // fixarray case 0x90 ... 0x9f: let count = Int(value - 0x90) let (array, remainder) = try unpackArray(data, count: count, compatibility: compatibility) return (.array(array), remainder) // fixstr case 0xa0 ... 0xbf: let count = Int(value - 0xa0) if compatibility { let (subdata, remainder) = try unpackData(data, count: count) return (.binary(subdata.data), remainder) } else { let (string, remainder) = try unpackString(data, count: count) return (.string(string), remainder) } // nil case 0xc0: return (.nil, data) // false case 0xc2: return (.bool(false), data) // true case 0xc3: return (.bool(true), data) // bin 8, 16, 32 case 0xc4 ... 0xc6: let intCount = 1 << Int(value - 0xc4) let (dataCount, remainder1) = try unpackInteger(data, count: intCount) let (subdata, remainder2) = try unpackData(remainder1, count: Int(dataCount)) return (.binary(subdata.data), remainder2) // ext 8, 16, 32 case 0xc7 ... 0xc9: let intCount = 1 << Int(value - 0xc7) let (dataCount, remainder1) = try unpackInteger(data, count: intCount) guard !remainder1.isEmpty else { throw MessagePackError.insufficientData } let type = Int8(bitPattern: remainder1[0]) let (subdata, remainder2) = try unpackData(remainder1[1 ..< remainder1.count], count: Int(dataCount)) return (.extended(type, subdata.data), remainder2) // float 32 case 0xca: let (intValue, remainder) = try unpackInteger(data, count: 4) let float = Float(bitPattern: UInt32(truncatingIfNeeded: intValue)) return (.float(float), remainder) // float 64 case 0xcb: let (intValue, remainder) = try unpackInteger(data, count: 8) let double = Double(bitPattern: intValue) return (.double(double), remainder) // uint 8, 16, 32, 64 case 0xcc ... 0xcf: let count = 1 << (Int(value) - 0xcc) let (integer, remainder) = try unpackInteger(data, count: count) return (.uint(integer), remainder) // int 8 case 0xd0: guard !data.isEmpty else { throw MessagePackError.insufficientData } let byte = Int8(bitPattern: data[0]) return (.int(Int64(byte)), data[1 ..< data.count]) // int 16 case 0xd1: let (bytes, remainder) = try unpackInteger(data, count: 2) let integer = Int16(bitPattern: UInt16(truncatingIfNeeded: bytes)) return (.int(Int64(integer)), remainder) // int 32 case 0xd2: let (bytes, remainder) = try unpackInteger(data, count: 4) let integer = Int32(bitPattern: UInt32(truncatingIfNeeded: bytes)) return (.int(Int64(integer)), remainder) // int 64 case 0xd3: let (bytes, remainder) = try unpackInteger(data, count: 8) let integer = Int64(bitPattern: bytes) return (.int(integer), remainder) // fixent 1, 2, 4, 8, 16 case 0xd4 ... 0xd8: let count = 1 << Int(value - 0xd4) guard !data.isEmpty else { throw MessagePackError.insufficientData } let type = Int8(bitPattern: data[0]) let (subdata, remainder) = try unpackData(data[1 ..< data.count], count: count) return (.extended(type, subdata.data), remainder) // str 8, 16, 32 case 0xd9 ... 0xdb: let countSize = 1 << Int(value - 0xd9) let (count, remainder1) = try unpackInteger(data, count: countSize) if compatibility { let (subdata, remainder2) = try unpackData(remainder1, count: Int(count)) return (.binary(subdata.data), remainder2) } else { let (string, remainder2) = try unpackString(remainder1, count: Int(count)) return (.string(string), remainder2) } // array 16, 32 case 0xdc ... 0xdd: let countSize = 1 << Int(value - 0xdb) let (count, remainder1) = try unpackInteger(data, count: countSize) let (array, remainder2) = try unpackArray(remainder1, count: Int(count), compatibility: compatibility) return (.array(array), remainder2) // map 16, 32 case 0xde ... 0xdf: let countSize = 1 << Int(value - 0xdd) let (count, remainder1) = try unpackInteger(data, count: countSize) let (dict, remainder2) = try unpackMap(remainder1, count: Int(count), compatibility: compatibility) return (.map(dict), remainder2) // negative fixint case 0xe0 ..< 0xff: return (.int(Int64(value) - 0x100), data) // negative fixint (workaround for rdar://19779978) case 0xff: return (.int(Int64(value) - 0x100), data) default: throw MessagePackError.invalidData } } /// Unpacks data into a MessagePackValue and returns the remaining data. /// /// - parameter data: The input data to unpack. /// /// - returns: A `MessagePackValue` and the not-unpacked remaining data. public func unpack(_ data: Data, compatibility: Bool = false) throws -> (value: MessagePackValue, remainder: Data) { let (value, remainder) = try unpack(Subdata(data: data), compatibility: compatibility) return (value, remainder.data) } /// Unpacks a data object into a `MessagePackValue`, ignoring excess data. /// /// - parameter data: The data to unpack. /// - parameter compatibility: When true, unpacks strings as binary data. /// /// - returns: The contained `MessagePackValue`. public func unpackFirst(_ data: Data, compatibility: Bool = false) throws -> MessagePackValue { return try unpack(data, compatibility: compatibility).value } /// Unpacks a data object into an array of `MessagePackValue` values. /// /// - parameter data: The data to unpack. /// - parameter compatibility: When true, unpacks strings as binary data. /// /// - returns: The contained `MessagePackValue` values. public func unpackAll(_ data: Data, compatibility: Bool = false) throws -> [MessagePackValue] { var values = [MessagePackValue]() var data = Subdata(data: data) while !data.isEmpty { let value: MessagePackValue (value, data) = try unpack(data, compatibility: compatibility) values.append(value) } return values }
mit
a791101b86b6e93ce791dd5647e097e7
33.107595
142
0.637873
4.012658
false
false
false
false
sudiptasahoo/IVP-Luncheon
IVP Luncheon/AppConstants.swift
1
1329
// // AppConstants.swift // RoposoTask // // Created by Sudipta Sahoo on 15/01/17. // Copyright © 2017 Sudipta Sahoo. All rights reserved. // import UIKit struct Constants { struct FOURSQUARE { static let CLIENT_ID = "OYRDUEDHAIEUUBXJOUDRZ2IDNUIPGAPVDTNQL2SSSX2SS23A" static let CLIENT_SECRET = "33IPKGMQPGTXU5WI2CBFCF5UTXC00V35GZLLL33UPBVEY1Q0" static let FOOD_CATEGORY_ID = "4d4b7105d754a06374d81259" } struct API{ static let v = "20170517" static let TIMEOUT : TimeInterval = 30.0 } struct URL { struct FOURSQUARE_API { static let scheme = "https" static let host = "api.foursquare.com" static let explore = "/v2/venues/explore" static let venueDetails = "/v2/venues/" } } struct IVP { struct GURGAON_OFFICE{ struct COORDINATE{ static let lat = "28.536086" static let long = "77.398080" } } } struct TimeoutInterval { } struct DateFormat { } struct KEYS { struct COORDINATE { static let USER_COORDINATE = "USER_COORDINATE" static let USER_LATITUDE = "USER_LATITUDE" static let USER_LONGITUDE = "USER_LONGITUDE" static let USER_ACCURACY = "USER_ACCURACY" static let USER_LOCALITY = "USER_LOCALITY" } } }
apache-2.0
e0d11871956e88ffb73ce44c9ce370d0
19.75
81
0.628765
3.239024
false
false
false
false
devpunk/cartesian
cartesian/View/DrawProjectShare/VDrawProjectShareButtons.swift
1
5702
import UIKit class VDrawProjectShareButtons:UIView { private weak var controller:CDrawProjectShare! private weak var buttonLeft:UIButton! private weak var buttonRightUpdate:UIButton! private weak var buttonRightPost:UIButton! private let kButtonRightWidth:CGFloat = 190 private let kCornerRadius:CGFloat = 10 private let kBorderWidth:CGFloat = 1 init(controller:CDrawProjectShare) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.cartesianBlue translatesAutoresizingMaskIntoConstraints = false layer.cornerRadius = kCornerRadius self.controller = controller let buttonLeft:UIButton = UIButton() buttonLeft.translatesAutoresizingMaskIntoConstraints = false buttonLeft.setTitle( NSLocalizedString("VDrawProjectShareButtons_buttonLeft", comment:""), for:UIControlState.normal) buttonLeft.setTitleColor( UIColor.white, for:UIControlState.normal) buttonLeft.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonLeft.titleLabel!.font = UIFont.bolder(size:14) buttonLeft.addTarget( self, action:#selector(actionShare(sender:)), for:UIControlEvents.touchUpInside) self.buttonLeft = buttonLeft let buttonRightPost:UIButton = UIButton() buttonRightPost.isHidden = true buttonRightPost.translatesAutoresizingMaskIntoConstraints = false buttonRightPost.setTitle( NSLocalizedString("VDrawProjectShareButtons_buttonRightPost", comment:""), for:UIControlState.normal) buttonRightPost.setTitleColor( UIColor.white, for:UIControlState.normal) buttonRightPost.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonRightPost.titleLabel!.font = UIFont.bolder(size:14) buttonRightPost.addTarget( self, action:#selector(actionPost(sender:)), for:UIControlEvents.touchUpInside) self.buttonRightPost = buttonRightPost let buttonRightUpdate:UIButton = UIButton() buttonRightUpdate.isHidden = true buttonRightUpdate.translatesAutoresizingMaskIntoConstraints = false buttonRightUpdate.setTitle( NSLocalizedString("VDrawProjectShareButtons_buttonRightUpdate", comment:""), for:UIControlState.normal) buttonRightUpdate.setTitleColor( UIColor.white, for:UIControlState.normal) buttonRightUpdate.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonRightUpdate.titleLabel!.font = UIFont.bolder(size:14) buttonRightUpdate.addTarget( self, action:#selector(actionUpdate(sender:)), for:UIControlEvents.touchUpInside) self.buttonRightUpdate = buttonRightUpdate let border:VBorder = VBorder(color:UIColor.white) addSubview(border) addSubview(buttonLeft) addSubview(buttonRightPost) addSubview(buttonRightUpdate) NSLayoutConstraint.equalsVertical( view:buttonLeft, toView:self) NSLayoutConstraint.leftToLeft( view:buttonLeft, toView:self) NSLayoutConstraint.rightToRight( view:buttonLeft, toView:self, constant:-kButtonRightWidth) NSLayoutConstraint.equalsVertical( view:buttonRightPost, toView:self) NSLayoutConstraint.rightToRight( view:buttonRightPost, toView:self) NSLayoutConstraint.width( view:buttonRightPost, constant:kButtonRightWidth) NSLayoutConstraint.equalsVertical( view:buttonRightUpdate, toView:self) NSLayoutConstraint.rightToRight( view:buttonRightUpdate, toView:self) NSLayoutConstraint.width( view:buttonRightUpdate, constant:kButtonRightWidth) NSLayoutConstraint.equalsVertical( view:border, toView:self) NSLayoutConstraint.leftToRight( view:border, toView:buttonLeft) NSLayoutConstraint.width( view:border, constant:kBorderWidth) } required init?(coder:NSCoder) { return nil } //MARK: actions func actionShare(sender button:UIButton) { controller.exportImage() } func actionPost(sender button:UIButton) { controller.postImage() } func actionUpdate(sender button:UIButton) { controller.updateImage() } //MARK: public func updateButtons() { var shouldPost:Bool = false if let postEnable:Bool = MSession.sharedInstance.settings?.shouldPost { shouldPost = postEnable } if shouldPost { if let _:String = controller.model.sharedId { buttonRightPost.isHidden = true buttonRightUpdate.isHidden = false } else { buttonRightPost.isHidden = false buttonRightUpdate.isHidden = true } } else { buttonRightPost.isHidden = true buttonRightUpdate.isHidden = true } } }
mit
757b4e2a4d91b6fc697d3222c1f76825
30.854749
88
0.611364
5.477426
false
false
false
false
toggl/superday
teferi/UI/Modules/Timeline/TimelineViewController.swift
1
12683
import RxSwift import RxCocoa import UIKit import CoreGraphics import RxDataSources protocol TimelineDelegate: class { func didScroll(oldOffset: CGFloat, newOffset: CGFloat) } class TimelineViewController : UIViewController { // MARK: Public Properties var date : Date { return self.viewModel.date } // MARK: Private Properties private let disposeBag = DisposeBag() fileprivate let viewModel : TimelineViewModel fileprivate let presenter : TimelinePresenter private var tableView : UITableView! private var willDisplayNewCell:Bool = false private var emptyStateView: EmptyStateView! private var voteView: TimelineVoteView! weak var delegate: TimelineDelegate? { didSet { let topInset = tableView.contentInset.top let offset = tableView.contentOffset.y delegate?.didScroll(oldOffset: offset + topInset, newOffset: offset + topInset) } } private var dataSource: RxTableViewSectionedAnimatedDataSource<TimelineSection>! // MARK: Initializers init(presenter: TimelinePresenter, viewModel: TimelineViewModel) { self.presenter = presenter self.viewModel = viewModel super.init(nibName: nil, bundle: nil) dataSource = RxTableViewSectionedAnimatedDataSource<TimelineSection>( animationConfiguration: AnimationConfiguration( insertAnimation: .fade, reloadAnimation: .fade, deleteAnimation: .fade ), configureCell: constructCell ) } required init?(coder: NSCoder) { fatalError("NSCoder init is not supported for this ViewController") } // MARK: UIViewController lifecycle override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: view.bounds) view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } emptyStateView = EmptyStateView.fromNib() view.addSubview(emptyStateView!) emptyStateView!.snp.makeConstraints{ make in make.edges.equalToSuperview() } emptyStateView?.isHidden = true tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.separatorStyle = .none tableView.allowsSelection = true tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.register(UINib.init(nibName: "TimelineCell", bundle: Bundle.main), forCellReuseIdentifier: TimelineCell.cellIdentifier) tableView.register(UINib.init(nibName: "ExpandedTimelineCell", bundle: Bundle.main), forCellReuseIdentifier: ExpandedTimelineCell.cellIdentifier) tableView.register(UINib.init(nibName: "CollapseCell", bundle: Bundle.main), forCellReuseIdentifier: CollapseCell.cellIdentifier) tableView.register(UINib.init(nibName: "CategoryCell", bundle: Bundle.main), forCellReuseIdentifier: CategoryCell.cellIdentifier) tableView.register(UINib.init(nibName: "ShortTimelineCell", bundle: Bundle.main), forCellReuseIdentifier: ShortTimelineCell.cellIdentifier) setTableViewContentInsets() createBindings() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if viewModel.canShowVotingUI() { showVottingUI() } setTableViewContentInsets() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel.active = true if !viewModel.canShowVotingUI() { tableView.tableFooterView = nil } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewModel.active = false } // MARK: Private Methods private func setTableViewContentInsets() { // Magic numbers and direct access to tabBar due to the many layers in the UI: VC-> Container-> Pager-> Timeline. // This should be fixed by using: VC -> CollectionView -> TableView // This way we can just use automaticallyAdjustsScrollViewInsets tableView.contentInset = UIEdgeInsets( top: 34, left: 0, bottom: 49 + (tabBarController?.tabBar.frame.height ?? 0), right: 0) } private func createBindings() { viewModel.timelineItems .map({ [TimelineSection(items:$0)] }) .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) viewModel.timelineItems .map{$0.count > 0} .drive(emptyStateView.rx.isHidden) .disposed(by: disposeBag) tableView.rx .modelSelected(TimelineItem.self) .subscribe(onNext: handleTableViewSelection ) .disposed(by: disposeBag) tableView.rx.willDisplayCell .subscribe(onNext: { [unowned self] (cell, indexPath) in guard self.willDisplayNewCell && indexPath.row == self.tableView.numberOfRows(inSection: 0) - 1 else { return } (cell as! TimelineCell).animateIntro() self.willDisplayNewCell = false }) .disposed(by: disposeBag) let oldOffset = tableView.rx.contentOffset.map({ $0.y }) let newOffset = tableView.rx.contentOffset.skip(1).map({ $0.y }) Observable<(CGFloat, CGFloat)>.zip(oldOffset, newOffset) { [unowned self] old, new -> (CGFloat, CGFloat) in // This closure prevents the header to change height when the scroll is bouncing let maxScroll = self.tableView.contentSize.height - self.tableView.frame.height + self.tableView.contentInset.bottom let minScroll = -self.tableView.contentInset.top if new < minScroll || old < minScroll { return (old, old) } if new > maxScroll || old > maxScroll { return (old, old) } return (old, new) } .subscribe(onNext: { [unowned self] (old, new) in let topInset = self.tableView.contentInset.top self.delegate?.didScroll(oldOffset: old + topInset, newOffset: new + topInset) }) .disposed(by: disposeBag) viewModel.didBecomeActiveObservable .subscribe(onNext: { [unowned self] in if self.viewModel.canShowVotingUI() { self.showVottingUI() } }) .disposed(by: disposeBag) viewModel.dailyVotingNotificationObservable .subscribe(onNext: onNotificationOpen) .disposed(by: disposeBag) } private func handleTableViewSelection(timelineItem: TimelineItem) { switch timelineItem { case .slot(let item), .commuteSlot(let item): if item.timeSlotEntities.count > 1 { viewModel.expandSlots(item: item) } else { presenter.showEditTimeSlot(with: item.startTime) } case .expandedSlot(let item, _): presenter.showEditTimeSlot(with: item.startTime) case .collapseButton(_), .expandedCommuteTitle(_), .expandedTitle(_): break } } private func showVottingUI() { tableView.tableFooterView = nil voteView = TimelineVoteView.fromNib() tableView.tableFooterView = voteView voteView.setVoteObservable .subscribe(onNext: viewModel.setVote) .disposed(by: disposeBag) } private func onNotificationOpen(on date: Date) { guard date.ignoreTimeComponents() == viewModel.date.ignoreTimeComponents(), viewModel.canShowVotingUI() else { return } if tableView.tableFooterView == nil { showVottingUI() } tableView.reloadData() let bottomOffset = CGPoint(x: 0, y: tableView.contentSize.height + tableView.tableFooterView!.bounds.height - tableView.bounds.size.height) tableView.setContentOffset(bottomOffset, animated: true) } private func handleNewItem(_ items: [SlotTimelineItem]) { let numberOfItems = tableView.numberOfRows(inSection: 0) guard numberOfItems > 0, items.count == numberOfItems + 1 else { return } willDisplayNewCell = true let scrollIndexPath = IndexPath(row: numberOfItems - 1, section: 0) tableView.scrollToRow(at: scrollIndexPath, at: .bottom, animated: true) } private func constructCell(dataSource: TableViewSectionedDataSource<TimelineSection>, tableView: UITableView, indexPath: IndexPath, timelineItem: TimelineItem) -> UITableViewCell { switch timelineItem { case .slot(let item): let cell = tableView.dequeueReusableCell(withIdentifier: TimelineCell.cellIdentifier, for: indexPath) as! TimelineCell cell.configure(slotTimelineItem: item) cell.selectionStyle = .none cell.editClickObservable .map{ [unowned self] item in let position = cell.categoryCircle.superview!.convert(cell.categoryCircle.center, to: self.view) return (position, item) } .subscribe(onNext: self.viewModel.notifyEditingBegan) .disposed(by: cell.disposeBag) return cell case .commuteSlot(let item): let cell = tableView.dequeueReusableCell(withIdentifier: ShortTimelineCell.cellIdentifier, for: indexPath) as! ShortTimelineCell cell.configure(slotTimelineItem: item) cell.selectionStyle = .none return cell case .expandedCommuteTitle(let item): let cell = tableView.dequeueReusableCell(withIdentifier: ShortTimelineCell.cellIdentifier, for: indexPath) as! ShortTimelineCell cell.configure(slotTimelineItem: item, showStartAndDuration: false) cell.selectionStyle = .none return cell case .expandedTitle(let item): let cell = tableView.dequeueReusableCell(withIdentifier: CategoryCell.cellIdentifier, for: indexPath) as! CategoryCell cell.configure(slotTimelineItem: item) cell.selectionStyle = .none cell.editClickObservable .map{ [unowned self] item in let position = cell.categoryCircle.superview!.convert(cell.categoryCircle.center, to: self.view) return (position, item) } .subscribe(onNext: self.viewModel.notifyEditingBegan) .disposed(by: cell.disposeBag) return cell case .expandedSlot(let item, let hasSeparator): let cell = tableView.dequeueReusableCell(withIdentifier: ExpandedTimelineCell.cellIdentifier, for: indexPath) as! ExpandedTimelineCell cell.configure(item: item, visibleSeparator: hasSeparator) cell.selectionStyle = .none return cell case .collapseButton(let color): let cell = tableView.dequeueReusableCell(withIdentifier: CollapseCell.cellIdentifier, for: indexPath) as! CollapseCell cell.configure(color: color) cell.selectionStyle = .none cell.collapseObservable .subscribe(onNext: viewModel.collapseSlots ) .disposed(by: cell.disposeBag) return cell } } private func buttonPosition(forCellIndex index: Int) -> CGPoint { guard let cell = tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? TimelineCell else { return CGPoint.zero } return cell.categoryCircle.convert(cell.categoryCircle.center, to: view) } }
bsd-3-clause
21c7fe0e872dc85086080bea6372c080
35.133903
182
0.603012
5.46681
false
false
false
false
ryanbooker/Swiftz
Tests/SwiftzTests/WriterSpec.swift
1
3667
// // WriterSpec.swift // Swiftz // // Created by Robert Widmann on 8/14/15. // Copyright © 2015-2016 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck extension Writer where T : Arbitrary { public static var arbitrary : Gen<Writer<W, T>> { return Gen<()>.zip(T.arbitrary, Gen.pure(W.mempty)).map(Writer.init) } public static func shrink(_ xs : Writer<W, T>) -> [Writer<W, T>] { let xs = T.shrink(xs.runWriter.0) return zip(xs, Array(repeating: W.mempty, count: xs.count)).map(Writer.init) } } extension Writer : WitnessedArbitrary { public typealias Param = T public static func forAllWitnessed<W : Monoid, A : Arbitrary>(_ wit : @escaping (A) -> T, pf : @escaping (Writer<W, T>) -> Testable) -> Property { return forAllShrink(Writer<W, A>.arbitrary, shrinker: Writer<W, A>.shrink, f: { bl in return pf(bl.fmap(wit)) }) } } class WriterSpec : XCTestCase { func testWriterProperties() { property("Writers obey reflexivity") <- forAll { (l : Writer<String, Int>) in return l == l } property("Writers obey symmetry") <- forAll { (x : Writer<String, Int>, y : Writer<String, Int>) in return (x == y) == (y == x) } property("Writers obey transitivity") <- forAll { (x : Writer<String, Int>, y : Writer<String, Int>, z : Writer<String, Int>) in return ((x == y) && (y == z)) ==> (x == z) } property("Writers obey negation") <- forAll { (x : Writer<String, Int>, y : Writer<String, Int>) in return (x != y) == !(x == y) } property("Writer obeys the Functor identity law") <- forAll { (x : Writer<String, Int>) in return (x.fmap(identity)) == identity(x) } property("Writer obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in return forAll { (x : Writer<String, Int>) in return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow)) } } property("Writer obeys the first Applicative composition law") <- forAll { (fl : Writer<String, ArrowOf<Int8, Int8>>, gl : Writer<String, ArrowOf<Int8, Int8>>, x : Writer<String, Int8>) in let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x)) } property("Writer obeys the second Applicative composition law") <- forAll { (fl : Writer<String, ArrowOf<Int8, Int8>>, gl : Writer<String, ArrowOf<Int8, Int8>>, x : Writer<String, Int8>) in let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) return (Writer<String, Int>.pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x)) } property("Writer obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Int>) in let f : (Int) -> Writer<String, Int> = Writer<String, Int>.pure • fa.getArrow return (Writer<String, Int>.pure(a) >>- f) == f(a) } property("Writer obeys the Monad right identity law") <- forAll { (m : Writer<String, Int>) in return (m >>- Writer<String, Int>.pure) == m } property("Writer obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, Int>, ga : ArrowOf<Int, Int>) in let f : (Int) -> Writer<String, Int> = Writer<String, Int>.pure • fa.getArrow let g : (Int) -> Writer<String, Int> = Writer<String, Int>.pure • ga.getArrow return forAll { (m : Writer<String, Int>) in return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g }) } } property("sequence occurs in order") <- forAll { (xs : [String]) in let ws: [Writer<String, String>] = xs.map(Writer<String, String>.pure) let seq = sequence(ws) return forAllNoShrink(Gen.pure(seq)) { ss in return ss.runWriter.0 == xs } } } }
bsd-3-clause
2b3cd2ef5d4f822213e47e0d43a33628
35.909091
191
0.61549
3.075758
false
false
false
false
josechagas/JLChatViewController
Classes/JLCustomTextView.swift
1
10529
// // JLCustomTextView.swift // ecommerce // // Created by José Lucas Souza das Chagas on 07/11/15. // Copyright © 2015 José Lucas Souza das Chagas. All rights reserved. // import UIKit //import QuartzCore /** A delegate that notifies when a file is added or removed */ protocol FileDelegate{ func fileAdded() func fileRemoved() } public class JLCustomTextView: UITextView,FileIndicatorViewDelegate { @IBInspectable var placeHolderText:String! = ""{ didSet{ self.placeHolder.placeholder = placeHolderText } } var placeHolder:UITextField! var placeHolderTopDist:NSLayoutConstraint! private var fileIndicatorView:JLFileIndicatorView! private var fileIndicatorViewHeight:NSLayoutConstraint! private let fileIndicatorViewHeightValue:CGFloat = 35 private(set) var fileAddedState:Bool = false var fileDelegate:FileDelegate? //a delegate to notify when some file is added to it override public var text:String!{ didSet{ showPlaceHolder(!thereIsSomeText()) } } override public var font:UIFont?{ didSet{ if placeHolder != nil { self.placeHolder.font = self.font } } } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) configCornerRadius() self.initPlaceHolder(CGPoint(x:self.contentInset.left, y:self.contentInset.top), size: CGSize(width: 20, height: 10), text: "") self.initFileIndicator() self.registerTextViewNotifications() self.layoutIfNeeded() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configCornerRadius() self.initPlaceHolder(CGPoint(x:self.contentInset.left, y:self.contentInset.top), size: CGSize(width: 20, height: 10), text: "") self.initFileIndicator() registerTextViewNotifications() self.layoutIfNeeded() } public override func intrinsicContentSize() -> CGSize { return super.intrinsicContentSize() } private func configCornerRadius(){ self.layer.masksToBounds = true self.layer.cornerRadius = 6 self.layer.borderWidth = 0.5 self.layer.borderColor = UIColor.grayColor().CGColor } /** Use this method for you know if there is some text. If you want to see if there is some character including \n for example use thereIsSomeChar() instead - returns : true if there is some text and false if there is not text */ public func thereIsSomeText()->Bool{ for char in self.text.characters{ if char != " " && char != "\n"{ return true } } return false } /** Use this method for you know if there is some character. - returns : true if there is some character and false if there is not */ public func thereIsSomeChar()->Bool{ return self.text.characters.count > 0 } /** Reset the textView for its default state. */ func resetTextView(){ self.scrollEnabled = false self.text = nil self.removeFile() } override public func paste(sender: AnyObject?) { super.paste(sender) } //MARK: - file indicator view delegate func didTapFileIndicatorView() { self.removeFile() } //MARK: - File added view /** Add a indicator of file added with 'JLFile' informations - parameter file: The 'JLFile' containing the informations */ public func addFile(file:JLFile){ //caso o valor antigo de fileAddedState for true quer dizer que ja havia algo adicionado entao nao precisa ajeitar o textinsets let correctEdges:Bool = !fileAddedState fileAddedState = true fileDelegate?.fileAdded() self.fileIndicatorView.addFileInformations(file) fileIndicatorViewHeight.constant = fileIndicatorViewHeightValue UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.layoutIfNeeded() }) { (finished) -> Void in var a = self.text a = a.stringByAppendingString(" ") self.text = a self.text = String(self.text.characters.dropLast()) if correctEdges{ self.correctEdgesForFile(self.fileIndicatorViewHeightValue) } } UIView.animateWithDuration(0.4, delay: 0.3, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.showPlaceHolder(false) self.fileIndicatorView.alpha = 1 }, completion: nil) } /** Remove the indicator of file added */ public func removeFile(){ if fileAddedState{ fileAddedState = false fileDelegate?.fileRemoved() fileIndicatorViewHeight.constant = 0 UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.fileIndicatorView.alpha = 0 }, completion: nil) UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.layoutIfNeeded() self.fileIndicatorView.layoutIfNeeded() }) { (finished) -> Void in var a = self.text a = a.stringByAppendingString(" ") self.text = a self.text = String(self.text.characters.dropLast()) self.correctEdgesForFile(-self.fileIndicatorViewHeightValue) } } } private func correctEdgesForFile(increaseAtTop:CGFloat){ self.textContainerInset = UIEdgeInsets(top: self.textContainerInset.top + increaseAtTop, left: self.textContainerInset.left, bottom: self.textContainerInset.bottom, right: self.textContainerInset.right) self.placeHolderTopDist.constant = self.textContainerInset.top } func initFileIndicator(){ fileIndicatorView = JLFileIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: fileIndicatorViewHeightValue)) fileIndicatorView.translatesAutoresizingMaskIntoConstraints = false self.fileIndicatorView.layer.zPosition = -1 fileIndicatorView.alpha = 0 fileIndicatorView.delegate = self self.addSubview(fileIndicatorView) //constraints fileIndicatorViewHeight = NSLayoutConstraint(item: fileIndicatorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0) fileIndicatorView.addConstraint(fileIndicatorViewHeight) let leadingAlignmentConstraint = NSLayoutConstraint(item: fileIndicatorView, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: self, attribute:NSLayoutAttribute.Leading, multiplier: 1, constant: 5) self.addConstraint(leadingAlignmentConstraint) let topAlignmentConstraint = NSLayoutConstraint(item: fileIndicatorView, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: self, attribute:NSLayoutAttribute.Top, multiplier: 1, constant: 5) self.addConstraint(topAlignmentConstraint) let width = NSLayoutConstraint(item: fileIndicatorView, attribute: NSLayoutAttribute.Width, relatedBy:NSLayoutRelation.LessThanOrEqual, toItem: self, attribute:NSLayoutAttribute.Width, multiplier: 1, constant: -5) self.addConstraint(width) } //MARK: - placeHolder methods private func initPlaceHolder(position:CGPoint,size:CGSize,text:String){ placeHolder = UITextField(frame: CGRect(origin: position, size: size)) placeHolder.placeholder = text placeHolder.enabled = false placeHolder.userInteractionEnabled = false placeHolder.font = self.font //do not add automatically the constraints placeHolder.translatesAutoresizingMaskIntoConstraints = false self.addSubview(placeHolder) //constraints // leading alignment let leadingAlignmentConstraint = NSLayoutConstraint(item: placeHolder, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: self, attribute:NSLayoutAttribute.Leading, multiplier: 1, constant: 5 + self.textContainerInset.left) self.addConstraint(leadingAlignmentConstraint) // top placeHolderTopDist = NSLayoutConstraint(item: placeHolder, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: self.textContainerInset.top/*8 + self.contentInset.top*/) self.addConstraint(placeHolderTopDist) } private func showPlaceHolder(show:Bool){ placeHolder.hidden = !show } //MARK: - notifications private func registerTextViewNotifications(){ //UITextViewTextDidChangeNotification NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(JLCustomTextView.didChangeText(_:)), name: UITextViewTextDidChangeNotification, object: nil) } func didChangeText(notification:NSNotification){ if thereIsSomeChar(){ showPlaceHolder(false) } else{ showPlaceHolder(true) } } }
mit
7726593cc96dd7481622aa4dd4c87439
28.484594
250
0.603078
5.513882
false
false
false
false
pascalbros/PAPermissions
Example/PAPermissionsApp/CustomPermissionsViewController.swift
1
3644
// // CustomPermissionsViewController.swift // PAPermissionsApp // // Created by Pasquale Ambrosini on 06/09/16. // Copyright © 2016 Pasquale Ambrosini. All rights reserved. // import UIKit import PAPermissions class CustomPermissionsViewController: PAPermissionsViewController { let bluetoothCheck = PABluetoothPermissionsCheck() let locationCheck = PALocationPermissionsCheck() let microphoneCheck = PAMicrophonePermissionsCheck() let motionFitnessCheck = PAMotionFitnessPermissionsCheck() let cameraCheck = PACameraPermissionsCheck() let photoLibraryCheck = PAPhotoLibraryPermissionsCheck() let mediaLibraryCheck = PAMediaLibraryPermissionsCheck() lazy var notificationsCheck : PAPermissionsCheck = { return PAUNNotificationPermissionsCheck() }() let customCheck = PACustomPermissionsCheck() let calendarCheck = PACalendarPermissionsCheck() let reminderCheck = PARemindersPermissionsCheck() let contactsCheck : PAPermissionsCheck = { return PACNContactsPermissionsCheck() }() override func viewDidLoad() { super.viewDidLoad() let permissions = [ PAPermissionsItem.itemForType(.calendar, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.reminders, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.contacts, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.bluetooth, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.location, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.microphone, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.motionFitness, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.photoLibrary, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.mediaLibrary, reason: PAPermissionDefaultReason)!, PAPermissionsItem.itemForType(.notifications, reason: "Required to send you great updates")!, PAPermissionsItem.itemForType(.camera, reason: PAPermissionDefaultReason)!, PAPermissionsItem(type: .custom, identifier: "my-custom-permission", title: "Custom Option", reason: "Optional", icon: UIImage(named: "pa_checkmark_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil)!, canBeDisabled: true)] let handlers = [ PAPermissionsType.calendar.rawValue: self.calendarCheck, PAPermissionsType.reminders.rawValue: self.reminderCheck, PAPermissionsType.contacts.rawValue: self.contactsCheck, PAPermissionsType.bluetooth.rawValue: self.bluetoothCheck, PAPermissionsType.location.rawValue: self.locationCheck, PAPermissionsType.microphone.rawValue: self.microphoneCheck, PAPermissionsType.motionFitness.rawValue: self.motionFitnessCheck, PAPermissionsType.photoLibrary.rawValue: self.photoLibraryCheck, PAPermissionsType.mediaLibrary.rawValue: self.mediaLibraryCheck, PAPermissionsType.camera.rawValue: self.cameraCheck, PAPermissionsType.notifications.rawValue: self.notificationsCheck, "my-custom-permission": self.customCheck] self.setupData(permissions, handlers: handlers) //////Colored background////// //self.tintColor = UIColor.white //self.backgroundColor = UIColor(red: 245.0/255.0, green: 94.0/255.0, blue: 78.0/255.0, alpha: 1.0) //////Blur background////// //self.tintColor = UIColor.white //self.backgroundImage = UIImage(named: "background.jpg") //self.useBlurBackground = true self.titleText = "My Awesome App" self.detailsText = "Please enable the following" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
be48e2ccb4f79c25075f706f87e2260c
43.426829
253
0.791381
4.265808
false
false
false
false
drahot/BSImagePicker
Pod/Classes/Controller/PhotosViewController.swift
1
24165
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos import BSGridCollectionViewLayout fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } final class PhotosViewController : UICollectionViewController { var selectionClosure: ((_ asset: PHAsset) -> Void)? var deselectionClosure: ((_ asset: PHAsset) -> Void)? var cancelClosure: ((_ assets: [PHAsset]) -> Void)? var finishClosure: ((_ assets: [PHAsset]) -> Void)? var doneBarButton: UIBarButtonItem? var cancelBarButton: UIBarButtonItem? var albumTitleView: AlbumTitleView? let expandAnimator = ZoomAnimator() let shrinkAnimator = ZoomAnimator() fileprivate var photosDataSource: PhotoCollectionViewDataSource? fileprivate var albumsDataSource: AlbumTableViewDataSource fileprivate let cameraDataSource: CameraCollectionViewDataSource fileprivate var composedDataSource: ComposedCollectionViewDataSource? fileprivate var defaultSelections: PHFetchResult<PHAsset>? let settings: BSImagePickerSettings fileprivate var doneBarButtonTitle: String? lazy var albumsViewController: AlbumsViewController = { let storyboard = UIStoryboard(name: "Albums", bundle: BSImagePickerViewController.bundle) let vc = storyboard.instantiateInitialViewController() as! AlbumsViewController vc.tableView.dataSource = self.albumsDataSource vc.tableView.delegate = self return vc }() fileprivate lazy var previewViewContoller: PreviewViewController? = { return PreviewViewController(nibName: nil, bundle: nil) }() required init(fetchResults: [PHFetchResult<PHAssetCollection>], defaultSelections: PHFetchResult<PHAsset>? = nil, settings aSettings: BSImagePickerSettings) { albumsDataSource = AlbumTableViewDataSource(fetchResults: fetchResults) cameraDataSource = CameraCollectionViewDataSource(settings: aSettings, cameraAvailable: UIImagePickerController.isSourceTypeAvailable(.camera)) self.defaultSelections = defaultSelections settings = aSettings super.init(collectionViewLayout: GridCollectionViewLayout()) PHPhotoLibrary.shared().register(self) } required init?(coder aDecoder: NSCoder) { fatalError("b0rk: initWithCoder not implemented") } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } override func loadView() { super.loadView() // Setup collection view collectionView?.backgroundColor = settings.backgroundColor collectionView?.allowsMultipleSelection = true // Set an empty title to get < back button title = " " // Set button actions and add them to navigation item doneBarButton?.target = self doneBarButton?.action = #selector(PhotosViewController.doneButtonPressed(_:)) cancelBarButton?.target = self cancelBarButton?.action = #selector(PhotosViewController.cancelButtonPressed(_:)) albumTitleView?.albumButton?.addTarget(self, action: #selector(PhotosViewController.albumButtonPressed(_:)), for: .touchUpInside) navigationItem.leftBarButtonItem = cancelBarButton navigationItem.rightBarButtonItem = doneBarButton navigationItem.titleView = albumTitleView if let album = albumsDataSource.fetchResults.first?.firstObject { initializePhotosDataSource(album, selections: defaultSelections) updateAlbumTitle(album) collectionView?.reloadData() } // Add long press recognizer let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(PhotosViewController.collectionViewLongPressed(_:))) longPressRecognizer.minimumPressDuration = 0.5 collectionView?.addGestureRecognizer(longPressRecognizer) // Set navigation controller delegate navigationController?.delegate = self // Register cells photosDataSource?.registerCellIdentifiersForCollectionView(collectionView) cameraDataSource.registerCellIdentifiersForCollectionView(collectionView) } // MARK: Appear/Disappear override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateDoneButton() } // MARK: Button actions @objc func cancelButtonPressed(_ sender: UIBarButtonItem) { guard let closure = cancelClosure, let photosDataSource = photosDataSource else { dismiss(animated: true, completion: nil) return } DispatchQueue.global().async { closure(photosDataSource.selections) } dismiss(animated: true, completion: nil) } @objc func doneButtonPressed(_ sender: UIBarButtonItem) { guard let closure = finishClosure, let photosDataSource = photosDataSource else { dismiss(animated: true, completion: nil) return } DispatchQueue.global().async { closure(photosDataSource.selections) } dismiss(animated: true, completion: nil) } @objc func albumButtonPressed(_ sender: UIButton) { guard let popVC = albumsViewController.popoverPresentationController else { return } popVC.permittedArrowDirections = .up popVC.sourceView = sender let senderRect = sender.convert(sender.frame, from: sender.superview) let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + (sender.frame.size.height / 2), width: senderRect.size.width, height: senderRect.size.height) popVC.sourceRect = sourceRect popVC.delegate = self albumsViewController.tableView.reloadData() present(albumsViewController, animated: true, completion: nil) } @objc func collectionViewLongPressed(_ sender: UIGestureRecognizer) { if sender.state == .began { // Disable recognizer while we are figuring out location and pushing preview sender.isEnabled = false collectionView?.isUserInteractionEnabled = false // Calculate which index path long press came from let location = sender.location(in: collectionView) let indexPath = collectionView?.indexPathForItem(at: location) if let vc = previewViewContoller, let indexPath = indexPath, let cell = collectionView?.cellForItem(at: indexPath) as? PhotoCell, let asset = cell.asset { // Setup fetch options to be synchronous let options = PHImageRequestOptions() options.isSynchronous = true // Load image for preview if let imageView = vc.imageView { PHCachingImageManager.default().requestImage(for: asset, targetSize:imageView.frame.size, contentMode: .aspectFit, options: options) { (result, _) in imageView.image = result } } // Setup animation expandAnimator.sourceImageView = cell.imageView expandAnimator.destinationImageView = vc.imageView shrinkAnimator.sourceImageView = vc.imageView shrinkAnimator.destinationImageView = cell.imageView navigationController?.pushViewController(vc, animated: true) } // Re-enable recognizer, after animation is done DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(expandAnimator.transitionDuration(using: nil) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { () -> Void in sender.isEnabled = true self.collectionView?.isUserInteractionEnabled = true }) } } // MARK: Private helper methods func updateDoneButton() { // Find right button if let subViews = navigationController?.navigationBar.subviews, let photosDataSource = photosDataSource { for view in subViews { if let btn = view as? UIButton , checkIfRightButtonItem(btn) { // Store original title if we havn't got it if doneBarButtonTitle == nil { doneBarButtonTitle = btn.title(for: UIControl.State()) } // Update title if let doneBarButtonTitle = doneBarButtonTitle { // Special case if we have selected 1 image and that is // the max number of allowed selections if (photosDataSource.selections.count == 1 && self.settings.maxNumberOfSelections == 1) { btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle)", forState: UIControl.State()) } else if photosDataSource.selections.count > 0 { btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle) (\(photosDataSource.selections.count))", forState: UIControl.State()) } else { btn.bs_setTitleWithoutAnimation(doneBarButtonTitle, forState: UIControl.State()) } // Enabled? doneBarButton?.isEnabled = photosDataSource.selections.count > 0 } // Stop loop break } } } self.navigationController?.navigationBar.setNeedsLayout() } // Check if a give UIButton is the right UIBarButtonItem in the navigation bar // Somewhere along the road, our UIBarButtonItem gets transformed to an UINavigationButton func checkIfRightButtonItem(_ btn: UIButton) -> Bool { guard let rightButton = navigationItem.rightBarButtonItem else { return false } // Store previous values let wasRightEnabled = rightButton.isEnabled let wasButtonEnabled = btn.isEnabled // Set a known state for both buttons rightButton.isEnabled = false btn.isEnabled = false // Change one and see if other also changes rightButton.isEnabled = true let isRightButton = btn.isEnabled // Reset rightButton.isEnabled = wasRightEnabled btn.isEnabled = wasButtonEnabled return isRightButton } func updateAlbumTitle(_ album: PHAssetCollection) { if let title = album.localizedTitle { // Update album title albumTitleView?.albumTitle = title } } func initializePhotosDataSource(_ album: PHAssetCollection, selections: PHFetchResult<PHAsset>? = nil) { // Set up a photo data source with album let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) initializePhotosDataSourceWithFetchResult(PHAsset.fetchAssets(in: album, options: fetchOptions), selections: selections) } func initializePhotosDataSourceWithFetchResult(_ fetchResult: PHFetchResult<PHAsset>, selections: PHFetchResult<PHAsset>? = nil) { let newDataSource = PhotoCollectionViewDataSource(fetchResult: fetchResult, selections: selections, settings: settings) // Transfer image size // TODO: Move image size to settings if let photosDataSource = photosDataSource { newDataSource.imageSize = photosDataSource.imageSize newDataSource.selections = photosDataSource.selections } photosDataSource = newDataSource // Hook up data source composedDataSource = ComposedCollectionViewDataSource(dataSources: [cameraDataSource, newDataSource]) collectionView?.dataSource = composedDataSource collectionView?.delegate = self } } // MARK: UICollectionViewDelegate extension PhotosViewController { override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { // NOTE: ALWAYS return false. We don't want the collectionView to be the source of thruth regarding selections // We can manage it ourself. // Camera shouldn't be selected, but pop the UIImagePickerController! if let composedDataSource = composedDataSource , composedDataSource.dataSources[indexPath.section].isEqual(cameraDataSource) { let cameraController = UIImagePickerController() cameraController.allowsEditing = false cameraController.sourceType = .camera cameraController.delegate = self self.present(cameraController, animated: true, completion: nil) return false } // Make sure we have a data source and that we can make selections guard let photosDataSource = photosDataSource, collectionView.isUserInteractionEnabled else { return false } // We need a cell guard let cell = collectionView.cellForItem(at: indexPath) as? PhotoCell else { return false } let asset = photosDataSource.fetchResult.object(at: indexPath.row) // Select or deselect? if let index = photosDataSource.selections.index(of: asset) { // Deselect // Deselect asset photosDataSource.selections.remove(at: index) // Update done button updateDoneButton() // Get indexPaths of selected items let selectedIndexPaths = photosDataSource.selections.flatMap({ (asset) -> IndexPath? in let index = photosDataSource.fetchResult.index(of: asset) guard index != NSNotFound else { return nil } return IndexPath(item: index, section: 1) }) // Reload selected cells to update their selection number UIView.setAnimationsEnabled(false) collectionView.reloadItems(at: selectedIndexPaths) UIView.setAnimationsEnabled(true) cell.photoSelected = false // Call deselection closure if let closure = deselectionClosure { DispatchQueue.global().async { closure(asset) } } } else if photosDataSource.selections.count < settings.maxNumberOfSelections { // Select // Select asset if not already selected photosDataSource.selections.append(asset) // Set selection number if let selectionCharacter = settings.selectionCharacter { cell.selectionString = String(selectionCharacter) } else { cell.selectionString = String(photosDataSource.selections.count) } cell.photoSelected = true // Update done button updateDoneButton() // Call selection closure if let closure = selectionClosure { DispatchQueue.global().async { closure(asset) } } } return false } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? CameraCell else { return } cell.startLiveBackground() // Start live background } } // MARK: UIPopoverPresentationControllerDelegate extension PhotosViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool { return true } } // MARK: UINavigationControllerDelegate extension PhotosViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .push { return expandAnimator } else { return shrinkAnimator } } } // MARK: UITableViewDelegate extension PhotosViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Update photos data source let album = albumsDataSource.fetchResults[indexPath.section][indexPath.row] initializePhotosDataSource(album) updateAlbumTitle(album) collectionView?.reloadData() // Dismiss album selection albumsViewController.dismiss(animated: true, completion: nil) } } // MARK: Traits extension PhotosViewController { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if let collectionViewFlowLayout = collectionViewLayout as? GridCollectionViewLayout { let itemSpacing: CGFloat = 2.0 let cellsPerRow = settings.cellsPerRow(traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass) collectionViewFlowLayout.itemSpacing = itemSpacing collectionViewFlowLayout.itemsPerRow = cellsPerRow photosDataSource?.imageSize = collectionViewFlowLayout.itemSize updateDoneButton() } } } // MARK: UIImagePickerControllerDelegate extension PhotosViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { picker.dismiss(animated: true, completion: nil) return } var placeholder: PHObjectPlaceholder? PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image) placeholder = request.placeholderForCreatedAsset }, completionHandler: { success, error in guard let placeholder = placeholder, let asset = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: nil).firstObject, success == true else { picker.dismiss(animated: true, completion: nil) return } DispatchQueue.main.async { // TODO: move to a function. this is duplicated in didSelect self.photosDataSource?.selections.append(asset) self.updateDoneButton() // Call selection closure if let closure = self.selectionClosure { DispatchQueue.global().async { closure(asset) } } picker.dismiss(animated: true, completion: nil) } }) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } // MARK: PHPhotoLibraryChangeObserver extension PhotosViewController: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { guard let photosDataSource = photosDataSource, let collectionView = collectionView else { return } DispatchQueue.main.async(execute: { () -> Void in if let photosChanges = changeInstance.changeDetails(for: photosDataSource.fetchResult as! PHFetchResult<PHObject>) { // Update collection view // Alright...we get spammed with change notifications, even when there are none. So guard against it if photosChanges.hasIncrementalChanges && (photosChanges.removedIndexes?.count > 0 || photosChanges.insertedIndexes?.count > 0 || photosChanges.changedIndexes?.count > 0) { // Update fetch result photosDataSource.fetchResult = photosChanges.fetchResultAfterChanges as! PHFetchResult<PHAsset> if let removed = photosChanges.removedIndexes { collectionView.deleteItems(at: removed.bs_indexPathsForSection(1)) } if let inserted = photosChanges.insertedIndexes { collectionView.insertItems(at: inserted.bs_indexPathsForSection(1)) } // Changes is causing issues right now...fix me later // Example of issue: // 1. Take a new photo // 2. We will get a change telling to insert that asset // 3. While it's being inserted we get a bunch of change request for that same asset // 4. It flickers when reloading it while being inserted // TODO: FIX // if let changed = photosChanges.changedIndexes { // print("changed") // collectionView.reloadItemsAtIndexPaths(changed.bs_indexPathsForSection(1)) // } // Reload view collectionView.reloadData() } else if photosChanges.hasIncrementalChanges == false { // Update fetch result photosDataSource.fetchResult = photosChanges.fetchResultAfterChanges as! PHFetchResult<PHAsset> collectionView.reloadData() // Reload view collectionView.reloadData() } } }) // TODO: Changes in albums } }
mit
78a60e87bc6616395ee914807d32efd4
41.920071
247
0.63127
6.122118
false
false
false
false
iWeslie/Ant
Ant/Ant/Me/Login/ProfileViewController.swift
2
9392
// // ViewController.swift // AntProfileDemo // // Created by Weslie on 2017/7/6. // Copyright © 2017年 Weslie. All rights reserved. // import UIKit let isLoginNotification = NSNotification.Name(rawValue:"didLogin") let appdelegate = UIApplication.shared.delegate as? AppDelegate class ProfileViewController: UIViewController { var modelView : UIView? var tableView: UITableView? var valueLabel : UILabel? var silderView : UISlider? var items = ["我的发布", "我的收藏", "正文字体", "个人设置"] var imgs = [#imageLiteral(resourceName: "profile_icon_edit"), #imageLiteral(resourceName: "profile_icon_collect"), #imageLiteral(resourceName: "profile_icon_textfont"), #imageLiteral(resourceName: "profile_icon_setting")] override func viewDidLoad() { super.viewDidLoad() self.navigationController?.delegate = self initTableView() } override func viewDidAppear(_ animated: Bool) { super.viewWillAppear(true) self.tabBarController?.tabBar.isHidden = false } } extension ProfileViewController { @objc func needLogin() { let alert = UIAlertController(title: "提示", message: "需要先登录才能进行改操作", preferredStyle: .alert) let notLogin = UIAlertAction(title: "暂不登陆", style: .cancel, handler: nil) let login = UIAlertAction(title: "立即登录", style: .default) { (_) in self.loadLoginViewController() } alert.addAction(login) alert.addAction(notLogin) self.present(alert, animated: true, completion: nil) } } extension ProfileViewController: UITableViewDelegate, UITableViewDataSource { fileprivate func initTableView() { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) self.tableView = UITableView(frame: frame, style: .grouped) self.tableView?.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.tableView?.dataSource = self self.tableView?.delegate = self self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 0.5) let avaNib = UINib(nibName: "LoginTableViewCell", bundle: nil) tableView?.register(avaNib, forCellReuseIdentifier: "login") self.view.addSubview(self.tableView!) } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 1: return 4 default: return 1 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: return 120 default: return 60 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 0 { return 10 } else { return 5 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 10 } else { return 0.000001 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if isLogin == true { switch indexPath.section { case 0: loadSelfProfileController() case 1: switch indexPath.row { case 0: print("my issue") let storyBoard = UIStoryboard(name: "Others", bundle: nil) let dest = storyBoard.instantiateViewController(withIdentifier: "youSentOut") as? OthersIssueVC self.present(dest!, animated: true, completion: nil) case 1: print("my favourite") case 2: addSliderView() case 3: print("my settings") default: break } case 2: print("advice") default: break } } else { if indexPath.section == 1 && indexPath.row == 2 { addSliderView() } else if indexPath.section == 0 { loadLoginViewController() } else { needLogin() } } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cells: UITableViewCell? if indexPath.section == 0 && indexPath.row == 0 { cells = tableView.dequeueReusableCell(withIdentifier: "login") } else { var commonCell = tableView.dequeueReusableCell(withIdentifier: "header") if commonCell == nil { commonCell = antTableViewCell.init(style: .default, reuseIdentifier: "header") } switch indexPath.section { case 1: commonCell?.textLabel?.text = items[indexPath.row] commonCell?.imageView?.image = imgs[indexPath.row] case 2: commonCell?.textLabel?.text = "建议反馈" commonCell?.imageView?.image = #imageLiteral(resourceName: "profile_icon_suggest") default: commonCell?.textLabel?.text = "" } cells = commonCell } cells?.selectionStyle = .none return cells! } } //MARK: - silder方法 extension ProfileViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.modelView?.removeFromSuperview() } // slider变动时改变label值 func sliderValueChanged(sender : UISlider) { self.valueLabel?.text = String(format: "设置字体倍数为%.2fX", sender.value) let alterVC = UIAlertController.init(title: "确认修改", message: "确认修改后请重启应用", preferredStyle: .alert) alterVC.addAction(UIAlertAction.init(title: "确认", style: .default, handler: { [weak self](action) in appdelegate?.fontSize = CGFloat(sender.value) self?.modelView?.removeFromSuperview() })) alterVC.addAction(UIAlertAction.init(title: "取消", style: .destructive, handler: {[weak self](action) in self?.modelView?.removeFromSuperview() })) self.present(alterVC, animated: true, completion: nil) } //添加Slider func addSliderView() { let modelView = UIView.init(frame: CGRect.init(x: 0, y: screenHeight * 0.3, width: screenWidth, height: 200)) modelView.backgroundColor = UIColor.init(white: 0.9, alpha: 0.5) self.modelView = modelView let silderView = UISlider.init(frame: CGRect.init(x: 20, y: 90, width: screenWidth - 40, height: 20)) silderView.minimumValue = 1.0 silderView.maximumValue = 1.5 silderView.isContinuous = false silderView.minimumTrackTintColor = appdelgate?.theme silderView.setValue(Float((appdelegate?.fontSize)!),animated:true) //添加当前值label self.valueLabel = UILabel.init(frame: CGRect.init(x: (screenWidth - 200) / 2, y: silderView.frame.maxY + 10 , width: 200, height: 40)) self.valueLabel?.textAlignment = .center self.valueLabel?.text = String(format: "设置字体倍数为%.2fX", silderView.value) self.valueLabel?.textColor = appdelgate?.theme self.modelView?.addSubview(self.valueLabel!) silderView.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged) self.modelView?.addSubview(silderView) self.silderView = silderView UIView.animate(withDuration: 0.25, animations: { self.view.addSubview(self.modelView!) }) } } extension ProfileViewController { fileprivate func loadLoginViewController() { let loginVC = LoginViewController() self.navigationController?.navigationBar.isTranslucent = false self.navigationController?.pushViewController(loginVC, animated: true) } fileprivate func loadSelfProfileController() { let selfprofileVC = UIStoryboard.init(name: "SelfProfile", bundle: nil).instantiateInitialViewController()! self.navigationController?.pushViewController(selfprofileVC, animated: true) self.tabBarController?.tabBar.isHidden = true } } extension ProfileViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { let isLoginVC = viewController is LoginViewController || viewController is LoginWithPwd || viewController is Register self.navigationController?.setNavigationBarHidden(isLoginVC, animated: true) if isLoginVC { self.tabBarController?.tabBar.isHidden = true } } }
apache-2.0
cbd37c48325d115edc028c6802f73396
33.241636
225
0.601998
4.946831
false
false
false
false