repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
bermudadigitalstudio/Titan
Tests/TitanRouterTests/TitanRouterTests.swift
1
10339
// Copyright 2017 Enervolution GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import TitanRouter import TitanCore let nullResponse = Response(-1, Data(), HTTPHeaders()) extension Response { init(_ string: String) { self.body = string.data(using: .utf8) ?? Data() self.code = 200 self.headers = HTTPHeaders() } init(_ data: Data) { self.body = data self.code = 200 self.headers = HTTPHeaders() } } final class TitanRouterTests: XCTestCase { static var allTests = [ ("testFunctionalMutableParams", testFunctionalMutableParams), ("testBasicGet", testBasicGet), ("testTitanEcho", testTitanEcho), ("testMultipleRoutes", testMultipleRoutes), ("testTitanSugar", testTitanSugar), ("testMiddlewareFunction", testMiddlewareFunction), ("testDifferentMethods", testDifferentMethods), ("testSamePathDifferentiationByMethod", testSamePathDifferentiationByMethod), ("testMatchingWildcardComponents", testMatchingWildcardComponents), ("testTypesafePathParams", testTypesafePathParams), ("testTypesafeMultipleParams", testTypesafeMultipleParams), ("testMismatchingLongPaths", testMismatchingLongPaths), ("testMatchingWithAQuery", testMatchingWithAQuery) ] var app: Titan! override func setUp() { app = Titan() } func testFunctionalMutableParams() { let app = Titan() app.get("/init") { (req, res) -> (RequestType, ResponseType) in var newReq = req.copy() var newRes = res.copy() newRes.body = "Hello World".data(using: .utf8) ?? Data() newReq.path = "/rewritten" newRes.code = 500 return (newReq, newRes) } app.addFunction { (req, res) -> (RequestType, ResponseType) in XCTAssertEqual(req.path, "/rewritten") return (req, res) } let response = app.app(request: Request(.get, "/init", "", HTTPHeaders()), response: nullResponse).1 XCTAssertEqual(response.code, 500) XCTAssertEqual(response.body, "Hello World") } func testAllMethods() { app.allMethods("/user/*") { (req, _) -> (RequestType, ResponseType) in // maybe do some tracing code here return (req, Response("Heyo")) } let response = app.app(request: Request(.custom(named: "ANYMETHOD"), "/user/whatever", "", HTTPHeaders()), response: nullResponse).1 XCTAssertEqual(response.code, 200) XCTAssertEqual(response.body, "Heyo") } func testBasicGet() { app.get("/username") { req, _ in return (req, Response("swizzlr")) } XCTAssertEqual(app.app(request: Request(.get, "/username"), response: nullResponse).1.body, "swizzlr") } func testTitanEcho() { app.get("/echoMyBody") { req, _ in return (req, Response(req.body)) } XCTAssertEqual(app.app(request: Request(.get, "/echoMyBody", "hello, this is my body"), response: nullResponse).1.body, "hello, this is my body") } func testMultipleRoutes() { app.get("/username") { req, _ in return (req, Response("swizzlr")) } app.get("/echoMyBody") { (req, _) -> (RequestType, ResponseType) in return (req, Response(req.body)) } XCTAssertEqual(String(data: app.app(request: Request(.get, "/echoMyBody", "hello, this is my body"), response: nullResponse).1.body, encoding: .utf8), "hello, this is my body") XCTAssertEqual(app.app(request: Request(.get, "/username"), response: nullResponse).1.body, "swizzlr") } func testTitanSugar() { let somePremadeFunction: TitanFunc = { req, res in return (req, res) } app.get(path: "/username", handler: somePremadeFunction) app.get("/username", somePremadeFunction) } func testMiddlewareFunction() { var start = Date() var end = start app.addFunction("*") { (req: RequestType, res: ResponseType) -> (RequestType, ResponseType) in start = Date() return (req, res) } app.get("/username") { req, _ in return (req, Response("swizzlr")) } app.addFunction("*") { (req: RequestType, res: ResponseType) -> (RequestType, ResponseType) in end = Date() return (req, res) } _ = app.app(request: Request(.get, "/username"), response: nullResponse).1 XCTAssertLessThan(start, end) } func testDifferentMethods() { app.get("/getSomething") { req, _ in return (req, Response("swizzlrGotSomething!")) } app.post("/postSomething") { req, _ in return (req, Response("something posted")) } app.put("/putSomething") { req, _ in return (req, Response( "i can confirm that stupid stuff is now on the server")) } app.patch("/patchSomething") { req, _ in return (req, Response("i guess we don't have a flat tire anymore?")) } app.delete("/deleteSomething") { req, _ in return (req, Response("error: could not find the USA or its principles")) } app.options("/optionSomething") { req, _ in return (req, Response("I sold movie rights!")) } app.head("/headSomething") { req, _ in return (req, Response("OWN GOAL!!")) } } func testSamePathDifferentiationByMethod() throws { var username = "" let created = try Response(201, "") app.get("/username") { req, _ in return (req, Response(username)) } app.post("/username") { (req: RequestType, _) in username = req.body! return (req, created) } let resp = app.app(request: Request(.post, "/username", "Lisa"), response: nullResponse).1 XCTAssertEqual(resp.code, 201) XCTAssertEqual(app.app(request: Request(.get, "/username"), response: nullResponse).1.body, "Lisa") } func testMatchingWildcardComponents() throws { app.get("/foo/{foo}/baz/{baz}/bar") { req, _, params in XCTAssertNotNil(params["foo"]) XCTAssertNotNil(params["baz"]) return (req, Response(200)) } let resp = app.app(request: Request(.get, "/foo/123456/baz/7890/bar"), response: nullResponse).1 XCTAssertEqual(resp.code, 200) } func testTypesafePathParams() { app.get("/foo/{id}/baz") { req, _, params in let id = params["id"] ?? "" return (req, Response(id)) } let resp = app.app(request: Request(.get, "/foo/567/baz"), response: nullResponse).1 XCTAssertEqual(resp.body, "567") } func testTypesafeMultipleParams() { app.get("/foo/{foo}/bar/{bar}") { req, _, params in let foo = params["foo"] ?? "" let bar = params["bar"] ?? "" return (req, Response("foo=\(foo), bar=\(bar)")) } let resp2 = app.app(request: Request(.get, "/foo/hello/bar/world"), response: nullResponse).1 XCTAssertEqual(resp2.body, "foo=hello, bar=world") app.get("/foo/{foo}/bar/{bar}/baz/{baz}") { req, _, params in let foo = params["foo"] ?? "" let bar = params["bar"] ?? "" let baz = params["baz"] ?? "" return (req, Response("foo=\(foo), bar=\(bar), baz=\(baz)")) } let resp3 = app.app(request: Request(.get, "/foo/hello/bar/world/baz/my"), response: nullResponse).1 XCTAssertEqual(resp3.body, "foo=hello, bar=world, baz=my") app.get(path: "/foo/{foo}/bar/{bar}/baz/{baz}/qux/{qux}") { req, _, params in let foo = params["foo"] ?? "" let bar = params["bar"] ?? "" let baz = params["baz"] ?? "" let qux = params["qux"] ?? "" return (req, Response("foo=\(foo), bar=\(bar), baz=\(baz), qux=\(qux)")) } let resp4 = app.app(request: Request(.get, "/foo/hello/bar/world/baz/my/qux/name"), response: nullResponse).1 XCTAssertEqual(resp4.body, "foo=hello, bar=world, baz=my, qux=name") app.get("/foo/{foo}/bar/{bar}/baz/{baz}/qux/{qux}/yex/{yex}") { req, _, params in let foo = params["foo"] ?? "" let bar = params["bar"] ?? "" let baz = params["baz"] ?? "" let qux = params["qux"] ?? "" let yex = params["yex"] ?? "" return (req, Response("foo=\(foo), bar=\(bar), baz=\(baz), qux=\(qux), yex=\(yex)")) } let resp5 = app.app(request: Request(.get, "/foo/hello/bar/world/baz/my/qux/name/yex/is"), response: nullResponse).1 XCTAssertEqual(resp5.body, "foo=hello, bar=world, baz=my, qux=name, yex=is") } func testMismatchingLongPaths() { app.get("/foo/{id}/thing") { req, _, params in XCTAssertNotNil(params["id"]) do { return (req, try Response(200, "Got foo")) } catch { return (req, Response(code: 500, body: Data(), headers: HTTPHeaders())) } } let resp = app.app(request: Request(.get, "/foo/bar"), response: nullResponse).1 XCTAssertNotEqual(resp.body, "Got foo") } func testMatchingWithAQuery() { app.get("/test/hello") { req, _ in return (req, Response(200)) } let resp = app.app(request: Request(.get, "/test/hello?query=thing&q=2"), response: nullResponse).1 XCTAssertEqual(resp.code, 200) } }
apache-2.0
f80c36aeffd10ebaffdaae8465364d01
36.733577
140
0.56756
4.037095
false
true
false
false
headione/criticalmaps-ios
CriticalMapsKit/Sources/AppFeature/AppFeatureCore.swift
1
14188
import ApiClient import ChatFeature import ComposableArchitecture import ComposableCoreLocation import FileClient import IDProvider import Logger import MapFeature import MapKit import NextRideFeature import PathMonitorClient import SettingsFeature import SharedModels import SocialFeature import TwitterFeedFeature import UIApplicationClient import UserDefaultsClient // MARK: State public struct AppState: Equatable { public init( locationsAndChatMessages: Result<LocationAndChatMessages, NSError>? = nil, didResolveInitialLocation: Bool = false, mapFeatureState: MapFeatureState = MapFeatureState( riders: [], userTrackingMode: UserTrackingState(userTrackingMode: .follow) ), socialState: SocialState = SocialState(), settingsState: SettingsState = SettingsState(), nextRideState: NextRideState = NextRideState(), requestTimer: RequestTimerState = RequestTimerState(), route: AppRoute? = nil, chatMessageBadgeCount: UInt = 0 ) { self.locationsAndChatMessages = locationsAndChatMessages self.didResolveInitialLocation = didResolveInitialLocation self.mapFeatureState = mapFeatureState self.socialState = socialState self.settingsState = settingsState self.nextRideState = nextRideState self.requestTimer = requestTimer self.route = route self.chatMessageBadgeCount = chatMessageBadgeCount } public var locationsAndChatMessages: Result<LocationAndChatMessages, NSError>? public var didResolveInitialLocation = false // Children states public var mapFeatureState = MapFeatureState( riders: [], userTrackingMode: UserTrackingState(userTrackingMode: .follow) ) public var socialState = SocialState() public var settingsState = SettingsState() public var nextRideState = NextRideState() public var requestTimer = RequestTimerState() // Navigation public var route: AppRoute? public var isChatViewPresented: Bool { route == .chat } public var isRulesViewPresented: Bool { route == .rules } public var isSettingsViewPresented: Bool { route == .settings } public var chatMessageBadgeCount: UInt = 0 public var hasConnectivity = true } // MARK: Actions public enum AppAction: Equatable { case appDelegate(AppDelegateAction) case onAppear case onDisappear case fetchData case fetchDataResponse(Result<LocationAndChatMessages, NSError>) case userSettingsLoaded(Result<UserSettings, NSError>) case observeConnection case observeConnectionResponse(NetworkPath) case setNavigation(tag: AppRoute.Tag?) case dismissSheetView case map(MapFeatureAction) case nextRide(NextRideAction) case requestTimer(RequestTimerAction) case settings(SettingsAction) case social(SocialAction) } // MARK: Environment public struct AppEnvironment { let locationsAndChatDataService: LocationsAndChatDataService let uuid: () -> UUID let date: () -> Date var userDefaultsClient: UserDefaultsClient var nextRideService: NextRideService var service: LocationsAndChatDataService var idProvider: IDProvider var mainQueue: AnySchedulerOf<DispatchQueue> var backgroundQueue: AnySchedulerOf<DispatchQueue> var locationManager: ComposableCoreLocation.LocationManager var uiApplicationClient: UIApplicationClient var fileClient: FileClient public var setUserInterfaceStyle: (UIUserInterfaceStyle) -> Effect<Never, Never> let pathMonitorClient: PathMonitorClient public init( locationsAndChatDataService: LocationsAndChatDataService = .live(), service: LocationsAndChatDataService = .live(), idProvider: IDProvider = .live(), mainQueue: AnySchedulerOf<DispatchQueue> = .main, backgroundQueue: AnySchedulerOf<DispatchQueue> = DispatchQueue(label: "background-queue").eraseToAnyScheduler(), locationManager: ComposableCoreLocation.LocationManager = .live, nextRideService: NextRideService = .live(), userDefaultsClient: UserDefaultsClient = .live(), uuid: @escaping () -> UUID = UUID.init, date: @escaping () -> Date = Date.init, uiApplicationClient: UIApplicationClient, fileClient: FileClient = .live, setUserInterfaceStyle: @escaping (UIUserInterfaceStyle) -> Effect<Never, Never>, pathMonitorClient: PathMonitorClient = .live(queue: .main) ) { self.locationsAndChatDataService = locationsAndChatDataService self.service = service self.idProvider = idProvider self.mainQueue = mainQueue self.backgroundQueue = backgroundQueue self.locationManager = locationManager self.nextRideService = nextRideService self.userDefaultsClient = userDefaultsClient self.uuid = uuid self.date = date self.uiApplicationClient = uiApplicationClient self.fileClient = fileClient self.setUserInterfaceStyle = setUserInterfaceStyle self.pathMonitorClient = pathMonitorClient } } extension AppEnvironment { public static let live = Self( service: .live(), idProvider: .live(), mainQueue: .main, uiApplicationClient: .live, setUserInterfaceStyle: { userInterfaceStyle in .fireAndForget { UIApplication.shared.firstWindowSceneWindow?.overrideUserInterfaceStyle = userInterfaceStyle } } ) } // MARK: Reducer struct ObserveConnectionIdentifier: Hashable {} /// Holds the logic for the AppFeature to update state and execute side effects public let appReducer = Reducer<AppState, AppAction, AppEnvironment>.combine( mapFeatureReducer.pullback( state: \.mapFeatureState, action: /AppAction.map, environment: { MapFeatureEnvironment( locationManager: $0.locationManager, mainQueue: $0.mainQueue ) } ), requestTimerReducer.pullback( state: \.requestTimer, action: /AppAction.requestTimer, environment: { RequestTimerEnvironment( mainQueue: $0.mainQueue ) } ), nextRideReducer.pullback( state: \.nextRideState, action: /AppAction.nextRide, environment: { NextRideEnvironment( service: $0.nextRideService, store: $0.userDefaultsClient, now: $0.date, mainQueue: $0.mainQueue, coordinateObfuscator: .live ) } ), settingsReducer.pullback( state: \.settingsState, action: /AppAction.settings, environment: { SettingsEnvironment( uiApplicationClient: $0.uiApplicationClient, setUserInterfaceStyle: $0.setUserInterfaceStyle, fileClient: $0.fileClient, backgroundQueue: $0.backgroundQueue, mainQueue: $0.mainQueue ) } ), socialReducer.pullback( state: \.socialState, action: /AppAction.social, environment: { SocialEnvironment( mainQueue: $0.mainQueue, uiApplicationClient: $0.uiApplicationClient, locationsAndChatDataService: $0.locationsAndChatDataService, idProvider: $0.idProvider, uuid: $0.uuid, date: $0.date, userDefaultsClient: $0.userDefaultsClient ) } ), Reducer { state, action, environment in switch action { case let .appDelegate(appDelegateAction): return .none case .onAppear: return .merge( Effect(value: .observeConnection), environment.fileClient .loadUserSettings() .map(AppAction.userSettingsLoaded), Effect(value: .map(.onAppear)), Effect(value: .requestTimer(.startTimer)) ) case .onDisappear: return Effect.cancel(id: ObserveConnectionIdentifier()) case .fetchData: struct GetLocationsId: Hashable {} let postBody = SendLocationAndChatMessagesPostBody( device: environment.idProvider.id(), location: state.settingsState.userSettings.enableObservationMode ? nil : Location(state.mapFeatureState.location) ) guard state.hasConnectivity else { logger.info("AppAction.fetchData not executed. Not connected to internet") return .none } return environment.service .getLocationsAndSendMessages(postBody) .receive(on: environment.mainQueue) .catchToEffect() .map(AppAction.fetchDataResponse) .cancellable(id: GetLocationsId()) case let .fetchDataResponse(.success(response)): state.locationsAndChatMessages = .success(response) state.socialState.chatFeautureState.chatMessages = .results(response.chatMessages) state.mapFeatureState.riderLocations = response.riderLocations if !state.isChatViewPresented { let cachedMessages = response.chatMessages .values .sorted(by: \.timestamp) let unreadMessagesCount = UInt( cachedMessages .lazy .filter { $0.timestamp > environment.userDefaultsClient.chatReadTimeInterval() } .count ) state.chatMessageBadgeCount = unreadMessagesCount } return .none case let .fetchDataResponse(.failure(error)): logger.info("FetchData failed: \(error)") state.locationsAndChatMessages = .failure(error) return .none case .observeConnection: return Effect(environment.pathMonitorClient.networkPathPublisher) .receive(on: environment.mainQueue) .eraseToEffect() .map(AppAction.observeConnectionResponse) .cancellable(id: ObserveConnectionIdentifier()) case let .observeConnectionResponse(networkPath): state.hasConnectivity = networkPath.status == .satisfied state.nextRideState.hasConnectivity = state.hasConnectivity logger.info("Is connected: \(state.hasConnectivity)") return .none case let .map(mapFeatureAction): switch mapFeatureAction { case let .locationManager(locationManagerAction): switch locationManagerAction { case .didUpdateLocations: if !state.didResolveInitialLocation { state.didResolveInitialLocation.toggle() if let coordinate = Coordinate(state.mapFeatureState.location), state.settingsState.userSettings.rideEventSettings.isEnabled { return Effect.merge( Effect(value: .fetchData), Effect(value: .nextRide(.getNextRide(coordinate))) ) } else { return Effect(value: .fetchData) } } else { return .none } default: return .none } default: return .none } case let .nextRide(nextRideAction): switch nextRideAction { case let .setNextRide(ride): state.mapFeatureState.nextRide = ride return Effect.concatenate( Effect(value: .map(.setNextRideBannerVisible(true))), Effect(value: .map(.setNextRideBannerExpanded(true))) .delay(for: 1.2, scheduler: environment.mainQueue) .eraseToEffect(), Effect(value: .map(.setNextRideBannerExpanded(false))) .delay(for: 10, scheduler: environment.mainQueue) .eraseToEffect() ) default: return .none } case let .userSettingsLoaded(result): state.settingsState.userSettings = (try? result.get()) ?? UserSettings() return .merge( environment.setUserInterfaceStyle(state.settingsState.userSettings.appearanceSettings.colorScheme.userInterfaceStyle) // NB: This is necessary because UIKit needs at least one tick of the run loop before we // can set the user interface style. .subscribe(on: environment.mainQueue) .fireAndForget() ) case .setNavigation(tag: let tag): switch tag { case .chat: state.route = .chat case .rules: state.route = .rules case .settings: state.route = .settings case .none: state.route = .none } return .none case .dismissSheetView: state.route = .none return .none case let .requestTimer(timerAction): switch timerAction { case .timerTicked: return Effect(value: .fetchData) default: return .none } case let .social(socialAction): switch socialAction { case .chat(.onAppear): state.chatMessageBadgeCount = 0 return .none default: return .none } case let .settings(settingsAction): switch settingsAction { case .rideevent(let .setRideEventsEnabled(isEnabled)): if !isEnabled { return Effect(value: .map(.setNextRideBannerVisible(false))) } else { return .none } default: return .none } } } ) .onChange(of: \.settingsState.userSettings.rideEventSettings) { rideEventSettings, state, _, environment in struct RideEventSettingsChange: Hashable {} // fetch next ride after settings have changed if let coordinate = Coordinate(state.mapFeatureState.location), rideEventSettings.isEnabled { return Effect(value: .nextRide(.getNextRide(coordinate))) .debounce(id: RideEventSettingsChange(), for: 1.5, scheduler: environment.mainQueue) } else { return .none } } extension SharedModels.Location { /// Creates a Location object from an optional ComposableCoreLocation.Location init?(_ location: ComposableCoreLocation.Location?) { guard let location = location else { return nil } self = SharedModels.Location( coordinate: Coordinate( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ), timestamp: location.timestamp.timeIntervalSince1970 ) } } extension SharedModels.Coordinate { /// Creates a Location object from an optional ComposableCoreLocation.Location init?(_ location: ComposableCoreLocation.Location?) { guard let location = location else { return nil } self = Coordinate( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ) } }
mit
8b3f641b17af6626c34f201ab76ade35
30.883146
138
0.682267
4.829135
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/iOSDCJP2016/EntityCellMapper.swift
1
1816
// // EntityCellMapper.swift // iOSDCJP2016 // // Created by hayashi311 on 6/8/16. // Copyright © 2016 hayashi311. All rights reserved. // import UIKit typealias SpeakerEntity = Speaker typealias SessionEntity = Session enum AnyEntity { case Speaker(speaker: SpeakerEntity) case Session(session: SessionEntity) var cellId: String { get { switch self { case .Speaker: return "SpeakerCell" case .Session: return "SessionCell" } } } } protocol EntityCellMapper: class, UITableViewDataSource { func entityAtIndexPath(index: NSIndexPath) -> AnyEntity? func numberOfSections() -> Int func numberOfEntitiesInSection(section: Int) -> Int } extension EntityCellMapper { func numberOfSections() -> Int { return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return numberOfSections() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfEntitiesInSection(section) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let entity = entityAtIndexPath(indexPath), let cell = tableView.dequeueReusableCellWithIdentifier(entity.cellId) else { return UITableViewCell() } switch (cell, entity) { case let (c as SpeakerTableViewCell, .Speaker(s)): c.nameLabel.text = s.name c.twitterAccountLabel.text = s.twitterAccount case let (c as SessionTableViewCell, .Session(s)): c.titleLabel.text = s.title default: break } return cell } }
mit
ad821adacbd5b3a68c3e7a644a18cf36
25.691176
109
0.62259
4.932065
false
false
false
false
135yshr/twift
Twift/TimelineViewController.swift
1
3246
// // TimelineViewController.swift // Twift // // Created by 135yshr on 2014/06/04. // Copyright (c) 2014 135yshr. All rights reserved. // import UIKit import Twitter import Accounts class TimelineViewController: UITableViewController { var statuses = NSArray() override func viewDidLoad() { super.viewDidLoad() let accountStore = ACAccountStore() let twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) let handler: ACAccountStoreRequestAccessCompletionHandler = {granted, error in if(!granted) { NSLog("ユーザーがアクセスを拒否しました。") return } let twitterAccounts = accountStore.accountsWithAccountType(twitterAccountType) if(twitterAccounts.count > 0){ let account = twitterAccounts[0] as ACAccount let url = NSURL.URLWithString("https://api.twitter.com/1/statuses/home_timeline.json") let hendler: TWRequestHandler = {responseData, urlRes, error in if(responseData == nil) { NSLog("\(error)") return } var error: NSErrorPointer = nil self.statuses = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: error) as NSArray if(self.statuses == nil) { NSLog("\(error)") return } dispatch_async(dispatch_get_main_queue(), {self.tableView.reloadData()}) } let request = TWRequest(URL: url, parameters: nil, requestMethod: TWRequestMethod.GET) request.account = account request.performRequestWithHandler(hendler) } } accountStore.requestAccessToAccountsWithType(twitterAccountType, handler) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return statuses.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let CellIdentifier = "Cell" var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: CellIdentifier) cell.textLabel.font = UIFont.systemFontOfSize(11.0) let status: NSDictionary! = statuses[indexPath.row] as NSDictionary! let text = status.objectForKey("text") as String cell.textLabel.text = text return cell } @IBAction func pressComposeButton() { if(TWTweetComposeViewController.canSendTweet()) { let composeViewController = TWTweetComposeViewController() self.presentModalViewController(composeViewController, animated: true) } } }
mit
63255edf1187a6068db8a12f3ef4ffbf
35.5
114
0.611146
5.674912
false
false
false
false
carabina/Lantern
LanternModel/PageMapper+InfoPresenting.swift
1
7426
// // PageMapper+InfoPresenting.swift // Hoverlytics // // Created by Patrick Smith on 28/04/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Foundation import Ono extension NSURL { var burnt_pathWithQuery: String? { if let path = path { if let query = query { return "\(path)?\(query)" } else { return path } } return nil } } public enum PagePresentedInfoIdentifier: String { case requestedURL = "requestedURL" case statusCode = "statusCode" case MIMEType = "MIMEType" case pageTitle = "pageTitle" case h1 = "h1" case metaDescription = "metaDescription" case pageByteCount = "pageByteCount" case pageByteCountBeforeBodyTag = "pageBeforeBodyTagBytes" case pageByteCountAfterBodyTag = "pageAfterBodyTagBytes" case internalLinkCount = "internalLinkCount" case internalLinks = "internalLinks" case externalLinkCount = "externalLinkCount" case externalLinks = "externalLinks" public var longerFormInformation: PagePresentedInfoIdentifier? { switch self { case .internalLinkCount: return .internalLinks case .externalLinkCount: return .externalLinks default: return nil } } public func titleForBaseContentType(baseContentType: BaseContentType?) -> String { switch self { case .requestedURL: if let baseContentType = baseContentType { switch baseContentType { case .LocalHTMLPage: return "Page URL" case .Image: return "Image URL" case .Feed: return "Feed URL" default: break } } return "URL" case .statusCode: return "Status Code" case .MIMEType: return "MIME Type" case .pageTitle: return "Title" case .h1: return "H1" case .metaDescription: return "Meta Description" case .pageByteCount: return "Total Bytes" case .pageByteCountBeforeBodyTag: return "<head> Bytes" case .pageByteCountAfterBodyTag: return "<body> Bytes" case .internalLinkCount, .internalLinks: return "Internal Links" case .externalLinkCount, .externalLinks: return "External Links" } } private func stringValueForMultipleElementsContent(elements: [ONOXMLElement]) -> String? { switch elements.count { case 1: let element = elements[0] var stringValue = element.stringValue() // Conforms spaces and new lines into single spaces stringValue = stringValue.stringByReplacingOccurrencesOfString("[\\s]+", withString: " ", options: .RegularExpressionSearch, range: nil) // Trim whitespace from ends let whitespaceCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() stringValue = stringValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return stringValue case 0: return nil default: return "(multiple)" } } private func stringValueForMultipleElements(elements: [ONOXMLElement], attribute: String) -> String? { switch elements.count { case 1: let element = elements[0] if let stringValue = element[attribute] as? String { return stringValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } else { return nil } case 0: return nil default: return "(multiple)" } } private static var byteFormatter: NSByteCountFormatter = { let byteFormatter = NSByteCountFormatter() byteFormatter.countStyle = .Binary byteFormatter.adaptive = false return byteFormatter }() public func validatedStringValueForPendingURL(requestedURL: NSURL) -> ValidatedStringValue { switch self { case .requestedURL: #if DEBUG && false return ValidatedStringValue(string: "\(requestedURL)") #endif if let requestedPath = requestedURL.burnt_pathWithQuery { return ValidatedStringValue(string: requestedPath) } default: break } return .Missing } public func validatedStringValueInPageInfo(pageInfo: PageInfo, pageMapper: PageMapper) -> ValidatedStringValue { switch self { case .requestedURL: let requestedURL = pageInfo.requestedURL if let requestedPath = pageInfo.requestedURL.burnt_pathWithQuery { if let finalURL = pageInfo.finalURL, let finalURLPath = finalURL.burnt_pathWithQuery where requestedURL.absoluteString != finalURL.absoluteString { if let redirectionInfo = pageMapper.redirectedDestinationURLToInfo[finalURL] { return ValidatedStringValue(string: "\(requestedPath) (\(finalURLPath))") } if let requestedScheme = requestedURL.scheme, let finalScheme = finalURL.scheme { if requestedScheme != finalScheme { return ValidatedStringValue(string: "\(requestedPath) (\(finalURLPath) to \(finalScheme))") } } return ValidatedStringValue(string: "\(requestedPath) (\(finalURLPath))") } #if DEBUG && false return ValidatedStringValue(string: "\(requestedURL) \(pageInfo.finalURL)") #endif return ValidatedStringValue(string: requestedPath) } case .statusCode: return ValidatedStringValue(string: String(pageInfo.statusCode)) case .MIMEType: if let MIMEType = pageInfo.MIMEType?.stringValue { return ValidatedStringValue( string: MIMEType ) } case .pageTitle: if let pageTitleElements = pageInfo.contentInfo?.pageTitleElements { return ValidatedStringValue.validateContentOfElements(pageTitleElements) } case .h1: if let h1Elements = pageInfo.contentInfo?.h1Elements { return ValidatedStringValue.validateContentOfElements(h1Elements) } case .metaDescription: if let metaDescriptionElements = pageInfo.contentInfo?.metaDescriptionElements { return ValidatedStringValue.validateAttribute("content", ofElements: metaDescriptionElements) } case .pageByteCount: if let byteCount = pageInfo.byteCount { return ValidatedStringValue( string: PagePresentedInfoIdentifier.byteFormatter.stringFromByteCount(Int64(byteCount)) ) } else { return .NotRequested } case .pageByteCountBeforeBodyTag: if let byteCountBeforeBody = pageInfo.contentInfo?.preBodyByteCount { return ValidatedStringValue( string: PagePresentedInfoIdentifier.byteFormatter.stringFromByteCount(Int64(byteCountBeforeBody)) ) } case .pageByteCountAfterBodyTag: if let byteCount = pageInfo.byteCount, byteCountBeforeBody = pageInfo.contentInfo?.preBodyByteCount { return ValidatedStringValue( string: PagePresentedInfoIdentifier.byteFormatter.stringFromByteCount(Int64(byteCount - byteCountBeforeBody)) ) } case .internalLinkCount: if let localPageURLs = pageInfo.contentInfo?.localPageURLs { return ValidatedStringValue( string: String(localPageURLs.count) ) } case .internalLinks: if let localPageURLs = pageInfo.contentInfo?.localPageURLs { return ValidatedStringValue.Multiple( localPageURLs.map { URL in ValidatedStringValue( string: URL.absoluteString ) } ) } case .externalLinkCount: if let externalPageURLs = pageInfo.contentInfo?.externalPageURLs { return ValidatedStringValue( string: String(externalPageURLs.count) ) } case .externalLinks: if let externalPageURLs = pageInfo.contentInfo?.externalPageURLs { return ValidatedStringValue.Multiple( externalPageURLs.map { URL in ValidatedStringValue( string: URL.absoluteString ) } ) } } return .Missing } }
apache-2.0
b6de263e468407070cd3dfa16c32b2cd
27.026415
139
0.724212
3.937434
false
false
false
false
shafiullakhan/LaunchFromBrowser
LaunchFromBrowser_Swift/LaunchFromBrowser_Swift/MasterViewController.swift
1
1714
// // MasterViewController.swift // LaunchFromBrowser_Swift // // Created by Shafi on 09/07/15. // Copyright (c) 2015 Shaffiulla. All rights reserved. // import UIKit class MasterViewController: UITableViewController { // String to be displayed on Detail Screen var detailScreenText:String = "" ; var numberOfRow:Int = 5; var isFromBrowser:Bool = false; override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() } 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 == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { self.detailScreenText = (!self.isFromBrowser) ? "Normal Navigation from Master To Detail Page for Row :\(indexPath.row + 1)" : self.detailScreenText; } (segue.destinationViewController as! DetailViewController).detailItem = self.detailScreenText } } func refreshTableView(){ self.tableView.reloadData() } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfRow } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let cellTitle = "Row : \(indexPath.row + 1)"; cell.textLabel!.text = cellTitle return cell } }
mit
c7d2be18fa243a4ee2fcbe27928fc207
25.369231
153
0.738623
4.13012
false
false
false
false
ByteriX/BxInputController
BxInputController/Sources/Decorators/BxInputStandartErrorRowDecorator.swift
1
4949
/** * @file BxInputStandartErrorRowDecorator.swift * @namespace BxInputController * * @details Standart decoration for showing error message in row * @date 24.04.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit import BxObjC import BxTextField /// Standart decoration for showing error message in row open class BxInputStandartErrorRowDecorator : BxInputRowDecorator { /// highlighed color for marking a value. If is nil then get value from BxInputSettings Default nil. public var color : UIColor? = nil /// if is defined, will change existing placeholder of value to this value public var placeholder : String? = nil /// if is defined, will change existing subtitle of row to this value. public var subtitle : String? = nil // default init public init() { // } /// method will return view when will use to foregen changes: Shake for example open func getForegenView(binder: BxInputRowBinder) -> UIView? { var view: UIView? = nil // First searching if let cell = binder.viewCell as? BxInputFieldCell, let text = cell.valueTextField.text, text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty == false || text.isEmpty == true && cell.valueTextField.placeholder?.isEmpty == false { view = cell.valueTextField } else if let cell = binder.viewCell as? BxInputTitleCell, let text = cell.titleLabel.text, text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty == false { view = cell.titleLabel } else if let cell = binder.viewCell as? BxInputTextMemoCell { view = cell.textView } // Last chance find view if view == nil, let cell = binder.viewCell as? BxInputFieldCell { view = cell.valueTextField } return view } /// method calls when need show activation of something event open func activate(binder: BxInputRowBinder) { // common changes UIView.animate(withDuration: 0.5) { [weak self] in self?.update(binder: binder) } // foregen changes with views let view: UIView? = getForegenView(binder: binder) if let view = view, binder.owner?.settings.isErrorHasShake ?? false { DispatchQueue.main.async { let shift = view.frame.size.height * 2 view.shakeX(withOffset: abs(shift), breakFactor: 0.5, duration: 0.5 + abs(shift / 100.0), maxShakes: Int(abs(shift * 2.0))) } } } /// method calls when binder update row open func update(binder: BxInputRowBinder) { var color = UIColor.red if let thisColor = self.color { color = thisColor } else if let globalColor = binder.owner?.settings.errorColor { color = globalColor } if let cell = binder.viewCell as? BxInputTitleCell { cell.titleLabel.textColor = color if let cell = binder.viewCell as? BxInputFieldCell { cell.valueTextField.textColor = color var placeholder = self.placeholder if placeholder == nil { placeholder = binder.rowData.placeholder } if let placeholder = placeholder { cell.valueTextField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [BxTextField.attributedKeyForegroundColor : color.withAlphaComponent(0.3)]) } } if let subtitleLabel = cell.subtitleLabel { subtitleLabel.textColor = color if let errorSubtitleAlignment = binder.owner?.settings.errorSubtitleAlignment { subtitleLabel.textAlignment = errorSubtitleAlignment } if let subtitle = subtitle { subtitleLabel.text = subtitle } } } else if let cell = binder.viewCell as? BxInputTextMemoCell { cell.textView.textColor = color var placeholder = self.placeholder if placeholder == nil { placeholder = binder.rowData.placeholder } if let placeholder = placeholder { cell.textView.placeholderColor = color.withAlphaComponent(0.3) cell.textView.placeholder = placeholder } } } /// method calls when need show activation of something event open func deactivate(binder: BxInputRowBinder) { binder.update() } }
mit
059af1b4058ff58c050119448d4f73c2
37.069231
191
0.605375
4.919483
false
false
false
false
muukii0803/PhotosPicker
PhotosPicker/Sources/PhotosPickerAssets.swift
2
5753
// PhotosPickerAssets.swift // // Copyright (c) 2015 muukii // // 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 Photos import AssetsLibrary import CoreLocation public protocol PhotosPickerAssets { func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) func enumerateAssetsUsingBlock(block: ((asset: PhotosPickerAsset) -> Void)?) } public class PhotosPickerAssetsGroup: PhotosPickerAssets { public private(set) var assets : [PhotosPickerAsset] = [] public init(assets: [PhotosPickerAsset]) { self.assets = assets } public func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in let dividedAssets = divideByDay(dateSortedAssets: self) dispatch_async(dispatch_get_main_queue(), { () -> Void in result?(dividedAssets: dividedAssets) }) }) } public func enumerateAssetsUsingBlock(block: ((asset: PhotosPickerAsset) -> Void)?) { let sortedAssets = self.assets.sorted({ $0.creationDate.compare($1.creationDate) == NSComparisonResult.OrderedDescending }) for asset in sortedAssets { block?(asset: asset) } } } extension PHFetchResult: PhotosPickerAssets { public func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in let dividedAssets = divideByDay(dateSortedAssets: self) dispatch_async(dispatch_get_main_queue(), { () -> Void in result?(dividedAssets: dividedAssets) }) }) } public func enumerateAssetsUsingBlock(block: ((asset: PhotosPickerAsset) -> Void)?) { self.enumerateObjectsUsingBlock { (asset, index, stop) -> Void in if let asset = asset as? PHAsset { block?(asset: asset) } } } } extension ALAssetsGroup: PhotosPickerAssets { public func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in let dividedAssets = divideByDay(dateSortedAssets: self) dispatch_async(dispatch_get_main_queue(), { () -> Void in result?(dividedAssets: dividedAssets) }) }) } public func enumerateAssetsUsingBlock(block: ((asset: PhotosPickerAsset) -> Void)?) { self.enumerateAssetsUsingBlock { (asset, index, stop) -> Void in block?(asset: asset) } } } public typealias DividedDayPhotosPickerAssets = [DayPhotosPickerAssets] public struct DayPhotosPickerAssets: Printable { public var date: NSDate public var assets: [PhotosPickerAsset] = [] public init(date: NSDate, assets: [PhotosPickerAsset] = []) { self.date = date self.assets = assets } public var description: String { var string: String = "\n Date:\(date) \nAssets: \(assets) \n" return string } } private func divideByDay(#dateSortedAssets: PhotosPickerAssets) -> DividedDayPhotosPickerAssets { var dayAssets = DividedDayPhotosPickerAssets() var tmpDayAsset: DayPhotosPickerAssets! var processingDate: NSDate! dateSortedAssets.enumerateAssetsUsingBlock { (asset) -> Void in processingDate = dateWithOutTime(asset.creationDate) if tmpDayAsset != nil && processingDate.isEqualToDate(tmpDayAsset!.date) == false { dayAssets.append(tmpDayAsset!) tmpDayAsset = nil } if tmpDayAsset == nil { tmpDayAsset = DayPhotosPickerAssets(date: processingDate) } tmpDayAsset.assets.append(asset) } return dayAssets } private func dateWithOutTime(date: NSDate!) -> NSDate { let calendar: NSCalendar = NSCalendar.currentCalendar() let units: NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay let comp: NSDateComponents = calendar.components(units, fromDate: date) return calendar.dateFromComponents(comp)! }
mit
5297fedb1f4a43ecba4bfe8c95428d3d
32.841176
131
0.640188
4.867174
false
false
false
false
LacieJiang/Custom-2048
Custom-2048/Custom-2048/Models/GameModel.swift
1
14386
// // GameModel.swift // Custom-2048 // // Created by liyinjiang on 6/17/14. // import UIKit enum MoveDirection: NSInteger { case Up case Down case Left case Right } protocol GameModelProtocol { func scoreChanged(newScore: Int) func moveOneTile(#from: (Int, Int), to: (Int, Int), value: Int) func moveTwoTiles(#from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int) func insertTile(at: (Int, Int), value: Int) } class GameModel: NSObject { var score: Int = 0 { didSet { self.delegate.scoreChanged(score) } } let dimension: Int let winValue: Int let delegate: GameModelProtocol var gameState: TileModel[] var commandQueue: MoveCommand[] var timer: NSTimer let maxCommands = 100 let queueDelay = 0.3 init(dimension d: Int, winValue w: Int, delegate: GameModelProtocol) { self.dimension = d self.winValue = w self.delegate = delegate self.gameState = TileModel[]() for i in 0..dimension { for j in 0..dimension { self.gameState.append(TileModel()) } } self.commandQueue = MoveCommand[]() self.timer = NSTimer() super.init() } func reset() { self.score = 0 self.gameState.removeAll(keepCapacity: true) self.timer.invalidate() } func userHasWon() -> (Int, Int)? { for i in 0..self.gameState.count { let tileModel = self.gameState[i]; if tileModel.value == self.winValue { return (i / self.dimension, i % self.dimension) } } return nil } func userHasLost() -> Bool { for i in 0..self.gameState.count { if self.gameState[i].empty { return false } } for i in 0..self.dimension { for j in 0..self.dimension { let tile = self.tileFor((i, j)) if (j != self.dimension - 1 && tile.value == self.tileFor((i, j + 1)).value) { return false } if (i != self.dimension - 1 && tile.value == self.tileFor((i + 1, j)).value) { return false } } } return true } // insert func insertAtRandomLocationTileWith(value: Int) { var openSpots = gameboardEmptySpots() if (openSpots.count == 0) { return } let idx = Int(arc4random_uniform(UInt32(openSpots.count - 1))) let (x, y) = openSpots[idx] insertTile((x, y), value: value) } func insertTile(at: (Int, Int), value: Int) { let tileModel = self.tileFor(at) if (!tileModel.empty) { return } tileModel.empty = false tileModel.value = value self.delegate.insertTile(at, value: value) } // move func performUpMove() -> Bool { var atLeastOneMove = false for column in 0..self.dimension { var thisColumnTiles: TileModel[] = TileModel[]() for row in 0..self.dimension { thisColumnTiles.append(self.tileFor((row, column))) } var ordersArray = self.merge(thisColumnTiles) if ordersArray.count > 0 { atLeastOneMove = true for i in 0..ordersArray.count { var order = ordersArray[i] if order.doubleMove { let source1 = (order.source1, column) let source2 = (order.source2, column) let destination = (order.destination, column) var source1Tile = self.tileFor(source1) source1Tile.empty = true var source2Tile = self.tileFor(source2) source2Tile.empty = true var destinationTile = self.tileFor(destination) destinationTile.value = order.value destinationTile.empty = false self.delegate.moveTwoTiles(from: (source1, source2), to: destination, value: destinationTile.value) } else { let source = (order.source1, column) let destination = (order.destination, column) var sourceTile = self.tileFor(source) sourceTile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveOneTile(from: source, to: destination, value: destinationTile.value) } } } } return atLeastOneMove } func performDownMove() -> Bool { var atLeastOneMove = false for column in 0..self.dimension { var thisColumnTiles: TileModel[] = TileModel[]() for (var row = (self.dimension - 1); row >= 0; --row) { thisColumnTiles.append(self.tileFor((row, column))) } var ordersArray = self.merge(thisColumnTiles) if ordersArray.count > 0 { atLeastOneMove = true for i in 0..ordersArray.count { let dim = self.dimension - 1 var order = ordersArray[i] if order.doubleMove { let source1 = (dim - order.source1, column) let source2 = (dim - order.source2, column) let destination = (dim - order.destination, column) var source1Tile = self.tileFor(source1) source1Tile.empty = true var source2Tile = self.tileFor(source2) source2Tile.empty = true var destinationTile = self.tileFor(destination) destinationTile.value = order.value destinationTile.empty = false self.delegate.moveTwoTiles(from: (source1, source2), to: destination, value: destinationTile.value) } else { let source = (dim - order.source1, column) let destination = (dim - order.destination, column) var sourceTile = self.tileFor(source) sourceTile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveOneTile(from: source, to: destination, value: destinationTile.value) } } } } return atLeastOneMove } func performLeftMove() -> Bool { var atLeastOneMove = false for row in 0..self.dimension { var thisRowTiles: TileModel[] = TileModel[]() for column in 0..self.dimension { thisRowTiles.append(self.tileFor((row, column))) } var ordersArray: MoveOrder[] = self.merge(thisRowTiles) if ordersArray.count > 0 { atLeastOneMove = true for i in 0..ordersArray.count { var order = ordersArray[i] if order.doubleMove { let source1 = (row, order.source1) let source2 = (row, order.source2) let destination = (row, order.destination) var source1Tile = self.tileFor(source1) source1Tile.empty = true var source2Tile = self.tileFor(source2) source2Tile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveTwoTiles(from: (source1, source2), to: destination, value: order.value) } else { let source = (row, order.source1) let destination = (row, order.destination) var sourceTile = self.tileFor(source) sourceTile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveOneTile(from: source, to: destination, value: order.value) } } } } return atLeastOneMove } func performRightMove() -> Bool { var atLeastOneMove = false for row in 0..self.dimension { var thisRowTiles: TileModel[] = TileModel[]() for (var column = self.dimension - 1; column >= 0; --column) { thisRowTiles.append(self.tileFor((row, column))) } var ordersArray = self.merge(thisRowTiles) if ordersArray.count > 0 { var dim = self.dimension - 1 atLeastOneMove = true for i in 0..ordersArray.count { let order = ordersArray[i] if order.doubleMove { let source1 = (row, dim - order.source1) let source2 = (row, dim - order.source2) let destination = (row, dim - order.destination) var source1Tile = self.tileFor(source1) source1Tile.empty = true var source2Tile = self.tileFor(source2) source2Tile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveTwoTiles(from: (source1, source2), to: destination, value: order.value) } else { let source = (row, dim - order.source1) let destination = (row, dim - order.destination) var sourceTile = self.tileFor(source) sourceTile.empty = true var destinationTile = self.tileFor(destination) destinationTile.empty = false destinationTile.value = order.value self.delegate.moveOneTile(from: source, to: destination, value: order.value) } } } } return atLeastOneMove } // private func moveCommand(direction d: MoveDirection, completion t: (Bool) -> ()) { if self.commandQueue.count > maxCommands { return } let command = MoveCommand(moveDirection: d, completionFunc: t) self.commandQueue.append(command) if !timer.valid { self.timerFired(timer) } } func timerFired(timer: NSTimer) { if self.commandQueue.count == 0 { return } var changed = false while self.commandQueue.count > 0 { let command = self.commandQueue[0] self.commandQueue.removeAtIndex(0) switch command.direction { case .Up: changed = self.performUpMove() case .Down: changed = self.performDownMove() case .Left: changed = self.performLeftMove() case .Right: changed = self.performRightMove() } command.completion(changed) if changed { break } } self.timer = NSTimer.scheduledTimerWithTimeInterval(self.queueDelay, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: false) } func merge(group: TileModel[]) -> MoveOrder[] { var ctr: Int = 0 // STEP 1: collapse all tiles (remove any interstital space) // e.g. |[2] [ ] [ ] [4]| becomes [[2] [4]| // At this point, tiles either move or don't move, and their value remains the same var stack1: MergeTile[] = MergeTile[]() for i in 0..self.dimension { let tile = group[i] if tile.empty { continue } var mergeTile = MergeTile() mergeTile.originalIndexA = i mergeTile.value = tile.value if i == ctr { mergeTile.mode = MergeTileMode.NoAction } else { mergeTile.mode = MergeTileMode.Move } stack1.append(mergeTile) ctr++ } if stack1.count == 0 { return MoveOrder[]() } else if stack1.count == 1 { if stack1[0].mode == MergeTileMode.Move { var mergeTile = stack1[0] as MergeTile return [MoveOrder.singleMoveOrderWithSource(mergeTile.originalIndexA, destination: 0, newValue: mergeTile.value)] } else { return MoveOrder[]() } } // STEP 2: starting from the left, and moving to the right, collapse tiles // e.g. |[8][8][4][2][2]| should become |[16][4][4]| // e.g. |[2][2][2]| should become |[4][2]| // At this point, tiles may become the subject of a single or double merge ctr = 0 var priorMergeHasHappened = false var stack2: MergeTile[] = MergeTile[]() while (ctr < stack1.count - 1) { var mergeTile1 = stack1[ctr] as MergeTile var mergeTile2 = stack1[ctr + 1] as MergeTile if mergeTile1.value == mergeTile2.value { assert(mergeTile1.mode != MergeTileMode.SingleCombine && mergeTile2.mode != MergeTileMode.SingleCombine && mergeTile1.mode != MergeTileMode.DoubleCombine && mergeTile2.mode != MergeTileMode.DoubleCombine, "Should not be able to get in a state where already-combined tiles are recombined") if mergeTile1.mode == MergeTileMode.NoAction && !priorMergeHasHappened { priorMergeHasHappened = true var newTile: MergeTile = MergeTile() newTile.mode = MergeTileMode.SingleCombine newTile.originalIndexA = mergeTile2.originalIndexA newTile.value = mergeTile1.value * 2 self.score += newTile.value stack2.append(newTile) } else { var newTile: MergeTile = MergeTile() newTile.mode = MergeTileMode.DoubleCombine newTile.originalIndexA = mergeTile1.originalIndexA newTile.originalIndexB = mergeTile2.originalIndexA newTile.value = mergeTile1.value * 2 self.score += newTile.value stack2.append(newTile) } ctr += 2 } else { stack2.append(mergeTile1) if stack2.count - 1 != ctr { mergeTile1.mode = MergeTileMode.Move } ctr++ } if ctr == stack1.count - 1 { var item = stack1[ctr] as MergeTile stack2.append(item) if stack2.count - 1 != ctr { item.mode = MergeTileMode.Move } } } // STEP 3: create move orders for each mergeTile that did change this round var stack3: MoveOrder[] = MoveOrder[]() for i in 0..stack2.count { var tile = stack2[i] switch (tile.mode) { case .Empty,.NoAction: continue case .Move, .SingleCombine: stack3.append(MoveOrder.singleMoveOrderWithSource(tile.originalIndexA, destination: i, newValue: tile.value)) case .DoubleCombine: stack3.append(MoveOrder.doubleMoveOrderWithFirstSource(tile.originalIndexA, secondSource: tile.originalIndexB, destination: i, newValue: tile.value)) } } return stack3 } func gameboardEmptySpots() -> (Int, Int)[] { var openSpots = Array<(Int, Int)>() for i in 0..self.dimension { for j in 0..self.dimension { let tileModel = self.tileFor((i, j)) if (tileModel.empty) { openSpots += (i, j) } } } return openSpots } func tileFor(position: (Int, Int)) -> TileModel { let idx: Int = position.0 * self.dimension + position.1 return gameState[idx] } }
bsd-2-clause
adad8474f8243ea4e94fa2e9f1d05a77
32.61215
296
0.605241
3.999444
false
false
false
false
Raizlabs/Geode
Example/View Controllers/RootViewController.swift
1
2951
// // RootViewController.swift // Example // // Created by John Watson on 1/27/16. // // Copyright © 2016 Raizlabs. All rights reserved. // http://raizlabs.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit final class RootViewController: UITableViewController { fileprivate struct Row { let title: String let viewController: UIViewController.Type } fileprivate let reuseIdentifier = "com.raizlabs.geode.view-controller-cell" fileprivate let rows = [ Row(title: "One-shot Location Monitoring", viewController: OneShotViewController.self), Row(title: "Continuous Location Monitoring", viewController: ContinuousViewontroller.self), ] override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Geode" tableView.tableFooterView = UIView() tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier) } } // MARK: - Table View Data Source extension RootViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = rows[(indexPath as NSIndexPath).row] let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) ?? UITableViewCell() cell.textLabel?.text = row.title return cell } } // MARK: - Table View Delegate extension RootViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = rows[(indexPath as NSIndexPath).row] navigationController?.pushViewController(row.viewController.init(), animated: true) } }
mit
39adcc0d369bf93dbc4671b91f750fb7
33.302326
109
0.72
4.765751
false
false
false
false
akupara/Vishnu
Vishnu/Matsya/UIColor+LerpExtension.swift
1
2226
// // UIColor+LerpExtension.swift // Vishnu // // Created by Daniel Lu on 6/15/16. // Copyright © 2016 Daniel Lu. All rights reserved. // import UIKit extension UIColor { private struct Utility { static func lerp(start start: CGFloat, end: CGFloat, faction: CGFloat) -> CGFloat{ return faction * (end - start) + start } } public class func colorInRGBLerpFrom(start start: UIColor, to end:UIColor, withFraction fraction: CGFloat) -> UIColor { let clampedFaction = max(0.0, min(1.0, fraction)) let zero:CGFloat = 0.0 var (red1, green1, blue1, alpha1) = (zero, zero, zero, zero) start.getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1) var (red2, green2, blue2, alpha2) = (zero, zero, zero, zero) end.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2) let r:CGFloat = Utility.lerp(start: red1, end: red2, faction: clampedFaction) let g:CGFloat = Utility.lerp(start: green1, end: green2, faction: clampedFaction) let b:CGFloat = Utility.lerp(start: blue1, end: blue2, faction: clampedFaction) let a:CGFloat = Utility.lerp(start: alpha1, end: alpha2, faction: clampedFaction) return UIColor(red: r, green: g, blue: b, alpha: a) } public class func colorInHSVFrom(start start:UIColor, to end:UIColor, withFaction faction:CGFloat) -> UIColor { let clampedFaction = max(0, min(1, faction)) let zero:CGFloat = 0.0 var (h1, s1, b1, a1) = (zero, zero, zero, zero) start.getHue(&h1, saturation: &s1, brightness: &b1, alpha: &a1) var (h2, s2, b2, a2) = (zero, zero, zero, zero) end.getHue(&h2, saturation: &s2, brightness: &b2, alpha: &a2) let h:CGFloat = Utility.lerp(start: h1, end: h2, faction: clampedFaction) let s:CGFloat = Utility.lerp(start: s1, end: s2, faction: clampedFaction) let b:CGFloat = Utility.lerp(start: b1, end: b2, faction: clampedFaction) let a:CGFloat = Utility.lerp(start: a1, end: a2, faction: clampedFaction) return UIColor(hue: h, saturation: s, brightness: b, alpha: a) } }
mit
4b96751ef227379f92deb849185d2fb7
40.981132
123
0.614831
3.386606
false
false
false
false
sandalsoft/SyncAsync
SyncAsync.playground/Sources/SyncAsync.swift
1
19191
import Foundation // MARK: Utils - private struct Semaphore { let semaphore = dispatch_semaphore_create(0) func signal() { dispatch_semaphore_signal(semaphore) } func wait() { dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } } private let async = { dispatch_async(dispatch_queue_create("", DISPATCH_QUEUE_SERIAL), $0) } // MARK: - toAsync - // MARK: No Error public func toAsync<O>(f: () -> O) -> (completionHandler: O -> ()) -> () { return { ch in async { ch(f()) } } } public func toAsync<I0, O>(f: (I0) -> O) -> (I0, completionHandler: O -> ()) -> () { return { i0, ch in async { ch(f(i0)) } } } public func toAsync<I0, I1, O>(f: (I0, I1) -> O) -> (I0, I1, completionHandler: O -> ()) -> () { return { i0, i1, ch in async { ch(f(i0, i1)) } } } public func toAsync<I0, I1, I2, O>(f: (I0, I1, I2) -> O) -> (I0, I1, I2, completionHandler: O -> ()) -> () { return { i0, i1, i2, ch in async { ch(f(i0, i1, i2)) } } } public func toAsync<I0, I1, I2, I3, O>(f: (I0, I1, I2, I3) -> O) -> (I0, I1, I2, I3, completionHandler: O -> ()) -> () { return { i0, i1, i2, i3, ch in async { ch(f(i0, i1, i2, i3)) } } } // MARK: - Error public func toAsync<O>(f: () throws -> O) -> (completionHandler: O -> (), errorHandler: ErrorType -> ()) -> () { return { ch, eh in async { do { try ch(f()) } catch { eh(error) } } } } public func toAsync<I0, O>(f: (I0) throws -> O) -> (I0, completionHandler: O -> (), errorHandler: ErrorType -> ()) -> () { return { i0, ch, eh in async { do { try ch(f(i0)) } catch { eh(error) } } } } public func toAsync<I0, I1, O>(f: (I0, I1) throws -> O) -> (I0, I1, completionHandler: O -> (), errorHandler: ErrorType -> ()) -> () { return { i0, i1, ch, eh in async { do { try ch(f(i0, i1)) } catch { eh(error) } } } } public func toAsync<I0, I1, I2, O>(f: (I0, I1, I2) throws -> O) -> (I0, I1, I2, completionHandler: O -> (), errorHandler: ErrorType -> ()) -> () { return { i0, i1, i2, ch, eh in async { do { try ch(f(i0, i1, i2)) } catch { eh(error) } } } } public func toAsync<I0, I1, I2, I3, O>(f: (I0, I1, I2, I3) throws -> O) -> (I0, I1, I2, I3, completionHandler: O -> (), errorHandler: ErrorType -> ()) -> () { return { i0, i1, i2, i3, ch, eh in async { do { try ch(f(i0, i1, i2, i3)) } catch { eh(error) } } } } // MARK: - toSync - // MARK: No Error public func toSync<I, O, R>(f: (I, completionHandler: O -> ()) -> R, start: R -> () = { _ in }) -> I -> O { return { input in let semaphore = Semaphore() var output: O! start(f(input) { output = $0 semaphore.signal() }) semaphore.wait() return output } } public func toSync<O, R>(f: (completionHandler: O -> ()) -> R, start: R -> () = { _ in }) -> () -> O { return toSync({ f(completionHandler: $1) }, start: start) } public func toSync<I0, I1, O, R>(f: (I0, I1, completionHandler: O -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) -> O { return toSync({ f($0.0, $0.1, completionHandler: $1) }, start: start) } public func toSync<I0, I1, I2, O, R>(f: (I0, I1, I2, completionHandler: O -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) -> O { return toSync({ f($0.0, $0.1, $0.2, completionHandler: $1) }, start: start) } public func toSync<I0, I1, I2, I3, O, R>(f: (I0, I1, I2, I3, completionHandler: O -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) -> O { return toSync({ f($0.0, $0.1, $0.2, $0.3, completionHandler: $1) }, start: start) } // MARK: - Error // MARK: Error Handler public func toSync<I, O, R>(f: (I, completionHandler: O -> Void, errorHandler: ErrorType -> Void) -> R, start: R -> () = {_ in }) -> I throws -> O { return { i0 in let sema = Semaphore() var error: ErrorType?, output: O! start(f(i0, completionHandler: { output = $0 sema.signal() }, errorHandler: { error = $0 sema.signal() })) sema.wait() if let error = error { throw error } return output } } public func toSync<I, O, R, E: ErrorType>(f: (I, completionHandler: O -> Void, errorHandler: E -> Void) -> R, start: R -> () = {_ in }) -> I throws -> O { return { i0 in let sema = Semaphore() var error: E?, output: O! start(f(i0, completionHandler: { output = $0 sema.signal() }, errorHandler: { error = $0 sema.signal() })) sema.wait() if let error = error { throw error } return output } } public func toSync<O, R>(f: (completionHandler: O -> Void, errorHandler: ErrorType -> Void) -> R, start: R -> () = {_ in }) -> Void throws -> O { return toSync({ i, ch, eh in f(completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<O, R, E: ErrorType>(f: (completionHandler: O -> Void, errorHandler: E -> Void) -> R, start: R -> () = {_ in }) -> Void throws -> O { return toSync({ i, ch, eh in f(completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, O, R>(f: (I1, I2, completionHandler: O -> Void, errorHandler: ErrorType -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, O, R, E: ErrorType>(f: (I1, I2, completionHandler: O -> Void, errorHandler: E -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, I3, O, R>(f: (I1, I2, I3, completionHandler: O -> Void, errorHandler: ErrorType -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2, I3) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, i.2, completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, I3, O, R, E: ErrorType>(f: (I1, I2, I3, completionHandler: O -> Void, errorHandler: E -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2, I3) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, i.2, completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, I3, I4, O, R>(f: (I1, I2, I3, I4, completionHandler: O -> Void, errorHandler: ErrorType -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2, I3, I4) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, i.2, i.3, completionHandler: ch, errorHandler: eh) }, start: start) } public func toSync<I1, I2, I3, I4, O, R, E: ErrorType>(f: (I1, I2, I3, I4, completionHandler: O -> Void, errorHandler: E -> Void) -> R, start: R -> () = {_ in }) -> (I1, I2, I3, I4) throws -> O { return toSync({ i, ch, eh in f(i.0, i.1, i.2, i.3, completionHandler: ch, errorHandler: eh) }, start: start) } // MARK: No Error Handler public func toSync<I, O, R>(f: (I, completionHandler: (O, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> I throws -> O { return { input in let semaphore = Semaphore() var error: ErrorType?, output: O! start(f(input) { (output, error) = ($0, $1) semaphore.signal() }) semaphore.wait() if let error = error { throw error } return output } } public func toSync<I, O, R, E: ErrorType>(f: (I, completionHandler: (O, E?) -> ()) -> R, start: R -> () = { _ in }) -> I throws -> O { return { input in let semaphore = Semaphore() var error: E?, output: O! start(f(input) { (output, error) = ($0, $1) semaphore.signal() }) semaphore.wait() if let error = error { throw error } return output } } public func toSync<I0, R>(f: (I0, completionHandler: (ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> () { return toSync({ i, ch in f(i) { ch((), $0) } }, start: start) } public func toSync<I0, R, E: ErrorType>(f: (I0, completionHandler: (E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> () { return toSync({ i, ch in f(i) { ch((), $0) } }, start: start) } public func toSync<I0, O0, O1, R>(f: (I0, completionHandler: (O0, O1, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1) { return toSync({ i, ch in f(i) { ch(($0, $1), $2) } }, start: start) } public func toSync<I0, O0, O1, R, E: ErrorType>(f: (I0, completionHandler: (O0, O1, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1) { return toSync({ i, ch in f(i) { ch(($0, $1), $2) } }, start: start) } public func toSync<I0, O0, O1, O2, R>(f: (I0, completionHandler: (O0, O1, O2, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i) { ch(($0, $1, $2), $3) } }, start: start) } public func toSync<I0, O0, O1, O2, R, E: ErrorType>(f: (I0, completionHandler: (O0, O1, O2, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i) { ch(($0, $1, $2), $3) } }, start: start) } public func toSync<I0, O0, O1, O2, O3, R>(f: (I0, completionHandler: (O0, O1, O2, O3, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i) { ch(($0, $1, $2, $3), $4) } }, start: start) } public func toSync<I0, O0, O1, O2, O3, R, E: ErrorType>(f: (I0, completionHandler: (O0, O1, O2, O3, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i) { ch(($0, $1, $2, $3), $4) } }, start: start) } public func toSync<R>(f: (completionHandler: (ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> () { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<R, E: ErrorType>(f: (completionHandler: (E?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> () { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<I0, I1, R>(f: (I0, I1, completionHandler: (ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> () { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, R, E: ErrorType>(f: (I0, I1, completionHandler: (E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> () { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, R>(f: (I0, I1, I2, completionHandler: (ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> () { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, R, E: ErrorType>(f: (I0, I1, I2, completionHandler: (E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> () { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, R>(f: (I0, I1, I2, I3, completionHandler: (ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> () { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, R, E: ErrorType>(f: (I0, I1, I2, I3, completionHandler: (E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> () { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<O0, R>(f: (completionHandler: (O0, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<O0, R, E: ErrorType>(f: (completionHandler: (O0, E?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, R>(f: (I0, I1, completionHandler: (O0, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, R, E: ErrorType>(f: (I0, I1, completionHandler: (O0, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, R>(f: (I0, I1, I2, completionHandler: (O0, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, R, E: ErrorType>(f: (I0, I1, I2, completionHandler: (O0, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, R>(f: (I0, I1, I2, I3, completionHandler: (O0, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, R, E: ErrorType>(f: (I0, I1, I2, I3, completionHandler: (O0, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<O0, O1, R>(f: (completionHandler: (O0, O1, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<O0, O1, R, E: ErrorType>(f: (completionHandler: (O0, O1, E?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, R>(f: (I0, I1, completionHandler: (O0, O1, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, R, E: ErrorType>(f: (I0, I1, completionHandler: (O0, O1, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, R>(f: (I0, I1, I2, completionHandler: (O0, O1, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, R, E: ErrorType>(f: (I0, I1, I2, completionHandler: (O0, O1, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, R>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, R, E: ErrorType>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<O0, O1, O2, R>(f: (completionHandler: (O0, O1, O2, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1, O2) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<O0, O1, O2, R, E: ErrorType>(f: (completionHandler: (O0, O1, O2, E?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1, O2) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, O2, R>(f: (I0, I1, completionHandler: (O0, O1, O2, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, O2, R, E: ErrorType>(f: (I0, I1, completionHandler: (O0, O1, O2, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, O2, R>(f: (I0, I1, I2, completionHandler: (O0, O1, O2, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, O2, R, E: ErrorType>(f: (I0, I1, I2, completionHandler: (O0, O1, O2, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, O2, R>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, O2, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, O2, R, E: ErrorType>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, O2, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1, O2) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<O0, O1, O2, O3, R>(f: (completionHandler: (O0, O1, O2, O3, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<O0, O1, O2, O3, R, E: ErrorType>(f: (completionHandler: (O0, O1, O2, O3, E?) -> ()) -> R, start: R -> () = { _ in }) -> () throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, O2, O3, R>(f: (I0, I1, completionHandler: (O0, O1, O2, O3, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, O0, O1, O2, O3, R, E: ErrorType>(f: (I0, I1, completionHandler: (O0, O1, O2, O3, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, O2, O3, R>(f: (I0, I1, I2, completionHandler: (O0, O1, O2, O3, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, O0, O1, O2, O3, R, E: ErrorType>(f: (I0, I1, I2, completionHandler: (O0, O1, O2, O3, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, i.2, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, O2, O3, R>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, O2, O3, ErrorType?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) } public func toSync<I0, I1, I2, I3, O0, O1, O2, O3, R, E: ErrorType>(f: (I0, I1, I2, I3, completionHandler: (O0, O1, O2, O3, E?) -> ()) -> R, start: R -> () = { _ in }) -> (I0, I1, I2, I3) throws -> (O0, O1, O2, O3) { return toSync({ i, ch in f(i.0, i.1, i.2, i.3, completionHandler: ch) }, start: start) }
mit
d813949234d2aabfc9deeb14bddd7783
56.807229
216
0.548799
2.398275
false
false
false
false
Gofake1/Color-Picker
Color Picker/ColorPickerView.swift
1
1512
// // ColorPickerView.swift // Color Picker // // Created by David Wu on 7/2/17. // Copyright © 2017 Gofake1. All rights reserved. // import Cocoa /// `ColorPickerViewController` content view. Allows colors to be dragged in. class ColorPickerView: NSView { override func awakeFromNib() { registerForDraggedTypes([.color]) } // MARK: - NSDraggingDestination override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { return .copy } override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { let pasteboard = sender.draggingPasteboard() guard let colors = pasteboard.readObjects(forClasses: [NSColor.self], options: nil) as? [NSColor], colors.count > 0 else { return false } // Cancel if dragged color is the same as the current color return ColorController.shared.selectedColor != colors[0] } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { let pasteboard = sender.draggingPasteboard() guard let colors = pasteboard.readObjects(forClasses: [NSColor.self], options: nil) as? [NSColor], colors.count > 0 else { return false } ColorController.shared.setColor(colors[0]) return true } // MARK: - // Allows mouse click to lose `ColorPickerViewController`'s text field's focus override func mouseDown(with event: NSEvent) { window?.makeFirstResponder(self) } }
mit
78a9e73239428205307382d8c5ec3baa
30.479167
106
0.662475
4.751572
false
false
false
false
StephenZhuang/BlackHospital
BlackHospital/BlackHospital/HospitalTableViewController.swift
1
5480
// // HospitalTableViewController.swift // BlackHospital // // Created by Stephen Zhuang on 16/8/8. // Copyright © 2016年 StephenZhuang. All rights reserved. // import UIKit import Realm import RealmSwift class HospitalTableViewController: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating { var hospitals: Results<Hospital>! var searchResults = Array<Hospital>() var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() // 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() searchController = UISearchController(searchResultsController: nil) searchController.delegate = self searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false self.tableView.tableHeaderView = searchController.searchBar } 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 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if searchController.active { return searchResults.count } else { return hospitals.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) var hospital: Hospital? if searchController.active { hospital = searchResults[indexPath.row] } else { hospital = hospitals[indexPath.row] } cell.textLabel?.text = hospital?.name; // Configure the cell... return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var hospital: Hospital? if searchController.active { hospital = searchResults[indexPath.row] } else { hospital = hospitals[indexPath.row] } let image = UIImage(named: "60") let url = NSURL(string: "http://finance.ifeng.com/a/20160504/14362042_0.shtml") let string = (hospital?.name)!+"属于莆田系医院,小伙伴们千万不要去!" let activityController = UIActivityViewController(activityItems: [image! ,url!,string], applicationActivities: nil) self.presentViewController(activityController, animated: true, completion: nil) } /* // 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 } */ func updateSearchResultsForSearchController(searchController: UISearchController) { let searchText = searchController.searchBar.text var arr = Array<Hospital>() for hospital in self.hospitals { if (hospital.name as NSString).containsString(searchText!) { arr.append(hospital) } } searchResults = arr self.tableView.reloadData() } /* // 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
5696827a0bd5e6a061edea99197160d4
36.267123
157
0.682963
5.615067
false
false
false
false
vandilsonlima/VLPin
Example/VLPin/ViewController.swift
1
2590
// // ViewController.swift // VLPin // // Created by vandilsonlima on 07/05/2017. // Copyright (c) 2017 vandilsonlima. All rights reserved. // import UIKit import VLPin class ViewController: UIViewController { private let squareSideSize: CGFloat = 100 private let squareSapcing: CGFloat = 20 override func loadView() { view = UIView() view.backgroundColor = .white let backgroundView = UIView() backgroundView.backgroundColor = .lightGray view.addSubview(backgroundView) backgroundView.makeEdges(equalTo: view, withMargins: (10, 10, -10, -10)) let squareView = UIView() squareView.backgroundColor = .blue backgroundView.addSubview(squareView) squareView.makeWidth(equalTo: squareSideSize) squareView.makeHeight(equalTo: squareSideSize) squareView.makeCenter(equalTo: view) let topSquareView = UIView() topSquareView.backgroundColor = .blue backgroundView.addSubview(topSquareView) topSquareView.makeWidth(equalTo: squareSideSize) topSquareView.makeHeight(equalTo: squareSideSize) topSquareView.makeCenterX(equalTo: squareView) topSquareView.makeBottom(equalTo: .top(-squareSapcing), of: squareView) let leadingSquareView = UIView() leadingSquareView.backgroundColor = .blue backgroundView.addSubview(leadingSquareView) leadingSquareView.makeWidth(equalTo: squareSideSize) leadingSquareView.makeHeight(equalTo: squareSideSize) leadingSquareView.makeCenterY(equalTo: squareView) leadingSquareView.makeTrailing(equalTo: .leading(-squareSapcing), of: squareView) let bottomSquareView = UIView() bottomSquareView.backgroundColor = .blue backgroundView.addSubview(bottomSquareView) bottomSquareView.makeWidth(equalTo: squareSideSize) bottomSquareView.makeHeight(equalTo: squareSideSize) bottomSquareView.makeCenterX(equalTo: squareView) bottomSquareView.makeTop(equalTo: .bottom(squareSapcing), of: squareView) let trailingSquareView = UIView() trailingSquareView.backgroundColor = .blue backgroundView.addSubview(trailingSquareView) trailingSquareView.makeWidth(equalTo: squareSideSize) trailingSquareView.makeHeight(equalTo: squareSideSize) trailingSquareView.makeCenterY(equalTo: squareView) trailingSquareView.makeLeading(equalTo: .trailing(squareSapcing), of: squareView) } }
mit
dae23e3e8c81f84d1dd2ccb02800cf30
38.242424
89
0.701544
4.700544
false
false
false
false
enmiller/ENMBadgedBarButtonItem-Swift
SampleApp-Swift/BadgedBarButtonItem/BadgedBarButtonItem.swift
1
10388
// // BadgedBarButtonItem.swift // BadgedBarButtonItem // // Created by Eric Miller on 6/2/14. // Copyright (c) 2014 Tiny Zepplin. All rights reserved. // import UIKit import Foundation import QuartzCore open class BadgedBarButtonItem: UIBarButtonItem { var badgeLabel: UILabel = UILabel() @IBInspectable public var badgeValue: Int = 0 { didSet { updateBadgeValue() } } fileprivate var _badgeValueString: String? fileprivate var badgeValueString: String { get { if let customString = _badgeValueString { return customString } return "\(badgeValue)" } set { _badgeValueString = newValue } } /** When the badgeValue is set to `0`, this flag will be checked to determine if the badge should be hidden. Defaults to true. */ public var shouldHideBadgeAtZero: Bool = true /** Flag indicating if the `badgeValue` should be animated when the value is changed. Defaults to true. */ public var shouldAnimateBadge: Bool = true /** A collection of properties that define the layout and behavior of the badge. Accessable after initialization if run-time updates are required. */ public var badgeProperties: BadgeProperties public init(customView: UIView, value: Int, badgeProperties: BadgeProperties = BadgeProperties()) { self.badgeProperties = badgeProperties super.init() badgeValue = value self.customView = customView commonInit() updateBadgeValue() } public init(startingBadgeValue: Int, frame: CGRect, title: String? = nil, image: UIImage?, badgeProperties: BadgeProperties = BadgeProperties()) { self.badgeProperties = badgeProperties super.init() performStoryboardInitalizationSetup(with: frame, title: title, image: image) self.badgeValue = startingBadgeValue updateBadgeValue() } public required init?(coder aDecoder: NSCoder) { self.badgeProperties = BadgeProperties() super.init(coder: aDecoder) var buttonFrame: CGRect = CGRect.zero if let image = self.image { buttonFrame = CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height) } else if let title = self.title { let lbl = UILabel() lbl.text = title let textSize = lbl.sizeThatFits(CGSize(width: 100.0, height: 100.0)) buttonFrame = CGRect(x: 0.0, y: 0.0, width: textSize.width + 2.0, height: textSize.height) } performStoryboardInitalizationSetup(with: buttonFrame, title: self.title, image: self.image) commonInit() } private func performStoryboardInitalizationSetup(with frame: CGRect, title: String? = nil, image: UIImage?) { let btn = createInternalButton(frame: frame, title: title, image: image) self.customView = btn btn.addTarget(self, action: #selector(internalButtonTapped(_:)), for: .touchUpInside) } private func commonInit() { badgeLabel.font = badgeProperties.font badgeLabel.textColor = badgeProperties.textColor badgeLabel.backgroundColor = badgeProperties.backgroundColor } } // MARK: - Public Functions public extension BadgedBarButtonItem { /** Programmatically adds a target-action pair to the BadgedBarButtonItem */ func addTarget(_ target: AnyObject, action: Selector) { self.target = target self.action = action } /** Creates the internal UIButton to be used as the custom view of the UIBarButtonItem. - Note: Subclassable for further customization. - Parameter frame: The frame of the final BadgedBarButtonItem - Parameter title: The title of the BadgedBarButtonItem. Optional. Defaults to nil. - Parameter image: The image of the BadgedBarButtonItem. Optional. */ func createInternalButton(frame: CGRect, title: String? = nil, image: UIImage?) -> UIButton { let btn = UIButton(type: .custom) btn.setImage(image, for: UIControl.State()) btn.setTitle(title, for: UIControl.State()) btn.setTitleColor(UIColor.black, for: UIControl.State()) btn.frame = frame return btn } /** Calculates the update position of the badge using the button's frame. Can be subclassed for further customization. */ func calculateUpdatedBadgeFrame(usingFrame frame: CGRect) { let offset = CGFloat(4.0) badgeProperties.originalFrame.origin.x = (frame.size.width - offset) - badgeLabel.frame.size.width/2 } } // MARK: - Private Functions fileprivate extension BadgedBarButtonItem { func updateBadgeValue() { guard !shouldBadgeHide(badgeValue) else { if (badgeLabel.superview != nil) { removeBadge() } return } if (badgeLabel.superview != nil) { animateBadgeValueUpdate() } else { badgeLabel = self.createBadgeLabel() updateBadgeProperties() customView?.addSubview(badgeLabel) // Pull the setting of the value and layer border radius off onto the next event loop. DispatchQueue.main.async() { () -> Void in self.badgeLabel.text = self.badgeValueString self.updateBadgeFrame() } } } func animateBadgeValueUpdate() { if shouldAnimateBadge, badgeLabel.text != badgeValueString { let animation: CABasicAnimation = CABasicAnimation() animation.keyPath = "transform.scale" animation.fromValue = 1.5 animation.toValue = 1 animation.duration = 0.2 animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 1.3, 1.0, 1.0) badgeLabel.layer.add(animation, forKey: "bounceAnimation") } badgeLabel.text = badgeValueString; UIView.animate(withDuration: 0.2) { self.updateBadgeFrame() } } func updateBadgeFrame() { let expectedLabelSize: CGSize = badgeExpectedSize() var minHeight = expectedLabelSize.height minHeight = (minHeight < badgeProperties.minimumWidth) ? badgeProperties.minimumWidth : expectedLabelSize.height var minWidth = expectedLabelSize.width let horizontalPadding = badgeProperties.horizontalPadding minWidth = (minWidth < minHeight) ? minHeight : expectedLabelSize.width let nFrame = CGRect( x: badgeProperties.originalFrame.origin.x, y: badgeProperties.originalFrame.origin.y, width: minWidth + horizontalPadding, height: minHeight + horizontalPadding ) UIView.animate(withDuration: 0.2) { self.badgeLabel.frame = nFrame } self.badgeLabel.layer.cornerRadius = (minHeight + horizontalPadding) / 2 } func removeBadge() { let duration = shouldAnimateBadge ? 0.08 : 0.0 let currentTransform = badgeLabel.layer.transform let tf = CATransform3DMakeScale(0.001, 0.001, 1.0) badgeLabel.layer.transform = tf let scaleAnimation = CABasicAnimation() scaleAnimation.fromValue = currentTransform scaleAnimation.duration = duration scaleAnimation.isRemovedOnCompletion = true badgeLabel.layer.add(scaleAnimation, forKey: "transform") badgeLabel.layer.opacity = 0.0 let opacityAnimation = CABasicAnimation() opacityAnimation.fromValue = 1.0 opacityAnimation.duration = duration opacityAnimation.isRemovedOnCompletion = true opacityAnimation.delegate = self badgeLabel.layer.add(opacityAnimation, forKey: "opacity") CATransaction.begin() CATransaction.setCompletionBlock({ self.badgeLabel.removeFromSuperview() }) } func createBadgeLabel() -> UILabel { let frame = CGRect( x: badgeProperties.originalFrame.origin.x, y: badgeProperties.originalFrame.origin.y, width: badgeProperties.originalFrame.width, height: badgeProperties.originalFrame.height ) let label = UILabel(frame: frame) label.textColor = badgeProperties.textColor label.font = badgeProperties.font label.backgroundColor = badgeProperties.backgroundColor label.textAlignment = NSTextAlignment.center label.layer.cornerRadius = frame.size.width / 2 label.clipsToBounds = true return label } func badgeExpectedSize() -> CGSize { let frameLabel: UILabel = self.duplicateLabel(badgeLabel) frameLabel.sizeToFit() let expectedLabelSize: CGSize = frameLabel.frame.size return expectedLabelSize } func duplicateLabel(_ labelToCopy: UILabel) -> UILabel { let dupLabel = UILabel(frame: labelToCopy.frame) dupLabel.text = labelToCopy.text dupLabel.font = labelToCopy.font return dupLabel } func shouldBadgeHide(_ value: Int) -> Bool { return (value == 0) && shouldHideBadgeAtZero } func updateBadgeProperties() { if let customView = self.customView { calculateUpdatedBadgeFrame(usingFrame: customView.frame) } } @objc func internalButtonTapped(_ sender: UIButton) { guard let action = self.action, let target = self.target else { preconditionFailure("Developer Error: The BadgedBarButtonItem requires a target-action pair") } UIApplication.shared.sendAction(action, to: target, from: self, for: nil) } } extension BadgedBarButtonItem: CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if flag { self.badgeLabel.removeFromSuperview() } } }
mit
581a3c1e1cc43565152e0713745881e3
32.509677
120
0.622064
5.054988
false
false
false
false
iOS-mamu/SS
P/Potatso/Advance/ProxySelectionViewController.swift
1
2553
// // ProxySelectionViewController.swift // Potatso // // Created by LEI on 3/10/16. // Copyright © 2016 TouchingApp. All rights reserved. // import UIKit import Eureka import PotatsoLibrary import PotatsoModel class ProxySelectionViewController: FormViewController { var proxies: [Proxy] = [] var selectedProxies: NSMutableSet var callback: (([Proxy]) -> Void)? init(selectedProxies: [Proxy], callback: (([Proxy]) -> Void)?) { self.selectedProxies = NSMutableSet(array: selectedProxies) self.callback = callback super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Choose Proxy".localized() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) generateForm() } func generateForm() { form.delegate = nil form.removeAll() proxies = defaultRealm.objects(Proxy).sorted(byProperty: "createAt").map{ $0 } form +++ Section("Proxy".localized()) let sets = proxies.filter { $0.name != nil } for proxy in sets { form[0] <<< CheckRow(proxy.name) { $0.title = proxy.name $0.value = selectedProxies.contains(proxy) }.onChange({ [unowned self] (row) in self.selectProxy(row) }) } form[0] <<< BaseButtonRow () { $0.title = "Add Proxy".localized() }.cellUpdate({ (cell, row) in cell.textLabel?.textColor = Color.Brand }).onCellSelection({ [unowned self] (cell, row) -> () in self.showProxyConfiguration(nil) }) form.delegate = self tableView?.reloadData() } func selectProxy(_ selectedRow: CheckRow) { selectedProxies.removeAllObjects() let values = form.values() for proxy in proxies { if let checked = values[proxy.name] as? Bool, checked && proxy.name == selectedRow.title { selectedProxies.add(proxy) } } self.callback?(selectedProxies.allObjects as! [Proxy]) close() } func showProxyConfiguration(_ proxy: Proxy?) { let vc = ProxyConfigurationViewController(upstreamProxy: proxy) navigationController?.pushViewController(vc, animated: true) } }
mit
b4c676ae331d7fe1a7b72b20c2cd976d
29.746988
102
0.587382
4.623188
false
false
false
false
ChristianPraiss/Osmosis
Pod/Classes/FindOperation.swift
1
1471
// // FindOperation.swift // Pods // // Created by Christian Praiß on 12/25/15. // // import Foundation import Kanna internal class FindOperation: OsmosisOperation { var query: OsmosisSelector var type: HTMLSelectorType var next: OsmosisOperation? var errorHandler: OsmosisErrorCallback? init(query: OsmosisSelector, type: HTMLSelectorType, errorHandler: OsmosisErrorCallback? = nil){ self.query = query self.type = type self.errorHandler = errorHandler } func execute(doc: HTMLDocument?, currentURL: NSURL?, node: XMLElement?, dict: [String: AnyObject]) { switch type { case .CSS: if let nodes = node?.css(query.selector) where nodes.count != 0 { for node in nodes { next?.execute(doc, currentURL: currentURL, node: node, dict: dict) } } else { self.errorHandler?(error: NSError(domain: "No node found for \(self.query)", code: 500, userInfo: nil)) } case .XPath: if let nodes = node?.xpath(query.selector) where nodes.count != 0 { for node in nodes { next?.execute(doc, currentURL: currentURL, node: node, dict: dict) } } else { self.errorHandler?(error: NSError(domain: "No node found for \(self.query)", code: 500, userInfo: nil)) } } } }
mit
db443cb93ee5710fb8ac55126942bb2a
31.688889
119
0.570748
4.298246
false
false
false
false
Swift-Flow/Swift-Flow
ReSwift/CoreTypes/StoreType.swift
2
6554
// // StoreType.swift // ReSwift // // Created by Benjamin Encz on 11/28/15. // Copyright © 2015 ReSwift Community. All rights reserved. // /** Defines the interface of Stores in ReSwift. `Store` is the default implementation of this interface. Applications have a single store that stores the entire application state. Stores receive actions and use reducers combined with these actions, to calculate state changes. Upon every state update a store informs all of its subscribers. */ public protocol StoreType: DispatchingStoreType { associatedtype State /// The current state stored in the store. var state: State! { get } /** The main dispatch function that is used by all convenience `dispatch` methods. This dispatch function can be extended by providing middlewares. */ var dispatchFunction: DispatchFunction! { get } /** Subscribes the provided subscriber to this store. Subscribers will receive a call to `newState` whenever the state in this store changes. - parameter subscriber: Subscriber that will receive store updates - note: Subscriptions are not ordered, so an order of state updates cannot be guaranteed. */ func subscribe<S: StoreSubscriber>(_ subscriber: S) where S.StoreSubscriberStateType == State /** Subscribes the provided subscriber to this store. Subscribers will receive a call to `newState` whenever the state in this store changes and the subscription decides to forward state update. - parameter subscriber: Subscriber that will receive store updates - parameter transform: A closure that receives a simple subscription and can return a transformed subscription. Subscriptions can be transformed to only select a subset of the state, or to skip certain state updates. - note: Subscriptions are not ordered, so an order of state updates cannot be guaranteed. */ func subscribe<SelectedState, S: StoreSubscriber>( _ subscriber: S, transform: ((Subscription<State>) -> Subscription<SelectedState>)? ) where S.StoreSubscriberStateType == SelectedState /** Subscribes the provided subscriber to this store. Subscribers will receive a call to `newState` whenever the state in this store changes and the subscription decides to forward state update. This variation is used when substate conforms to `Equatable` and `automaticallySkipsRepeats` is enabled on the store. - parameter subscriber: Subscriber that will receive store updates - parameter transform: A closure that receives a simple subscription and can return a transformed subscription. Subscriptions can be transformed to only select a subset of the state, or to skip certain state updates. - note: Subscriptions are not ordered, so an order of state updates cannot be guaranteed. */ func subscribe<SelectedState: Equatable, S: StoreSubscriber>( _ subscriber: S, transform: ((Subscription<State>) -> Subscription<SelectedState>)? ) where S.StoreSubscriberStateType == SelectedState /** Unsubscribes the provided subscriber. The subscriber will no longer receive state updates from this store. - parameter subscriber: Subscriber that will be unsubscribed */ func unsubscribe(_ subscriber: AnyStoreSubscriber) /** Dispatches an action creator to the store. Action creators are functions that generate actions. They are called by the store and receive the current state of the application and a reference to the store as their input. Based on that input the action creator can either return an action or not. Alternatively the action creator can also perform an asynchronous operation and dispatch a new action at the end of it. Example of an action creator: ``` func deleteNote(noteID: Int) -> ActionCreator { return { state, store in // only delete note if editing is enabled if (state.editingEnabled == true) { return NoteDataAction.DeleteNote(noteID) } else { return nil } } } ``` This action creator can then be dispatched as following: ``` store.dispatch( noteActionCreator.deleteNote(3) ) ``` */ func dispatch(_ actionCreator: ActionCreator) /** Dispatches an async action creator to the store. An async action creator generates an action creator asynchronously. */ func dispatch(_ asyncActionCreator: AsyncActionCreator) /** Dispatches an async action creator to the store. An async action creator generates an action creator asynchronously. Use this method if you want to wait for the state change triggered by the asynchronously generated action creator. This overloaded version of `dispatch` calls the provided `callback` as soon as the asynchronously dispatched action has caused a new state calculation. - Note: If the ActionCreator does not dispatch an action, the callback block will never be called */ func dispatch(_ asyncActionCreator: AsyncActionCreator, callback: DispatchCallback?) /** An optional callback that can be passed to the `dispatch` method. This callback will be called when the dispatched action triggers a new state calculation. This is useful when you need to wait on a state change, triggered by an action (e.g. wait on a successful login). However, you should try to use this callback very seldom as it deviates slightly from the unidirectional data flow principal. */ associatedtype DispatchCallback = (State) -> Void /** An ActionCreator is a function that, based on the received state argument, might or might not create an action. Example: ``` func deleteNote(noteID: Int) -> ActionCreator { return { state, store in // only delete note if editing is enabled if (state.editingEnabled == true) { return NoteDataAction.DeleteNote(noteID) } else { return nil } } } ``` */ associatedtype ActionCreator = (_ state: State, _ store: StoreType) -> Action? /// AsyncActionCreators allow the developer to wait for the completion of an async action. associatedtype AsyncActionCreator = (_ state: State, _ store: StoreType, _ actionCreatorCallback: (ActionCreator) -> Void) -> Void }
mit
f766d1c674349f43814fa7bf62c3e4a6
38.239521
98
0.697085
5.284677
false
false
false
false
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
Branch-TestBed-Swift/TestBed-Swift/BranchUniversalObjectData.swift
1
6645
// // BranchUniversalObjectData.swift // TestBed-Swift // // Created by David Westgate on 9/17/17. // Copyright © 2017 Branch Metrics. All rights reserved. // import Foundation struct BranchUniversalObjectData { static let userDefaults = UserDefaults.standard static let universalObjectKeys: Set = ["$publicly_indexable","$keywords", "$canonical_identifier","$exp_date","$content_type", "$og_title", "$og_description","$og_image_url", "$og_image_width", "$og_image_height","$og_video", "$og_url", "$og_type","$og_redirect", "$og_app_id", "$twitter_card","$twitter_title", "$twitter_description", "$twitter_image_url","$twitter_site","$twitter_app_country", "$twitter_player","$twitter_player_width","$twitter_player_height", "$custom_meta_tags", "customData"] static let systemKeys: Set = ["+clicked_branch_link","+referrer","~referring_link","+is_first_session", "~id","~creation_source","+match_guaranteed","$identity_id", "$one_time_use_used","+click_timestamp"] static func defaultUniversalObject() -> BranchUniversalObject { let universalObject = BranchUniversalObject.init() universalObject.contentMetadata.contentSchema = BranchContentSchema.commerceProduct universalObject.title = "Nike Woolen Sox" universalObject.canonicalIdentifier = "nike/5324" universalObject.contentDescription = "Fine combed woolen sox for those who love your foot" universalObject.contentMetadata.currency = BNCCurrency.USD universalObject.contentMetadata.price = 80.2 universalObject.contentMetadata.quantity = 5 universalObject.contentMetadata.sku = "110112467" universalObject.contentMetadata.productName = "Woolen Sox" universalObject.contentMetadata.productCategory = BNCProductCategory(rawValue: "Apparel & Accessories") universalObject.contentMetadata.productBrand = "Nike" universalObject.contentMetadata.productVariant = "Xl" universalObject.contentMetadata.ratingAverage = 3.3 universalObject.contentMetadata.ratingCount = 5 universalObject.contentMetadata.ratingMax = 2.8 universalObject.contentMetadata.contentSchema = BranchContentSchema.commerceProduct return universalObject } static func universalObject() -> [String: AnyObject] { if let value = userDefaults.dictionary(forKey: "universalObject") { return value as [String : AnyObject] } else { let value = [String: AnyObject]() userDefaults.set(value, forKey: "universalObject") return value } } static func setUniversalObject(_ parameters: [String: AnyObject]) { var params = parameters var universalObject = [String: AnyObject]() for key in LinkPropertiesData.linkPropertiesKeys { params.removeValue(forKey: key) } for key in systemKeys { params.removeValue(forKey: key) } for key in universalObjectKeys { if let value = parameters[key] { universalObject[key] = value as AnyObject? params.removeValue(forKey: key) } } for param in params { universalObject["customData"]?.add(param) } userDefaults.set(universalObject, forKey: "universalObject") } static func clearUniversalObject() { userDefaults.set([String: AnyObject](), forKey: "universalObject") } static func branchUniversalObject() -> BranchUniversalObject { let uo = universalObject() let branchUniversalObject: BranchUniversalObject if let canonicalIdentifier = uo["$canonical_identifier"] as? String { branchUniversalObject = BranchUniversalObject.init(canonicalIdentifier: canonicalIdentifier) } else { var canonicalIdentifier = "" for _ in 1...18 { canonicalIdentifier.append(String(arc4random_uniform(10))) } branchUniversalObject = BranchUniversalObject.init(canonicalIdentifier: canonicalIdentifier) } for key in uo.keys { guard uo[key] != nil else { continue } let value = uo[key]!.description!() switch key { case "$canonical_identifier": branchUniversalObject.canonicalIdentifier = value case "$og_description": branchUniversalObject.contentDescription = value case "$exp_date": let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let expirationDate = dateFormatter.date(from:value) branchUniversalObject.expirationDate = expirationDate case "$og_image_url": branchUniversalObject.imageUrl = value case "$keywords": branchUniversalObject.keywords = uo[key] as! [AnyObject] as? [String] case "$og_title": branchUniversalObject.title = value case "$content_type": if let contentType = uo[key] { branchUniversalObject.contentMetadata.contentSchema = contentType as? BranchContentSchema } case "$price": if let price = uo[key] as? String { let formatter = NumberFormatter() formatter.generatesDecimalNumbers = true branchUniversalObject.contentMetadata.price = formatter.number(from: price) as? NSDecimalNumber ?? 0 } case "$currency": if let currency = uo[key] as? String { branchUniversalObject.contentMetadata.currency = BNCCurrency(rawValue: currency) } case "customData": if let data = uo[key] as? [String: String] { branchUniversalObject.setValuesForKeys(data) } default: branchUniversalObject.setValue(uo[key], forKey: key) } } return branchUniversalObject } }
mit
445ad926688a4e6397c794b59a8204af
43.891892
120
0.579771
5.611486
false
false
false
false
dshahidehpour/IGListKit
Examples/Examples-macOS/IGListKitExamples/Helpers/Shuffle.swift
3
1544
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation extension MutableCollection where Indices.Iterator.Element == Index { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) swap(&self[firstUnshuffled], &self[i]) } } } extension Sequence { /// Returns an array with the contents of this sequence, shuffled. var shuffled: [Iterator.Element] { var result = Array(self) result.shuffle() return result } }
bsd-3-clause
1029348c773f10336ab3e0bc2e1e0df0
32.565217
97
0.666451
4.780186
false
false
false
false
SereivoanYong/Charts
Source/Charts/Renderers/RadarRenderer.swift
1
10526
// // RadarRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import UIKit open class RadarRenderer: LineRadarRenderer { open unowned let chart: RadarChartView public init(chart: RadarChartView, animator: Animator, viewPortHandler: ViewPortHandler) { self.chart = chart super.init(animator: animator, viewPortHandler: viewPortHandler) } open override func drawData(context: CGContext) { let radarData = chart.data if radarData != nil { let mostEntries = radarData?.maxEntryCountSet?.entries.count ?? 0 for set in radarData!.dataSets as! [IRadarChartDataSet] { if set.isVisible { drawDataSet(context: context, dataSet: set, mostEntries: mostEntries) } } } } /// Draws the RadarDataSet /// /// - parameter context: /// - parameter dataSet: /// - parameter mostEntries: the entry count of the dataset with the most entries internal func drawDataSet(context: CGContext, dataSet: IRadarChartDataSet, mostEntries: Int) { context.saveGState() let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let path = CGMutablePath() var hasMovedToPoint = false for (j, e) in dataSet.entries.enumerated() { let p = ChartUtils.getPosition(center: center, dist: (e.y - chart.chartYMin) * factor * phaseY, angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle) if p.x.isNaN { continue } if !hasMovedToPoint { path.move(to: p) hasMovedToPoint = true } else { path.addLine(to: p) } } // if this is the largest set, close it if dataSet.entries.count < mostEntries { // if this is not the largest set, draw a line to the center before closing path.addLine(to: center) } path.closeSubpath() // draw filled if dataSet.isDrawFilledEnabled { if let fill = dataSet.fill { drawFilledPath(context: context, path: path, fill: fill, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } // draw the line (only if filled is disabled or alpha is below 255) if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0 { context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.setLineWidth(dataSet.lineWidth) context.setAlpha(1.0) context.beginPath() context.addPath(path) context.strokePath() } context.restoreGState() } open override func drawValues(context: CGContext) { guard let data = chart.data else { return } let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let yoffset: CGFloat = 5.0 for (i, dataSet) in (data.dataSets as! [IRadarChartDataSet]).enumerated() where shouldDrawValues(forDataSet: dataSet) { let iconsOffset = dataSet.iconsOffset for (j, entry) in dataSet.entries.enumerated() { let p = ChartUtils.getPosition( center: center, dist: (entry.y - chart.chartYMin) * factor * animator.phaseY, angle: sliceangle * CGFloat(j) * animator.phaseX + chart.rotationAngle) let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } if dataSet.isDrawValuesEnabled { ChartUtils.drawText( context: context, text: formatter.stringForValue(entry.y, entry: entry, dataSetIndex: i, viewPortHandler: viewPortHandler), point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } if dataSet.isDrawIconsEnabled, let icon = entry.icon { var pIcon = ChartUtils.getPosition( center: center, dist: entry.y * factor * animator.phaseY + iconsOffset.y, angle: sliceangle * CGFloat(j) * animator.phaseX + chart.rotationAngle) pIcon.y += iconsOffset.x ChartUtils.drawImage(context: context, image: icon, x: pIcon.x, y: pIcon.y, size: icon.size) } } } } open override func drawExtras(context: CGContext) { drawWeb(context: context) } fileprivate var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open func drawWeb(context: CGContext) { guard let data = chart.data else { return } let sliceangle = chart.sliceAngle context.saveGState() // calculate the factor that is needed for transforming the value to // pixels let factor = chart.factor let rotationangle = chart.rotationAngle let center = chart.centerOffsets // draw the web lines that come from the center context.setLineWidth(chart.webLineWidth) context.setStrokeColor(chart.webColor.cgColor) context.setAlpha(chart.webAlpha) let xIncrements = 1 + chart.skipWebLineCount let maxEntryCount = chart.data?.maxEntryCountSet?.entries.count ?? 0 for i in stride(from: 0, to: maxEntryCount, by: xIncrements) { let p = ChartUtils.getPosition( center: center, dist: chart.yRange * factor, angle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } // draw the inner-web context.setLineWidth(chart.innerWebLineWidth) context.setStrokeColor(chart.innerWebColor.cgColor) context.setAlpha(chart.webAlpha) let labelCount = chart.yAxis.entries.count for j in 0 ..< labelCount { for i in 0 ..< data.entryCount { let r = (chart.yAxis.entries[j] - chart.chartYMin) * factor let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle) let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } } context.restoreGState() } fileprivate var _highlightPointBuffer = CGPoint() open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let radarData = chart.data as? RadarData else { return } context.saveGState() let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value pixels let factor = chart.factor let center = chart.centerOffsets for high in indices { guard let set = chart.data?.getDataSetByIndex(high.dataSetIndex) as? IRadarChartDataSet, set.isHighlightEnabled else { continue } guard let e = set.entries[Int(high.x)] as? RadarEntry else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setLineWidth(radarData.highlightLineWidth) context.setLineDash(radarData.highlightLineDash) context.setStrokeColor(set.highlightColor.cgColor) let y = e.y - chart.chartYMin _highlightPointBuffer = ChartUtils.getPosition( center: center, dist: y * factor * animator.phaseY, angle: sliceangle * high.x * animator.phaseX + chart.rotationAngle) high.drawPosition = _highlightPointBuffer // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) if set.isDrawHighlightCircleEnabled { if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN { var strokeColor = set.highlightCircleStrokeColor if strokeColor == nil { strokeColor = set.color(atIndex: 0) } if set.highlightCircleStrokeAlpha < 1.0 { strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha) } drawHighlightCircle( context: context, atPoint: _highlightPointBuffer, innerRadius: set.highlightCircleInnerRadius, outerRadius: set.highlightCircleOuterRadius, fillColor: set.highlightCircleFillColor, strokeColor: strokeColor, strokeWidth: set.highlightCircleStrokeWidth) } } } context.restoreGState() } internal func drawHighlightCircle( context: CGContext, atPoint point: CGPoint, innerRadius: CGFloat, outerRadius: CGFloat, fillColor: UIColor?, strokeColor: UIColor?, strokeWidth: CGFloat) { context.saveGState() if let fillColor = fillColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) if innerRadius > 0.0 { context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)) } context.setFillColor(fillColor.cgColor) context.fillPath(using: .evenOdd) } if let strokeColor = strokeColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) context.setStrokeColor(strokeColor.cgColor) context.setLineWidth(strokeWidth) context.strokePath() } context.restoreGState() } }
apache-2.0
f52f29e44394eed8b2ac7dbd5b8228cb
31.091463
164
0.640794
4.741441
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/core/extensions/MasterKey+Helper.swift
1
2284
// // MasterKey+Helper.swift // Bartleby macOS // // Created by Benoit Pereira da silva on 12/08/2017. // import Foundation #if os(OSX) import Cocoa #endif extension MasterKey{ #if os(OSX) open static func save(from document:BartlebyDocument){ do{ // Create a master key from the current document. let masterKey = MasterKey() masterKey.password = document.currentUser.password ?? Default.NO_PASSWORD masterKey.key = document.metadata.sugar // Ask where to save its crypted data let encoded = try JSON.encoder.encode(masterKey) let data = try Bartleby.cryptoDelegate.encryptData(encoded, useKey: Bartleby.configuration.KEY) let url = document.fileURL let ext = (url?.pathExtension == nil) ? "" : "."+url!.pathExtension let name = url?.lastPathComponent.replacingOccurrences(of:ext, with: "") ?? NSLocalizedString("Untitled", comment: "Untitled") if let window=document.windowControllers.first?.window{ let savePanel = NSSavePanel() savePanel.message = NSLocalizedString("Where do you want to save the key?", comment: "Where do you want to save the key?") savePanel.prompt = NSLocalizedString("Save", comment: "Save") savePanel.nameFieldStringValue = name savePanel.canCreateDirectories = true savePanel.allowedFileTypes=["bky"] savePanel.beginSheetModal(for:window,completionHandler: { (result) in if result==NSApplication.ModalResponse.OK { if let url = savePanel.url { syncOnMain{ do{ try data.write(to: url, options: Data.WritingOptions.atomic) }catch{ document.log("\(error)",category:Default.LOG_IDENTITY) } } } } savePanel.close() }) } }catch{ document.log("\(error)",category:Default.LOG_IDENTITY) } } #endif }
apache-2.0
5bff87507447f6a81bae885886aec427
39.785714
138
0.539405
5.287037
false
false
false
false
muyexi/StaticTableViewController
Sources/StaticTableViewController.swift
1
4801
import UIKit open class StaticTableViewController: UITableViewController, TableViewConfigDelegate { open var animateSectionHeaders = false open var insertAnimation: UITableView.RowAnimation = .fade open var deleteAnimation: UITableView.RowAnimation = .fade open var reloadAnimation: UITableView.RowAnimation = .fade var tableViewWrapper: TableViewWrapper? override open func viewDidLoad() { super.viewDidLoad() tableViewWrapper = TableViewWrapper(tableView: tableView, configDelegate: self) } // MARK: - API open func update(cells: UITableViewCell...) { update(cells: cells) } open func set(cells: UITableViewCell..., hidden: Bool) { set(cells: cells, hidden: hidden) } open func set(cells: UITableViewCell..., height: CGFloat) { set(cells: cells, height: height) } open func update(cells: [UITableViewCell]) { cells.forEach { cell in tableViewWrapper?.row(with: cell).update() } } open func set(cells: [UITableViewCell], hidden: Bool) { cells.forEach { (cell: UITableViewCell) in tableViewWrapper?.row(with: cell).hiding = hidden } } open func set(cells: [UITableViewCell], height: CGFloat) { cells.forEach { (cell: UITableViewCell) in tableViewWrapper?.row(with: cell).height = height } } open func isHidden(cell: UITableViewCell) -> Bool { return tableViewWrapper!.row(with: cell).hidden } open func reloadData(animated: Bool) { tableViewWrapper!.reloadRows(animated: animated) } // MARK: UITableViewDataSource override open func numberOfSections(in tableView: UITableView) -> Int { if let wrapper = tableViewWrapper { return wrapper.sections.filter { $0.rows.count != 0 }.count } else { return super.numberOfSections(in: tableView) } } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let wrapper = tableViewWrapper { return wrapper.sections[section].numberOfVisibleRows() } else { return super.tableView(tableView, numberOfRowsInSection: section) } } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let wrapper = tableViewWrapper { return wrapper.visibleRow(with: indexPath).cell } else { return super.tableView(tableView, cellForRowAt: indexPath) } } override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let wrapper = tableViewWrapper { let row = wrapper.visibleRow(with: indexPath) if row.height != CGFloat.greatestFiniteMagnitude { return row.height } else { return super.tableView(tableView, heightForRowAt: row.indexPath) } } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let height = super.tableView(tableView, heightForHeaderInSection: section) return headerFooterHeightForSection(section, height: height) } override open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let height = super.tableView(tableView, heightForFooterInSection: section) return headerFooterHeightForSection(section, height: height) } override open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if isSectionEmpty(section) { return nil } else { return super.tableView(tableView, titleForHeaderInSection: section) } } override open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if isSectionEmpty(section) { return nil } else { return super.tableView(tableView, titleForFooterInSection: section) } } // MARK: - Private func headerFooterHeightForSection(_ section: Int, height: CGFloat) -> CGFloat { let section = tableViewWrapper?.sections[section] if section?.numberOfVisibleRows() == 0 { return 0 } else { return height } } func isSectionEmpty(_ section: Int) -> Bool { return tableView.dataSource?.tableView(tableView, numberOfRowsInSection: section) == 0 } }
mit
477396d89cbef6508f932a31f403c454
33.789855
114
0.634035
5.358259
false
false
false
false
cuappdev/podcast-ios
old/Podcast/RecommendedSeriesCollectionViewFlowLayout.swift
1
1498
// // RecommendedSeriesCollectionViewFlowLayout.swift // Podcast // // Created by Kevin Greer on 2/19/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit enum CollectionLayoutType { case discover case profile case continueListening } class RecommendedSeriesCollectionViewFlowLayout: UICollectionViewFlowLayout { let leadingPadding: CGFloat = 18 static let widthHeight: CGFloat = 100 var collectionLayoutType: CollectionLayoutType init(layoutType: CollectionLayoutType) { self.collectionLayoutType = layoutType super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepare() { super.prepare() scrollDirection = .horizontal switch collectionLayoutType { case .continueListening: itemSize = CGSize(width: (collectionView?.frame.width)! - 3 * leadingPadding, height: (collectionView?.frame.height)!) minimumInteritemSpacing = leadingPadding sectionInset = UIEdgeInsets(top: 0, left: leadingPadding, bottom: 0, right: leadingPadding) default: itemSize = CGSize(width: RecommendedSeriesCollectionViewFlowLayout.widthHeight, height: (collectionView?.frame.height)!) minimumInteritemSpacing = 6 sectionInset = UIEdgeInsets(top: 0, left: leadingPadding, bottom: 0, right: leadingPadding) } } }
mit
8ed4b7761e77a929fc4632462ed639d6
28.94
132
0.691383
5.162069
false
false
false
false
mac-cain13/DocumentStore
DocumentStore/Query/KeyPath+ConstantValues.swift
1
5938
// // KeyPath+ConstantValues.swift // DocumentStore // // Created by Mathijs Kadijk on 07-07-17. // Copyright © 2017 Mathijs Kadijk. All rights reserved. // import Foundation // MARK: Compare `KeyPath`s to constant values /// Equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: `StorableValue` on the right side of the comparison /// - Returns: A `Predicate` representing the comparison public func == <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .equalTo) } /// Not equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func != <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .notEqualTo) } /// Greater than operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func > <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .greaterThan) } /// Greater than or equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func >= <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .greaterThanOrEqualTo) } /// Less than operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func < <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .lessThan) } /// Less than or equal operator. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: Will work on all types, even on for example strings. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Value on the right side of the comparison to compare against /// - Returns: A `Predicate` representing the comparison public func <= <Root, Value>(left: KeyPath<Root, Value>, right: Value) -> Predicate<Root> where Value: IndexableValue { let rightExpression = Expression<Root, Value>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .lessThanOrEqualTo) } /// Like operator, similar in behavior to SQL LIKE. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Note: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 /// or more characters. /// /// - Parameters: /// - left: `KeyPath` on the left side of the comparison /// - right: Like pattern on the right side of the comparison /// - Returns: A `Predicate` representing the comparison public func ~= <Root>(left: KeyPath<Root, String>, right: String) -> Predicate<Root> { let rightExpression = Expression<Root, String>(forConstantValue: right) return Predicate(left: left.expressionOrFatalError, right: rightExpression, comparisonOperator: .like) } /// Equates the `KeyPath` to false. /// /// - Warning: Using a `KeyPath` that is not an `Index` for the related `Document` will result in /// a fatal error. /// /// - Parameter keyPath: `KeyPath` to check for the value false /// - Returns: A `Predicate` representing the comparison prefix public func ! <Root>(keyPath: KeyPath<Root, Bool>) -> Predicate<Root> { let rightExpression = Expression<Root, Bool>(forConstantValue: false) return Predicate(left: keyPath.expressionOrFatalError, right: rightExpression, comparisonOperator: .equalTo) }
mit
5983bdaa92790b1ba33d7bc47d0c5a23
43.977273
120
0.704228
4.102972
false
false
false
false
garygriswold/Bible.js
Plugins/AWS/src/ios/AWS/AwsS3.swift
1
17086
// // AwsS3.swift // AWS_S3_Prototype // // Created by Gary Griswold on 5/15/17. // Copyright © 2017 ShortSands. All rights reserved. // import Foundation import AWSCore public class AwsS3 { private let region: AwsS3Region private let transfer: AWSS3TransferUtility private var userAgent: String? = nil init(region: AwsS3Region, credential: Credentials) { self.region = region let endpoint = AWSEndpoint(region: region.type, service: AWSServiceType.S3, useUnsafeURL: false)! let configuration = AWSServiceConfiguration(region: region.type, endpoint: endpoint, credentialsProvider: credential.provider) let transferUtility = AWSS3TransferUtilityConfiguration() let key = credential.name + region.name // This is identical to the key used in AwsS3Manager AWSS3TransferUtility.register( with: configuration!, transferUtilityConfiguration: transferUtility, forKey: key ) self.transfer = AWSS3TransferUtility.s3TransferUtility(forKey: key) } deinit { print("****** deinit AwsS3 ******") } /** * A Unit Test Method */ public func echo3(message: String) -> String { return message; } ///////////////////////////////////////////////////////////////////////// // URL signing Functions ///////////////////////////////////////////////////////////////////////// /** * This method produces a presigned URL for a GET from an AWS S3 bucket */ public func preSignedUrlGET(s3Bucket: String, s3Key: String, expires: Int, complete: @escaping (_ url:URL?) -> Void) { let request = AWSS3GetPreSignedURLRequest() request.httpMethod = AWSHTTPMethod.GET request.bucket = s3Bucket request.key = s3Key request.expires = Date(timeIntervalSinceNow: TimeInterval(expires)) presignURL(request: request, complete: complete) } /** * This method produces a presigned URL for a PUT to an AWS S3 bucket */ public func preSignedUrlPUT(s3Bucket: String, s3Key: String, expires: Int, contentType: String, complete: @escaping (_ url:URL?) -> Void) { let request = AWSS3GetPreSignedURLRequest() request.httpMethod = AWSHTTPMethod.PUT request.bucket = s3Bucket request.key = s3Key request.expires = Date(timeIntervalSinceNow: TimeInterval(expires)) request.contentType = contentType presignURL(request: request, complete: complete) } /** * This private method is the actual preSignedURL call */ private func presignURL(request: AWSS3GetPreSignedURLRequest, complete: @escaping (_ url:URL?) -> Void) { let builder = AWSS3PreSignedURLBuilder.default() builder.getPreSignedURL(request).continueWith { (task) -> URL? in if let error = task.error { print("Error: \(error)") complete(nil) } else { let presignedURL = task.result! complete(presignedURL as URL) } return nil } } ///////////////////////////////////////////////////////////////////////// // Download Functions ///////////////////////////////////////////////////////////////////////// /** * Download Text to String object */ public func downloadText(s3Bucket: String, s3Key: String, complete: @escaping (_ error:Error?, _ data:String?) -> Void) { let bucket = self.regionalizeBucket(bucket: s3Bucket) let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadText \(bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadText \(bucket) \(s3Key)") } let datastring = (data != nil) ? String(data: data!, encoding: String.Encoding.utf8) as String? : "" complete(error, datastring) }) } self.transfer.downloadData(fromBucket: bucket, key: s3Key, expression: nil, completionHandler: completionHandler) } /** * Download Binary object to Data, receiving code might need to convert it needed form */ public func downloadData(s3Bucket: String, s3Key: String, complete: @escaping (_ error:Error?, _ data:Data?) -> Void) { let bucket = self.regionalizeBucket(bucket: s3Bucket) let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadData \(bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadData \(bucket) \(s3Key)") } complete(error, data) }) } self.transfer.downloadData(fromBucket: bucket, key: s3Key, expression: nil, completionHandler: completionHandler) } /** * Download File. This works for binary and text files. This method does not use * TransferUtility.fileDownload, because it is unable to provide accurate errors * when the file IO fails. */ public func downloadFile(s3Bucket: String, s3Key: String, filePath: URL, complete: @escaping (_ error:Error?) -> Void) { let bucket = self.regionalizeBucket(bucket: s3Bucket) let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadFile \(bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadFile \(bucket) \(s3Key)") } complete(error) }) } self.transfer.download(to: filePath, bucket: bucket, key: s3Key, expression: nil, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } /** * Download zip file and unzip it. When the optional view parameter is set a deterministic * progress circle is displayed. */ public func downloadZipFile(s3Bucket: String, s3Key: String, filePath: URL, view: UIView?, complete: @escaping (_ error:Error?) -> Void) { let bucket = regionalizeBucket(bucket: s3Bucket) let temporaryDirectory: URL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) // Identify temp file for zip file download let tempZipURL = temporaryDirectory.appendingPathComponent(NSUUID().uuidString + ".zip") print("temp URL to store file \(tempZipURL.absoluteString)") let expression = AWSS3TransferUtilityDownloadExpression() expression.setValue(self.getUserAgent(), forRequestHeader: "User-Agent") let progressCircle = ProgressCircle() if let vue = view { progressCircle.addToParentAndCenter(view: vue) expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: { progressCircle.progress = CGFloat(progress.fractionCompleted) if progress.isFinished || progress.isCancelled { progressCircle.remove() } })} } let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadZipFile \(bucket) \(s3Key) Error: \(err)") progressCircle.remove() complete(err) } else { print("Download SUCCESS in s3.downloadZipFile \(bucket) \(s3Key)") do { var unzippedURL: URL = URL(fileURLWithPath: "") // unzip zip file try Zip.unzipFile(tempZipURL, destination: temporaryDirectory, overwrite: true, password: nil, progress: nil, fileOutputHandler: { unzippedFile in print("Unipped File \(unzippedFile)") unzippedURL = URL(fileURLWithPath: unzippedFile.absoluteString) } ) // remove unzipped file if it already exists self.removeItemNoThrow(at: filePath) // move unzipped file to destination try FileManager.default.moveItem(at: unzippedURL, to: filePath) print("SUCCESS in s3.downloadZipFile \(bucket) \(s3Key)") complete(nil) } catch let cotError { print("ERROR in s3.downloadZipFile \(bucket) \(s3Key) Error: \(cotError)") progressCircle.remove() complete(cotError) } self.removeItemNoThrow(at: tempZipURL) } }) } self.transfer.download(to: tempZipURL, bucket: bucket, key: s3Key, expression: expression, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } private func removeItemNoThrow(at: URL) -> Void { do { try FileManager.default.removeItem(at: at) } catch CocoaError.fileNoSuchFile { print("No Such File to delete \(at)") } catch let error { print("Deletion of \(at) Failed \(error)") } } ///////////////////////////////////////////////////////////////////////// // Upload Functions ///////////////////////////////////////////////////////////////////////// /** * Upload Analytics from a Dictionary, that is converted to JSON. */ public func uploadAnalytics(sessionId: String, timestamp: String, prefix: String, dictionary: [String: String], complete: @escaping (_ error: Error?) -> Void) { var message: Data do { message = try JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions.prettyPrinted) } catch let jsonError { print("ERROR while converting message to JSON \(jsonError)") let errorMessage = "{\"Error\": \"AwsS3.uploadAnalytics \(jsonError.localizedDescription)\"}" message = errorMessage.data(using: String.Encoding.utf8)! } // debug print("message \(String(describing: String(data: message, encoding: String.Encoding.utf8)))") uploadAnalytics(sessionId: sessionId, timestamp: timestamp, prefix: prefix, json: message, complete: complete) } /** * Upload Analytics from a JSON text String in Data form. This one is intended for the Cordova Plugin to use */ public func uploadAnalytics(sessionId: String, timestamp: String, prefix: String, json: Data, complete: @escaping (_ error: Error?) -> Void) { //let s3Bucket = "analytics-" + self.endpoint.regionName + "-shortsands" let s3Bucket = "analytics-" + self.region.name + "-shortsands" let s3Key = sessionId + "-" + timestamp let jsonPrefix = "{\"" + prefix + "\": " let jsonSuffix = "}" var message: Data = jsonPrefix.data(using: String.Encoding.utf8)! message.append(json) message.append(jsonSuffix.data(using: String.Encoding.utf8)!) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: message, contentType: "application/json", complete: complete) } /** * Upload string object to bucket */ public func uploadText(s3Bucket: String, s3Key: String, data: String, contentType: String, complete: @escaping (_ error: Error?) -> Void) { let textData = data.data(using: String.Encoding.utf8) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: textData!, contentType: contentType, complete: complete) } /** * Upload object in Data form to bucket. Data must be prepared to correct form * before calling this function. */ public func uploadData(s3Bucket: String, s3Key: String, data: Data, contentType: String, complete: @escaping (_ error: Error?) -> Void) { let bucket = self.regionalizeBucket(bucket: s3Bucket) let completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock = {(task, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.uploadData \(bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.uploadData \(bucket) \(s3Key)") } complete(error) }) } self.transfer.uploadData(data, bucket: bucket, key: s3Key, contentType: contentType, expression: nil, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } /** * Upload file to bucket, this works for text or binary files * Warning: This method is only included to permit symmetric testing of download/upload * It does not use the uploadFile method of TransferUtility, but uploads data. * So, it should not be used for large object unless it is fixed. I was not * able to get the uploadFile method of TransferUtility to work */ public func uploadFile(s3Bucket: String, s3Key: String, filePath: URL, contentType: String, complete: @escaping (_ error: Error?) -> Void) { do { let data = try Data(contentsOf: filePath, options: Data.ReadingOptions.uncached) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: data, contentType: contentType, complete: complete) } catch let cotError { print("ERROR in s3.uploadFile, while reading file \(s3Bucket) \(s3Key) \(cotError.localizedDescription)") complete(cotError) } } private func getUserAgent() -> String { if (self.userAgent == nil) { var result: [String] = [] result.append("v1") result.append(Locale.current.identifier) result.append(Locale.preferredLanguages.joined(separator: ",")) let device = UIDevice.current result.append("Apple") result.append(device.model) result.append("ios") result.append(device.systemVersion) let info = Bundle.main.infoDictionary result.append(info?["CFBundleIdentifier"] as? String ?? "") result.append(info?["CFBundleShortVersionString"] as? String ?? "") self.userAgent = result.joined(separator: ":") } return self.userAgent! } private func regionalizeBucket(bucket: String) -> String { let bucket2: NSString = bucket as NSString if bucket2.contains("oldregion") { switch(self.region.type) { case AWSRegionType.USEast1: return bucket2.replacingOccurrences(of: "oldregion", with: "na-va") case AWSRegionType.EUWest1: return bucket2.replacingOccurrences(of: "oldregion", with: "eu-ie") case AWSRegionType.APNortheast1: return bucket2.replacingOccurrences(of: "oldregion", with: "as-jp") case AWSRegionType.APSoutheast1: return bucket2.replacingOccurrences(of: "oldregion", with: "as-sg") case AWSRegionType.APSoutheast2: return bucket2.replacingOccurrences(of: "oldregion", with: "oc-au") default: return bucket2.replacingOccurrences(of: "oldregion", with: "na-va") } } if bucket2.contains("region") { return bucket2.replacingOccurrences(of: "region", with: self.region.name) } if bucket2.contains("%R") { return bucket2.replacingOccurrences(of: "%R", with: self.region.name) } return bucket } }
mit
cf2dbb2916c932738cc8eefbdaa1aab9
46.196133
120
0.563886
4.913719
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift
34
11649
// // Observable+Single.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // MARK: distinct until changed extension ObservableType where E: Equatable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged() -> Observable<E> { return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) } } extension ObservableType { /** Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K: Equatable>(keySelector: (E) throws -> K) -> Observable<E> { return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) } /** Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged(comparer: (lhs: E, rhs: E) throws -> Bool) -> Observable<E> { return self.distinctUntilChanged({ $0 }, comparer: comparer) } /** Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K>(keySelector: (E) throws -> K, comparer: (lhs: K, rhs: K) throws -> Bool) -> Observable<E> { return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) } } // MARK: doOn extension ObservableType { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter eventHandler: Action to invoke for each event in the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(eventHandler: (Event<E>) throws -> Void) -> Observable<E> { return Do(source: self.asObservable(), eventHandler: eventHandler) } /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(onNext onNext: (E throws -> Void)? = nil, onError: (ErrorType throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) -> Observable<E> { return Do(source: self.asObservable()) { e in switch e { case .Next(let element): try onNext?(element) case .Error(let e): try onError?(e) case .Completed: try onCompleted?() } } } /** Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOnNext(onNext: (E throws -> Void)) -> Observable<E> { return self.doOn(onNext: onNext) } /** Invokes an action for the Error event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOnError(onError: (ErrorType throws -> Void)) -> Observable<E> { return self.doOn(onError: onError) } /** Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOnCompleted(onCompleted: (() throws -> Void)) -> Observable<E> { return self.doOn(onCompleted: onCompleted) } } // MARK: startWith extension ObservableType { /** Prepends a sequence of values to an observable sequence. - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) - parameter elements: Elements to prepend to the specified sequence. - returns: The source sequence prepended with the specified values. */ @warn_unused_result(message="http://git.io/rxs.uo") public func startWith(elements: E ...) -> Observable<E> { return StartWith(source: self.asObservable(), elements: elements) } } // MARK: retry extension ObservableType { /** Repeats the source observable sequence until it successfully terminates. **This could potentially create an infinite sequence.** - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - returns: Observable sequence to repeat until it successfully terminates. */ @warn_unused_result(message="http://git.io/rxs.uo") public func retry() -> Observable<E> { return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) } /** Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. If you encounter an error and want it to retry once, then you must use `retry(2)` - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - parameter maxAttemptCount: Maximum number of times to repeat the sequence. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ @warn_unused_result(message="http://git.io/rxs.uo") public func retry(maxAttemptCount: Int) -> Observable<E> { return CatchSequence(sources: Repeat(count: maxAttemptCount, repeatedValue: self.asObservable())) } /** Repeats the source observable sequence on error when the notifier emits a next value. If the source observable errors and the notifier completes, it will complete the source sequence. - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. */ @warn_unused_result(message="http://git.io/rxs.uo") public func retryWhen<TriggerObservable: ObservableType, Error: ErrorType>(notificationHandler: Observable<Error> -> TriggerObservable) -> Observable<E> { return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) } /** Repeats the source observable sequence on error when the notifier emits a next value. If the source observable errors and the notifier completes, it will complete the source sequence. - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. */ @warn_unused_result(message="http://git.io/rxs.uo") public func retryWhen<TriggerObservable: ObservableType>(notificationHandler: Observable<ErrorType> -> TriggerObservable) -> Observable<E> { return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) } } // MARK: scan extension ObservableType { /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ @warn_unused_result(message="http://git.io/rxs.uo") public func scan<A>(seed: A, accumulator: (A, E) throws -> A) -> Observable<A> { return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) } }
mit
a879b08f4f044f5c25e3b228fef254a3
44.151163
253
0.709478
4.785538
false
false
false
false
brianjmoore/material-components-ios
components/NavigationBar/examples/NavigationBarTypicalUseExample.swift
1
1855
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialNavigationBar open class NavigationBarTypicalUseSwiftExample: NavigationBarTypicalUseExample { override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Navigation Bar (Swift)" navBar = MDCNavigationBar() navBar!.observe(navigationItem) navBar!.backgroundColor = UIColor(white: 0.1, alpha: 1.0) let mutator = MDCNavigationBarTextColorAccessibilityMutator() mutator.mutate(navBar!) view.addSubview(navBar!) navBar!.translatesAutoresizingMaskIntoConstraints = false let viewBindings = ["navBar": navBar!] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[navBar]|", options: [], metrics: nil, views: viewBindings) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[navBar]", options: [], metrics: nil, views: viewBindings) view.addConstraints(constraints) self.setupExampleViews() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } override open var prefersStatusBarHidden: Bool { return true } }
apache-2.0
61f8dcc6e5b09851dd3bcd56ab1f664a
29.916667
86
0.756873
4.907407
false
false
false
false
multinerd/Mia
Mia/Extensions/UIView/UIView+Animations.swift
1
621
import UIKit public extension UIView { /// Rotates a view to a specific value. /// /// - Parameters: /// - value: The value to rotate the view. /// - duration: The duration it takes to rotate the view. Defaults to 0.2. public func rotate(_ value: CGFloat, duration: CFTimeInterval = 0.2) { let animation = CABasicAnimation(keyPath: "transform.rotation") animation.toValue = value animation.duration = duration animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards self.layer.add(animation, forKey: nil) } }
mit
084077bfcf1c5a5de418acbb0ccbf697
26
80
0.647343
4.634328
false
false
false
false
towlebooth/watchos-sabbatical-countdown-part2
SabbaticalCountdown2/DisplayViewController.swift
1
1890
// // DisplayViewController.swift // SabbaticalCountdown2 // // Created by Chad Towle on 11/29/15. // Copyright © 2015 Intertech. All rights reserved. // import UIKit import WatchConnectivity class DisplayViewController: UIViewController, WCSessionDelegate { @IBOutlet weak var startDateLabel: UILabel! var savedDate: NSDate = NSDate() let userCalendar = NSCalendar.currentCalendar() var session: WCSession! override func viewDidLoad() { super.viewDidLoad() if (WCSession.isSupported()) { session = WCSession.defaultSession() session.delegate = self; session.activateSession() } // get values from user defaults let defaults = NSUserDefaults.standardUserDefaults() if let dateString = defaults.stringForKey("dateKey") { startDateLabel.text = dateString } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveSegue(segue:UIStoryboardSegue) { let dateFormat = NSDateFormatter() dateFormat.calendar = userCalendar dateFormat.dateFormat = "yyyy-MM-dd" let savedDateString = dateFormat.stringFromDate(savedDate) startDateLabel.text = savedDateString // save to user defaults for use here in phone app let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(savedDateString, forKey: "dateKey") // save values to session to be shared with watch let applicationDict = ["dateKey":savedDateString] do { try session.updateApplicationContext(applicationDict) } catch { print("Error updating application context.") } } }
mit
d6753f7556dae17d575db24ddd48e9e3
28.515625
66
0.639492
5.572271
false
true
false
false
EZ-NET/CodePiece
CodePiece/Windows/Timeline/SupportTypes/TimelineStatusView.swift
1
1547
// // TimelineStatusView.swift // CodePiece // // Created by Tomohiro Kumagai on H27/11/08. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import Cocoa import ESTwitter @objcMembers final class TimelineStatusView: NSView { @IBOutlet var statusLabel: NSTextField? { didSet { statusLabel?.stringValue = "" applyForegroundColorToStatusLabel() } } enum State { case ok(String) case error(GetStatusesError) } var state: State = .ok("") { didSet { applyForegroundColorToStatusLabel() setNeedsDisplay(frame) statusLabel?.stringValue = message #if DEBUG if case .error = state { NSLog("An error occurres when updating timeline: \(message)") } #endif } } private func applyForegroundColorToStatusLabel() { statusLabel?.textColor = foregroundColor } var message: String { switch state { case .ok(let message): return message case .error(let error): return "\(error)" } } func clearMessage() { state = .ok("") } var foregroundColor: NSColor { switch state { case .ok: return .statusOkTextColor case .error: return .statusErrorTextColor } } var backgroundColor: NSColor { switch state { case .ok: return .statusOkBackgroundColor case .error: return .statusErrorBackgroundColor } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) backgroundColor.set() dirtyRect.fill() } }
gpl-3.0
fe1ce7d957ec34bda415ec30b8a4b065
14.098039
65
0.632468
3.77451
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Stores/StatsStore+Cache.swift
1
2695
protocol StatsStoreCacheable { associatedtype StatsStoreType func containsCachedData(for type: StatsStoreType) -> Bool func containsCachedData(for types: [StatsStoreType]) -> Bool } extension StatsStoreCacheable { func containsCachedData(for types: [StatsStoreType]) -> Bool { return types.first { containsCachedData(for: $0) } != nil } } extension StatsInsightsStore: StatsStoreCacheable { func containsCachedData(for type: InsightType) -> Bool { switch type { case .viewsVisitors: return true case .latestPostSummary: return state.lastPostInsight != nil case .allTimeStats, .growAudience: return state.allTimeStats != nil case .followersTotals, .followers: return state.dotComFollowers != nil && state.emailFollowers != nil case .mostPopularTime, .annualSiteStats: return state.annualAndMostPopularTime != nil case .tagsAndCategories: return state.topTagsAndCategories != nil case .comments: return state.topCommentsInsight != nil case .todaysStats: return state.todaysStats != nil case .postingActivity: return state.postingActivity != nil case .publicize: return state.publicizeFollowers != nil case .allDotComFollowers: return state.allDotComFollowers != nil case .allEmailFollowers: return state.allEmailFollowers != nil case .allComments: return state.allCommentsInsight != nil case .allTagsAndCategories: return state.allTagsAndCategories != nil case .allAnnual: return state.allAnnual != nil default: return false } } } extension StatsPeriodStore: StatsStoreCacheable { func containsCachedData(for type: PeriodType) -> Bool { switch type { case .summary: return state.summary != nil case .topPostsAndPages: return state.topPostsAndPages != nil case .topReferrers: return state.topReferrers != nil case .topPublished: return state.topPublished != nil case .topClicks: return state.topClicks != nil case .topAuthors: return state.topAuthors != nil case .topSearchTerms: return state.topSearchTerms != nil case .topCountries: return state.topCountries != nil case .topVideos: return state.topVideos != nil case .topFileDownloads: return state.topFileDownloads != nil } } }
gpl-2.0
5b66f4a5ec9c77f0a1430f71cf74b984
33.113924
66
0.614842
4.864621
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/lib/models/guarantor.swift
1
1062
// // guarantor.swift // CDAKit // // Created by Eric Whitley on 11/30/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation //NOTE: making this an CDAKEntry subclass - This is a change to the Ruby code /** CDA Guarantor. Individual legally responsible for all patient charges */ public class CDAKGuarantor: CDAKEntry { // MARK: CDA properties ///Organization public var organization: CDAKOrganization? ///Person public var person: CDAKPerson? // MARK: Standard properties ///Debugging description override public var description: String { return super.description + " person: \(person), organization: \(organization)" } } extension CDAKGuarantor { // MARK: - JSON Generation ///Dictionary for JSON data override public var jsonDict: [String: AnyObject] { var dict = super.jsonDict if let organization = organization { dict["organization"] = organization.jsonDict } if let person = person { dict["person"] = person.jsonDict } return dict } }
mit
d5fe490822d7f47f33ce39a7d6274f8c
20.673469
82
0.683318
4.295547
false
false
false
false
tonystone/tracelog
Tests/TraceLogTests/Internal/Utilities/Streams/FileOutputStreamTests.swift
1
9127
/// /// FileOutputStreamTests.swift /// /// Copyright 2019 Tony Stone /// /// 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. /// /// Created by Tony Stone on 1/18/19. /// import XCTest @testable import TraceLog class FileOutputStreamTests: XCTestCase { // MARK: - Initialization Tests /// Test that a FileOutputStream can be creates using a URL. /// func testInitWithURL() throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } XCTAssertNoThrow(try FileOutputStream(url: inputURL, options: [.create])) } /// Test that a FileOutputStream fails when given a URL of a file that does not exist. /// func testInitWithURLFailsWithInvalidURL() { let inputURL = self.temporaryFileURL() XCTAssertThrowsError(try FileOutputStream(url: inputURL, options: []), "Should throw but did not.") { error in switch error { case FileOutputStreamError.invalidURL(_): break default: XCTFail() } } } // MARK: - position tests /// Test that a FileOutputStream.position returns the correct value after writing to a file. /// func testPositionReturnsCorrectValueOnNormalFile() throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let stream = try FileOutputStream(url: inputURL, options: [.create]) switch stream.write(Array<UInt8>(repeating: 255, count: 10)) { case .success(let written): XCTAssertEqual(written, 10) default: XCTFail() } XCTAssertEqual(stream.position, 10) } // MARK: write tests func testWriteToFile() throws { let inputBytes = Array<UInt8>(repeating: 128, count: 10) try self._testWrite(with: inputBytes) } func testWriteWithSystemPageSizes() throws { let pageSizes = [1024, 4 * 1024, Int(PIPE_BUF)] for size in pageSizes { try self._testWrite(with: Array<UInt8>(repeating: 128, count: size)) } } func testWriteWithJustOverSystemPageSizes() throws { let pageSizes = [1024, 4 * 1024, Int(PIPE_BUF)] for size in pageSizes { try self._testWrite(with: Array<UInt8>(repeating: 128, count: size + 1)) } } func testWriteWithLargeWrites() throws { try self._testWrite(with: Array<UInt8>(repeating: 128, count: 1024 * 1024 + 1)) } private func _testWrite(with bytes: [UInt8], file: StaticString = #file, line: UInt = #line) throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let stream = try FileOutputStream(url: inputURL, options: [.create]) switch stream.write(bytes) { case .success(let written): XCTAssertEqual(written, bytes.count, file: file, line: line) XCTAssertEqual(try Data(contentsOf: inputURL), Data(bytes), file: file, line: line) default: XCTFail(file: file, line: line) } } func testThatConcurrentMultipleWritesDontProducePartialWrites() throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let stream = try FileOutputStream(url: inputURL, options: [.create]) /// Note: 10 iterations seems to be the amount of concurrent /// runs Dispatch will give us so we limit it to that and /// instead have each block write many times. /// DispatchQueue.concurrentPerform(iterations: 10) { (iteration) in for writeNumber in 0..<5000 { /// Random delay between writes usleep(UInt32.random(in: 1...1000)) let iterationMessage = "Iteration \(iteration), write \(writeNumber)" let bytes = Array("\(iterationMessage).".utf8) switch stream.write(bytes) { case .success(let written): XCTAssertEqual(written, bytes.count, "\(iterationMessage): failed byte count test.") default: XCTFail("\(iterationMessage): failed.") } } } } func testThatConcurrentMultipleWritesDontProduceInterleaving() throws { try self._testInterleaving(inputString: "This text string should not be interleaved and should have a newline at the end.") } func testThatConcurrentMultipleWritesDontProduceInterleavingWithLargeWrites() throws { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let length = 1024 * 1024 + 1 let input = String((0...length).compactMap{ _ in letters.randomElement() }) try self._testInterleaving(inputString: input, writes: 10) } func _testInterleaving(inputString: String, workers: Int = 10, writes: Int = 5000, file: StaticString = #file, line: UInt = #line) throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let stream = try FileOutputStream(url: inputURL, options: [.create]) /// Note: 10 iterations seems to be the amount of concurrent /// runs Dispatch will give us so we limit it to that and /// instead have each block write many times. /// DispatchQueue.concurrentPerform(iterations: workers) { (iteration) in for _ in 0..<writes { /// Random delay between writes usleep(UInt32.random(in: 1...1000)) _ = stream.write(Array("\(inputString)\n".utf8)) } } let reader = try TextFileLineReader(url: inputURL, encoding: .utf8) var interleaved = 0 var lineCount = 0 /// Loop through each line looking for interleaved lines. while let line = reader.next() { if line.count > 0 { lineCount += 1 if line != inputString { interleaved += 1 } } } XCTAssertEqual(lineCount, workers * writes, file: file, line: line) XCTAssertEqual(interleaved, 0, "File contains \(interleaved) lines.", file: file, line: line) } func testWriteThrowsOnAClosedFileDescriptor() throws { let inputBytes = Array<UInt8>(repeating: 128, count: 10) let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let stream = try FileOutputStream(url: inputURL, options: [.create]) /// Close the file so the write fails. stream.close() switch stream.write(inputBytes) { case .failure(.disconnected(let message)): XCTAssertEqual(message, "Bad file descriptor") default: XCTFail() } } func testWritePerformance() throws { let inputURL = self.temporaryFileURL() defer { self.removeFileIfExists(url: inputURL) } let inputBytes = Array<UInt8>(repeating: 128, count: 128) let stream = try FileOutputStream(url: inputURL, options: [.create]) self.measure { for _ in 0..<100000 { switch stream.write(inputBytes) { case .success(_): break default: XCTFail() } } } } // MARK: - Test helper functions private func temporaryFileURL() -> URL { let directory = NSTemporaryDirectory() let filename = "test-\(UUID().uuidString).bin" let fileURL = URL(fileURLWithPath: directory).appendingPathComponent(filename) // Return the temporary file URL for use in a test method. return fileURL } private func removeFileIfExists(url: URL) { do { let fileManager = FileManager.default // Check that the file exists before trying to delete it. if fileManager.fileExists(atPath: url.path) { // Perform the deletion. try fileManager.removeItem(at: url) // Verify that the file no longer exists after the deletion. XCTAssertFalse(fileManager.fileExists(atPath: url.path)) } } catch { // Treat any errors during file deletion as a test failure. XCTFail("Error while deleting temporary file: \(error)") } } }
apache-2.0
0f562f863a99d3aa472d88711c01f6b4
32.555147
143
0.602608
4.84191
false
true
false
false
scheib/chromium
ios/chrome/widget_kit_extension/quick_actions_widget.swift
2
4974
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import SwiftUI import WidgetKit struct QuickActionsWidget: Widget { // Changing |kind| or deleting this widget will cause all installed instances of this widget to // stop updating and show the placeholder state. let kind: String = "QuickActionsWidget" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in QuickActionsWidgetEntryView(entry: entry) } .configurationDisplayName( Text("IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_DISPLAY_NAME") ) .description(Text("IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_DESCRIPTION")) .supportedFamilies([.systemMedium]) } } struct QuickActionsWidgetEntryView: View { var entry: Provider.Entry @Environment(\.redactionReasons) var redactionReasons private let searchAreaHeight: CGFloat = 92 private let separatorHeight: CGFloat = 32 private let incognitoA11yLabel: LocalizedStringKey = "IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_INCOGNITO_A11Y_LABEL" private let voiceSearchA11yLabel: LocalizedStringKey = "IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_VOICE_SEARCH_A11Y_LABEL" private let qrA11yLabel: LocalizedStringKey = "IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_QR_SCAN_A11Y_LABEL" var body: some View { VStack(spacing: 0) { ZStack { Color("widget_background_color") .unredacted() VStack { Spacer() Link(destination: WidgetConstants.QuickActionsWidget.searchUrl) { ZStack { RoundedRectangle(cornerRadius: 26) .frame(height: 52) .foregroundColor(Color("widget_search_bar_color")) HStack(spacing: 12) { Image("widget_chrome_logo") .clipShape(Circle()) // Without .clipShape(Circle()), in the redacted/placeholder // state the Widget shows an rectangle placeholder instead of // a circular one. .padding(.leading, 8) .unredacted() Text("IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_TITLE") .font(.subheadline) .foregroundColor(Color("widget_text_color")) Spacer() } } .frame(minWidth: 0, maxWidth: .infinity) .padding([.leading, .trailing], 11) } .accessibility( label: Text( "IDS_IOS_WIDGET_KIT_EXTENSION_QUICK_ACTIONS_SEARCH_A11Y_LABEL" ) ) Spacer() } .frame(height: searchAreaHeight) } ZStack { Rectangle() .foregroundColor(Color("widget_actions_row_background_color")) .frame(minWidth: 0, maxWidth: .infinity) HStack { // Show interactive buttons if the widget is fully loaded, and show // the custom placeholder otherwise. if redactionReasons.isEmpty { Link(destination: WidgetConstants.QuickActionsWidget.incognitoUrl) { Image("widget_incognito_icon") .frame(minWidth: 0, maxWidth: .infinity) } .accessibility(label: Text(incognitoA11yLabel)) Separator(height: separatorHeight) Link( destination: WidgetConstants.QuickActionsWidget.voiceSearchUrl ) { Image("widget_voice_search_icon") .frame(minWidth: 0, maxWidth: .infinity) } .accessibility(label: Text(voiceSearchA11yLabel)) Separator(height: separatorHeight) Link(destination: WidgetConstants.QuickActionsWidget.qrCodeUrl) { Image("widget_qr_icon") .frame(minWidth: 0, maxWidth: .infinity) } .accessibility(label: Text(qrA11yLabel)) } else { ButtonPlaceholder() Separator(height: separatorHeight) ButtonPlaceholder() Separator(height: separatorHeight) ButtonPlaceholder() } } .frame(minWidth: 0, maxWidth: .infinity) .padding([.leading, .trailing], 11) } } } } struct Separator: View { let height: CGFloat var body: some View { RoundedRectangle(cornerRadius: 1) .foregroundColor(Color("widget_separator_color")) .frame(width: 2, height: height) } } struct ButtonPlaceholder: View { private let widthOfPlaceholder: CGFloat = 28 var body: some View { Group { RoundedRectangle(cornerRadius: 4, style: .continuous) .frame(width: widthOfPlaceholder, height: widthOfPlaceholder) .foregroundColor(Color("widget_text_color")) .opacity(0.3) }.frame(minWidth: 0, maxWidth: .infinity) } }
bsd-3-clause
ab5c79830164a4c5daee04b7b122dea9
35.306569
97
0.613792
4.477048
false
false
false
false
banxi1988/BXViewPager
Pod/Classes/BXTab.swift
1
519
// // BXTab.swift // BXViewPager // // Created by Haizhen Lee on 15/11/18. // Copyright © 2015年 CocoaPods. All rights reserved. // import UIKit // MARK: BXTab Model open class BXTab{ open static let INVALID_POSITION = -1 open var tag:AnyObject? open var icon:UIImage? open var text:String? open var contentDesc:String? open var badgeValue:String? open var position = BXTab.INVALID_POSITION public init(text:String?,icon:UIImage? = nil){ self.text = text self.icon = icon } }
mit
2b9abaa3b6d701e41c4657a4dce35c2e
18.111111
53
0.678295
3.329032
false
false
false
false
kharrison/CodeExamples
AutoLayout/AutoLayout/LayoutGuideController.swift
1
5854
// // LayoutGuideController.swift // AutoLayout // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2016 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import UIKit final class LayoutGuideController: UIViewController { // Use layout guides as an alternative to spacer views // The two buttons will be placed between the view margins // with equal spacing between the buttons and the margins // so that the width of the three guides is equal. // = |+++++++++++************+++++++++++************+++++++++++| = // = |+ leading +* no *+ middle +* yes *+ trailing+| = // = |+ guide +* button *+ guide +* button *+ guide +| = // = |+++++++++++************+++++++++++************+++++++++++| = let leadingGuide = UILayoutGuide() let noButton = UIButton(type: .custom) let middleGuide = UILayoutGuide() let yesButton = UIButton(type: .custom) let trailingGuide = UILayoutGuide() override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() } private func setupViews() { // Configure the buttons and add them to the superview noButton.translatesAutoresizingMaskIntoConstraints = false noButton.setTitle("No", for: .normal) let redImage = UIImage(named: "redButton") noButton.setBackgroundImage(redImage, for: .normal) noButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) noButton.addTarget(self, action: #selector(LayoutGuideController.noThanks(_:)), for: .touchUpInside) yesButton.translatesAutoresizingMaskIntoConstraints = false yesButton.setTitle("Yes please!", for: .normal) let greenImage = UIImage(named: "greenButton") yesButton.setBackgroundImage(greenImage, for: .normal) yesButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) yesButton.addTarget(self, action: #selector(LayoutGuideController.yesPlease(_:)), for: .touchUpInside) view.addSubview(noButton) view.addSubview(yesButton) // Add the layout guides to the view // Note that the guides are not part of the // view hierarchy view.addLayoutGuide(leadingGuide) view.addLayoutGuide(middleGuide) view.addLayoutGuide(trailingGuide) } private func setupConstraints() { // The views are spaced relative to the margings of // the superview. To space the views relative to the // edges of the super view replace "margins" with // "view" in the constraints below let margins = view.layoutMarginsGuide NSLayoutConstraint.activate([ // leading to trailing constraints // working from left to right margins.leadingAnchor.constraint(equalTo: leadingGuide.leadingAnchor), leadingGuide.trailingAnchor.constraint(equalTo: noButton.leadingAnchor), noButton.trailingAnchor.constraint(equalTo: middleGuide.leadingAnchor), middleGuide.trailingAnchor.constraint(equalTo: yesButton.leadingAnchor), yesButton.trailingAnchor.constraint(equalTo: trailingGuide.leadingAnchor), trailingGuide.trailingAnchor.constraint(equalTo: margins.trailingAnchor), // The buttons should have the same width noButton.widthAnchor.constraint(equalTo: yesButton.widthAnchor), // The guides should have the same width leadingGuide.widthAnchor.constraint(equalTo: middleGuide.widthAnchor), leadingGuide.widthAnchor.constraint(equalTo: trailingGuide.widthAnchor), // Center everything vertically in the super view leadingGuide.centerYAnchor.constraint(equalTo: view.centerYAnchor), middleGuide.centerYAnchor.constraint(equalTo: view.centerYAnchor), trailingGuide.centerYAnchor.constraint(equalTo: view.centerYAnchor), noButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), yesButton.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } @objc private func noThanks(_ sender: UIButton) { print("No thanks!") } @objc private func yesPlease(_ sender: UIButton) { print("Yes please!") } }
bsd-3-clause
023cce8e868eaed8dbb5cb3c1dc91747
44.379845
110
0.683464
4.846026
false
false
false
false
ubi-naist/SenStick
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/LegacyDFU/Characteristics/DFUControlPoint.swift
2
19006
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal enum DFUOpCode : UInt8 { case startDfu = 1 case initDfuParameters = 2 case receiveFirmwareImage = 3 case validateFirmware = 4 case activateAndReset = 5 case reset = 6 case reportReceivedImageSize = 7 // unused in this library case packetReceiptNotificationRequest = 8 case responseCode = 16 case packetReceiptNotification = 17 var code: UInt8 { return rawValue } } internal enum InitDfuParametersRequest : UInt8 { case receiveInitPacket = 0 case initPacketComplete = 1 var code: UInt8 { return rawValue } } internal enum Request { case jumpToBootloader case startDfu(type: UInt8) case startDfu_v1 case initDfuParameters(req: InitDfuParametersRequest) case initDfuParameters_v1 case receiveFirmwareImage case validateFirmware case activateAndReset case reset case packetReceiptNotificationRequest(number: UInt16) var data : Data { switch self { case .jumpToBootloader: let bytes:[UInt8] = [DFUOpCode.startDfu.code, FIRMWARE_TYPE_APPLICATION] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 2) case .startDfu(let type): let bytes:[UInt8] = [DFUOpCode.startDfu.code, type] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 2) case .startDfu_v1: let bytes:[UInt8] = [DFUOpCode.startDfu.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .initDfuParameters(let req): let bytes:[UInt8] = [DFUOpCode.initDfuParameters.code, req.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 2) case .initDfuParameters_v1: let bytes:[UInt8] = [DFUOpCode.initDfuParameters.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .receiveFirmwareImage: let bytes:[UInt8] = [DFUOpCode.receiveFirmwareImage.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .validateFirmware: let bytes:[UInt8] = [DFUOpCode.validateFirmware.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .activateAndReset: let bytes:[UInt8] = [DFUOpCode.activateAndReset.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .reset: let bytes:[UInt8] = [DFUOpCode.reset.code] return Data(bytes: UnsafePointer<UInt8>(bytes), count: 1) case .packetReceiptNotificationRequest(let number): let data = NSMutableData(capacity: 5)! let bytes:[UInt8] = [DFUOpCode.packetReceiptNotificationRequest.code] data.append(bytes, length: 1) var n = number.littleEndian withUnsafePointer(to: &n) { data.append(UnsafeRawPointer($0), length: 2) } return (NSData(data: data as Data) as Data) } } var description : String { switch self { case .jumpToBootloader: return "Jump to bootloader (Op Code = 1, Upload Mode = 4)" case .startDfu(let type): return "Start DFU (Op Code = 1, Upload Mode = \(type))" case .startDfu_v1: return "Start DFU (Op Code = 1)" case .initDfuParameters(_): return "Initialize DFU Parameters" case .initDfuParameters_v1: return "Initialize DFU Parameters" case .receiveFirmwareImage: return "Receive Firmware Image (Op Code = 3)" case .validateFirmware: return "Validate Firmware (Op Code = 4)" case .activateAndReset: return "Activate and Reset (Op Code = 5)" case .reset: return "Reset (Op Code = 6)" case .packetReceiptNotificationRequest(let number): return "Packet Receipt Notif Req (Op Code = 8, Value = \(number))" } } } internal enum DFUResultCode : UInt8 { case success = 1 case invalidState = 2 case notSupported = 3 case dataSizeExceedsLimit = 4 case crcError = 5 case operationFailed = 6 var description: String { switch self { case .success: return "Success" case .invalidState: return "Device is in invalid state" case .notSupported: return "Operation not supported" case .dataSizeExceedsLimit: return "Data size exceeds limit" case .crcError: return "CRC Error" case .operationFailed: return "Operation failed" } } var code: UInt8 { return rawValue } } internal struct Response { let opCode : DFUOpCode? let requestOpCode : DFUOpCode? let status : DFUResultCode? init?(_ data: Data) { var opCode : UInt8 = 0 var requestOpCode : UInt8 = 0 var status : UInt8 = 0 (data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1)) (data as NSData).getBytes(&requestOpCode, range: NSRange(location: 1, length: 1)) (data as NSData).getBytes(&status, range: NSRange(location: 2, length: 1)) self.opCode = DFUOpCode(rawValue: opCode) self.requestOpCode = DFUOpCode(rawValue: requestOpCode) self.status = DFUResultCode(rawValue: status) if self.opCode != .responseCode || self.requestOpCode == nil || self.status == nil { return nil } } var description: String { return "Response (Op Code = \(requestOpCode!.rawValue), Status = \(status!.rawValue))" } } internal struct PacketReceiptNotification { let opCode : DFUOpCode? let bytesReceived : UInt32 init?(_ data: Data) { var opCode: UInt8 = 0 (data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1)) self.opCode = DFUOpCode(rawValue: opCode) if self.opCode != .packetReceiptNotification { return nil } // According to https://github.com/NordicSemiconductor/IOS-Pods-DFU-Library/issues/54 // in SDK 5.2.0.39364 the bytesReveived value in a PRN packet is 16-bit long, instad of 32-bit. // However, the packet is still 5 bytes long and the two last bytes are 0x00-00. // This has to be taken under consideration when comparing number of bytes sent and received as // the latter counter may rewind if fw size is > 0xFFFF bytes (LegacyDFUService:L372). var bytesReceived: UInt32 = 0 (data as NSData).getBytes(&bytesReceived, range: NSRange(location: 1, length: 4)) self.bytesReceived = bytesReceived } } @objc internal class DFUControlPoint : NSObject, CBPeripheralDelegate { static let UUID = CBUUID(string: "00001531-1212-EFDE-1523-785FEABCD123") static func matches(_ characteristic: CBCharacteristic) -> Bool { return characteristic.uuid.isEqual(UUID) } private var characteristic: CBCharacteristic private var logger: LoggerHelper private var success: Callback? private var proceed: ProgressCallback? private var report: ErrorCallback? private var request: Request? private var uploadStartTime: CFAbsoluteTime? private var resetSent = false internal var valid: Bool { return characteristic.properties.isSuperset(of: [CBCharacteristicProperties.write, CBCharacteristicProperties.notify]) } // MARK: - Initialization init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) { self.characteristic = characteristic self.logger = logger } // MARK: - Characteristic API methods /** Enables notifications for the DFU Control Point characteristics. Reports success or an error using callbacks. - parameter success: method called when notifications were successfully enabled - parameter report: method called in case of an error */ func enableNotifications(onSuccess success: Callback?, onError report: ErrorCallback?) { // Save callbacks self.success = success self.report = report // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self logger.v("Enabling notifications for \(characteristic.uuid.uuidString)...") logger.d("peripheral.setNotifyValue(true, for: \(characteristic.uuid.uuidString))") peripheral.setNotifyValue(true, for: characteristic) } /** Sends given request to the DFU Control Point characteristic. Reports success or an error using callbacks. - parameter request: request to be sent - parameter success: method called when peripheral reported with status success - parameter report: method called in case of an error */ func send(_ request: Request, onSuccess success: Callback?, onError report: ErrorCallback?) { // Save callbacks and parameter self.success = success self.report = report self.request = request self.resetSent = false // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self switch request { case .initDfuParameters(let req): if req == InitDfuParametersRequest.receiveInitPacket { logger.a("Writing \(request.description)...") } case .initDfuParameters_v1: logger.a("Writing \(request.description)...") case .jumpToBootloader, .activateAndReset, .reset: // Those three requests may not be confirmed by the remote DFU target. The device may be restarted before sending the ACK. // This would cause an error in peripheral:didWriteValueForCharacteristic:error, which can be ignored in this case. resetSent = true default: break } logger.v("Writing to characteristic \(characteristic.uuid.uuidString)...") logger.d("peripheral.writeValue(0x\(request.data.hexString), for: \(characteristic.uuid.uuidString), type: .withResponse)") peripheral.writeValue(request.data, for: characteristic, type: .withResponse) } /** Sets the callbacks used later on when a Packet Receipt Notification is received, a device reported an error or the whole firmware has been sent and the notification with success status was received. Sending the firmware is done using DFU Packet characteristic. - parameter success: method called when peripheral reported with status success - parameter proceed: method called the a PRN has been received and sending following data can be resumed - parameter report: method called in case of an error */ func waitUntilUploadComplete(onSuccess success: Callback?, onPacketReceiptNofitication proceed: ProgressCallback?, onError report: ErrorCallback?) { // Save callbacks. The proceed callback will be called periodically whenever a packet receipt notification is received. It resumes uploading. self.success = success self.proceed = proceed self.report = report self.uploadStartTime = CFAbsoluteTimeGetCurrent() // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self logger.a("Uploading firmware...") logger.v("Sending firmware DFU Packet characteristic...") } // MARK: - Peripheral Delegate callbacks func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if error != nil { logger.e("Enabling notifications failed") logger.e(error!) report?(.enablingControlPointFailed, "Enabling notifications failed") } else { logger.v("Notifications enabled for \(characteristic.uuid.uuidString)") logger.a("DFU Control Point notifications enabled") success?() } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { // This method, according to the iOS documentation, should be called only after writing with response to a characteristic. // However, on iOS 10 this method is called even after writing without response, which is a bug. // The DFU Control Point characteristic always writes with response, in oppose to the DFU Packet, which uses write without response. guard characteristic.uuid.isEqual(DFUControlPoint.UUID) else { return } if error != nil { if !resetSent { logger.e("Writing to characteristic failed") logger.e(error!) report?(.writingCharacteristicFailed, "Writing to characteristic failed") } else { // When a 'JumpToBootloader', 'Activate and Reset' or 'Reset' command is sent the device may reset before sending the acknowledgement. // This is not a blocker, as the device did disconnect and reset successfully. logger.a("\(request!.description) request sent") logger.w("Device disconnected before sending ACK") logger.w(error!) success?() } } else { logger.i("Data written to \(characteristic.uuid.uuidString)") switch request! { case .startDfu(_), .startDfu_v1, .validateFirmware: logger.a("\(request!.description) request sent") // do not call success until we get a notification case .jumpToBootloader, .activateAndReset, .reset, .packetReceiptNotificationRequest(_): logger.a("\(request!.description) request sent") // there will be no notification send after these requests, call success() immetiatelly // (for .ReceiveFirmwareImage the notification will be sent after firmware upload is complete) success?() case .initDfuParameters(_), .initDfuParameters_v1: // Log was created before sending the Op Code // do not call success until we get a notification break case .receiveFirmwareImage: if proceed == nil { success?() } } } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { // Ignore updates received for other characteristics guard characteristic.uuid.isEqual(DFUControlPoint.UUID) else { return } if error != nil { // This characteristic is never read, the error may only pop up when notification is received logger.e("Receiving notification failed") logger.e(error!) report?(.receivingNotificationFailed, "Receiving notification failed") } else { // During the upload we may get either a Packet Receipt Notification, or a Response with status code if proceed != nil { if let prn = PacketReceiptNotification(characteristic.value!) { proceed!(prn.bytesReceived) return } } // Otherwise... logger.i("Notification received from \(characteristic.uuid.uuidString), value (0x): \(characteristic.value!.hexString)") // Parse response received let response = Response(characteristic.value!) if let response = response { logger.a("\(response.description) received") if response.status == .success { switch response.requestOpCode! { case .initDfuParameters: logger.a("Initialize DFU Parameters completed") case .receiveFirmwareImage: let interval = CFAbsoluteTimeGetCurrent() - uploadStartTime! as CFTimeInterval logger.a("Upload completed in \(interval.format(".2")) seconds") default: break } success?() } else { logger.e("Error \(response.status!.code): \(response.status!.description)") report?(DFUError(rawValue: Int(response.status!.rawValue))!, response.status!.description) } } else { logger.e("Unknown response received: 0x\(characteristic.value!.hexString)") report?(.unsupportedResponse, "Unsupported response received: 0x\(characteristic.value!.hexString)") } } } }
mit
f095b4798b97914a30dc3a5f8e7bff24
43.931442
152
0.628328
5.127057
false
false
false
false
yangboz/TheRealBishop
Swift/DataStructure_Swift/DataStructure_Swift/GameScene.swift
1
1312
// // GameScene.swift // DataStructure_Swift // // Created by yangboz on 14-7-14. // Copyright (c) 2014年 GODPAPER. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Hello, World!"; myLabel.fontSize = 65; myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(myLabel) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */ for touch: AnyObject in touches { let location = touch.locationInNode(self) let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.position = location let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
9e73f6783b99a864c76cfb9606e56a09
28.111111
93
0.58626
4.763636
false
false
false
false
haijianhuo/TopStore
TopStore/Vendors/HHImageCropper/HHImageScrollView.swift
1
10021
// // HHImageScrollView.swift // BoxAvatar // // Created by Haijian Huo on 8/13/17. // Copyright © 2017 Haijian Huo. All rights reserved. // import UIKit class HHImageScrollView: UIScrollView { var zoomView: UIImageView? var aspectFill: Bool = false private var imageSize: CGSize? private var pointToCenterAfterResize: CGPoint = .zero private var scaleToRestoreAfterResize: CGFloat = 0 private var sizeChanging: Bool = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.aspectFill = false self.showsVerticalScrollIndicator = false self.showsHorizontalScrollIndicator = false self.bouncesZoom = true self.scrollsToTop = false self.decelerationRate = UIScrollViewDecelerationRateFast self.delegate = self } override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) self.centerZoomView() } func setAspectFill(aspectFill: Bool) { if self.aspectFill != aspectFill { self.aspectFill = aspectFill if self.zoomView != nil { self.setMaxMinZoomScalesForCurrentBounds() if (self.zoomScale < self.minimumZoomScale) { self.zoomScale = self.minimumZoomScale } } } } override var frame: CGRect { willSet { self.sizeChanging = !newValue.size.equalTo(self.frame.size) if (self.sizeChanging) { self.prepareToResize() } } didSet { if (self.sizeChanging) { self.recoverFromResizing() } self.centerZoomView() } } // MARK: - Center zoomView within scrollView fileprivate func centerZoomView() { guard let zoomView = self.zoomView else { return } // center zoomView as it becomes smaller than the size of the screen // we need to use contentInset instead of contentOffset for better positioning when zoomView fills the screen if (self.aspectFill) { var top: CGFloat = 0 var left: CGFloat = 0 // center vertically if (self.contentSize.height < self.bounds.height) { top = (self.bounds.height - self.contentSize.height) * 0.5 } // center horizontally if (self.contentSize.width < self.bounds.width) { left = (self.bounds.width - self.contentSize.width) * 0.5 } self.contentInset = UIEdgeInsetsMake(top, left, top, left); } else { var frameToCenter = zoomView.frame // center horizontally if (frameToCenter.width < self.bounds.width) { frameToCenter.origin.x = (self.bounds.width - frameToCenter.width) * 0.5 } else { frameToCenter.origin.x = 0 } // center vertically if (frameToCenter.height < self.bounds.height) { frameToCenter.origin.y = (self.bounds.height - frameToCenter.height) * 0.5 } else { frameToCenter.origin.y = 0 } zoomView.frame = frameToCenter } } // MARK: - Configure scrollView to display new image func displayImage(image: UIImage) { // clear view for the previous image self.zoomView?.removeFromSuperview() self.zoomView = nil // reset our zoomScale to 1.0 before doing any further calculations self.zoomScale = 1.0 // make views to display the new image let zoomView = UIImageView(image: image) self.addSubview(zoomView) self.zoomView = zoomView self.configureForImageSize(imageSize: image.size) } private func configureForImageSize(imageSize: CGSize) { self.imageSize = imageSize self.contentSize = imageSize self.setMaxMinZoomScalesForCurrentBounds() self.setInitialZoomScale() self.setInitialContentOffset() self.contentInset = .zero } private func setMaxMinZoomScalesForCurrentBounds() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size // calculate min/max zoomscale let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise var minScale: CGFloat = 0 if (!self.aspectFill) { minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible } else { minScale = max(xScale, yScale) // use maximum of these to allow the image to fill the screen } var maxScale = max(xScale, yScale) // Image must fit/fill the screen, even if its size is smaller. let xImageScale = maxScale * imageSize.width / boundsSize.width let yImageScale = maxScale * imageSize.height / boundsSize.height var maxImageScale = max(xImageScale, yImageScale) maxImageScale = max(minScale, maxImageScale) maxScale = max(maxScale, maxImageScale) // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if (minScale > maxScale) { minScale = maxScale; } self.maximumZoomScale = maxScale self.minimumZoomScale = minScale } private func setInitialZoomScale() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise let scale = max(xScale, yScale) self.zoomScale = scale } private func setInitialContentOffset() { guard let zoomView = self.zoomView else { return } let boundsSize = self.bounds.size let frameToCenter = zoomView.frame var contentOffset: CGPoint = .zero if (frameToCenter.width > boundsSize.width) { contentOffset.x = (frameToCenter.width - boundsSize.width) * 0.5 } else { contentOffset.x = 0 } if (frameToCenter.height > boundsSize.height) { contentOffset.y = (frameToCenter.height - boundsSize.height) * 0.5 } else { contentOffset.y = 0 } self.setContentOffset(contentOffset, animated: false) } // MARK: // MARK: Methods called during rotation to preserve the zoomScale and the visible portion of the image // MARK: Rotation support private func prepareToResize() { guard let zoomView = self.zoomView else { return } let boundsCenter = CGPoint(x: self.bounds.midX, y: self.bounds.midY) pointToCenterAfterResize = self.convert(boundsCenter, to: zoomView) self.scaleToRestoreAfterResize = self.zoomScale // If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum // allowable scale when the scale is restored. if Float(self.scaleToRestoreAfterResize) <= Float(self.minimumZoomScale) + Float.ulpOfOne { self.scaleToRestoreAfterResize = 0 } } private func recoverFromResizing() { guard let zoomView = self.zoomView else { return } self.setMaxMinZoomScalesForCurrentBounds() // Step 1: restore zoom scale, first making sure it is within the allowable range. let maxZoomScale = max(self.minimumZoomScale, scaleToRestoreAfterResize) self.zoomScale = min(self.maximumZoomScale, maxZoomScale) // Step 2: restore center point, first making sure it is within the allowable range. // 2a: convert our desired center point back to our own coordinate space let boundsCenter = self.convert(self.pointToCenterAfterResize, from: zoomView) // 2b: calculate the content offset that would yield that center point var offset = CGPoint(x: boundsCenter.x - self.bounds.size.width / 2.0, y: boundsCenter.y - self.bounds.size.height / 2.0) // 2c: restore offset, adjusted to be within the allowable range let maxOffset = self.maximumContentOffset() let minOffset = self.minimumContentOffset() var realMaxOffset = min(maxOffset.x, offset.x) offset.x = max(minOffset.x, realMaxOffset) realMaxOffset = min(maxOffset.y, offset.y) offset.y = max(minOffset.y, realMaxOffset) self.contentOffset = offset } private func maximumContentOffset() -> CGPoint { let contentSize = self.contentSize let boundsSize = self.bounds.size return CGPoint(x: contentSize.width - boundsSize.width, y: contentSize.height - boundsSize.height) } private func minimumContentOffset() -> CGPoint { return .zero } } // MARK: UIScrollViewDelegate extension HHImageScrollView: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.zoomView } func scrollViewDidZoom(_ scrollView: UIScrollView) { self.centerZoomView() } }
mit
14a6176d34ad9c701e7a215ca0c57c24
33.67128
129
0.602695
5.05295
false
false
false
false
Shirley0202/notes
下载器/MZDownloadManager-master/Example/MZDownloadManager/MZAvailableDownloadsViewController.swift
1
3976
// // MZAvailableDownloadsViewController.swift // MZDownloadManager // // Created by Muhammad Zeeshan on 23/10/2014. // Copyright (c) 2014 ideamakerz. All rights reserved. // import UIKit import MZDownloadManager class MZAvailableDownloadsViewController: UITableViewController { var mzDownloadingViewObj : MZDownloadManagerViewController? var availableDownloadsArray: [String] = [] let myDownloadPath = MZUtility.baseFilePath + "/My Downloads" override func viewDidLoad() { super.viewDidLoad() if !FileManager.default.fileExists(atPath: myDownloadPath) { try! FileManager.default.createDirectory(atPath: myDownloadPath, withIntermediateDirectories: true, attributes: nil) } debugPrint("custom download path: \(myDownloadPath)") availableDownloadsArray.append("https://www.dropbox.com/s/yrura6qlcgcwpp4/file1.mp4?dl=1") availableDownloadsArray.append("https://www.dropbox.com/s/y9kgs6caztxxjdh/AlecrimCoreData-master.zip?dl=1") availableDownloadsArray.append("https://www.dropbox.com/s/73ymbx6icoiqus9/file2.mp4?dl=1") availableDownloadsArray.append("https://www.dropbox.com/s/4pw4jwiju0eon6r/file3.mp4?dl=1") availableDownloadsArray.append("https://www.dropbox.com/s/2bmbk8id7nseirq/file4.mp4?dl=1") availableDownloadsArray.append("https://www.dropbox.com/s/cw7wfyaic9rtzwd/GCDExample-master.zip?dl=1") self.setUpDownloadingViewController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setUpDownloadingViewController() { let tabBarTabs : NSArray? = self.tabBarController?.viewControllers as NSArray? let mzDownloadingNav : UINavigationController = tabBarTabs?.object(at: 1) as! UINavigationController mzDownloadingViewObj = mzDownloadingNav.viewControllers[0] as? MZDownloadManagerViewController } } //MARK: UITableViewDataSource Handler Extension extension MZAvailableDownloadsViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availableDownloadsArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier : NSString = "AvailableDownloadsCell" let cell : UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier as String, for: indexPath) as UITableViewCell let fileURL : NSString = availableDownloadsArray[(indexPath as NSIndexPath).row] as NSString let fileName : NSString = fileURL.lastPathComponent as NSString cell.textLabel?.text = fileName as String return cell } } //MARK: UITableViewDelegate Handler Extension extension MZAvailableDownloadsViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let fileURL : NSString = availableDownloadsArray[(indexPath as NSIndexPath).row] as NSString var fileName : NSString = fileURL.lastPathComponent as NSString fileName = MZUtility.getUniqueFileNameWithPath((myDownloadPath as NSString).appendingPathComponent(fileName as String) as NSString) //Use it download at default path i.e document directory // mzDownloadingViewObj?.downloadManager.addDownloadTask(fileName as String, fileURL: fileURL as String) mzDownloadingViewObj?.downloadManager.addDownloadTask(fileName as String, fileURL: fileURL as String, destinationPath: myDownloadPath) availableDownloadsArray.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.right) } }
mit
c38f6dba298e23c1530b84d729c9ca09
43.674157
148
0.727113
4.790361
false
false
false
false
shubham01/StyleGuide
StyleGuide/Classes/Extensions.swift
1
911
// // Extensions.swift // StyleGuide // // Created by Shubham Agrawal on 27/10/17. // import Foundation extension UIView { @IBInspectable var viewCornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var viewBorderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var viewBorderColor: UIColor? { get { if let color = layer.borderColor { return UIColor(cgColor: color) } else { return nil } } set { if let color = newValue?.cgColor { layer.borderColor = color } } } }
mit
0489be3f988f6c9a36ba13c762c63894
20.690476
50
0.49506
5.033149
false
false
false
false
Rajat-Dhasmana/wain
constraintsfinal/ConstraintsDemo/ConstraintsDemo/AppDelegate.swift
1
4609
// // AppDelegate.swift // ConstraintsDemo // // Created by Rajat Dhasmana on 06/03/17. // Copyright © 2017 appinventiv. 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. self.saveContext() } // MARK: - Core Data stack 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: "ConstraintsDemo") 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)") } } } }
mit
5c8751b2e18c45fbcedc1f3a0b69cdbd
48.548387
285
0.687066
5.855146
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/UI/FormAppearance.swift
1
2671
// Copyright DApps Platform Inc. All rights reserved. import Foundation import Eureka struct AppFormAppearance { static func textArea(tag: String? = .none, callback: @escaping (TextAreaRow) -> Void) -> TextAreaRow { let textArea = TextAreaRow(tag) { $0.title = "" }.onRowValidationChanged { AppFormAppearance.onRowValidationChanged(baseCell: $0, row: $1) } callback(textArea) return textArea } static func textField(tag: String? = .none, callback: @escaping (TextRow) -> Void) -> TextRow { let textField = TextRow(tag) { $0.title = "" }.cellUpdate { cell, row in if !row.isValid { cell.textField?.textColor = .red } }.onRowValidationChanged { AppFormAppearance.onRowValidationChanged(baseCell: $0, row: $1) } callback(textField) return textField } static func textFieldFloat(tag: String? = .none, callback: @escaping (TextFloatLabelRow) -> Void) -> TextFloatLabelRow { let textField = TextFloatLabelRow(tag) { $0.title = "" }.cellUpdate { cell, row in if !row.isValid { cell.textField?.textColor = .red } }.onRowValidationChanged { AppFormAppearance.onRowValidationChanged(baseCell: $0, row: $1) } callback(textField) return textField } static func onRowValidationChanged(baseCell: BaseCell, row: BaseRow) { guard let rowIndex = row.indexPath?.row, let rowSection = row.section else { return } while rowSection.count > rowIndex + 1 && rowSection[rowIndex + 1] is LabelRow { rowSection.remove(at: rowIndex + 1) } if !row.isValid { for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() { let labelRow = LabelRow { $0.title = validationMsg $0.cell.height = { 36 } }.cellUpdate { cell, _ in cell.textLabel?.font = AppStyle.error.font cell.textLabel?.textColor = AppStyle.error.textColor } row.section?.insert(labelRow, at: row.indexPath!.row + index + 1) } } } static func button(_ title: String? = .none, callback: @escaping (ButtonRow) -> Void) -> ButtonRow { let button = ButtonRow(title) .cellUpdate { cell, _ in cell.textLabel?.textAlignment = .left cell.textLabel?.textColor = .black } callback(button) return button } }
gpl-3.0
0a5de2fef5c477038bf2d965283fbb7f
34.144737
124
0.564957
4.710758
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Libxml2/Converters/In/InNodeConverter.swift
2
3885
import Foundation import libxml2 class InNodeConverter: SafeConverter { init(shouldCollapseSpaces: Bool = true) { self.shouldCollapseSpaces = shouldCollapseSpaces } var shouldCollapseSpaces: Bool = true /// Converts a single node (from libxml2) into an HTML.Node. /// /// - Parameters: /// - attributes: the libxml2 attribute to convert. /// /// - Returns: an HTML.Node. /// func convert(_ rawNode: xmlNode) -> Node { var node: Node switch rawNode.type { case XML_TEXT_NODE: node = createTextNode(rawNode) case XML_CDATA_SECTION_NODE: node = createTextNode(rawNode) case XML_COMMENT_NODE: node = createCommentNode(rawNode) default: node = createElementNode(rawNode) } return node } fileprivate func createAttributes(fromNode rawNode: xmlNode) -> [Attribute] { let attributesConverter = InAttributesConverter() return attributesConverter.convert(rawNode.properties) } /// Creates an HTML.Node from a libxml2 element node. /// /// - Parameters: /// - rawNode: the libxml2 xmlNode. /// /// - Returns: the HTML.ElementNode /// fileprivate func createElementNode(_ rawNode: xmlNode) -> ElementNode { let nodeName = getNodeName(rawNode) switch nodeName.lowercased() { case RootNode.name: return createRootNode(rawNode) default: break } var children = [Node]() if rawNode.children != nil { let nodesConverter = InNodesConverter(shouldCollapseSpaces: shouldCollapseSpaces) children.append(contentsOf: nodesConverter.convert(rawNode.children)) } let attributes = createAttributes(fromNode: rawNode) let node = ElementNode(name: nodeName, attributes: attributes, children: children) // TODO: This can be optimized to be set during instantiation of the child nodes. // for child in children { child.parent = node } return node } /// Creates an HTML.RootNode from a libxml2 element root node. /// /// - Parameters: /// - rawNode: the libxml2 xmlNode. /// /// - Returns: the HTML.RootNode /// fileprivate func createRootNode(_ rawNode: xmlNode) -> RootNode { var children = [Node]() if rawNode.children != nil { let nodesConverter = InNodesConverter(shouldCollapseSpaces: shouldCollapseSpaces) children.append(contentsOf: nodesConverter.convert(rawNode.children)) } let node = RootNode(children: children) // TODO: This can be optimized to be set during instantiation of the child nodes. // for child in children { child.parent = node } return node } /// Creates an HTML.TextNode from a libxml2 element node. /// /// - Parameters: /// - rawNode: the libxml2 xmlNode. /// /// - Returns: the HTML.TextNode /// fileprivate func createTextNode(_ rawNode: xmlNode) -> TextNode { let text = String(cString: rawNode.content) let node = TextNode(text: text) node.shouldCollapseSpaces = shouldCollapseSpaces return node } /// Creates an HTML.CommentNode from a libxml2 element node. /// /// - Parameters: /// - rawNode: the libxml2 xmlNode. /// /// - Returns: the HTML.CommentNode /// fileprivate func createCommentNode(_ rawNode: xmlNode) -> CommentNode { let text = String(cString: rawNode.content) let node = CommentNode(text: text) return node } fileprivate func getNodeName(_ rawNode: xmlNode) -> String { return String(cString: rawNode.name) } }
mpl-2.0
772b81711eec83d88174e1fcddd808ee
27.992537
93
0.604118
4.619501
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TransactionsRouter/TransactionFlowAction.swift
1
4230
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import ToolKit /// Represents all types of transactions the user can perform public enum TransactionFlowAction { // Restores an existing order. case order(OrderDetails) /// Performs a buy. If `CryptoAccount` is `nil`, the users will be presented with a crypto currency selector. case buy(CryptoAccount?) /// Performs a sell. If `CryptoCurrency` is `nil`, the users will be presented with a crypto currency selector. case sell(CryptoAccount?) /// Performs a swap. If `CryptoCurrency` is `nil`, the users will be presented with a crypto currency selector. case swap(CryptoAccount?) /// Performs a send. If `BlockchainAccount` is `nil`, the users will be presented with a crypto account selector. case send(BlockchainAccount?, TransactionTarget?) /// Performs a receive. If `CryptoAccount` is `nil`, the users will be presented with a crypto account selector. case receive(CryptoAccount?) /// Performs an interest transfer. case interestTransfer(CryptoInterestAccount) /// Performs an interest withdraw. case interestWithdraw(CryptoInterestAccount) /// Performs a withdraw. case withdraw(FiatAccount) /// Performs a deposit. case deposit(FiatAccount) /// Signs a transaction case sign(sourceAccount: BlockchainAccount, destination: TransactionTarget) } extension TransactionFlowAction: Equatable { public static func == (lhs: TransactionFlowAction, rhs: TransactionFlowAction) -> Bool { switch (lhs, rhs) { case (.buy(let lhsAccount), .buy(let rhsAccount)), (.sell(let lhsAccount), .sell(let rhsAccount)), (.swap(let lhsAccount), .swap(let rhsAccount)), (.receive(let lhsAccount), .receive(let rhsAccount)): return lhsAccount?.identifier == rhsAccount?.identifier case (.interestTransfer(let lhsAccount), .interestTransfer(let rhsAccount)), (.interestWithdraw(let lhsAccount), .interestWithdraw(let rhsAccount)): return lhsAccount.identifier == rhsAccount.identifier case (.withdraw(let lhsAccount), .withdraw(let rhsAccount)), (.deposit(let lhsAccount), .deposit(let rhsAccount)): return lhsAccount.identifier == rhsAccount.identifier case (.order(let lhsOrder), .order(let rhsOrder)): return lhsOrder.identifier == rhsOrder.identifier case (.sign(let lhsAccount, let lhsDestination), .sign(let rhsAccount, let rhsDestination)): return lhsAccount.identifier == rhsAccount.identifier && lhsDestination.label == rhsDestination.label case (.send(let lhsFromAccount, let lhsDestination), .send(let rhsFromAccount, let rhsDestination)): return lhsFromAccount?.identifier == rhsFromAccount?.identifier && lhsDestination?.label == rhsDestination?.label default: return false } } } extension TransactionFlowAction { var isCustodial: Bool { switch self { case .buy, .sell, .swap: return true case .send(let account, _), .sign(let account as BlockchainAccount?, _), .receive(let account as BlockchainAccount?): return account?.accountType.isCustodial ?? false case .order, .interestTransfer, .interestWithdraw, .withdraw, .deposit: return true } } } extension TransactionFlowAction { var asset: AssetAction { switch self { case .buy: return .buy case .sell: return .sell case .swap: return .swap case .send: return .send case .receive: return .receive case .order: return .buy case .deposit: return .deposit case .withdraw: return .withdraw case .interestTransfer: return .interestTransfer case .interestWithdraw: return .interestWithdraw case .sign: return .sign } } }
lgpl-3.0
ba2bc4baa019af06b97d7e9edda3dc74
37.099099
117
0.632774
4.951991
false
false
false
false
anilkumarbp/swift-sdk-new
src/Subscription/crypt/UInt32Extension.swift
9
2965
// // UInt32Extension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 02/09/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation /** array of bytes */ extension UInt32 { public func bytes(_ totalBytes: Int = sizeof(UInt32)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } public static func withBytes(bytes: ArraySlice<UInt8>) -> UInt32 { return UInt32.withBytes(Array(bytes)) } /** Int with array bytes (little-endian) */ public static func withBytes(bytes: [UInt8]) -> UInt32 { return integerWithBytes(bytes) } } /** Shift bits */ extension UInt32 { /** Shift bits to the left. All bits are shifted (including sign bit) */ private mutating func shiftLeft(count: UInt32) -> UInt32 { if (self == 0) { return self; } var bitsCount = UInt32(sizeof(UInt32) * 8) var shiftCount = Swift.min(count, bitsCount - 1) var shiftedValue:UInt32 = 0; for bitIdx in 0..<bitsCount { // if bit is set then copy to result and shift left 1 var bit = 1 << bitIdx if ((self & bit) == bit) { shiftedValue = shiftedValue | (bit << shiftCount) } } if (shiftedValue != 0 && count >= bitsCount) { // clear last bit that couldn't be shifted out of range shiftedValue = shiftedValue & (~(1 << (bitsCount - 1))) } self = shiftedValue return self } /** Shift bits to the right. All bits are shifted (including sign bit) */ private mutating func shiftRight(count: UInt32) -> UInt32 { if (self == 0) { return self; } var bitsCount = UInt32(sizeofValue(self) * 8) if (count >= bitsCount) { return 0 } var maxBitsForValue = UInt32(floor(log2(Double(self)) + 1)) var shiftCount = Swift.min(count, maxBitsForValue - 1) var shiftedValue:UInt32 = 0; for bitIdx in 0..<bitsCount { // if bit is set then copy to result and shift left 1 var bit = 1 << bitIdx if ((self & bit) == bit) { shiftedValue = shiftedValue | (bit >> shiftCount) } } self = shiftedValue return self } } /** shift left and assign with bits truncation */ public func &<<= (inout lhs: UInt32, rhs: UInt32) { lhs.shiftLeft(rhs) } /** shift left with bits truncation */ public func &<< (lhs: UInt32, rhs: UInt32) -> UInt32 { var l = lhs; l.shiftLeft(rhs) return l } /** shift right and assign with bits truncation */ func &>>= (inout lhs: UInt32, rhs: UInt32) { lhs.shiftRight(rhs) } /** shift right and assign with bits truncation */ func &>> (lhs: UInt32, rhs: UInt32) -> UInt32 { var l = lhs; l.shiftRight(rhs) return l }
mit
9994a788be5e009b7c3ce3ce4812cca4
26.462963
77
0.56425
4.067215
false
false
false
false
modocache/swift
test/expr/capture/generic_params.swift
4
1490
// RUN: %target-swift-frontend -dump-ast %s 2>&1 | %FileCheck %s func doSomething<T>(_ t: T) {} // CHECK: func_decl "outerGeneric(t:x:)"<T> interface type='<τ_0_0> (t: τ_0_0, x: AnyObject) -> ()' func outerGeneric<T>(t: T, x: AnyObject) { // Simple case -- closure captures outer generic parameter // CHECK: closure_expr type='() -> ()' {{.*}} discriminator=0 captures=(<generic> t) single-expression _ = { doSomething(t) } // Special case -- closure does not capture outer generic parameters // CHECK: closure_expr type='() -> ()' {{.*}} discriminator=1 captures=(x) single-expression _ = { doSomething(x) } // Special case -- closure captures outer generic parameter, but it does not // appear as the type of any expression // CHECK: closure_expr type='() -> ()' {{.*}} discriminator=2 captures=(<generic> x) _ = { if x is T {} } // Nested generic functions always capture outer generic parameters, even if // they're not mentioned in the function body // CHECK: func_decl "innerGeneric(u:)"<U> interface type='<τ_0_0, τ_1_0> (u: τ_1_0) -> ()' {{.*}} captures=(<generic> ) func innerGeneric<U>(u: U) {} // Make sure we look through typealiases typealias TT = (a: T, b: T) // CHECK: func_decl "localFunction(tt:)" interface type='<τ_0_0> (tt: (a: τ_0_0, b: τ_0_0)) -> ()' {{.*}} captures=(<generic> ) func localFunction(tt: TT) {} // CHECK: closure_expr type='(TT) -> ()' {{.*}} captures=(<generic> ) let _: (TT) -> () = { _ in } }
apache-2.0
5e2ea996e0688e15cdce1ce55403e22d
42.588235
129
0.609987
3.32287
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/HappeningsNS.swift
1
1879
// // HappeningsNS.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 26/10/17. // import Foundation class HappeningsNS: BaseNS { static let shared = HappeningsNS() lazy var awesomeRequester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm) override init() {} var lastHappeningsRequest: URLSessionDataTask? func fetchHappenings(params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping ([Happening], ErrorData?) -> Void) { func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping ([Happening], ErrorData?) -> Void ) -> Bool { if let jsonObject = data { self.lastHappeningsRequest = nil response(HappeningsMP.parseHappeningsFrom(jsonObject), nil) return true } else { self.lastHappeningsRequest = nil if let error = error { response([Happening](), error) return false } response([Happening](), ErrorData(.unknown, "response Data could not be parsed")) return false } } let url = ACConstants.shared.happenings let method: URLMethod = .GET if params.contains(.shouldFetchFromCache) { _ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: nil), response: response) } lastHappeningsRequest = awesomeRequester.performRequestAuthorized( url, forceUpdate: true, completion: { (data, error, responseType) in if processResponse(data: data, error: error, response: response) { self.saveToCache(url, method: method, bodyDict: nil, data: data) } }) } }
mit
7412855c8ec44ebb8de53388f334370b
35.843137
134
0.591272
4.793367
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Extensions/UITabBarController+Extensions.swift
1
2282
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import UIKit extension UITabBarController { open func setTabBarHidden(_ hide: Bool, animated: Bool) { let frame = tabBar.frame let offsetY = hide ? frame.size.height : -frame.size.height var newFrame = frame newFrame.origin.y = view.frame.maxY + offsetY tabBar.isHidden = false UIView.animate(withDuration: animated ? 0.35 : 0.0, delay: 0, options: .beginFromCurrentState) { self.tabBar.frame = newFrame } completion: { complete in if complete { self.tabBar.isHidden = hide } } } } extension UITabBarController { func isRootViewController(_ viewController: UIViewController) -> Bool { guard let viewControllers = viewControllers else { return false } if let navigationController = viewController.navigationController { return viewControllers.contains(navigationController) } return viewControllers.contains(viewController) } } // MARK: - Forwarding extension UITabBarController { // Autorotation Fix. Simply override `supportedInterfaceOrientations` method in // any view controller and it would respect that orientation setting per view // controller. open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { selectedViewController?.preferredInterfaceOrientations ?? preferredInterfaceOrientations ?? selectedViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations } open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { selectedViewController?.interfaceOrientationForPresentation ?? interfaceOrientationForPresentation ?? selectedViewController?.preferredInterfaceOrientationForPresentation ?? super.preferredInterfaceOrientationForPresentation } open override var shouldAutorotate: Bool { selectedViewController?.isAutorotateEnabled ?? isAutorotateEnabled ?? selectedViewController?.shouldAutorotate ?? super.shouldAutorotate } }
mit
69f97bbc1e7919a1c325269680e22766
33.044776
104
0.688295
6.425352
false
false
false
false
KaushalElsewhere/MockingBird
MockingBird/Views/MyProfileAvatarCell.swift
1
1149
// // MyProfileAvatarCell.swift // MockingBird // // Created by Kaushal Elsewhere on 12/08/16. // Copyright © 2016 Elsewhere. All rights reserved. // import UIKit class MyProfileAvatarCell: TableViewCell { lazy var avatar: UIImageView = { let imageView = UIImageView() imageView.userInteractionEnabled = true imageView.layer.cornerRadius = 30 imageView.layer.borderWidth = 1 imageView.layer.backgroundColor = UIColor.blackColor().CGColor imageView.layer.masksToBounds = false imageView.image = UIImage(named: "camera.png") imageView.contentMode = .ScaleAspectFit return imageView }() override func setupViews() { //backgroundColor = .yellowColor() contentView.addSubview(avatar) setupConstraints() } override func setupConstraints() { let superView = contentView avatar.snp_makeConstraints { (make) in make.top.equalTo(20) make.bottom.equalTo(20) make.centerX.equalTo(superView.snp_centerX) make.width.height.equalTo(60) } } }
mit
26dacd1316b67e85db08d086f588f58b
27.7
70
0.634146
4.843882
false
false
false
false
jlukanta/OneMarket
OneMarket/OneMarket/ItemListVC.swift
1
2423
import UIKit class ItemListVC: UITableViewController { // Item service this screen will use public var itemService:ItemService! // Data private var items:[DailyItems]! // Allows us to organize items by date private struct DailyItems { var date: Date var items: [Item] init (date: Date, items: [Item]) { self.date = date self.items = items } } // User has selected a cell -- de-select it and show details page override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: SegueId.ItemDetails, sender: self) } // Register the kind of cell that we are going to use in the list override func viewDidLoad () { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: CellId.Item) } // Load items list from storage override func viewWillAppear(_ animated: Bool) { let dates = itemService.getAssignedDates() items = dates.map { (date) -> DailyItems in DailyItems(date: date, items: itemService.getItemsSortedByName(day: date)) } tableView.reloadData() } // Number of sections (i.e. the various different days) override func numberOfSections(in tableView: UITableView) -> Int { return items.count } // Title of sections (i.e. what the day is) override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return String(describing: items[section].date) } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return items[section].items.count } // Display cell (with item name) override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellId.Item)! let item = items[indexPath.section].items[indexPath.row] cell.textLabel!.text = item.name return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) // Prepare transition to details screen if (segue.identifier == SegueId.ItemDetails) { let vc = segue.destination as! ItemDetailsVC let indexPath = tableView.indexPathForSelectedRow! let item = items[indexPath.section].items[indexPath.row] vc.itemId = item.id } } }
mit
f6e3d3bd997ad6f9a058b3fe203837e1
30.064103
107
0.695006
4.503717
false
false
false
false
novastorm/Udacity-MemeMe
MemeMe/MemeTableViewController.swift
1
2030
// // MemeTableViewController.swift // MemeMe // // Created by Adland Lee on 2/21/16. // Copyright © 2016 Adland Lee. All rights reserved. // import UIKit class MemeTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var memes: [Meme] { return (UIApplication.shared.delegate as! AppDelegate).memes } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) (view as! UITableView).reloadData() } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "MemeTableViewCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)! let meme = memes[indexPath.row] // Set the name and image cell.imageView?.image = meme.memedImage cell.textLabel?.text = "\(meme.topText!) \(meme.bottomText!)" return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { (UIApplication.shared.delegate as! AppDelegate).memes.remove(at: indexPath.row) (view as! UITableView).deleteRows(at: [indexPath], with: .automatic) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC = storyboard!.instantiateViewController(withIdentifier: "MemeDetailViewController") as! MemeDetailViewController detailVC.meme = memes[indexPath.row] navigationController!.pushViewController(detailVC, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memes.count } } class MemeTableViewCell: UITableViewCell { // TODO: Customize cell layout }
mit
09e34c340002afb3e1b169778b2c73b0
32.816667
133
0.675702
5.242894
false
false
false
false
RoverPlatform/rover-ios
Sources/Data/SyncCoordinator/SyncCoordinatorService.swift
1
4099
// // SyncCoordinatorService.swift // RoverData // // Created by Sean Rucker on 2018-09-24. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import os.log import UIKit class SyncCoordinatorService: SyncCoordinator { let client: SyncClient var syncTask: URLSessionTask? var completionHandlers = [(UIBackgroundFetchResult) -> Void]() var participants = [SyncParticipant]() init(client: SyncClient) { self.client = client } func sync(completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { var intialParticipants = [SyncParticipant]() var intialRequests = [SyncRequest]() for participant in self.participants { if let request = participant.initialRequest() { intialParticipants.append(participant) intialRequests.append(request) } } self.sync(participants: intialParticipants, requests: intialRequests, completionHandler: completionHandler) } func sync(participants: [SyncParticipant], requests: [SyncRequest], completionHandler: ((UIBackgroundFetchResult) -> Void)? = nil) { if let newHandler = completionHandler { self.completionHandlers.append(newHandler) } if self.syncTask != nil { os_log("Sync already in-progress", log: .sync, type: .debug) return } self.recursiveSync(participants: participants, requests: requests) } func recursiveSync(participants: [SyncParticipant], requests: [SyncRequest], newData: Bool = false) { if participants.isEmpty || requests.isEmpty { if newData { self.invokeCompletionHandlers(.newData) } else { self.invokeCompletionHandlers(.noData) } return } // Refactoring this wouldn't add a lot of value, so silence the closure length warning. // swiftlint:disable:next closure_body_length let task = self.client.task(with: requests) { [weak self] result in DispatchQueue.main.async { guard let _self = self else { return } _self.syncTask = nil switch result { case .error(let error, _): if let error = error { os_log("Sync task failed: %@", log: .sync, type: .error, error.logDescription) } else { os_log("Sync task failed", log: .sync, type: .error) } _self.invokeCompletionHandlers(.failed) case .success(let data): var results = [SyncResult]() var nextParticipants = [SyncParticipant]() var nextRequests = [SyncRequest]() var newData = newData for participant in participants { let result = participant.saveResponse(data) results.append(result) if case .newData(let nextRequest) = result { newData = true if let nextRequest = nextRequest { nextParticipants.append(participant) nextRequests.append(nextRequest) } } } _self.recursiveSync(participants: nextParticipants, requests: nextRequests, newData: newData) } } } task.resume() self.syncTask = task } func invokeCompletionHandlers(_ result: UIBackgroundFetchResult) { let completionHandlers = self.completionHandlers self.completionHandlers = [] completionHandlers.forEach { $0(result) } } }
apache-2.0
6e5be005cfd8c0f349ef972792c2ffde
34.947368
136
0.525134
5.731469
false
false
false
false
naokits/bluemix-swift-demo-ios
Pods/BMSCore/Source/Security/Identity/BaseAppIdentity.swift
2
1511
/* *     Copyright 2015 IBM Corp. *     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. */ /// This class represents the base app identity class, with default methods and keys public class BaseAppIdentity : AppIdentity{ public static let ID = "id" public static let VERSION = "version" public internal(set) var jsonData : [String:String] = ([:]) public var id:String? { get{ return jsonData[BaseAppIdentity.ID] } } public var version:String? { get{ return jsonData[BaseAppIdentity.VERSION] } } public init() { jsonData[BaseAppIdentity.ID] = NSBundle(forClass:object_getClass(self)).bundleIdentifier; jsonData[BaseAppIdentity.VERSION] = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String; } public init(map: [String:AnyObject]?) { guard let json = map as? [String:String] else { jsonData = ([:]) return } jsonData = json } }
mit
df24a541db4e0d58be8d4cd7a40fac42
29.854167
117
0.680621
3.970509
false
false
false
false
Dougly/2For1
2for1/PlayerCollectionView.swift
1
4083
// // PlayerCollectionViewDelegate.swift // 2for1 // // Created by Douglas Galante on 1/21/17. // Copyright © 2017 Flatiron. All rights reserved. // import UIKit class PlayerCollectionView: NSObject, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UpdateCollectionViewDelegate { let store = DataStore.sharedInstance var delegate: SetupViewController? let screenWidth = UIScreen.main.bounds.width var spacing: CGFloat! var sectionInsets: UIEdgeInsets! var size: CGSize! var numberOfCellsPerRow: CGFloat = 3 func configureLayout () { let desiredSpacing: CGFloat = 5 let itemWidth = (screenWidth / numberOfCellsPerRow) - (desiredSpacing + 2) let itemHeight = itemWidth * 1.25 spacing = desiredSpacing sectionInsets = UIEdgeInsets(top: spacing * 2, left: spacing, bottom: spacing, right: spacing) size = CGSize(width: itemWidth, height: itemHeight) } func reloadCollectionView(withPlayer handle: String) { delegate?.reloadCollectionView(withPlayer: handle) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return store.players.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "playerCell", for: indexPath) as! CustomPlayerCell let player = store.players[indexPath.row] cell.tagLabel.text = player.tag cell.pictureImageView.image = player.playerImage cell.contentView.layer.borderColor = UIColor.themeBlue.cgColor if cell.isSelected { cell.contentView.layer.borderWidth = 3 } else { cell.contentView.layer.borderWidth = 0 } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return spacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return spacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! CustomPlayerCell guard let viewController = delegate else { return } if cell.contentView.layer.borderWidth == 0 { cell.contentView.layer.borderWidth = 3 store.players[indexPath.item].isSelected = true viewController.selectedIndexPaths.append(indexPath) } else { cell.contentView.layer.borderWidth = 0 store.players[indexPath.item].isSelected = false for (index, ip) in viewController.selectedIndexPaths.enumerated() { if indexPath == ip { viewController.selectedIndexPaths.remove(at: index) } } } viewController.selectedIndexPaths.sort { $0.row > $1.row } if viewController.selectedIndexPaths.count >= 2 && viewController.playerCollectionViewBottomConstraint.constant == 0 { viewController.showStartGameButton() } else if viewController.selectedIndexPaths.count < 2 { viewController.hideStartGameButton() } } }
mit
135ef7f7dbe413e1a3f2e3a035449b44
36.796296
175
0.680059
5.765537
false
false
false
false
lawrencehjf/ColorSenseRainbow
ColorSenseRainbow/HSBFloatSeeker.swift
1
4885
// // HSBFloatSeeker.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-08-02. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class HSBFloatSeeker: Seeker { override init () { super.init() var error : NSError? // Swift // The values 0 and 1 are valid so everything after is optional. The solution "\\.?[0-9]*" isn't optimal // because the period could be specified without any digits after and a match be made or vice versa. var regex = NSRegularExpression ( pattern: "(?:NS|UI)Color\\s*\\(\\s*hue:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*saturation:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*brightness:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*alpha:\\s*([01]|[01]\\.[0-9]+)\\s*\\)", options: .allZeros, error: &error ) if regex == nil { println ( "Error creating Swift HSB float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } regex = NSRegularExpression ( pattern: "NSColor\\s*\\(\\s*(?:calibrated|device)Hue:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*saturation:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*brightness:\\s*([01]|[01]\\.[0-9]+)\\s*,\\s*alpha:\\s*([01]|[01]\\.[0-9]+)\\s*\\)", options: .allZeros, error: &error ) if regex == nil { println ( "Error creating Swift NSColor calibrated, device HSB float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } // Objective-C - Only functions with alpha defined regex = NSRegularExpression ( pattern: "\\[\\s*(?:NS|UI)Color\\s*colorWithHue:\\s*([01]|[01]\\.[0-9]+)f?\\s*saturation:\\s*([01]|[01]\\.[0-9]+)f?\\s*brightness:\\s*([01]|[01]\\.[0-9]+)f?\\s*alpha:\\s*([01]|[01]\\.[0-9]+)f?\\s*\\]", options: .allZeros, error: &error ) if regex == nil { println ( "Error creating Objective-C HSB float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } // Don't care about saving the Calibrated or Device since we assume that any function that // replace the values will do so selectively instead of overwriting the whole string. regex = NSRegularExpression ( pattern: "\\[\\s*NSColor\\s*colorWith(?:Calibrated|Device)Hue:\\s*([01]|[01]\\.[0-9]+)f?\\s*saturation:\\s*([01]|[01]\\.[0-9]+)f?\\s*brightness:\\s*([01]|[01]\\.[0-9]+)f?\\s*alpha:\\s*([01]|[01]\\.[0-9]+)f?\\s*\\]", options: .allZeros, error: &error ) if regex == nil { println ( "Error creating Objective-C calibrated, device HSB calculated float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } } override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? { if ( ( match.numberOfRanges == 4 ) || ( match.numberOfRanges == 5 ) ) { var alphaValue : CGFloat = 1.0 let matchString = stringFromRange( match.range, line: line ) let hueString = stringFromRange( match.rangeAtIndex( 1 ), line: line ) let saturationString = stringFromRange( match.rangeAtIndex( 2 ), line: line ) let brightnessString = stringFromRange( match.rangeAtIndex( 3 ), line: line ) var capturedStrings = [ matchString, hueString, saturationString, brightnessString ] if ( match.numberOfRanges == 5 ) { let alphaString = stringFromRange( match.rangeAtIndex( 4 ), line: line ) alphaValue = CGFloat ( ( alphaString as NSString).doubleValue ) capturedStrings.append( alphaString ) } let hueValue = CGFloat ( ( hueString as NSString).doubleValue ) let saturationValue = CGFloat ( ( saturationString as NSString).doubleValue ) let brightnessValue = CGFloat ( ( brightnessString as NSString).doubleValue ) let hueColor = NSColor ( calibratedHue: hueValue, saturation: saturationValue, brightness: brightnessValue, alpha: alphaValue ) if let rgbColor = hueColor.colorUsingColorSpace( NSColorSpace.genericRGBColorSpace() ) { // If not converted to RGB ColorSpace then the plugin would crash later on. var searchResult = SearchResult ( color: rgbColor, textCheckingResult: match, capturedStrings: capturedStrings ) searchResult.creationType = .DefaultHSB return searchResult } } return nil } }
mit
fab59baf0ced6151bbf22a32a8eba5e7
46.427184
289
0.556602
4.39694
false
false
false
false
landakram/kiwi
Kiwi/Wiki/Indexer.swift
1
5195
// // Indexer.swift // Kiwi // // Created by Mark Hudnall on 11/12/16. // Copyright © 2016 Mark Hudnall. All rights reserved. // import Foundation import YapDatabase import YapDatabase.YapDatabaseFullTextSearch import RxSwift class Indexer { static let sharedInstance = Indexer() let backingStore: YapDatabase let filesystem: EventedFilesystem let indexingRoot: Path var disposeBag = DisposeBag() init(backingStore: YapDatabase = Yap.sharedInstance, filesystem: EventedFilesystem = Filesystem.sharedInstance, root: Path = Wiki.WIKI_PATH) { self.backingStore = backingStore self.filesystem = filesystem self.indexingRoot = root self.start() } func start() { self.filesystem.events.subscribe(onNext: { (event: FilesystemEvent) in switch event { case .delete(let path): let relativePath = path.relativeTo(self.filesystem.root) if self.pathIsIndexed(path: relativePath) { let permalink = pathToPermalink(path: path) self.remove(permalink: permalink) } case .write(let path): let relativePath = path.relativeTo(self.filesystem.root) if self.pathIsIndexed(path: relativePath) { do { let file: File<String> = try self.filesystem.read(path: relativePath) if let page = toPage(file) { self.index(page: page) } } catch { } } } }).disposed(by: self.disposeBag) } private func pathIsIndexed(path: Path) -> Bool { return path.commonAncestor(self.indexingRoot) == self.indexingRoot } func remove(permalink: String) { let connection = self.backingStore.newConnection() connection.readWrite { (transaction: YapDatabaseReadWriteTransaction) in transaction.removeObject(forKey: permalink, inCollection: "pages") } } func index(page: Page) { let connection = self.backingStore.newConnection() connection.readWrite({ (transaction: YapDatabaseReadWriteTransaction!) in let encodablePage = transaction.object(forKey: page.permalink, inCollection: "pages") as? EncodablePage if encodablePage == nil || encodablePage!.page.modifiedTime.compare(page.modifiedTime as Date) == .orderedAscending { transaction.setObject(EncodablePage(page: page), forKey: page.permalink, inCollection: "pages") } }) } func list() -> [String] { var results: [String] = [] self.backingStore.newConnection().read({ (transaction) in if let tx = transaction.ext("orderdedByModifiedTimeDesc") as? YapDatabaseViewTransaction { tx.enumerateKeys(inGroup: "pages") { (collection, key, index, stop) in results.append(key) } } }) return results } func get(permalink: String) -> Page? { var page: Page? // TODO: previously, this used `beginLongLivedReadTransaction` but I removed it here. // Does that matter? self.backingStore.newConnection().read({ (transaction) in if let encodablePage = transaction.object(forKey: permalink, inCollection: "pages") as? EncodablePage { page = encodablePage.page } }) return page } func find(snippet: String) -> [String] { var results: [String] = [] self.backingStore.newConnection().read({ (transaction: YapDatabaseReadTransaction) in let t = transaction.ext("fts") as! YapDatabaseFullTextSearchTransaction t.enumerateKeys(matching: snippet, using: { (collection, key, stop) in results.append(key) }) }) return results } } class EncodablePage: NSObject, NSCoding { let page: Page init(page: Page) { self.page = page } required init?(coder decoder: NSCoder) { let rawContent = decoder.decodeObject(forKey: "rawContent") as! String let permalink = decoder.decodeObject(forKey: "permalink") as! String let name = decoder.decodeObject(forKey: "name") as! String let modifiedTime = (decoder.decodeObject(forKey: "modifiedTime") as! NSDate) as Date let createdTime = (decoder.decodeObject(forKey: "createdTime") as! NSDate) as Date self.page = Page(rawContent: rawContent, permalink: permalink, name: name, modifiedTime: modifiedTime, createdTime: createdTime, isDirty: false) } func encode(with coder: NSCoder) { coder.encode(self.page.rawContent, forKey: "rawContent") coder.encode(self.page.permalink, forKey: "permalink") coder.encode(self.page.name, forKey: "name") coder.encode(self.page.modifiedTime, forKey: "modifiedTime") coder.encode(self.page.createdTime, forKey: "createdTime") } }
mit
2aad808648bbb65d112342ed5190fb89
35.836879
152
0.602041
4.675068
false
false
false
false
interchen/ICWebViewController
ICWebViewController/ICWXWebViewController.swift
1
5568
// // ICWXWebViewController.swift // ICWebViewController // // Created by 陈 颜俊 on 2017/3/3. // Copyright © 2017年 azhunchen. All rights reserved. // import UIKit import WebKit open class ICWXWebViewController: ICWebViewController, WKNavigationDelegate, UIGestureRecognizerDelegate { var backButtonTitle: String! var closeButtonTitle: String! fileprivate var isPresent = false fileprivate var closeBarButton: UIBarButtonItem! fileprivate var backBarButton: UIBarButtonItem! deinit { self.webView.navigationDelegate = nil } public convenience init(_ url: URL) { self.init() self.url = url self.backButtonTitle = "返回" self.closeButtonTitle = "关闭" } public convenience init(_ url: URL, backButtonTitle: String?, closeButtonTitle: String?) { self.init() self.url = url self.backButtonTitle = backButtonTitle ?? "返回" self.closeButtonTitle = closeButtonTitle ?? "关闭" } override open func viewDidLoad() { super.viewDidLoad() self.webView.navigationDelegate = self self.setupBarButtons() self.isPresent = self.presentingViewController != nil if isPresent { self.navigationItem.leftBarButtonItems = [self.closeBarButton] } else { self.navigationItem.leftBarButtonItems = [self.backBarButton] } } weak var originalGestureDelegate: UIGestureRecognizerDelegate? override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.originalGestureDelegate = self.navigationController?.interactivePopGestureRecognizer?.delegate self.navigationController?.interactivePopGestureRecognizer?.delegate = self } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.interactivePopGestureRecognizer?.delegate = self.originalGestureDelegate } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UI fileprivate func setupBarButtons() { let closeButton = UIButton(type: .system) closeButton.setTitle(self.closeButtonTitle, for: .normal) closeButton.setTitleColor(self.navigationController?.navigationBar.tintColor, for: .normal) closeButton.tintColor = self.navigationController?.navigationBar.tintColor closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) closeButton.addTarget(self, action: #selector(handleClose), for: .touchUpInside) closeButton.sizeToFit() closeButton.contentEdgeInsets = UIEdgeInsetsMake(1, -10, 0, 0) self.closeBarButton = UIBarButtonItem(customView: closeButton) let backImage = UIImage(named: "icon_back", in: Bundle.init(for: ICWXWebViewController.self), compatibleWith: nil) let backButton = UIButton(type: .system) backButton.setTitle(self.backButtonTitle, for: .normal) backButton.setTitleColor(self.navigationController?.navigationBar.tintColor, for: .normal) backButton.tintColor = self.navigationController?.navigationBar.tintColor backButton.setImage(backImage, for: .normal) backButton.setImage(backImage, for: .highlighted) backButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) backButton.addTarget(self, action: #selector(handleBack), for: .touchUpInside) backButton.sizeToFit() backButton.contentEdgeInsets = UIEdgeInsetsMake(2, -15, 0, 0) backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0) self.backBarButton = UIBarButtonItem(customView: backButton) } // MARK: - Action func handleClose() { if isPresent { self.dismiss(animated: true, completion: nil) } else { _ = self.navigationController?.popViewController(animated: true) } } func handleBack() { if self.webView.canGoBack { //网页返回 self.webView.goBack() } else { //原生导航返回 self.handleClose() } } // MARK: - WKNavigationDelegate open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(.allow) updateBackButtons(navigationAction) } open func updateBackButtons(_ navigationAction: WKNavigationAction) { switch navigationAction.navigationType { case .backForward: if isPresent, !self.webView.canGoBack { self.navigationItem.leftBarButtonItems = [self.closeBarButton] } else { if self.navigationItem.leftBarButtonItems?.count != 2 { self.navigationItem.leftBarButtonItems = [self.backBarButton, self.closeBarButton] } } default: break } } // MARK: - UIGestureRecognizerDelegate open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UIScreenEdgePanGestureRecognizer, !self.webView.canGoBack { return true } return false } }
mit
fa8eb85d874b124dafd4a7e0b751d852
35.576159
162
0.660511
5.42002
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TableOfContentsPresentationController.swift
1
10329
import UIKit // MARK: - Delegate @objc public protocol TableOfContentsPresentationControllerTapDelegate { func tableOfContentsPresentationControllerDidTapBackground(_ controller: TableOfContentsPresentationController) } open class TableOfContentsPresentationController: UIPresentationController, Themeable { var theme = Theme.standard var displaySide = TableOfContentsDisplaySide.left var displayMode = TableOfContentsDisplayMode.modal // MARK: - init public required init(presentedViewController: UIViewController, presentingViewController: UIViewController?, tapDelegate: TableOfContentsPresentationControllerTapDelegate) { self.tapDelegate = tapDelegate super.init(presentedViewController: presentedViewController, presenting: presentedViewController) } weak open var tapDelegate: TableOfContentsPresentationControllerTapDelegate? open var minimumVisibleBackgroundWidth: CGFloat = 60.0 open var maximumTableOfContentsWidth: CGFloat = 300.0 open var statusBarEstimatedHeight: CGFloat { return max(UIApplication.shared.workaroundStatusBarFrame.size.height, presentedView?.safeAreaInsets.top ?? 0) } // MARK: - Views lazy var statusBarBackground: UIView = { let view = UIView(frame: CGRect.zero) view.autoresizingMask = .flexibleWidth view.layer.shadowOpacity = 0.8 view.layer.shadowOffset = CGSize(width: 0, height: 5) view.clipsToBounds = false return view }() lazy var closeButton:UIButton = { let button = UIButton(frame: CGRect.zero) button.setImage(UIImage(named: "close"), for: .normal) button.addTarget(self, action: #selector(TableOfContentsPresentationController.didTap(_:)), for: .touchUpInside) button.accessibilityHint = WMFLocalizedString("table-of-contents-close-accessibility-hint", value:"Close", comment:"Accessibility hint for closing table of contents {{Identical|Close}}") button.accessibilityLabel = WMFLocalizedString("table-of-contents-close-accessibility-label", value:"Close Table of contents", comment:"Accessibility label for closing table of contents") button.translatesAutoresizingMaskIntoConstraints = false return button }() var closeButtonTrailingConstraint: NSLayoutConstraint? var closeButtonLeadingConstraint: NSLayoutConstraint? var closeButtonTopConstraint: NSLayoutConstraint? var closeButtonBottomConstraint: NSLayoutConstraint? lazy var backgroundView :UIVisualEffectView = { let view = UIVisualEffectView(frame: CGRect.zero) view.autoresizingMask = .flexibleWidth view.effect = UIBlurEffect(style: .light) view.alpha = 0.0 let tap = UITapGestureRecognizer.init() tap.addTarget(self, action: #selector(TableOfContentsPresentationController.didTap(_:))) view.addGestureRecognizer(tap) view.contentView.addSubview(self.statusBarBackground) let closeButtonDimension: CGFloat = 44 let widthConstraint = self.closeButton.widthAnchor.constraint(equalToConstant: closeButtonDimension) let heightConstraint = self.closeButton.heightAnchor.constraint(equalToConstant: closeButtonDimension) let leadingConstraint = view.contentView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: self.closeButton.leadingAnchor, constant: 0) let trailingConstraint = view.contentView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: self.closeButton.trailingAnchor, constant: 0) let topConstraint = view.contentView.layoutMarginsGuide.topAnchor.constraint(equalTo: self.closeButton.topAnchor, constant: 0) let bottomConstraint = view.contentView.layoutMarginsGuide.bottomAnchor.constraint(equalTo: self.closeButton.bottomAnchor, constant: 0) trailingConstraint.isActive = false bottomConstraint.isActive = false closeButtonLeadingConstraint = leadingConstraint closeButtonTrailingConstraint = trailingConstraint closeButtonTopConstraint = topConstraint closeButtonBottomConstraint = bottomConstraint self.closeButton.frame = CGRect(x: 0, y: 0, width: closeButtonDimension, height: closeButtonDimension) self.closeButton.addConstraints([widthConstraint, heightConstraint]) view.contentView.addSubview(self.closeButton) view.contentView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) return view }() func updateStatusBarBackgroundFrame() { self.statusBarBackground.frame = CGRect(x: self.backgroundView.bounds.minX, y: self.backgroundView.bounds.minY, width: self.backgroundView.bounds.width, height: self.frameOfPresentedViewInContainerView.origin.y) } func updateButtonConstraints() { switch self.displaySide { case .right: fallthrough case .left: closeButtonLeadingConstraint?.isActive = false closeButtonBottomConstraint?.isActive = false closeButtonTrailingConstraint?.isActive = true closeButtonTopConstraint?.isActive = true break } return () } @objc func didTap(_ tap: UITapGestureRecognizer) { self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self) } // MARK: - Accessibility func togglePresentingViewControllerAccessibility(_ accessible: Bool) { self.presentingViewController.view.accessibilityElementsHidden = !accessible } // MARK: - UIPresentationController override open func presentationTransitionWillBegin() { guard let containerView = self.containerView, let presentedView = self.presentedView else { return } // Add the dimming view and the presented view to the heirarchy self.backgroundView.frame = containerView.bounds updateStatusBarBackgroundFrame() containerView.addSubview(self.backgroundView) if self.traitCollection.verticalSizeClass == .compact { self.statusBarBackground.isHidden = true } updateButtonConstraints() containerView.addSubview(presentedView) // Hide the presenting view controller for accessibility self.togglePresentingViewControllerAccessibility(false) apply(theme: theme) // Fade in the dimming view alongside the transition if let transitionCoordinator = self.presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 1.0 }, completion:nil) } } override open func presentationTransitionDidEnd(_ completed: Bool) { if !completed { self.backgroundView.removeFromSuperview() } } override open func dismissalTransitionWillBegin() { if let transitionCoordinator = self.presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 0.0 }, completion:nil) } } override open func dismissalTransitionDidEnd(_ completed: Bool) { if completed { self.backgroundView.removeFromSuperview() self.togglePresentingViewControllerAccessibility(true) self.presentedView?.layer.cornerRadius = 0 self.presentedView?.layer.borderWidth = 0 self.presentedView?.layer.shadowOpacity = 0 self.presentedView?.clipsToBounds = true } } override open var frameOfPresentedViewInContainerView : CGRect { guard let containerView = containerView else { return .zero } var frame = containerView.bounds var bgWidth = self.minimumVisibleBackgroundWidth var tocWidth = frame.size.width - bgWidth if tocWidth > self.maximumTableOfContentsWidth { tocWidth = self.maximumTableOfContentsWidth bgWidth = frame.size.width - tocWidth } frame.origin.y = self.statusBarEstimatedHeight + 0.5 frame.size.height -= frame.origin.y switch displaySide { case .right: frame.origin.x += bgWidth break default: break } frame.size.width = tocWidth return frame } override open func viewWillTransition(to size: CGSize, with transitionCoordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: transitionCoordinator) transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in guard let containerView = self.containerView else { return } self.backgroundView.frame = containerView.bounds let frame = self.frameOfPresentedViewInContainerView self.presentedView!.frame = frame self.updateStatusBarBackgroundFrame() self.updateButtonConstraints() }, completion:nil) } public func apply(theme: Theme) { self.theme = theme guard self.containerView != nil else { return } // Add shadow to the presented view self.presentedView?.layer.shadowOpacity = 0.8 self.presentedView?.layer.shadowColor = theme.colors.shadow.cgColor self.presentedView?.layer.shadowOffset = CGSize(width: 3, height: 5) self.presentedView?.clipsToBounds = false self.closeButton.setImage(UIImage(named: "close"), for: .normal) self.statusBarBackground.isHidden = false self.backgroundView.effect = UIBlurEffect(style: theme.blurEffectStyle) self.statusBarBackground.backgroundColor = theme.colors.paperBackground self.statusBarBackground.layer.shadowColor = theme.colors.shadow.cgColor self.closeButton.tintColor = theme.colors.primaryText } }
mit
256d932d3d4f853dbe01bc01186643c4
40.987805
219
0.699196
6.126335
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/Reader/ViewModel/ZSFontViewModel.swift
1
4447
// // ZSFontViewModel.swift // zhuishushenqi // // Created by caony on 2018/9/13. // Copyright © 2018年 QS. All rights reserved. // import Foundation class ZSFontViewModel { var webService = ZSFontService() // http://statics.zhuishushenqi.com/fonts/fz-qkbys.TTF // http://statics.zhuishushenqi.com/fonts/fz-yhzx.TTF // http://statics.zhuishushenqi.com/fonts/fz-xjlt-new.ttf // http://statics.zhuishushenqi.com/fonts/fz-sxslkt.ttf // http://statics.zhuishushenqi.com/fonts/fz-mwt.ttf var fonts = [["key":"system", "name":"系统默认", "image":""], ["key":"fz-yhzx.TTF", "name":"方正悠黑", "image":"fzyouhei"], ["key":"fz-qkbys.TTF", "name":"方正清刻本悦宋", "image":"fzqingke"], ["key":"fz-xjlt-new.ttf", "name":"方正金陵细", "image":"fzxijinling"], ["key":"fz-sxslkt.ttf", "name":"方正苏新诗柳楷", "image":"fzsuxinshil"], ["key":"fz-mwt.ttf", "name":"方正喵呜", "image":"fzmiaowu"], ["key":"ltt.ttf", "name":"兰亭黑", "image":"lantingh"], ["key":"fz-kt.ttf", "name":"楷体", "image":"kai"], ["key":"fz-wbt.ttf", "name":"魏碑", "image":"weibei"], ["key":"ypt.ttf", "name":"雅痞", "image":"yapi"], ["key":"hkppt.ttf", "name":"翩翩体", "image":"pianpian"], ["key":"hylst.ttf", "name":"隶书", "image":"li"], ["key":"Redocn.ttf", "name":"日文字体", "image":"riwen"] ] var selectedIndexPath = IndexPath(item: 0, section: 0) func fetchFont(indexPath:IndexPath, handler:ZSBaseCallback<Bool>?) { var dict = fonts[indexPath.row] let path:String = "\(NSHomeDirectory())/Documents/\(dict["key"] ?? "")" if FileManager.default.fileExists(atPath: path) { handler?(true) } else { let url = "http://statics.zhuishushenqi.com/fonts/\(dict["key"] ?? "")" webService.fetchFont(url: url) { (json) in if let _ = json?["url"] { handler?(true) } else { handler?(false) } } } } func fileExist(indexPath:IndexPath) -> Bool { var dict = fonts[indexPath.row] let path:String = "\(NSHomeDirectory())/Documents/\(dict["key"] ?? "")" let exist = FileManager.default.fileExists(atPath: path) return exist } func copyFont() { for font in fonts { let file = font["key"] ?? "" let path = "\(NSHomeDirectory())/Documents/\(file)" let bundlePath = Bundle.main.path(forResource: file, ofType: nil) ?? "" let exist = FileManager.default.fileExists(atPath: bundlePath) if exist { try? FileManager.default.copyItem(atPath: bundlePath, toPath: path) } } } func fontArray(path:String, size:CGFloat) { let fontPath = CFStringCreateWithCString(nil, path.cString(using: .utf8), CFStringBuiltInEncodings.UTF8.rawValue) if let fontURL = CFURLCreateWithFileSystemPath(nil, fontPath, CFURLPathStyle.cfurlposixPathStyle, false) { let fontArray = CTFontManagerCreateFontDescriptorsFromURL(fontURL) CTFontManagerRegisterFontsForURL(fontURL, CTFontManagerScope.none, nil) var customAttay:[UIFont] = [] for item in 0..<CFArrayGetCount(fontArray) { let discriptor = CFArrayGetValueAtIndex(fontArray, item) as! CTFontDescriptor let font:CTFont = CTFontCreateWithFontDescriptor(discriptor, size, nil) if let fontName = CTFontCopyName(font, kCTFontPostScriptNameKey) as String? { let cusFont = UIFont(name: fontName, size: size) customAttay.append(cusFont!) } } } } }
mit
a303f17ef6fc52aa68dd4660a09e47f1
37.122807
121
0.493787
4.127255
false
false
false
false
mdmsua/Bamboo
Bamboo/ServerRepository.swift
1
1934
// // ServerRepository.swift // Bamboo // // Created by Dmytro Morozov on 09.05.16. // Copyright © 2016 Dmytro Morozov. All rights reserved. // import Foundation class ServerRepository { private let localStore = NSUserDefaults.standardUserDefaults() private let cloudStore = NSUbiquitousKeyValueStore.defaultStore() private let all = "servers" private let one = "server" func load() -> [Server] { if let decoded = cloudStore.objectForKey(all) as? NSData { if let servers = NSKeyedUnarchiver.unarchiveObjectWithData(decoded) as? [Server] { return servers } } return [Server]() } func save(servers: [Server]) { let encoded = NSKeyedArchiver.archivedDataWithRootObject(servers) cloudStore.setObject(encoded, forKey: all) } func get() -> Server? { if let decoded = localStore.objectForKey(one) as? NSData { if let server = NSKeyedUnarchiver.unarchiveObjectWithData(decoded) as? Server { return server } } return nil } func set(server: Server?) { defer { localStore.synchronize() } if let server = server { let encoded = NSKeyedArchiver.archivedDataWithRootObject(server) localStore.setObject(encoded, forKey: one) } else { localStore.removeObjectForKey(one) } } func add(server: Server) { var servers = self.load() servers.append(server) self.save(servers) } func update(server: Server) { var servers = self.load() let index = servers.indexOf { s in s.location == server.location } if let index = index { servers[index] = server self.save(servers) } else { self.add(server) } } }
apache-2.0
feeb365f4ca85b6499b74c846e6899bd
25.479452
94
0.574237
4.714634
false
false
false
false
hollance/swift-algorithm-club
Red-Black Tree/RedBlackTree.playground/Sources/RedBlackTree.swift
2
25349
//Copyright (c) 2016 Matthijs Hollemans and contributors // //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 private enum RBTreeColor { case red case black } private enum RotationDirection { case left case right } // MARK: - RBNode public class RBTreeNode<T: Comparable>: Equatable { public typealias RBNode = RBTreeNode<T> fileprivate var color: RBTreeColor = .black fileprivate var key: T? var leftChild: RBNode? var rightChild: RBNode? fileprivate weak var parent: RBNode? public init(key: T?, leftChild: RBNode?, rightChild: RBNode?, parent: RBNode?) { self.key = key self.leftChild = leftChild self.rightChild = rightChild self.parent = parent self.leftChild?.parent = self self.rightChild?.parent = self } public convenience init(key: T?) { self.init(key: key, leftChild: RBNode(), rightChild: RBNode(), parent: RBNode()) } // For initialising the nullLeaf public convenience init() { self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil) self.color = .black } var isRoot: Bool { return parent == nil } var isLeaf: Bool { return rightChild == nil && leftChild == nil } var isNullLeaf: Bool { return key == nil && isLeaf && color == .black } var isLeftChild: Bool { return parent?.leftChild === self } var isRightChild: Bool { return parent?.rightChild === self } var grandparent: RBNode? { return parent?.parent } var sibling: RBNode? { if isLeftChild { return parent?.rightChild } else { return parent?.leftChild } } var uncle: RBNode? { return parent?.sibling } public func getKey() -> T? { return key } } // MARK: - RedBlackTree public class RedBlackTree<T: Comparable> { public typealias RBNode = RBTreeNode<T> fileprivate(set) var root: RBNode fileprivate(set) var size = 0 fileprivate let nullLeaf = RBNode() fileprivate let allowDuplicateNode: Bool public init(_ allowDuplicateNode: Bool = false) { root = nullLeaf self.allowDuplicateNode = allowDuplicateNode } } // MARK: - Size extension RedBlackTree { public func count() -> Int { return size } public func isEmpty() -> Bool { return size == 0 } public func allElements() -> [T] { var nodes: [T] = [] getAllElements(node: root, nodes: &nodes) return nodes } private func getAllElements(node: RBTreeNode<T>, nodes: inout [T]) { guard !node.isNullLeaf else { return } if let left = node.leftChild { getAllElements(node: left, nodes: &nodes) } if let key = node.key { nodes.append(key) } if let right = node.rightChild { getAllElements(node: right, nodes: &nodes) } } } // MARK: - Equatable protocol extension RBTreeNode { static public func == <T>(lhs: RBTreeNode<T>, rhs: RBTreeNode<T>) -> Bool { return lhs.key == rhs.key } } // MARK: - Finding a nodes successor and predecessor extension RBTreeNode { /* * Returns the inorder successor node of a node * The successor is a node with the next larger key value of the current node */ public func getSuccessor() -> RBNode? { // If node has right child: successor min of this right tree if let rightChild = self.rightChild { if !rightChild.isNullLeaf { return rightChild.minimum() } } // Else go upward until node left child var currentNode = self var parent = currentNode.parent while currentNode.isRightChild { if let parent = parent { currentNode = parent } parent = currentNode.parent } return parent } /* * Returns the inorder predecessor node of a node * The predecessor is a node with the next smaller key value of the current node */ public func getPredecessor() -> RBNode? { // if node has left child: predecessor is min of this left tree if let leftChild = leftChild, !leftChild.isNullLeaf { return leftChild.maximum() } // else go upward while node is left child var currentNode = self var parent = currentNode.parent while currentNode.isLeftChild { if let parent = parent { currentNode = parent } parent = currentNode.parent } return parent } } // MARK: - Searching extension RBTreeNode { /* * Returns the node with the minimum key of the current subtree */ public func minimum() -> RBNode? { if let leftChild = leftChild { if !leftChild.isNullLeaf { return leftChild.minimum() } return self } return self } /* * Returns the node with the maximum key of the current subtree */ public func maximum() -> RBNode? { if let rightChild = rightChild { if !rightChild.isNullLeaf { return rightChild.maximum() } return self } return self } } extension RedBlackTree { /* * Returns the node with the given key |input| if existing */ public func search(input: T) -> RBNode? { return search(key: input, node: root) } /* * Returns the node with given |key| in subtree of |node| */ fileprivate func search(key: T, node: RBNode?) -> RBNode? { // If node nil -> key not found guard let node = node else { return nil } // If node is nullLeaf == semantically same as if nil if !node.isNullLeaf { if let nodeKey = node.key { // Node found if key == nodeKey { return node } else if key < nodeKey { return search(key: key, node: node.leftChild) } else { return search(key: key, node: node.rightChild) } } } return nil } } // MARK: - Finding maximum and minimum value extension RedBlackTree { /* * Returns the minimum key value of the whole tree */ public func minValue() -> T? { guard let minNode = root.minimum() else { return nil } return minNode.key } /* * Returns the maximum key value of the whole tree */ public func maxValue() -> T? { guard let maxNode = root.maximum() else { return nil } return maxNode.key } } // MARK: - Inserting new nodes extension RedBlackTree { /* * Insert a node with key |key| into the tree * 1. Perform normal insert operation as in a binary search tree * 2. Fix red-black properties * Runntime: O(log n) */ public func insert(key: T) { // If key must be unique and find the key already existed, quit if search(input: key) != nil && !allowDuplicateNode { return } if root.isNullLeaf { root = RBNode(key: key) } else { insert(input: RBNode(key: key), node: root) } size += 1 } /* * Nearly identical insert operation as in a binary search tree * Differences: All nil pointers are replaced by the nullLeaf, we color the inserted node red, * after inserting we call insertFixup to maintain the red-black properties */ private func insert(input: RBNode, node: RBNode) { guard let inputKey = input.key, let nodeKey = node.key else { return } if inputKey < nodeKey { guard let child = node.leftChild else { addAsLeftChild(child: input, parent: node) return } if child.isNullLeaf { addAsLeftChild(child: input, parent: node) } else { insert(input: input, node: child) } } else { guard let child = node.rightChild else { addAsRightChild(child: input, parent: node) return } if child.isNullLeaf { addAsRightChild(child: input, parent: node) } else { insert(input: input, node: child) } } } private func addAsLeftChild(child: RBNode, parent: RBNode) { parent.leftChild = child child.parent = parent child.color = .red insertFixup(node: child) } private func addAsRightChild(child: RBNode, parent: RBNode) { parent.rightChild = child child.parent = parent child.color = .red insertFixup(node: child) } /* * Fixes possible violations of the red-black property after insertion * Only violation of red-black properties occurs at inserted node |z| and z.parent * We have 3 distinct cases: case 1, 2a and 2b * - case 1: may repeat, but only h/2 steps, where h is the height of the tree * - case 2a -> case 2b -> red-black tree * - case 2b -> red-black tree */ private func insertFixup(node z: RBNode) { if !z.isNullLeaf { guard let parentZ = z.parent else { return } // If both |z| and his parent are red -> violation of red-black property -> need to fix it if parentZ.color == .red { guard let uncle = z.uncle else { return } // Case 1: Uncle red -> recolor + move z if uncle.color == .red { parentZ.color = .black uncle.color = .black if let grandparentZ = parentZ.parent { grandparentZ.color = .red // Move z to grandparent and check again insertFixup(node: grandparentZ) } } // Case 2: Uncle black else { var zNew = z // Case 2.a: z right child -> rotate if parentZ.isLeftChild && z.isRightChild { zNew = parentZ leftRotate(node: zNew) } else if parentZ.isRightChild && z.isLeftChild { zNew = parentZ rightRotate(node: zNew) } // Case 2.b: z left child -> recolor + rotate zNew.parent?.color = .black if let grandparentZnew = zNew.grandparent { grandparentZnew.color = .red if z.isLeftChild { rightRotate(node: grandparentZnew) } else { leftRotate(node: grandparentZnew) } // We have a valid red-black-tree } } } } root.color = .black } } // MARK: - Deleting a node extension RedBlackTree { /* * Delete a node with key |key| from the tree * 1. Perform standard delete operation as in a binary search tree * 2. Fix red-black properties * Runntime: O(log n) */ public func delete(key: T) { if size == 1 { root = nullLeaf size -= 1 } else if let node = search(key: key, node: root) { if !node.isNullLeaf { delete(node: node) size -= 1 } } } /* * Nearly identical delete operation as in a binary search tree * Differences: All nil pointers are replaced by the nullLeaf, * after deleting we call insertFixup to maintain the red-black properties if the delted node was * black (as if it was red -> no violation of red-black properties) */ private func delete(node z: RBNode) { var nodeY = RBNode() var nodeX = RBNode() if let leftChild = z.leftChild, let rightChild = z.rightChild { if leftChild.isNullLeaf || rightChild.isNullLeaf { nodeY = z } else { if let successor = z.getSuccessor() { nodeY = successor } } } if let leftChild = nodeY.leftChild { if !leftChild.isNullLeaf { nodeX = leftChild } else if let rightChild = nodeY.rightChild { nodeX = rightChild } } nodeX.parent = nodeY.parent if let parentY = nodeY.parent { // Should never be the case, as parent of root = nil if parentY.isNullLeaf { root = nodeX } else { if nodeY.isLeftChild { parentY.leftChild = nodeX } else { parentY.rightChild = nodeX } } } else { root = nodeX } if nodeY != z { z.key = nodeY.key } // If sliced out node was red -> nothing to do as red-black-property holds // If it was black -> fix red-black-property if nodeY.color == .black { deleteFixup(node: nodeX) } } /* * Fixes possible violations of the red-black property after deletion * We have w distinct cases: only case 2 may repeat, but only h many steps, where h is the height * of the tree * - case 1 -> case 2 -> red-black tree * case 1 -> case 3 -> case 4 -> red-black tree * case 1 -> case 4 -> red-black tree * - case 3 -> case 4 -> red-black tree * - case 4 -> red-black tree */ private func deleteFixup(node x: RBNode) { var xTmp = x if !x.isRoot && x.color == .black { guard var sibling = x.sibling else { return } // Case 1: Sibling of x is red if sibling.color == .red { // Recolor sibling.color = .black if let parentX = x.parent { parentX.color = .red // Rotation if x.isLeftChild { leftRotate(node: parentX) } else { rightRotate(node: parentX) } // Update sibling if let sibl = x.sibling { sibling = sibl } } } // Case 2: Sibling is black with two black children if sibling.leftChild?.color == .black && sibling.rightChild?.color == .black { // Recolor sibling.color = .red // Move fake black unit upwards if let parentX = x.parent { deleteFixup(node: parentX) } // We have a valid red-black-tree } else { // Case 3: a. Sibling black with one black child to the right if x.isLeftChild && sibling.rightChild?.color == .black { // Recolor sibling.leftChild?.color = .black sibling.color = .red // Rotate rightRotate(node: sibling) // Update sibling of x if let sibl = x.sibling { sibling = sibl } } // Still case 3: b. One black child to the left else if x.isRightChild && sibling.leftChild?.color == .black { // Recolor sibling.rightChild?.color = .black sibling.color = .red // Rotate leftRotate(node: sibling) // Update sibling of x if let sibl = x.sibling { sibling = sibl } } // Case 4: Sibling is black with red right child // Recolor if let parentX = x.parent { sibling.color = parentX.color parentX.color = .black // a. x left and sibling with red right child if x.isLeftChild { sibling.rightChild?.color = .black // Rotate leftRotate(node: parentX) } // b. x right and sibling with red left child else { sibling.leftChild?.color = .black //Rotate rightRotate(node: parentX) } // We have a valid red-black-tree xTmp = root } } } xTmp.color = .black } } // MARK: - Rotation extension RedBlackTree { /* * Left rotation around node x * Assumes that x.rightChild y is not a nullLeaf, rotates around the link from x to y, * makes y the new root of the subtree with x as y's left child and y's left child as x's right * child, where n = a node, [n] = a subtree * | | * x y * / \ ~> / \ * [A] y x [C] * / \ / \ * [B] [C] [A] [B] */ fileprivate func leftRotate(node x: RBNode) { rotate(node: x, direction: .left) } /* * Right rotation around node y * Assumes that y.leftChild x is not a nullLeaf, rotates around the link from y to x, * makes x the new root of the subtree with y as x's right child and x's right child as y's left * child, where n = a node, [n] = a subtree * | | * x y * / \ <~ / \ * [A] y x [C] * / \ / \ * [B] [C] [A] [B] */ fileprivate func rightRotate(node x: RBNode) { rotate(node: x, direction: .right) } /* * Rotation around a node x * Is a local operation preserving the binary-search-tree property that only exchanges pointers. * Runntime: O(1) */ private func rotate(node x: RBNode, direction: RotationDirection) { var nodeY: RBNode? = RBNode() // Set |nodeY| and turn |nodeY|'s left/right subtree into |x|'s right/left subtree switch direction { case .left: nodeY = x.rightChild x.rightChild = nodeY?.leftChild x.rightChild?.parent = x case .right: nodeY = x.leftChild x.leftChild = nodeY?.rightChild x.leftChild?.parent = x } // Link |x|'s parent to nodeY nodeY?.parent = x.parent if x.isRoot { if let node = nodeY { root = node } } else if x.isLeftChild { x.parent?.leftChild = nodeY } else if x.isRightChild { x.parent?.rightChild = nodeY } // Put |x| on |nodeY|'s left switch direction { case .left: nodeY?.leftChild = x case .right: nodeY?.rightChild = x } x.parent = nodeY } } // MARK: - Verify extension RedBlackTree { /* * Verifies that the existing tree fulfills all red-black properties * Returns true if the tree is a valid red-black tree, false otherwise */ public func verify() -> Bool { if root.isNullLeaf { print("The tree is empty") return true } return property2() && property4() && property5() } // Property 1: Every node is either red or black -> fullfilled through setting node.color of type // RBTreeColor // Property 2: The root is black private func property2() -> Bool { if root.color == .red { print("Property-Error: Root is red") return false } return true } // Property 3: Every nullLeaf is black -> fullfilled through initialising nullLeafs with color = black // Property 4: If a node is red, then both its children are black private func property4() -> Bool { return property4(node: root) } private func property4(node: RBNode) -> Bool { if node.isNullLeaf { return true } if let leftChild = node.leftChild, let rightChild = node.rightChild { if node.color == .red { if !leftChild.isNullLeaf && leftChild.color == .red { print("Property-Error: Red node with key \(String(describing: node.key)) has red left child") return false } if !rightChild.isNullLeaf && rightChild.color == .red { print("Property-Error: Red node with key \(String(describing: node.key)) has red right child") return false } } return property4(node: leftChild) && property4(node: rightChild) } return false } // Property 5: For each node, all paths from the node to descendant leaves contain the same number // of black nodes (same blackheight) private func property5() -> Bool { if property5(node: root) == -1 { return false } else { return true } } private func property5(node: RBNode) -> Int { if node.isNullLeaf { return 0 } guard let leftChild = node.leftChild, let rightChild = node.rightChild else { return -1 } let left = property5(node: leftChild) let right = property5(node: rightChild) if left == -1 || right == -1 { return -1 } else if left == right { let addedHeight = node.color == .black ? 1 : 0 return left + addedHeight } else { print("Property-Error: Black height violated at node with key \(String(describing: node.key))") return -1 } } } // MARK: - Debugging extension RBTreeNode: CustomDebugStringConvertible { public var debugDescription: String { var s = "" if isNullLeaf { s = "nullLeaf" } else { if let key = key { s = "key: \(key)" } else { s = "key: nil" } if let parent = parent { s += ", parent: \(String(describing: parent.key))" } if let left = leftChild { s += ", left = [" + left.debugDescription + "]" } if let right = rightChild { s += ", right = [" + right.debugDescription + "]" } s += ", color = \(color)" } return s } } extension RedBlackTree: CustomDebugStringConvertible { public var debugDescription: String { return root.debugDescription } } extension RBTreeNode: CustomStringConvertible { public var description: String { var s = "" if isNullLeaf { s += "nullLeaf" } else { if let left = leftChild { s += "(\(left.description)) <- " } if let key = key { s += "\(key)" } else { s += "nil" } s += ", \(color)" if let right = rightChild { s += " -> (\(right.description))" } } return s } } extension RedBlackTree: CustomStringConvertible { public var description: String { if root.isNullLeaf { return "[]" } else { return root.description } } }
mit
c0baf8c321bb36b05ce3eec5971ad03b
29.913415
114
0.51217
4.606397
false
false
false
false
Grievoushead/SwiftHelloWorld
MyPlayground.playground/section-1.swift
1
2114
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" println(str); var sampleVariable = 1 // This is how you define a new variable let sampleConstant = "Constant" // This is how you define a new constant var sampleInteger: Int = 3 // Defining a variable with an explicit type let sampleString: String = "Another Constant" // Including values/expressions inside strings ("The sum is: 4") let sumString = "The sum is: \(sampleVariable + sampleInteger)" var sampleList = ["item1", "item2", "item3"] // Defining an array var sampleDict = ["key1" : "value1", "key2" : "value2"] // Defining a dictionary sampleList[1] = "Updated Item" // Setting the value of an element println(sampleDict["key2"]) // Reading the value of an element //3.2 Conditions & Loops // This is how you define an optional var optionalString: String? = "Temp" // This is a simple condition if (sampleInteger > 4) { println("true") } else { // Using 'if' and 'let' together allows you to check for values that might be missing if let nonOptionalString = optionalString { println("The string's value is: \(nonOptionalString)") } else { // If we made it here, it means that the optionalString's value was nil } } // This is how you use a switch statement switch sampleString { // Switch statements aren't limited to just integers case "Constant": sampleInteger = 10 // No need to add 'break' statements. Only matching ones will be executed case "Another Constant", "Some Constant": sampleInteger = 11 // Switch statements support a variety of comparison operations case let x where x.hasPrefix("Constant"): sampleInteger = 12 // The switch must cover all cases, so a default case should be used default: sampleInteger = 13 } // A simple for loop for (var i = 0; i < 6; i++) { println("This is round #\(i)") } // A simple loop on a dictionary for (key, value) in sampleDict { println("The value for \(key) is \(value)") } // A simple loop on an array for item in sampleList { println("The current item is \(item)") }
mit
4a9553f976718da61c2b64b820a7782b
24.46988
90
0.691107
3.78853
false
false
false
false
gtranchedone/AlgorithmsSwift
Algorithms.playground/Pages/Problem - Spiral Ordering of 2D array.xcplaygroundpage/Contents.swift
1
1086
//: [Previous](@previous) import Foundation func spiralOrderOfMatrix<T>(matrix: [[T]]) -> [T] { var result = [T]() let numberOfIterations = Int(ceil(Double(matrix.count) / 2.0)) for var offset = 0; offset < numberOfIterations; offset++ { if offset == matrix.count - offset - 1 { result.append(matrix[offset][offset]) continue } for var i = offset; i < matrix.count - offset; i++ { result.append(matrix[offset][i]) } for var i = offset + 1; i < matrix.count - offset - 1; i++ { result.append(matrix[i][matrix.count - offset - 1]) } for var i = matrix.count - offset - 1; i > offset; i-- { result.append(matrix[matrix.count - 1 - offset][i]) } for var i = matrix.count - offset - 1; i > offset; i-- { result.append(matrix[i][offset]) } } return result } spiralOrderOfMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) spiralOrderOfMatrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) //: [Next](@next)
mit
1f14a4df8389cdfeb0d36d9197ad5d1a
32.9375
84
0.528545
3.300912
false
false
false
false
jhliberty/GitLabKit
GitLabKit/Event.swift
1
5091
// // Event.swift // GitLabKit // // Copyright (c) 2015 orih. 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 import Mantle public class Event: GitLabModel, Fetchable { public var id: NSNumber? public var projectId: NSNumber? public var actionName: String? public var targetId: NSNumber? public var targetType: String? public var authorId: NSNumber? public var authorUsername: String? public var data: EventData? public var targetTitle: String? public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "id" : "id", "projectId" : "project_id", "actionName" : "action_name", "targetId" : "target_id", "targetType" : "target_type", "authorId" : "author_id", "authorUsername" : "author_username", "data" : "data", "targetTitle" : "target_title", ] return baseKeys + newKeys } class func dataJSONTransformer() -> NSValueTransformer { return ModelUtil<EventData>.transformer() } } public class EventData: GitLabModel { public var before: String? public var after: String? public var ref: String? public var userId: NSNumber? public var userName: String? public var repository: Repository? public var commits: [EventCommit]? public var totalCommitsCount: NSNumber? public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "before" : "before", "after" : "after", "ref" : "ref", "userId" : "user_id", "userName" : "user_name", "repository" : "repository", "commits" : "commits", "totalCommitsCount" : "total_commits_count", ] return baseKeys + newKeys } class func repositoryJSONTransformer() -> NSValueTransformer { return ModelUtil<Repository>.transformer() } class func commitsJSONTransformer() -> NSValueTransformer { return ModelUtil<EventCommit>.arrayTransformer() } } public class Repository: GitLabModel { public var name: String? public var url: String? public var descriptionText: String? public var homepage: String? public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "name" : "name", "url" : "url", "descriptionText" : "description", "homepage" : "homepage", ] return baseKeys + newKeys } } public class EventCommit: GitLabModel { public var id: NSNumber? public var message: String? public var timestamp: NSDate? public var url: String? public var author: CommitAuthor? public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "id" : "id", "message" : "message", "timestamp" : "timestamp", "url" : "url", "author" : "author", ] return baseKeys + newKeys } class func timestampJSONTransformer() -> NSValueTransformer { return dateTimeTransformer } class func authorJSONTransformer() -> NSValueTransformer { return ModelUtil<CommitAuthor>.transformer() } }
mit
69fbbbf49c5c794c7d841f919c21a81a
35.633094
87
0.618543
4.594765
false
false
false
false
puffinsupply/TransitioningKit
Example/Example/ThirdViewControllerDismissAnimator.swift
1
1394
import UIKit class ThirdViewControllerDismissAnimator: NSObject, UIViewControllerAnimatedTransitioning { // MARK: Public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.2 } func animateTransition(context: UIViewControllerContextTransitioning) { let toNavigationController = context.viewControllerForKey(UITransitionContextToViewControllerKey) as! UINavigationController let fromView = context.viewForKey(UITransitionContextFromViewKey)! let toView = toNavigationController.topViewController!.view let fromViewButton = fromView.subviews.first as! UIButton let toViewButton = toView.subviews.first as! UIButton UIView.animateWithDuration( 0.5, animations: { fromViewButton.transform = CGAffineTransformMakeTranslation(0, fromView.frame.height) fromView.backgroundColor = UIColor.clearColor() }, completion: { _ in context.completeTransition(!context.transitionWasCancelled()) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: { toViewButton.transform = CGAffineTransformIdentity }, completion: nil ) } ) } }
mit
ecd1aad17ab94fca409f58f257e0e9b6
32.190476
128
0.685079
6.140969
false
false
false
false
ktakayama/SimpleRSSReader
Pods/RealmResultsController/Source/RealmExtension.swift
1
6684
// // RealmExtension.swift // redbooth-ios-sdk // // Created by Isaac Roldan on 4/8/15. // Copyright © 2015 Redbooth Inc. // import Foundation import RealmSwift extension Realm { //MARK: Add /** Wrapper of realm.add() The adition to the realm works the same way as the original method. It will notify any active RealmResultsController of the addition. Original Realm Doc: Adds or updates an object to be persisted it in this Realm. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. When added, all linked (child) objects referenced by this object will also be added to the Realm if they are not already in it. If the object or any linked objects already belong to a different Realm an exception will be thrown. Use one of the `create` functions to insert a copy of a persisted object into a different Realm. The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `invalidated` must be false). - parameter object: Object to be added to this Realm. - parameter update: If true will try to update existing objects with the same primary key. */ public func addNotified<N: Object>(object: N, update: Bool = false) { defer { add(object, update: update) } var primaryKey: String? primaryKey = (object as Object).dynamicType.primaryKey() guard let pKey = primaryKey, let primaryKeyValue = (object as Object).valueForKey(pKey) else { return } if let _ = objectForPrimaryKey((object as Object).dynamicType.self, key: primaryKeyValue) { RealmNotification.loggerForRealm(self).didUpdate(object) return } RealmNotification.loggerForRealm(self).didAdd(object) } /** Wrapper of realm.add([]) The aditions to the realm works the same way as the original method. It will notify any active RealmResultsController of the additions. Original Realm Doc: Adds or updates objects in the given sequence to be persisted it in this Realm. - see: add(object:update:) - parameter objects: A sequence which contains objects to be added to this Realm. - parameter update: If true will try to update existing objects with the same primary key. */ public func addNotified<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) { for object in objects { addNotified(object, update: update) } } /** Wrapper of realm.create() The creation to the realm works the same way as the original method. It will notify any active RealmResultsController of the creation. Original Realm Doc: Create an `Object` with the given value. Creates or updates an instance of this object and adds it to the `Realm` populating the object with the given value. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. - parameter type The object type to create. - parameter value The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in NSJSONSerialization, or an Array with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in an Array, all properties must be present, valid and in the same order as the properties defined in the model. - parameter update If true will try to update existing objects with the same primary key. - returns: The created object. */ public func createNotified<T: Object>(type: T.Type, value: AnyObject = [:], var update: Bool = false) -> T? { let createBlock = { return self.create(type, value: value, update: update) } var create = true guard let primaryKey = T.primaryKey() else { return nil } guard let primaryKeyValue = value.valueForKey(primaryKey) else { return nil } if let _ = objectForPrimaryKey(type, key: primaryKeyValue) { create = false update = true } let createdObject = createBlock() if create { RealmNotification.loggerForRealm(self).didAdd(createdObject) } else { RealmNotification.loggerForRealm(self).didUpdate(createdObject) } return createdObject } //MARK: Delete /** Wrapper of realm.delete() The deletion works the same way as the original Realm method. It will notify any active RealmResultsController of the deletion Original Realm Doc: Deletes the given object from this Realm. - parameter object: The object to be deleted. */ public func deleteNotified(object: Object) { RealmNotification.loggerForRealm(self).didDelete(object) delete(object) } /** Wrapper of realm.delete() The deletion works the same way as the original Realm method. It will notify any active RealmResultsController of the deletion Deletes the given objects from this Realm. - parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`, or any other enumerable SequenceType which generates Object. */ public func deleteNotified<S: SequenceType where S.Generator.Element: Object>(objects: S) { for object in objects { deleteNotified(object) } } //MARK: Execute /** Execute a given RealmRequest in the current Realm (ignoring the realm in which the Request was created) - parameter request RealmRequest to execute - returns Realm Results<T> */ public func execute<T: Object>(request: RealmRequest<T>) -> Results<T> { return objects(request.entityType).filter(request.predicate).sorted(request.sortDescriptors) } } extension Results { /** Transform a Results<T> into an Array<T> - returns Array<T> */ func toArray() -> [T] { var array = [T]() for result in self { array.append(result) } return array } }
mit
90ec4f83866a10bad5f073f2397769fd
34.737968
474
0.66138
4.776984
false
false
false
false
away4m/Vendors
Vendors/Extensions/Float.swift
1
3206
// // Float.swift // Pods // // Created by away4m on 12/30/16. // // #if canImport(CoreGraphics) import CoreGraphics #endif // MARK: - Properties public extension Float { // Absolute of float value. public var abs: Float { return Swift.abs(self) } // String with number and current locale currency. public var asLocaleCurrency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self as NSNumber)! } #if canImport(CoreGraphics) /// SwifterSwift: CGFloat. public var cgFloat: CGFloat { return CGFloat(self) } #endif // Ceil of float value. public var ceil: Float { return Foundation.ceil(self) } // Radian value of degree input. public var degreesToRadians: Float { return Float(Double.pi) * self / 180.0 } // Floor of float value. public var floor: Float { return Foundation.floor(self) } // Degree value of radian input. public var radiansToDegrees: Float { return self * 180 / Float(Double.pi) } public func roundToPlaces(places: Int) -> Float { let divisor = pow(10.0, Float(places)) return Darwin.round(self * divisor) / divisor } } // MARK: - Methods extension Float { // Random float between two float values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. /// - Returns: random float between two Float values. public static func randomBetween(min: Float, max: Float) -> Float { let delta = max - min return min + Float(arc4random_uniform(UInt32(delta))) } } // MARK: - Operators precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator **: PowerPrecedence /// SwifterSwift: Value of exponentiation. /// /// - Parameters: /// - lhs: base float. /// - rhs: exponent float. /// - Returns: exponentiation result (4.4 ** 0.5 = 2.0976176963). public func ** (lhs: Float, rhs: Float) -> Float { // http://nshipster.com/swift-operators/ return pow(lhs, rhs) } // swiftlint:disable next identifier_name prefix operator √ /// SwifterSwift: Square root of float. /// /// - Parameter float: float value to find square root for /// - Returns: square root of given float. public prefix func √ (float: Float) -> Float { // http://nshipster.com/swift-operators/ return sqrt(float) } infix operator ± // Tuple of plus-minus operation. /// /// - Parameters: /// - lhs: float number /// - rhs: float number /// - Returns: tuple of plus-minus operation ( 2.5 ± 1.5 -> (4, 1)). public func ± (lhs: Float, rhs: Float) -> (Float, Float) { // http://nshipster.com/swift-operators/ return (lhs + rhs, lhs - rhs) } prefix operator ± // Tuple of plus-minus operation. /// /// - Parameter int: float number /// - Returns: tuple of plus-minus operation (± 2.5 -> (2.5, -2.5)). public prefix func ± (Float: Float) -> (Float, Float) { // http://nshipster.com/swift-operators/ return 0 ± Float }
mit
81b28c6f8c3b521b3e1713f389b55f75
24.97561
72
0.628482
3.877427
false
false
false
false
rc2server/appserverSwift
Sources/Rc2AppServer/SessionSocket.swift
1
2594
// // SessionSocket.swift // // Copyright ©2017 Mark Lilback. This file is licensed under the ISC license. // import Foundation import Dispatch import PerfectWebSockets import MJLLogger import servermodel import Rc2Model protocol SessionSocketDelegate { func closed(socket: SessionSocket) func handle(command: SessionCommand, socket: SessionSocket) } class SessionSocket: Hashable { fileprivate let socket: WebSocket fileprivate let lockQueue: DispatchQueue let user: User let settings: AppSettings let delegate: SessionSocketDelegate weak var session: Session? var watchingVariables: Bool = false required init(socket: WebSocket, user: User, settings: AppSettings, delegate: SessionSocketDelegate) { self.socket = socket self.user = user self.settings = settings self.delegate = delegate lockQueue = DispatchQueue(label: "socket queue (\(user.login))") } var hashValue: Int { return ObjectIdentifier(self).hashValue } /// starts listening for messages func start() { DispatchQueue.global().async { [weak self] in self?.readNextMessage() } } func close() { lockQueue.sync { socket.close() } } func send(data: Data, completion: (@escaping () -> Void)) { lockQueue.sync { // TODO: this is copying the bytes. Is this possible to do w/o a copy? Maybe not, since it happens asynchronously let rawdata = [UInt8](data) socket.sendBinaryMessage(bytes: rawdata, final: true, completion: completion) } } /// start processing input private func readNextMessage() { socket.readBytesMessage { [weak self] (bytes, opcode, isFinal) in switch opcode { case .binary, .text: self?.handle(bytes: bytes) case .close, .invalid: self?.closed() return default: Log.error("got unhandled opcode \(opcode) from websocket") } DispatchQueue.global().async { [weak self] in self?.readNextMessage() } } } /// process bytes received from the network. only internal access control to allow for unit tests func handle(bytes: [UInt8]?) { guard let bytes = bytes else { return } //process bytes let data = Data(bytes) do { let command: SessionCommand = try settings.decode(data: data) delegate.handle(command: command, socket: self) } catch { Log.warn("Got error decoding message from client") } } /// called when remote closes the connection private func closed() { Log.info("remote closed socket connection") delegate.closed(socket: self) } // Equatable support static func == (lhs: SessionSocket, rhs: SessionSocket) -> Bool { return lhs.socket == rhs.socket } }
isc
93f3b9afcf69379e3a782a4c7e84bbed
24.93
116
0.711145
3.657264
false
false
false
false
kzaher/RxSwift
RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift
7
3471
// // RxCollectionViewReactiveArrayDataSource.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift // objc monkey business class _RxCollectionViewReactiveArrayDataSource : NSObject , UICollectionViewDataSource { @objc(numberOfSectionsInCollectionView:) func numberOfSections(in: UICollectionView) -> Int { 1 } func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { _collectionView(collectionView, numberOfItemsInSection: section) } fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { _collectionView(collectionView, cellForItemAt: indexPath) } } class RxCollectionViewReactiveArrayDataSourceSequenceWrapper<Sequence: Swift.Sequence> : RxCollectionViewReactiveArrayDataSource<Sequence.Element> , RxCollectionViewDataSourceType { typealias Element = Sequence override init(cellFactory: @escaping CellFactory) { super.init(cellFactory: cellFactory) } func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Sequence>) { Binder(self) { collectionViewDataSource, sectionModels in let sections = Array(sectionModels) collectionViewDataSource.collectionView(collectionView, observedElements: sections) }.on(observedEvent) } } // Please take a look at `DelegateProxyType.swift` class RxCollectionViewReactiveArrayDataSource<Element> : _RxCollectionViewReactiveArrayDataSource , SectionedViewDataSourceType { typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell var itemModels: [Element]? func modelAtIndex(_ index: Int) -> Element? { itemModels?[index] } func model(at indexPath: IndexPath) throws -> Any { precondition(indexPath.section == 0) guard let item = itemModels?[indexPath.item] else { throw RxCocoaError.itemsNotYetBound(object: self) } return item } var cellFactory: CellFactory init(cellFactory: @escaping CellFactory) { self.cellFactory = cellFactory } // data source override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { itemModels?.count ?? 0 } override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) } // reactive func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) { self.itemModels = observedElements collectionView.reloadData() // workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index collectionView.collectionViewLayout.invalidateLayout() } } #endif
mit
9c033b387f1799de3f8ef420026744cb
31.12963
149
0.709222
5.745033
false
false
false
false
AdilVirani/IntroiOS
DNApp/CommentsTableViewController.swift
1
5723
// // CommentsTableViewController.swift // DNApp // // Created by Meng To on 2015-03-08. // Copyright (c) 2015 Meng To. All rights reserved. // import UIKit class CommentsTableViewController: UITableViewController, CommentTableViewCellDelegate, StoryTableViewCellDelegate, ReplyViewControllerDelegate { var story: JSON! var comments: [JSON]! var transitionManager = TransitionManager() override func viewDidLoad() { super.viewDidLoad() comments = flattenComments(story["comments"].array ?? []) refreshControl?.addTarget(self, action: "reloadStory", forControlEvents: UIControlEvents.ValueChanged) tableView.estimatedRowHeight = 140 tableView.rowHeight = UITableViewAutomaticDimension } @IBAction func shareButtonDidTouch(sender: AnyObject) { let title = story["title"].string ?? "" let url = story["url"].string ?? "" let activityViewController = UIActivityViewController(activityItems: [title, url], applicationActivities: nil) activityViewController.setValue(title, forKey: "subject") activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop] presentViewController(activityViewController, animated: true, completion: nil) } func reloadStory() { view.showLoading() DNService.storyForId(story["id"].int!, response: { (JSON) -> () in self.view.hideLoading() self.story = JSON["story"] self.comments = self.flattenComments(JSON["story"]["comments"].array ?? []) self.tableView.reloadData() self.refreshControl?.endRefreshing() }) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifer = indexPath.row == 0 ? "StoryCell" : "CommentCell" let cell = tableView.dequeueReusableCellWithIdentifier(identifer) as UITableViewCell! if let storyCell = cell as? StoryTableViewCell { storyCell.configureWithStory(story) storyCell.delegate = self } if let commentCell = cell as? CommentTableViewCell { let comment = comments[indexPath.row - 1] commentCell.configureWithComment(comment) commentCell.delegate = self } return cell } // MARK: CommentTableViewCellDelegate func commentTableViewCellDidTouchUpvote(cell: CommentTableViewCell) { if let token = LocalStore.getToken() { let indexPath = tableView.indexPathForCell(cell)! let comment = comments[indexPath.row - 1] let commentId = comment["id"].int! DNService.upvoteCommentWithId(commentId, token: token, response: { (successful) -> () in }) LocalStore.saveUpvotedComment(commentId) cell.configureWithComment(comment) } else { performSegueWithIdentifier("LoginSegue", sender: self) } } func commentTableViewCellDidTouchComment(cell: CommentTableViewCell) { if LocalStore.getToken() == nil { performSegueWithIdentifier("LoginSegue", sender: self) } else { performSegueWithIdentifier("ReplySegue", sender: cell) } } // MARK: StoryTableViewCellDelegate func storyTableViewCellDidTouchUpvote(cell: StoryTableViewCell, sender: AnyObject) { if let token = LocalStore.getToken() { let indexPath = tableView.indexPathForCell(cell)! let storyId = story["id"].int! DNService.upvoteStoryWithId(storyId, token: token, response: { (successful) -> () in }) LocalStore.saveUpvotedStory(storyId) cell.configureWithStory(story) } else { performSegueWithIdentifier("LoginSegue", sender: self) } } func storyTableViewCellDidTouchComment(cell: StoryTableViewCell, sender: AnyObject) { if LocalStore.getToken() == nil { performSegueWithIdentifier("LoginSegue", sender: self) } else { performSegueWithIdentifier("ReplySegue", sender: cell) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ReplySegue" { let toView = segue.destinationViewController as! ReplyViewController if let cell = sender as? CommentTableViewCell { let indexPath = tableView.indexPathForCell(cell)! let comment = comments[indexPath.row - 1] toView.comment = comment } if let cell = sender as? StoryTableViewCell { toView.story = story } toView.delegate = self toView.transitioningDelegate = transitionManager } } // MARK: ReplyViewControllerDelegate func replyViewControllerDidSend(controller: ReplyViewController) { reloadStory() } // Helper func flattenComments(comments: [JSON]) -> [JSON] { let flattenedComments = comments.map(commentsForComment).reduce([], combine: +) return flattenedComments } func commentsForComment(comment: JSON) -> [JSON] { let comments = comment["comments"].array ?? [] return comments.reduce([comment]) { acc, x in acc + self.commentsForComment(x) } } }
apache-2.0
b16070746548b3b9f2c58f7691afda90
33.269461
145
0.623799
5.572541
false
false
false
false
swiftingio/architecture-wars-mvc
MyCards/MyCards/CoreDataWorker.swift
1
3464
// // CoreDataWorker.swift // Created by swifting.io Team // import Foundation import CoreData protocol CoreDataWorkerProtocol { func get<Entity: ManagedObjectConvertible> (with predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int?, completion: @escaping (Result<[Entity]>) -> Void) func upsert<Entity: ManagedObjectConvertible> (entities: [Entity], completion: @escaping (Error?) -> Void) func remove<Entity: ManagedObjectConvertible> (entities: [Entity], completion: @escaping (Error?) -> Void) } extension CoreDataWorkerProtocol { func get<Entity: ManagedObjectConvertible> (with predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, fetchLimit: Int? = nil, completion: @escaping (Result<[Entity]>) -> Void) { get(with: predicate, sortDescriptors: sortDescriptors, fetchLimit: fetchLimit, completion: completion) } } enum CoreDataWorkerError: Error { case cannotFetch(String) case cannotSave(Error) } class CoreDataWorker: CoreDataWorkerProtocol { let coreData: CoreDataServiceProtocol init(coreData: CoreDataServiceProtocol = CoreDataService.shared) { self.coreData = coreData } func get<Entity: ManagedObjectConvertible> (with predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int?, completion: @escaping (Result<[Entity]>) -> Void) { coreData.performForegroundTask { context in do { let fetchRequest = Entity.ManagedObject.fetchRequest() fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sortDescriptors if let fetchLimit = fetchLimit { fetchRequest.fetchLimit = fetchLimit } let results = try context.fetch(fetchRequest) as? [Entity.ManagedObject] let items: [Entity] = results?.flatMap { $0.toEntity() as? Entity } ?? [] completion(.success(items)) } catch { let fetchError = CoreDataWorkerError.cannotFetch("Cannot fetch error: \(error))") completion(.failure(fetchError)) } } } func upsert<Entity: ManagedObjectConvertible> (entities: [Entity], completion: @escaping (Error?) -> Void) { coreData.performBackgroundTask { context in _ = entities.flatMap({ (entity) -> Entity.ManagedObject? in return entity.toManagedObject(in: context) }) do { try context.save() completion(nil) } catch { completion(CoreDataWorkerError.cannotSave(error)) } } } func remove<Entity: ManagedObjectConvertible> (entities: [Entity], completion: @escaping (Error?) -> Void) { coreData.performBackgroundTask { (context) in for entity in entities { if let managedEntity = entity.toManagedObject(in: context) { context.delete(managedEntity) } } do { try context.save() completion(nil) } catch { completion(CoreDataWorkerError.cannotSave(error)) } } } }
mit
56a9c8aa57737463b4a8498c5ff6e51b
32.307692
97
0.585162
5.248485
false
false
false
false
calvinWen/SwiftMusicPlayer
SwiftMusic 2/SwiftMusic/MainMusicViewController.swift
1
12905
// // MainMusicViewController.swift // SwiftMusic // // Created by 科文 on 2017/5/3. // Copyright © 2017年 科文. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class MainMusicViewController: UIViewController,UITabBarDelegate { @IBOutlet weak var containerView: UIView! @IBOutlet weak var miniPlayerView: UIView! @IBOutlet weak var miniPlayerButton: UIButton! @IBOutlet weak var tabBar: UITabBar! var nowNum:Int! var timer:Timer! var musicTalbleVC: MuiscListViewController! private var moreVC: UINavigationController! fileprivate var modalVC :DetailMusicViewController! private var animator : ARNTransitionAnimator? var musicModel:Music? var musicArry:Array<Music>! // var isPlay : Bool!=false @IBAction func ClickMiniPlayerBtn(_ sender: Any) { if self.musicModel != nil { self.present(self.modalVC, animated: true, completion: nil) // self.navigationController?.pushViewController(self.modalVC, animated: true) } } @IBAction func nextMusicBtn(_ sender: Any) { self.nowNum=self.nowNum+1 if self.nowNum>=self.musicArry.count{ self.nowNum=0 } if AudioPlayer.nextsong(num: self.nowNum){ refreashView() } } @IBAction func musicPlayBtn(_ sender: Any) { let sender=sender as! UIButton // if isPlay { // AudioPlayer.pause() // isPlay=false // sender.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) // }else{ // AudioPlayer.play() // isPlay=true // sender.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) // } if AudioPlayer.play(){ sender.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) }else{ sender.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) } } func setStatusBarBackgroundColor(color : UIColor) { let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as? UIView)?.value(forKey: "statusBar") as? UIView statusBar?.backgroundColor=color } override func viewDidLoad() { super.viewDidLoad() let session:AVAudioSession=AVAudioSession.sharedInstance() do{ try session.setCategory(AVAudioSessionCategoryPlayback) try session.setActive(true) } catch{ } //1.告诉系统接受远程响应事件,并注册成为第一响应者 UIApplication.shared.beginReceivingRemoteControlEvents() self.becomeFirstResponder() self.modalVC=self.storyboard?.instantiateViewController(withIdentifier: "DetailMusicViewController") as! DetailMusicViewController self.modalVC.modalPresentationStyle = .overFullScreen//弹出属性 self.setupAnimator() self.miniPlayerWork() self.musicArry=Music.getALL() self.tabBar.delegate=self self.moreVC = self.storyboard?.instantiateViewController(withIdentifier: "aboutVC") as! UINavigationController if self.tabBar.selectedItem == nil { } // Do any additional setup after loading the view. } func setupAnimator(){ let animation=MusicPlayerTransitionAnimation(rootVC: self, modalVC: self.modalVC) animation.completion = { [weak self] isPresenting in if isPresenting { guard let _self=self else{ return }//再次强引用 let modalGestureHandler=TransitionGestureHandler (targetVC: _self, direction: .bottom) modalGestureHandler.registerGesture(_self.modalVC.view) modalGestureHandler.panCompletionThreshold=15.0 _self.animator?.registerInteractiveTransitioning(.dismiss, gestureHandler: modalGestureHandler) }else{ self?.setupAnimator() } } let miniPlayerGestureHandler = TransitionGestureHandler(targetVC: self, direction: .top) miniPlayerGestureHandler.registerGesture(self.miniPlayerView) miniPlayerGestureHandler.panCompletionThreshold=15.0 self.animator=ARNTransitionAnimator(duration: 0.5, animation: animation) self.animator?.registerInteractiveTransitioning(.present, gestureHandler: miniPlayerGestureHandler) self.modalVC.transitioningDelegate=self.animator } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 1 { let newController = self.musicTalbleVC! let oldController = childViewControllers.last! if newController != oldController { // self.setStatusBarBackgroundColor(color: UIColor.white) oldController.willMove(toParentViewController: nil) addChildViewController(newController) newController.view.frame = oldController.view.frame //isAnimating = true transition(from: oldController, to: newController, duration: 0.5, options: UIViewAnimationOptions.transitionFlipFromLeft, animations: nil, completion: { (finished) -> Void in oldController.removeFromParentViewController() newController.didMove(toParentViewController: self) //self.isAnimating = false }) } }else{ let newController = self.moreVC! let oldController = childViewControllers.last! if newController != oldController { self.setStatusBarBackgroundColor(color: UIColor.clear) oldController.willMove(toParentViewController: nil) addChildViewController(newController) newController.view.frame = oldController.view.frame transition(from: oldController, to: newController, duration: 0.5, options: UIViewAnimationOptions.transitionFlipFromRight, animations: nil, completion: { (finished) -> Void in oldController.removeFromParentViewController() newController.didMove(toParentViewController: self) //self.isAnimating = false }) } } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Dad2Son" { self.musicTalbleVC=segue.destination as! MuiscListViewController } } func miniPlayerWork(){ let musicImg=self.miniPlayerView.viewWithTag(1) as! UIImageView let musicName = self.miniPlayerView.viewWithTag(2) as! UILabel let musicPlayBtn = self.miniPlayerView.viewWithTag(3) as! UIButton // let nextMusicBtn = self.miniPlayerView.viewWithTag(4) as! UIButton self.musicTalbleVC.musicPlayByTableViewCell={ [weak self] musicNum in self?.musicModel=self?.musicArry[musicNum] self?.nowNum=musicNum self?.miniPlayerWork() } if self.musicModel != nil { musicName.text=self.musicModel?.musicName musicImg.image=UIImage (data: (self.musicModel?.musicimg)!) if AudioPlayer.share(model: self.musicModel!){ self.modalVC.model=musicModel if AudioPlayer.isPlaying(){ musicPlayBtn.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) }else{ musicPlayBtn.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) } self.musicTalbleVC?.tableVIew.reloadData() if self.timer == nil{ self.timer=Timer .scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.setBackground), userInfo: nil, repeats: true) } } } } override func viewWillAppear(_ animated: Bool) { // self.setStatusBarBackgroundColor(color: UIColor.white) //self.timeStop() } override func viewWillDisappear(_ animated: Bool) { refreashView() // UIApplication.shared.endReceivingRemoteControlEvents() // self.resignFirstResponder() } override var canBecomeFirstResponder: Bool{ return true } func refreashView(){ self.musicModel=AudioPlayer.activeSong() if self.musicModel != nil { DispatchQueue.main.async(execute: { self.nowNum=(self.musicModel?.musicNum)!-1 let musicImg=self.miniPlayerView.viewWithTag(1) as! UIImageView let musicName = self.miniPlayerView.viewWithTag(2) as! UILabel let musicPlayBtn = self.miniPlayerView.viewWithTag(3) as! UIButton musicName.text=self.musicModel?.musicName musicImg.image=UIImage (data: (self.musicModel?.musicimg)!) if AudioPlayer.isPlaying(){ musicPlayBtn.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) }else{ musicPlayBtn.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) } self.musicTalbleVC?.tableVIew.reloadData() }) } } } extension MainMusicViewController { func setBackground() { //大标题 - 小标题 - 歌曲总时长 - 歌曲当前播放时长 - 封面 self.musicModel=AudioPlayer.activeSong() var settings = [MPMediaItemPropertyTitle: self.musicModel?.musicName, MPMediaItemPropertyArtist: self.musicModel?.musicAuthor , MPMediaItemPropertyPlaybackDuration: "\(AudioPlayer.musicDuration())", MPNowPlayingInfoPropertyElapsedPlaybackTime: "\(AudioPlayer.currentTime())",MPMediaItemPropertyArtwork: MPMediaItemArtwork.init(image: UIImage (data: (self.musicModel?.musicimg)!)!)] as [String : Any] MPNowPlayingInfoCenter.default().setValue(settings, forKey: "nowPlayingInfo") if AudioPlayer.progress() > 0.99 { // 自动播放下一曲 ()后台 self.nowNum=self.nowNum+1 if self.nowNum>=self.musicArry.count{ self.nowNum=0 } if AudioPlayer.nextsong(num: self.nowNum){ refreashView() } } } func timeStop(){ if timer != nil{ self.timer.invalidate() self.timer=nil } } } extension MainMusicViewController { override func remoteControlReceived(with event: UIEvent?) { if event?.type == UIEventType.remoteControl { switch event!.subtype { case .remoteControlTogglePlayPause: if AudioPlayer.play(){ } case .remoteControlPreviousTrack: // ## <- ## self.nowNum=self.nowNum-1 if self.nowNum == -1{ self.nowNum=self.musicArry.count - 1 } if AudioPlayer.prevsong(num: self.nowNum){ self.musicModel=AudioPlayer.activeSong() refreashView() } case .remoteControlNextTrack: // ## -> ## self.nowNum=self.nowNum+1 if self.nowNum>=self.musicArry.count{ self.nowNum=0 } if AudioPlayer.nextsong(num: self.nowNum){ self.musicModel=AudioPlayer.activeSong() refreashView() } case .remoteControlPlay: // ## > ## if AudioPlayer.play(){ let musicPlayBtn = self.miniPlayerView.viewWithTag(3) as! UIButton if AudioPlayer.isPlaying(){ musicPlayBtn.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) }else{ musicPlayBtn.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) } }else{ } case .remoteControlPause: // ## || ## AudioPlayer.pause() let musicPlayBtn = self.miniPlayerView.viewWithTag(3) as! UIButton if AudioPlayer.isPlaying(){ musicPlayBtn.setImage(#imageLiteral(resourceName: "stopMusic"), for: .normal) }else{ musicPlayBtn.setImage(#imageLiteral(resourceName: "playmusic"), for: .normal) } default: break } } } }
apache-2.0
76bc52e68a5487a0f7a1da2880e5159d
39.66879
212
0.599608
5.007843
false
false
false
false
maxgoedjen/M3U8
M3U8/MapItem.swift
1
1029
// // MapItem.swift // M3U8 // // Created by Max Goedjen on 8/11/15. // Copyright © 2015 Max Goedjen. All rights reserved. // import Foundation public struct MapItem: Item { public let uri: String public let byteRange: ByteRange? public init(uri: String, byteRange: ByteRange? = nil) { self.uri = uri self.byteRange = byteRange } public init?(string: String) { let attributes = string.m3u8Attributes guard let uri = attributes["URI"] else { return nil } self.uri = uri if let byteRangeString = attributes["BYTERANGE"] { byteRange = ByteRange(string: byteRangeString) } else { byteRange = nil } } } extension MapItem { public var description: String { var strung = "#EXT-X-MAP:URI=\"\(uri)\"" if let byteRangeString = byteRange?.description { strung += ",BYTERANGE=\"\(byteRangeString)\"" } return strung } }
mit
b493bbbe8d56625ca8f01c93edfb6b39
21.369565
59
0.564202
4.213115
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Data Model/Conversation+AccessMode.swift
1
13721
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation private let zmLog = ZMSLog(tag: "ConversationLink") public enum SetAllowGuestsError: Error { case unknown } public enum SetAllowServicesError: Error { case unknown case invalidOperation } fileprivate extension ZMConversation { struct TransportKey { static let data = "data" static let uri = "uri" } } public enum WirelessLinkError: Error { case noCode case invalidResponse case invalidOperation case guestLinksDisabled case noConversation case unknown init?(response: ZMTransportResponse) { switch (response.httpStatus, response.payloadLabel()) { case (403, "invalid-op"?): self = .invalidOperation case (404, "no-conversation-code"?): self = .noCode case (404, "no-conversation"?): self = .noConversation case (409, "guest-links-disabled"?): self = .guestLinksDisabled case (400..<499, _): self = .unknown default: return nil } } } extension ZMConversation { /// Fetches the link to access the conversation. /// @param completion called when the operation is ended. Called with .success and the link fetched. If the link /// was not generated yet, it is called with .success(nil). public func fetchWirelessLink(in userSession: ZMUserSession, _ completion: @escaping (Result<String?>) -> Void) { guard canManageAccess else { return completion(.failure(WirelessLinkError.invalidOperation)) } guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(WirelessLinkError.unknown)) } let request = WirelessRequestFactory.fetchLinkRequest(for: self, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: managedObjectContext!) { response in if response.httpStatus == 200, let uri = response.payload?.asDictionary()?[ZMConversation.TransportKey.uri] as? String { completion(.success(uri)) } else if response.httpStatus == 404 { completion(.success(nil)) } else { let error = WirelessLinkError(response: response) ?? .unknown zmLog.debug("Error fetching wireless link: \(error)") completion(.failure(error)) } }) userSession.transportSession.enqueueOneTime(request) } var isLegacyAccessMode: Bool { return self.accessMode == [.invite] } /// Updates the conversation access mode if necessary and creates the link to access the conversation. public func updateAccessAndCreateWirelessLink(in userSession: ZMUserSession, _ completion: @escaping (Result<String>) -> Void) { // Legacy access mode: access and access_mode have to be updated in order to create the link. if isLegacyAccessMode { setAllowGuests(true, in: userSession) { result in switch result { case .failure(let error): completion(.failure(error)) case .success: self.createWirelessLink(in: userSession, completion) } } } else { createWirelessLink(in: userSession, completion) } } func createWirelessLink(in userSession: ZMUserSession, _ completion: @escaping (Result<String>) -> Void) { guard canManageAccess else { return completion(.failure(WirelessLinkError.invalidOperation)) } guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(WirelessLinkError.unknown)) } let request = WirelessRequestFactory.createLinkRequest(for: self, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: managedObjectContext!) { response in if response.httpStatus == 201, let payload = response.payload, let data = payload.asDictionary()?[ZMConversation.TransportKey.data] as? [String: Any], let uri = data[ZMConversation.TransportKey.uri] as? String { completion(.success(uri)) if let event = ZMUpdateEvent(fromEventStreamPayload: payload, uuid: nil) { // Process `conversation.code-update` event userSession.syncManagedObjectContext.performGroupedBlock { userSession.updateEventProcessor?.storeAndProcessUpdateEvents([event], ignoreBuffer: true) } } } else if response.httpStatus == 200, let payload = response.payload?.asDictionary(), let uri = payload[ZMConversation.TransportKey.uri] as? String { completion(.success(uri)) } else { let error = WirelessLinkError(response: response) ?? .unknown zmLog.error("Error creating wireless link: \(error)") completion(.failure(error)) } }) userSession.transportSession.enqueueOneTime(request) } /// Checks if a guest link can be generated or not public func canGenerateGuestLink(in userSession: ZMUserSession, _ completion: @escaping (Result<Bool>) -> Void) { guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(WirelessLinkError.unknown)) } let request = WirelessRequestFactory.guestLinkFeatureStatusRequest(for: self, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: managedObjectContext!) { response in switch response.httpStatus { case 200: guard let payload = response.payload?.asDictionary(), let data = payload["status"] as? String else { return completion(.failure(WirelessLinkError.invalidResponse)) } return completion(.success(data == "enabled")) case 404: let error = WirelessLinkError(response: response) ?? .unknown zmLog.error("Could not check guest link status: \(error)") completion(.failure(error)) default: completion(.failure(WirelessLinkError.unknown)) } }) userSession.transportSession.enqueueOneTime(request) } /// Deletes the existing wireless link. public func deleteWirelessLink(in userSession: ZMUserSession, _ completion: @escaping (VoidResult) -> Void) { guard canManageAccess else { return completion(.failure(WirelessLinkError.invalidOperation)) } guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(WirelessLinkError.unknown)) } let request = WirelessRequestFactory.deleteLinkRequest(for: self, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: managedObjectContext!) { response in if response.httpStatus == 200 { completion(.success) } else { let error = WirelessLinkError(response: response) ?? .unknown zmLog.debug("Error creating wireless link: \(error)") completion(.failure(error)) } }) userSession.transportSession.enqueueOneTime(request) } /// Changes the conversation access mode to allow guests. public func setAllowGuests(_ allowGuests: Bool, in userSession: ZMUserSession, _ completion: @escaping (VoidResult) -> Void) { guard canManageAccess else { return completion(.failure(WirelessLinkError.invalidOperation)) } guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(WirelessLinkError.unknown)) } setAllowGuestsAndServices(allowGuests: allowGuests, allowServices: self.allowServices, in: userSession, apiVersion: apiVersion, completion) } /// Changes the conversation access mode to allow services. public func setAllowServices(_ allowServices: Bool, in userSession: ZMUserSession, _ completion: @escaping (VoidResult) -> Void) { guard canManageAccess else { return completion(.failure(SetAllowServicesError.invalidOperation)) } guard let apiVersion = BackendInfo.apiVersion else { return completion(.failure(SetAllowServicesError.unknown)) } setAllowGuestsAndServices(allowGuests: self.allowGuests, allowServices: allowServices, in: userSession, apiVersion: apiVersion, completion) } /// Changes the conversation access mode to allow services. private func setAllowGuestsAndServices(allowGuests: Bool, allowServices: Bool, in userSession: ZMUserSession, apiVersion: APIVersion, _ completion: @escaping (VoidResult) -> Void) { let request = WirelessRequestFactory.setAccessRoles(allowGuests: allowGuests, allowServices: allowServices, for: self, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: managedObjectContext!) { response in if let payload = response.payload, let event = ZMUpdateEvent(fromEventStreamPayload: payload, uuid: nil) { self.allowGuests = allowGuests self.allowServices = allowServices // Process `conversation.access-update` event userSession.syncManagedObjectContext.performGroupedBlock { userSession.updateEventProcessor?.storeAndProcessUpdateEvents([event], ignoreBuffer: true) } completion(.success) } else { zmLog.debug("Error setting access role: \(response)") completion(.failure(SetAllowServicesError.unknown)) } }) userSession.transportSession.enqueueOneTime(request) } public var canManageAccess: Bool { guard let moc = self.managedObjectContext else { return false } let selfUser = ZMUser.selfUser(in: moc) return selfUser.canModifyAccessControlSettings(in: self) } } internal struct WirelessRequestFactory { static func fetchLinkRequest(for conversation: ZMConversation, apiVersion: APIVersion) -> ZMTransportRequest { guard let identifier = conversation.remoteIdentifier?.transportString() else { fatal("conversation is not yet inserted on the backend") } return .init(getFromPath: "/conversations/\(identifier)/code", apiVersion: apiVersion.rawValue) } static func guestLinkFeatureStatusRequest(for conversation: ZMConversation, apiVersion: APIVersion) -> ZMTransportRequest { guard let identifier = conversation.remoteIdentifier?.transportString() else { fatal("conversation is not yet inserted on the backend") } return .init(getFromPath: "/conversations/\(identifier)/features/conversationGuestLinks", apiVersion: apiVersion.rawValue) } static func createLinkRequest(for conversation: ZMConversation, apiVersion: APIVersion) -> ZMTransportRequest { guard let identifier = conversation.remoteIdentifier?.transportString() else { fatal("conversation is not yet inserted on the backend") } return .init(path: "/conversations/\(identifier)/code", method: .methodPOST, payload: nil, apiVersion: apiVersion.rawValue) } static func deleteLinkRequest(for conversation: ZMConversation, apiVersion: APIVersion) -> ZMTransportRequest { guard let identifier = conversation.remoteIdentifier?.transportString() else { fatal("conversation is not yet inserted on the backend") } return .init(path: "/conversations/\(identifier)/code", method: .methodDELETE, payload: nil, apiVersion: apiVersion.rawValue) } static func setAccessRoles(allowGuests: Bool, allowServices: Bool, for conversation: ZMConversation, apiVersion: APIVersion) -> ZMTransportRequest { guard let identifier = conversation.remoteIdentifier?.transportString() else { fatal("conversation is not yet inserted on the backend") } var accessRoles = conversation.accessRoles if allowServices { accessRoles.insert(.service) } else { accessRoles.remove(.service) } if allowGuests { accessRoles.insert(.guest) accessRoles.insert(.nonTeamMember) } else { accessRoles.remove(.guest) accessRoles.remove(.nonTeamMember) } let payload = [ "access": ConversationAccessMode.value(forAllowGuests: allowGuests).stringValue as Any, "access_role": ConversationAccessRole.fromAccessRoleV2(accessRoles).rawValue, "access_role_v2": accessRoles.map(\.rawValue) ] return .init(path: "/conversations/\(identifier)/access", method: .methodPUT, payload: payload as ZMTransportData, apiVersion: apiVersion.rawValue) } }
gpl-3.0
1111c9c74ed40ae8c01684d6f5e2a5bc
41.479876
185
0.652649
5.219095
false
false
false
false
adrfer/swift
test/SILGen/accessors.swift
2
9405
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s // Hold a reference to do to magically become non-POD. class Reference {} // A struct with a non-mutating getter and a mutating setter. struct OrdinarySub { var ptr = Reference() subscript(value: Int) -> Int { get { return value } set {} } } class A { var array = OrdinarySub() } func index0() -> Int { return 0 } func index1() -> Int { return 1 } // Verify that there is no unnecessary extra retain of ref.array. // rdar://19002913 func test0(ref: A) { ref.array[index0()] = ref.array[index1()] } // CHECK: sil hidden @_TF9accessors5test0FCS_1AT_ : $@convention(thin) (@owned A) -> () { // CHECK: bb0(%0 : $A): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF9accessors6index0FT_Si // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF9accessors6index1FT_Si // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = class_method %0 : $A, #A.array!getter.1 // CHECK-NEXT: [[T1:%.*]] = apply [[T0]](%0) // CHECK-NEXT: store [[T1]] to [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]] // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T1:%.*]] = function_ref @_TFV9accessors11OrdinarySubg9subscriptFSiSi // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]]) // CHECK-NEXT: release_value [[T0]] // Formal access to LHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $A, #A.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on %0 : $A // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFV9accessors11OrdinarySubs9subscriptFSiSi // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout A, @thick A.Type) -> ()>, case #Optional.Some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.None!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK:%.*]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout A, @thick A.Type) -> ()): // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A // CHECK-NEXT: store %0 to [[TEMP2]] : $*A // CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // Balance out the +1 from the function parameter. // CHECK-NEXT: strong_release %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // A struct with a mutating getter and a mutating setter. struct MutatingSub { var ptr = Reference() subscript(value: Int) -> Int { mutating get { return value } set {} } } class B { var array = MutatingSub() } func test1(ref: B) { ref.array[index0()] = ref.array[index1()] } // CHECK-LABEL: sil hidden @_TF9accessors5test1FCS_1BT_ : $@convention(thin) (@owned B) -> () { // CHECK: bb0(%0 : $B): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF9accessors6index0FT_Si // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF9accessors6index1FT_Si // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on %0 : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFV9accessors11MutatingSubg9subscriptFSiSi : $@convention(method) (Int, @inout MutatingSub) -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout B, @thick B.Type) -> ()>, case #Optional.Some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.None!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK:%.*]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> ()): // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store %0 to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // Formal access to LHS. // CHECK-NEXT: [[STORAGE2:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER2:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER2]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE2]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on %0 : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFV9accessors11MutatingSubs9subscriptFSiSi : $@convention(method) (Int, Int, @inout MutatingSub) -> () // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout B, @thick B.Type) -> ()>, case #Optional.Some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.None!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK:%.*]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> ()): // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store %0 to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE2]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER2]] // CHECK-NEXT: dealloc_stack [[STORAGE2]] // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // Balance out the +1 from the function parameter. // CHECK-NEXT: strong_release %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return struct RecInner { subscript(i: Int) -> Int { get { return i } } } struct RecOuter { var inner : RecInner { unsafeAddress { return nil } unsafeMutableAddress { return nil } } } func test_rec(inout outer: RecOuter) -> Int { return outer.inner[0] } // This uses the immutable addressor. // CHECK: sil hidden @_TF9accessors8test_recFRVS_8RecOuterSi : $@convention(thin) (@inout RecOuter) -> Int { // CHECK: function_ref @_TFV9accessors8RecOuterlu5innerVS_8RecInner : $@convention(method) (RecOuter) -> UnsafePointer<RecInner> struct Rec2Inner { subscript(i: Int) -> Int { mutating get { return i } } } struct Rec2Outer { var inner : Rec2Inner { unsafeAddress { return nil } unsafeMutableAddress { return nil } } } func test_rec2(inout outer: Rec2Outer) -> Int { return outer.inner[0] } // This uses the mutable addressor. // CHECK: sil hidden @_TF9accessors9test_rec2FRVS_9Rec2OuterSi : $@convention(thin) (@inout Rec2Outer) -> Int { // CHECK: function_ref @_TFV9accessors9Rec2Outerau5innerVS_9Rec2Inner : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
apache-2.0
5bbdaac5a4b8b9812473fbcc10b1db0f
48.5
261
0.627858
3.185976
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/OrderedDictionary.swift
1
11064
// // LinkedHashMap.swift // SwifSoup // // Created by Nabil Chatbi on 03/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation public class OrderedDictionary<Key: Hashable, Value: Equatable>: MutableCollection, Hashable { /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return _orderedKeys.index(after: i) } // ======================================================= // // MARK: - Type Aliases // ======================================================= // public typealias Element = (Key, Value) public typealias Index = Int // ======================================================= // // MARK: - Initialization // ======================================================= // public init() {} public init(count: Int) {} public init(elements: [Element]) { for (key, value) in elements { self[key] = value } } public func copy() -> Any { return copy(with: nil) } public func mutableCopy(with zone: NSZone? = nil) -> Any { return copy() } public func copy(with zone: NSZone? = nil) -> Any { let copy = OrderedDictionary<Key, Value>() //let copy = type(of:self).init() for element in orderedKeys { copy.put(value: valueForKey(key: element)!, forKey: element) } return copy } func clone() -> OrderedDictionary<Key, Value> { return copy() as! OrderedDictionary<Key, Value> } // ======================================================= // // MARK: - Accessing Keys & Values // ======================================================= // public var orderedKeys: [Key] { return _orderedKeys } public func keySet() -> [Key] { return _orderedKeys } public var orderedValues: [Value] { return _orderedKeys.flatMap { _keysToValues[$0] } } // ======================================================= // // MARK: - Managing Content Using Keys // ======================================================= // public subscript(key: Key) -> Value? { get { return valueForKey(key: key) } set(newValue) { if let newValue = newValue { updateValue(value: newValue, forKey: key) } else { removeValueForKey(key: key) } } } public func containsKey(key: Key) -> Bool { return _orderedKeys.contains(key) } public func valueForKey(key: Key) -> Value? { return _keysToValues[key] } public func get(key: Key) -> Value? { return valueForKey(key: key) } // required var for the Hashable protocol public var hashValue: Int { return 0 } public func hashCode() -> Int { return hashValue } @discardableResult private func updateValue(value: Value, forKey key: Key) -> Value? { if _orderedKeys.contains(key) { guard let currentValue = _keysToValues[key] else { fatalError("Inconsistency error occured in OrderedDictionary") } _keysToValues[key] = value return currentValue } else { _orderedKeys.append(key) _keysToValues[key] = value return nil } } public func put(value: Value, forKey key: Key) { self[key] = value } public func putAll(all: OrderedDictionary<Key, Value>) { for i in all.orderedKeys { put(value:all[i]!, forKey: i) } } @discardableResult public func removeValueForKey(key: Key) -> Value? { if let index = _orderedKeys.index(of: key) { guard let currentValue = _keysToValues[key] else { fatalError("Inconsistency error occured in OrderedDictionary") } _orderedKeys.remove(at: index) _keysToValues[key] = nil return currentValue } else { return nil } } @discardableResult public func remove(key: Key) -> Value? { return removeValueForKey(key:key) } public func removeAll(keepCapacity: Bool = true) { _orderedKeys.removeAll(keepingCapacity: keepCapacity) _keysToValues.removeAll(keepingCapacity: keepCapacity) } // ======================================================= // // MARK: - Managing Content Using Indexes // ======================================================= // public subscript(index: Index) -> Element { get { guard let element = elementAtIndex(index: index) else { fatalError("OrderedDictionary index out of range") } return element } set(newValue) { updateElement(element: newValue, atIndex: index) } } public func indexForKey(key: Key) -> Index? { return _orderedKeys.index(of: key) } public func elementAtIndex(index: Index) -> Element? { guard _orderedKeys.indices.contains(index) else { return nil } let key = _orderedKeys[index] guard let value = self._keysToValues[key] else { fatalError("Inconsistency error occured in OrderedDictionary") } return (key, value) } public func insertElementWithKey(key: Key, value: Value, atIndex index: Index) -> Value? { return insertElement(newElement: (key, value), atIndex: index) } public func insertElement(newElement: Element, atIndex index: Index) -> Value? { guard index >= 0 else { fatalError("Negative OrderedDictionary index is out of range") } guard index <= count else { fatalError("OrderedDictionary index out of range") } let (key, value) = newElement let adjustedIndex: Int let currentValue: Value? if let currentIndex = _orderedKeys.index(of: key) { currentValue = _keysToValues[key] adjustedIndex = (currentIndex < index - 1) ? index - 1 : index _orderedKeys.remove(at: currentIndex) _keysToValues[key] = nil } else { currentValue = nil adjustedIndex = index } _orderedKeys.insert(key, at: adjustedIndex) _keysToValues[key] = value return currentValue } @discardableResult public func updateElement(element: Element, atIndex index: Index) -> Element? { guard let currentElement = elementAtIndex(index: index) else { fatalError("OrderedDictionary index out of range") } let (newKey, newValue) = element _orderedKeys[index] = newKey _keysToValues[newKey] = newValue return currentElement } public func removeAtIndex(index: Index) -> Element? { if let element = elementAtIndex(index: index) { _orderedKeys.remove(at: index) _keysToValues.removeValue(forKey: element.0) return element } else { return nil } } // ======================================================= // // MARK: - CollectionType Conformance // ======================================================= // public var startIndex: Index { return _orderedKeys.startIndex } public var endIndex: Index { return _orderedKeys.endIndex } // ======================================================= // // MARK: - Internal Backing Store // ======================================================= // /// The backing store for the ordered keys. internal var _orderedKeys = [Key]() /// The backing store for the mapping of keys to values. internal var _keysToValues = [Key: Value]() } // ======================================================= // // MARK: - Initializations from Literals // ======================================================= // //extension OrderedDictionary: ExpressibleByArrayLiteral { // // public convenience init(arrayLiteral elements: Element...) { // self.init(elements: elements) // } //} // //extension OrderedDictionary: ExpressibleByDictionaryLiteral { // // public convenience init(dictionaryLiteral elements: Element...) { // self.init(elements: elements) // } // //} extension OrderedDictionary: LazySequenceProtocol { func generate() -> AnyIterator<Value> { var i = 0 return AnyIterator { if (i >= self.orderedValues.count) { return nil } i += 1 return self.orderedValues[i-1] } } } // ======================================================= // // MARK: - Description // ======================================================= // extension OrderedDictionary: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return constructDescription(debug: false) } public var debugDescription: String { return constructDescription(debug: true) } private func constructDescription(debug: Bool) -> String { // The implementation of the description is inspired by zwaldowski's implementation of the ordered dictionary. // See http://bit.ly/1VL4JUR if isEmpty { return "[:]" } func descriptionForItem(item: Any) -> String { var description = "" if debug { debugPrint(item, separator: "", terminator: "", to: &description) } else { print(item, separator: "", terminator: "", to: &description) } return description } let bodyComponents = map({ (key: Key, value: Value) -> String in return descriptionForItem(item: key) + ": " + descriptionForItem(item: value) }) let body = bodyComponents.joined(separator: ", ") return "[\(body)]" } } extension OrderedDictionary: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool { if(lhs.count != rhs.count) {return false} return (lhs._orderedKeys == rhs._orderedKeys) && (lhs._keysToValues == rhs._keysToValues) } } //public func == <Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool { // return lhs._orderedKeys == rhs._orderedKeys && lhs._keysToValues == rhs._keysToValues //}
mit
4b64cfd92df4cf221cbd9940a71951a9
27.885117
133
0.529061
4.905987
false
false
false
false
JGiola/swift
test/SILGen/protocol_with_superclass_where_clause.swift
1
13019
// RUN: %target-swift-emit-silgen -module-name protocol_with_superclass %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s // Protocols with superclass-constrained Self, written using a 'where' clause. class Concrete { typealias ConcreteAlias = String func concreteMethod(_: ConcreteAlias) {} } class Generic<T> : Concrete { typealias GenericAlias = (T, T) func genericMethod(_: GenericAlias) {} } protocol BaseProto {} protocol ProtoRefinesClass where Self : Generic<Int>, Self : BaseProto { func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) } extension ProtoRefinesClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass17ProtoRefinesClassPAAE019extensionMethodUsesF5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: [[METHOD:%.*]] = class_method [[UPCAST2]] : $Concrete, #Concrete.concreteMethod : (Concrete) -> (String) -> (), $@convention(method) (@guaranteed String, @guaranteed Concrete) -> () // CHECK-NEXT: apply [[METHOD]](%0, [[UPCAST2]]) // CHECK-NEXT: destroy_value [[UPCAST2]] concreteMethod(x) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK: [[METHOD:%.*]] = class_method [[UPCAST]] : $Generic<Int>, #Generic.genericMethod : <T> (Generic<T>) -> ((T, T)) -> (), $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, @guaranteed Generic<τ_0_0>) -> () // CHECK-NEXT: apply [[METHOD]]<Int>({{.*}}, [[UPCAST]]) // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: destroy_value [[UPCAST]] genericMethod(y) // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: destroy_value [[UPCAST]] : $Generic<Int> let _: Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[SELF]] : $Self to $Generic<Int> // CHECK-NEXT: [[UPCAST2:%.*]] = upcast [[UPCAST]] : $Generic<Int> to $Concrete // CHECK-NEXT: destroy_value [[UPCAST2]] : $Concrete let _: Concrete = self // CHECK: [[BOX:%.*]] = alloc_stack $BaseProto // CHECK-NEXT: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[ADDR:%.*]] = init_existential_addr [[BOX]] : $*BaseProto, $Self // CHECK-NEXT: store [[SELF]] to [init] [[ADDR]] : $*Self // CHECK-NEXT: destroy_addr [[BOX]] : $*BaseProto // CHECK-NEXT: dealloc_stack [[BOX]] : $*BaseProto let _: BaseProto = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Generic<Int> & BaseProto let _: BaseProto & Generic<Int> = self // CHECK: [[SELF:%.*]] = copy_value %3 : $Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[SELF]] : $Self : $Self, $Concrete & BaseProto let _: BaseProto & Concrete = self // CHECK: return } } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass22usesProtoRefinesClass1yyAA0eF5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesClass) -> () func usesProtoRefinesClass1(_ t: ProtoRefinesClass) { let x: ProtoRefinesClass.ConcreteAlias = "hi" _ = ProtoRefinesClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesClass.GenericAlias = (1, 2) _ = ProtoRefinesClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass22usesProtoRefinesClass2yyxAA0eF5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesClass> (@guaranteed T) -> () func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class GoodConformingClass : Generic<Int>, ProtoRefinesClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass19GoodConformingClassC015requirementUsesF5TypesyySS_Si_SittF : $@convention(method) (@guaranteed String, Int, Int, @guaranteed GoodConformingClass) -> () func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) } } protocol ProtoRefinesProtoWithClass where Self : ProtoRefinesClass {} extension ProtoRefinesProtoWithClass { // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass012ProtoRefinesD9WithClassPAAE026anotherExtensionMethodUsesG5TypesyySS_Si_SittF : $@convention(method) <Self where Self : ProtoRefinesProtoWithClass> (@guaranteed String, Int, Int, @guaranteed Self) -> () func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) { _ = ConcreteAlias.self _ = GenericAlias.self concreteMethod(x) genericMethod(y) let _: Generic<Int> = self let _: Concrete = self let _: BaseProto = self let _: BaseProto & Generic<Int> = self let _: BaseProto & Concrete = self } } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass016usesProtoRefinesE10WithClass1yyAA0efeG5Class_pF : $@convention(thin) (@guaranteed ProtoRefinesProtoWithClass) -> () func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) { let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi" _ = ProtoRefinesProtoWithClass.ConcreteAlias.self t.concreteMethod(x) let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2) _ = ProtoRefinesProtoWithClass.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass016usesProtoRefinesE10WithClass2yyxAA0efeG5ClassRzlF : $@convention(thin) <T where T : ProtoRefinesProtoWithClass> (@guaranteed T) -> () func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) { let x: T.ConcreteAlias = "hi" _ = T.ConcreteAlias.self t.concreteMethod(x) let y: T.GenericAlias = (1, 2) _ = T.GenericAlias.self t.genericMethod(y) t.requirementUsesClassTypes(x, y) let _: Generic<Int> = t let _: Concrete = t let _: BaseProto = t let _: BaseProto & Generic<Int> = t let _: BaseProto & Concrete = t } class ClassWithInits<T> { init(notRequiredInit: ()) {} required init(requiredInit: ()) {} } protocol ProtocolWithClassInits where Self : ClassWithInits<Int> {} // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass26useProtocolWithClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolWithClassInits.Type) -> () func useProtocolWithClassInits1(_ t: ProtocolWithClassInits.Type) { // CHECK: [[OPENED:%.*]] = open_existential_metatype %0 : $@thick ProtocolWithClassInits.Type // CHECK-NEXT: [[UPCAST:%.*]] = upcast [[OPENED]] : $@thick (@opened("{{.*}}", ProtocolWithClassInits) Self).Type to $@thick ClassWithInits<Int>.Type // CHECK-NEXT: [[METHOD:%.*]] = class_method [[UPCAST]] : $@thick ClassWithInits<Int>.Type, #ClassWithInits.init!allocator : <T> (ClassWithInits<T>.Type) -> (()) -> ClassWithInits<T>, $@convention(method) <τ_0_0> (@thick ClassWithInits<τ_0_0>.Type) -> @owned ClassWithInits<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]<Int>([[UPCAST]]) // CHECK-NEXT: [[CAST:%.*]] = unchecked_ref_cast [[RESULT]] : $ClassWithInits<Int> to $@opened("{{.*}}", ProtocolWithClassInits) Self // CHECK-NEXT: [[EXISTENTIAL:%.*]] = init_existential_ref [[CAST]] : $@opened("{{.*}}", ProtocolWithClassInits) Self : $@opened("{{.*}}", ProtocolWithClassInits) Self, $ProtocolWithClassInits // CHECK-NEXT: destroy_value [[EXISTENTIAL]] let _: ProtocolWithClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass26useProtocolWithClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolWithClassInits> (@thick T.Type) -> () func useProtocolWithClassInits2<T : ProtocolWithClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } protocol ProtocolRefinesClassInits where Self : ProtocolWithClassInits {} // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass29useProtocolRefinesClassInits1yyAA0efG5Inits_pXpF : $@convention(thin) (@thick ProtocolRefinesClassInits.Type) -> () func useProtocolRefinesClassInits1(_ t: ProtocolRefinesClassInits.Type) { let _: ProtocolRefinesClassInits = t.init(requiredInit: ()) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass29useProtocolRefinesClassInits2yyxmAA0efG5InitsRzlF : $@convention(thin) <T where T : ProtocolRefinesClassInits> (@thick T.Type) -> () func useProtocolRefinesClassInits2<T : ProtocolRefinesClassInits>(_ t: T.Type) { let _: T = T(requiredInit: ()) let _: T = t.init(requiredInit: ()) } class ClassWithDefault<T> { func makeT() -> T { while true {} } } protocol SillyDefault where Self : ClassWithDefault<Int> { func makeT() -> Int } class ConformsToSillyDefault : ClassWithDefault<Int>, SillyDefault {} // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW : // CHECK: class_method %1 : $ClassWithDefault<Int>, #ClassWithDefault.makeT : <T> (ClassWithDefault<T>) -> () -> T, $@convention(method) <τ_0_0> (@guaranteed ClassWithDefault<τ_0_0>) -> @out τ_0_0 // CHECK: return class BaseClass : BaseProto {} protocol RefinedProto where Self : BaseClass {} func takesBaseProtocol(_: BaseProto) {} func passesRefinedProtocol(_ r: RefinedProto) { takesBaseProtocol(r) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass21passesRefinedProtocolyyAA0E5Proto_pF : $@convention(thin) (@guaranteed RefinedProto) -> () // CHECK: bb0(%0 : @guaranteed $RefinedProto): // CHECK: [[OPENED:%.*]] = open_existential_ref %0 : $RefinedProto to $@opened("{{.*}}", RefinedProto) Self // CHECK-NEXT: [[BASE:%.*]] = alloc_stack $BaseProto // CHECK-NEXT: [[BASE_PAYLOAD:%.*]] = init_existential_addr [[BASE]] : $*BaseProto, $@opened("{{.*}}", RefinedProto) Self // CHECK-NEXT: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] : $@opened("{{.*}}", RefinedProto) Self // CHECK-NEXT: store [[OPENED_COPY]] to [init] [[BASE_PAYLOAD]] : $*@opened("{{.*}}", RefinedProto) Self // CHECK: [[FUNC:%.*]] = function_ref @$s24protocol_with_superclass17takesBaseProtocolyyAA0E5Proto_pF : $@convention(thin) (@in_guaranteed BaseProto) -> () // CHECK-NEXT: apply [[FUNC]]([[BASE]]) : $@convention(thin) (@in_guaranteed BaseProto) -> () // CHECK-NEXT: destroy_addr [[BASE]] : $*BaseProto // CHECK-NEXT: dealloc_stack [[BASE]] : $*BaseProto // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() func takesFuncTakingRefinedProto(arg: (RefinedProto) -> ()) {} func passesFuncTakingBaseClass() { let closure: (BaseClass) -> () = { _ in } takesFuncTakingRefinedProto(arg: closure) } // CHECK-LABEL: sil hidden [ossa] @$s24protocol_with_superclass25passesFuncTakingBaseClassyyF : $@convention(thin) () -> () // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s24protocol_with_superclass9BaseClassCIegg_AA12RefinedProto_pIegg_TR : $@convention(thin) (@guaranteed RefinedProto, @guaranteed @callee_guaranteed (@guaranteed BaseClass) -> ()) -> () // CHECK: [[PAYLOAD:%.*]] = open_existential_ref %0 : $RefinedProto to $@opened("{{.*}}", RefinedProto) Self // CHECK: [[COPY:%.*]] = copy_value [[PAYLOAD]] // CHECK: [[UPCAST:%.*]] = upcast [[COPY]] : $@opened("{{.*}}", RefinedProto) Self to $BaseClass // CHECK: [[BORROW:%.*]] = begin_borrow [[UPCAST]] // CHECK: apply %1([[BORROW]]) // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value [[UPCAST]] // CHECK: return // CHECK-LABEL: sil_witness_table hidden ConformsToSillyDefault: SillyDefault module protocol_with_superclass { // CHECK-NEXT: method #SillyDefault.makeT: <Self where Self : SillyDefault> (Self) -> () -> Int : @$s24protocol_with_superclass22ConformsToSillyDefaultCAA0fG0A2aDP5makeTSiyFTW // CHECK-NEXT: }
apache-2.0
3be297683d96cb507065284c0a3f0dc1
43.399317
282
0.676916
3.58968
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/MajorBackNavigationBar.swift
1
1638
// // MajorBackNavigationBar.swift // TelegramMac // // Created by keepcoder on 06/01/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Postbox class MajorBackNavigationBar: BackNavigationBar { private let disposable:MetaDisposable = MetaDisposable() private let context:AccountContext private let peerId:PeerId private let badgeNode:GlobalBadgeNode init(_ controller: ViewController, context: AccountContext, excludePeerId:PeerId) { self.context = context self.peerId = excludePeerId var layoutChanged:(()->Void)? = nil badgeNode = GlobalBadgeNode(context.account, sharedContext: context.sharedContext, excludeGroupId: Namespaces.PeerGroup.archive, view: View(), layoutChanged: { layoutChanged?() }) badgeNode.xInset = 0 super.init(controller) addSubview(badgeNode.view!) layoutChanged = { [weak self] in self?.needsLayout = true } } override func layout() { super.layout() self.badgeNode.view!.setFrameOrigin(NSMakePoint(min(frame.width == minWidth ? 30 : 22, frame.width - self.badgeNode.view!.frame.width - 4), 4)) } deinit { disposable.dispose() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } }
gpl-2.0
2992caa3d4368cdc76eeaf0461cf3b48
24.984127
167
0.628589
4.843195
false
false
false
false
wfilleman/ArraysPlayground
Arrays.playground/Pages/Array.map.xcplaygroundpage/Contents.swift
1
2779
//: [Previous](@previous) //: ## Swift Array.map //: * Use real weather data to convert into clean arrays for use by a caller. //: * Returned forecasted weather data from Open Weather Map is returned in a monster JSON result forecasted for the next 5 days. //: * Temperature data in JSON result is in Kelvin. import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true import Alamofire import SwiftyJSON import PromiseKit //: Promised function to return just the Forecasted data over the next 5 days every three hours. func returnWeatherForecast() -> Promise<JSON> { return Promise { fulfill, rejected in Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/forecast?id=\(cityID)&APPID=\(openWeatherAPIKey)").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print("JSON: \(json)") fulfill(json) } case .Failure(let error): print(error) rejected(error) } } } } //: ## Entry Point returnWeatherForecast() .then { weatherJSON -> Void in // Example: // * The .map operator on a Swift Array will iterate over each element of the ["list"] element to convert into another element. // * The "listObj" parameter is one element from the ["list"] JSON array in JSON. // * "listObj -> NSNumber" means take this element input in JSON and give back just a NSNumber // * maxTempForecast results in a type of [NSNumber] let maxTempForecast = weatherJSON["list"].arrayValue.map { listObj -> NSNumber in // Pull out the Max Temp for the day. Results are in Kelvin let maxTempK = listObj["main"]["temp_max"].numberValue // Return the Max Temp in Fahrenheit represented as a NSNumber return KtoF(maxTempK) } // START Exercise: Return the Forecasted Humidity instead. // Step 1: Find the Humidity JSON tag from the returned JSON. // Step 2: Setup the let variable to map to an array of NSNumbers. // Step 3: Pull out the humidity tag and convert to NSNumber to return to the map call. // Step 4: fulfill the Humidity array instead of maxTempForecast // Step 5: Change the map to return a string so that your values read: "50%" // REPLACE WITH YOUR CODE // END Excercise Code print(maxTempForecast) // Look at the Log for results } .error { error in print(error) } //: [Next](@next)
apache-2.0
5c60cf21594ebf4ce0791e78fc97553c
38.140845
160
0.61281
4.766724
false
false
false
false
coolsamson7/inject
Inject/configuration/FQN.swift
1
1335
// // FQN.swift // Inject // // Created by Andreas Ernst on 18.07.16. // Copyright © 2016 Andreas Ernst. All rights reserved. // /// A `FQN` is a fully qualified name containing a namespace and a key open class FQN : Hashable, CustomStringConvertible { // MARK: instance data var namespace : String var key : String // MARK: class func open class func fromString(_ str : String) -> FQN { let colon = str.range(of: ":") if colon != nil { let namespace = str[str.startIndex..<colon!.lowerBound] let key = str[colon!.upperBound..<str.endIndex] return FQN(namespace: namespace, key: key) } else { return FQN(namespace: "", key: str) } } // MARK: init public init(namespace : String = "", key : String) { self.namespace = namespace; self.key = key } // Hashable open var hashValue: Int { get { return namespace.hash &+ key.hash } } // MARK: implement CustomStringConvertible open var description: String { return "[namespace: \"\(namespace)\", key: \"\(key)\"]" } } public func ==(lhs: FQN, rhs: FQN) -> Bool { return lhs.namespace == rhs.namespace && lhs.key == rhs.key }
mit
b7ebc4d321352f62b5f8f64028f54d47
22.821429
70
0.546477
4.221519
false
false
false
false
bag-umbala/music-umbala
Music-Umbala/Music-Umbala/Controller/PlaylistDetailTableViewController.swift
1
3414
// // PlaylistDetailTableViewController.swift // Music-Umbala // // Created by Nam Nguyen on 6/2/17. // Copyright © 2017 Nam Vo. All rights reserved. // // MARK: ** ko su dung import UIKit class PlaylistDetailTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // 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() // self.navigationController?.navigationBar.isHidden = false self.tableView.delegate = self self.tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlaylistDetailCell", for: indexPath) as! SongOfflineTableViewCell cell.songName.text = "s" cell.singerOfSong.text = "d" cell.tag = indexPath.row return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0ee8543cc73a53ac55324302c48f4a4c
33.826531
136
0.673308
5.218654
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Edit data/Delete features (feature service)/DeleteFeaturesViewController.swift
1
5864
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class DeleteFeaturesViewController: UIViewController, AGSGeoViewTouchDelegate, AGSCalloutDelegate { @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISStreets) // Set touch delegate on map view as self. mapView.touchDelegate = self mapView.callout.delegate = self } } /// The feature table to delete features from. var featureTable: AGSServiceFeatureTable! /// The service geodatabase that contains damaged property features. var serviceGeodatabase: AGSServiceGeodatabase! /// The feature layer created from the feature table. var featureLayer: AGSFeatureLayer! /// Last identify operation. var lastQuery: AGSCancelable! /// The currently selected feature. var selectedFeature: AGSFeature! override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["DeleteFeaturesViewController"] // Load the service geodatabase. let damageFeatureService = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer")! loadServiceGeodatabase(from: damageFeatureService) } /// Load and set a service geodatabase from a feature service URL. /// - Parameter serviceURL: The URL to the feature service. func loadServiceGeodatabase(from serviceURL: URL) { let serviceGeodatabase = AGSServiceGeodatabase(url: serviceURL) serviceGeodatabase.load { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } else { let featureTable = serviceGeodatabase.table(withLayerID: 0)! self.featureTable = featureTable self.serviceGeodatabase = serviceGeodatabase // Add the feature layer to the operational layers on map. let featureLayer = AGSFeatureLayer(featureTable: featureTable) self.featureLayer = featureLayer self.mapView.map?.operationalLayers.add(featureLayer) self.mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: 544871.19, y: 6806138.66, spatialReference: .webMercator()), scale: 2e6)) } } } func showCallout(for feature: AGSFeature, at tapLocation: AGSPoint) { let title = feature.attributes["typdamage"] as! String mapView.callout.title = title mapView.callout.accessoryButtonImage = UIImage(named: "Discard") mapView.callout.show(for: feature, tapLocation: tapLocation, animated: true) } /// Delete a feature from the feature table. func deleteFeature(_ feature: AGSFeature) { featureTable.delete(feature) { [weak self] error in if let error = error { self?.presentAlert(message: "Error while deleting feature: \(error.localizedDescription)") } else { self?.applyEdits() } } } /// Apply local edits to the geodatabase. func applyEdits() { guard serviceGeodatabase.hasLocalEdits() else { return } serviceGeodatabase.applyEdits { [weak self] _, error in if let error = error { self?.presentAlert(message: "Error while applying edits: \(error.localizedDescription)") } } } // MARK: - AGSGeoViewTouchDelegate func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { if let query = lastQuery { query.cancel() } // Hide the callout. mapView.callout.dismiss() lastQuery = mapView.identifyLayer(featureLayer, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false) { [weak self] identifyLayerResult in guard let self = self else { return } self.lastQuery = nil if let feature = identifyLayerResult.geoElements.first as? AGSFeature { // Show callout for the feature. self.showCallout(for: feature, at: mapPoint) // Update selected feature. self.selectedFeature = feature } else if let error = identifyLayerResult.error { self.presentAlert(error: error) } } } // MARK: - AGSCalloutDelegate func didTapAccessoryButton(for callout: AGSCallout) { mapView.callout.dismiss() let alertController = UIAlertController(title: "Are you sure you want to delete the feature?", message: nil, preferredStyle: .alert) let alertAction = UIAlertAction(title: "Delete", style: .destructive) { [unowned self] _ in deleteFeature(selectedFeature) } alertController.addAction(alertAction) let cancelAlertAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(cancelAlertAction) alertController.preferredAction = cancelAlertAction present(alertController, animated: true) } }
apache-2.0
0107d6cb3482160d34cfe560feed5caa
43.090226
158
0.655355
4.794767
false
false
false
false
lelandjansen/fatigue
ios/fatigue/OccupationSettingController.swift
1
2337
import UIKit class RoleSettingController: UITableViewController { weak var delegate: SettingsDelegate? enum CellId: String { case roleCell } init() { super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = RoleSetting.settingName view.backgroundColor = .light } let items: [Role] = [ .pilot, .engineer ] var role = UserDefaults.standard.role var selectedIndexPath: IndexPath? override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = { guard let cell = tableView.dequeueReusableCell(withIdentifier: CellId.roleCell.rawValue) else { return UITableViewCell(style: .default, reuseIdentifier: CellId.roleCell.rawValue) } return cell }() if items[indexPath.row] == role { cell.accessoryType = .checkmark selectedIndexPath = indexPath } else { cell.accessoryType = .none } cell.textLabel?.text = items[indexPath.row].rawValue.capitalized cell.textLabel?.textColor = .dark cell.backgroundColor = .clear cell.tintColor = .violet return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let lastSelectedIndexPath = selectedIndexPath { tableView.cellForRow(at: lastSelectedIndexPath)?.accessoryType = .none } role = items[indexPath.row] tableView.deselectRow(at: indexPath, animated: true) tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark selectedIndexPath = indexPath } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UserDefaults.standard.role = role delegate?.setSelectedCellDetails(toValue: role.rawValue.capitalized) } }
apache-2.0
bce0e7b7b8a713101a01c0c026dd617e
29.350649
109
0.621309
5.409722
false
false
false
false
Danappelxx/MuttonChop
Tests/SpecTests/SpecTests.swift
1
101226
import XCTest import MuttonChop /** Section tags and End Section tags are used in combination to wrap a section of the template for iteration These tags' content MUST be a non-whitespace character sequence NOT containing the current closing delimiter; each Section tag MUST be followed by an End Section tag with the same content within the same section. This tag's content names the data to replace the tag. Name resolution is as follows: 1) Split the name on periods; the first part is the name to resolve, any remaining parts should be retained. 2) Walk the context stack from top to bottom, finding the first context that is a) a hash containing the name as a key OR b) an object responding to a method with the given name. 3) If the context is a hash, the data is the value associated with the name. 4) If the context is an object and the method with the given name has an arity of 1, the method SHOULD be called with a String containing the unprocessed contents of the sections; the data is the value returned. 5) Otherwise, the data is the value returned by calling the method with the given name. 6) If any name parts were retained in step 1, each should be resolved against a context stack containing only the result from the former resolution. If any part fails resolution, the result should be considered falsey, and should interpolate as the empty string. If the data is not of a list type, it is coerced into a list as follows: if the data is truthy (e.g. `!!data == true`), use a single-element list containing the data, otherwise use an empty list. For each element in the data list, the element MUST be pushed onto the context stack, the section MUST be rendered, and the element MUST be popped off the context stack. Section and End Section tags SHOULD be treated as standalone when appropriate. */ final class SectionsTests: XCTestCase { static var allTests: [(String, (SectionsTests) -> () throws -> Void)] { return [ ("testTruthy", testTruthy), ("testFalsey", testFalsey), ("testNullisfalsey", testNullisfalsey), ("testContext", testContext), ("testParentcontexts", testParentcontexts), ("testVariabletest", testVariabletest), ("testListContexts", testListContexts), ("testDeeplyNestedContexts", testDeeplyNestedContexts), ("testList", testList), ("testEmptyList", testEmptyList), ("testDoubled", testDoubled), ("testNested_Truthy", testNested_Truthy), ("testNested_Falsey", testNested_Falsey), ("testContextMisses", testContextMisses), ("testImplicitIterator_String", testImplicitIterator_String), ("testImplicitIterator_Integer", testImplicitIterator_Integer), ("testImplicitIterator_Decimal", testImplicitIterator_Decimal), ("testImplicitIterator_Array", testImplicitIterator_Array), ("testDottedNames_Truthy", testDottedNames_Truthy), ("testDottedNames_Falsey", testDottedNames_Falsey), ("testDottedNames_BrokenChains", testDottedNames_BrokenChains), ("testSurroundingWhitespace", testSurroundingWhitespace), ("testInternalWhitespace", testInternalWhitespace), ("testIndentedInlineSections", testIndentedInlineSections), ("testStandaloneLines", testStandaloneLines), ("testIndentedStandaloneLines", testIndentedStandaloneLines), ("testStandaloneLineEndings", testStandaloneLineEndings), ("testStandaloneWithoutPreviousLine", testStandaloneWithoutPreviousLine), ("testStandaloneWithoutNewline", testStandaloneWithoutNewline), ("testPadding", testPadding), ] } func testTruthy() throws { let templateString = "\"{{#boolean}}This should be rendered.{{/boolean}}\"" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "\"This should be rendered.\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Truthy sections should have their contents rendered.") } func testFalsey() throws { let templateString = "\"{{#boolean}}This should not be rendered.{{/boolean}}\"" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Falsey sections should have their contents omitted.") } func testNullisfalsey() throws { let templateString = "\"{{#null}}This should not be rendered.{{/null}}\"" let contextJSON = "{\"null\":null}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Null is falsey.") } func testContext() throws { let templateString = "\"{{#context}}Hi {{name}}.{{/context}}\"" let contextJSON = "{\"context\":{\"name\":\"Joe\"}}".data(using: .utf8)! let expected = "\"Hi Joe.\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Objects and hashes should be pushed onto the context stack.") } func testParentcontexts() throws { let templateString = "\"{{#sec}}{{a}}, {{b}}, {{c.d}}{{/sec}}\"" let contextJSON = "{\"sec\":{\"b\":\"bar\"},\"b\":\"wrong\",\"c\":{\"d\":\"baz\"},\"a\":\"foo\"}".data(using: .utf8)! let expected = "\"foo, bar, baz\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Names missing in the current context are looked up in the stack.") } func testVariabletest() throws { let templateString = "\"{{#foo}}{{.}} is {{foo}}{{/foo}}\"" let contextJSON = "{\"foo\":\"bar\"}".data(using: .utf8)! let expected = "\"bar is bar\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Non-false sections have their value at the top of context, accessible as {{.}} or through the parent context. This gives a simple way to display content conditionally if a variable exists. ") } func testListContexts() throws { let templateString = "{{#tops}}{{#middles}}{{tname.lower}}{{mname}}.{{#bottoms}}{{tname.upper}}{{mname}}{{bname}}.{{/bottoms}}{{/middles}}{{/tops}}" let contextJSON = "{\"tops\":[{\"middles\":[{\"mname\":\"1\",\"bottoms\":[{\"bname\":\"x\"},{\"bname\":\"y\"}]}],\"tname\":{\"lower\":\"a\",\"upper\":\"A\"}}]}".data(using: .utf8)! let expected = "a1.A1x.A1y." let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All elements on the context stack should be accessible within lists.") } func testDeeplyNestedContexts() throws { let templateString = "{{#a}}\n{{one}}\n{{#b}}\n{{one}}{{two}}{{one}}\n{{#c}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{#d}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{#five}}\n{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}\n{{one}}{{two}}{{three}}{{four}}{{.}}6{{.}}{{four}}{{three}}{{two}}{{one}}\n{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}\n{{/five}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{/d}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{/c}}\n{{one}}{{two}}{{one}}\n{{/b}}\n{{one}}\n{{/a}}\n" let contextJSON = "{\"b\":{\"two\":2},\"c\":{\"three\":3,\"d\":{\"four\":4,\"five\":5}},\"a\":{\"one\":1}}".data(using: .utf8)! let expected = "1\n121\n12321\n1234321\n123454321\n12345654321\n123454321\n1234321\n12321\n121\n1\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All elements on the context stack should be accessible.") } func testList() throws { let templateString = "\"{{#list}}{{item}}{{/list}}\"" let contextJSON = "{\"list\":[{\"item\":1},{\"item\":2},{\"item\":3}]}".data(using: .utf8)! let expected = "\"123\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Lists should be iterated; list items should visit the context stack.") } func testEmptyList() throws { let templateString = "\"{{#list}}Yay lists!{{/list}}\"" let contextJSON = "{\"list\":[]}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Empty lists should behave like falsey values.") } func testDoubled() throws { let templateString = "{{#bool}}\n* first\n{{/bool}}\n* {{two}}\n{{#bool}}\n* third\n{{/bool}}\n" let contextJSON = "{\"two\":\"second\",\"bool\":true}".data(using: .utf8)! let expected = "* first\n* second\n* third\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Multiple sections per template should be permitted.") } func testNested_Truthy() throws { let templateString = "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |" let contextJSON = "{\"bool\":true}".data(using: .utf8)! let expected = "| A B C D E |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nested truthy sections should have their contents rendered.") } func testNested_Falsey() throws { let templateString = "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |" let contextJSON = "{\"bool\":false}".data(using: .utf8)! let expected = "| A E |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nested falsey sections should be omitted.") } func testContextMisses() throws { let templateString = "[{{#missing}}Found key 'missing'!{{/missing}}]" let contextJSON = "{}".data(using: .utf8)! let expected = "[]" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Failed context lookups should be considered falsey.") } func testImplicitIterator_String() throws { let templateString = "\"{{#list}}({{.}}){{/list}}\"" let contextJSON = "{\"list\":[\"a\",\"b\",\"c\",\"d\",\"e\"]}".data(using: .utf8)! let expected = "\"(a)(b)(c)(d)(e)\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Implicit iterators should directly interpolate strings.") } func testImplicitIterator_Integer() throws { let templateString = "\"{{#list}}({{.}}){{/list}}\"" let contextJSON = "{\"list\":[1,2,3,4,5]}".data(using: .utf8)! let expected = "\"(1)(2)(3)(4)(5)\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Implicit iterators should cast integers to strings and interpolate.") } func testImplicitIterator_Decimal() throws { let templateString = "\"{{#list}}({{.}}){{/list}}\"" let contextJSON = "{\"list\":[1.1000000000000001,2.2000000000000002,3.2999999999999998,4.4000000000000004,5.5]}".data(using: .utf8)! let expected = "\"(1.1)(2.2)(3.3)(4.4)(5.5)\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Implicit iterators should cast decimals to strings and interpolate.") } func testImplicitIterator_Array() throws { let templateString = "\"{{#list}}({{#.}}{{.}}{{/.}}){{/list}}\"" let contextJSON = "{\"list\":[[1,2,3],[\"a\",\"b\",\"c\"]]}".data(using: .utf8)! let expected = "\"(123)(abc)\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Implicit iterators should allow iterating over nested arrays.") } func testDottedNames_Truthy() throws { let templateString = "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"Here\"" let contextJSON = "{\"a\":{\"b\":{\"c\":true}}}".data(using: .utf8)! let expected = "\"Here\" == \"Here\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be valid for Section tags.") } func testDottedNames_Falsey() throws { let templateString = "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"" let contextJSON = "{\"a\":{\"b\":{\"c\":false}}}".data(using: .utf8)! let expected = "\"\" == \"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be valid for Section tags.") } func testDottedNames_BrokenChains() throws { let templateString = "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"" let contextJSON = "{\"a\":{}}".data(using: .utf8)! let expected = "\"\" == \"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names that cannot be resolved should be considered falsey.") } func testSurroundingWhitespace() throws { let templateString = " | {{#boolean}}\t|\t{{/boolean}} | \n" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = " | \t|\t | \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Sections should not alter surrounding whitespace.") } func testInternalWhitespace() throws { let templateString = " | {{#boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = " | \n | \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Sections should not alter internal whitespace.") } func testIndentedInlineSections() throws { let templateString = " {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = " YES\n GOOD\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Single-line sections should not alter surrounding whitespace.") } func testStandaloneLines() throws { let templateString = "| This Is\n{{#boolean}}\n|\n{{/boolean}}\n| A Line\n" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "| This Is\n|\n| A Line\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone lines should be removed from the template.") } func testIndentedStandaloneLines() throws { let templateString = "| This Is\n {{#boolean}}\n|\n {{/boolean}}\n| A Line\n" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "| This Is\n|\n| A Line\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Indented standalone lines should be removed from the template.") } func testStandaloneLineEndings() throws { let templateString = "|\r\n{{#boolean}}\r\n{{/boolean}}\r\n|" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "|\r\n|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "\"\r\n\" should be considered a newline for standalone tags.") } func testStandaloneWithoutPreviousLine() throws { let templateString = " {{#boolean}}\n#{{/boolean}}\n/" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "#\n/" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to precede them.") } func testStandaloneWithoutNewline() throws { let templateString = "#{{#boolean}}\n/\n {{/boolean}}" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "#\n/\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to follow them.") } func testPadding() throws { let templateString = "|{{# boolean }}={{/ boolean }}|" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "|=|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } } /** Interpolation tags are used to integrate dynamic content into the template. The tag's content MUST be a non-whitespace character sequence NOT containing the current closing delimiter. This tag's content names the data to replace the tag. A single period (`.`) indicates that the item currently sitting atop the context stack should be used; otherwise, name resolution is as follows: 1) Split the name on periods; the first part is the name to resolve, any remaining parts should be retained. 2) Walk the context stack from top to bottom, finding the first context that is a) a hash containing the name as a key OR b) an object responding to a method with the given name. 3) If the context is a hash, the data is the value associated with the name. 4) If the context is an object, the data is the value returned by the method with the given name. 5) If any name parts were retained in step 1, each should be resolved against a context stack containing only the result from the former resolution. If any part fails resolution, the result should be considered falsey, and should interpolate as the empty string. Data should be coerced into a string (and escaped, if appropriate) before interpolation. The Interpolation tags MUST NOT be treated as standalone. */ final class InterpolationTests: XCTestCase { static var allTests: [(String, (InterpolationTests) -> () throws -> Void)] { return [ ("testNoInterpolation", testNoInterpolation), ("testBasicInterpolation", testBasicInterpolation), ("testHTMLEscaping", testHTMLEscaping), ("testTripleMustache", testTripleMustache), ("testAmpersand", testAmpersand), ("testBasicIntegerInterpolation", testBasicIntegerInterpolation), ("testTripleMustacheIntegerInterpolation", testTripleMustacheIntegerInterpolation), ("testAmpersandIntegerInterpolation", testAmpersandIntegerInterpolation), ("testBasicDecimalInterpolation", testBasicDecimalInterpolation), ("testTripleMustacheDecimalInterpolation", testTripleMustacheDecimalInterpolation), ("testAmpersandDecimalInterpolation", testAmpersandDecimalInterpolation), ("testBasicNullInterpolation", testBasicNullInterpolation), ("testTripleMustacheNullInterpolation", testTripleMustacheNullInterpolation), ("testAmpersandNullInterpolation", testAmpersandNullInterpolation), ("testBasicContextMissInterpolation", testBasicContextMissInterpolation), ("testTripleMustacheContextMissInterpolation", testTripleMustacheContextMissInterpolation), ("testAmpersandContextMissInterpolation", testAmpersandContextMissInterpolation), ("testDottedNames_BasicInterpolation", testDottedNames_BasicInterpolation), ("testDottedNames_TripleMustacheInterpolation", testDottedNames_TripleMustacheInterpolation), ("testDottedNames_AmpersandInterpolation", testDottedNames_AmpersandInterpolation), ("testDottedNames_ArbitraryDepth", testDottedNames_ArbitraryDepth), ("testDottedNames_BrokenChains", testDottedNames_BrokenChains), ("testDottedNames_BrokenChainResolution", testDottedNames_BrokenChainResolution), ("testDottedNames_InitialResolution", testDottedNames_InitialResolution), ("testDottedNames_ContextPrecedence", testDottedNames_ContextPrecedence), ("testImplicitIterators_BasicInterpolation", testImplicitIterators_BasicInterpolation), ("testImplicitIterators_HTMLEscaping", testImplicitIterators_HTMLEscaping), ("testImplicitIterators_TripleMustache", testImplicitIterators_TripleMustache), ("testImplicitIterators_Ampersand", testImplicitIterators_Ampersand), ("testImplicitIterators_BasicIntegerInterpolation", testImplicitIterators_BasicIntegerInterpolation), ("testInterpolation_SurroundingWhitespace", testInterpolation_SurroundingWhitespace), ("testTripleMustache_SurroundingWhitespace", testTripleMustache_SurroundingWhitespace), ("testAmpersand_SurroundingWhitespace", testAmpersand_SurroundingWhitespace), ("testInterpolation_Standalone", testInterpolation_Standalone), ("testTripleMustache_Standalone", testTripleMustache_Standalone), ("testAmpersand_Standalone", testAmpersand_Standalone), ("testInterpolationWithPadding", testInterpolationWithPadding), ("testTripleMustacheWithPadding", testTripleMustacheWithPadding), ("testAmpersandWithPadding", testAmpersandWithPadding), ] } func testNoInterpolation() throws { let templateString = "Hello from {Mustache}!\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Hello from {Mustache}!\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Mustache-free templates should render as-is.") } func testBasicInterpolation() throws { let templateString = "Hello, {{subject}}!\n" let contextJSON = "{\"subject\":\"world\"}".data(using: .utf8)! let expected = "Hello, world!\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Unadorned tags should interpolate content into the template.") } func testHTMLEscaping() throws { let templateString = "These characters should be HTML escaped: {{forbidden}}\n" let contextJSON = "{\"forbidden\":\"& \\\" < >\"}".data(using: .utf8)! let expected = "These characters should be HTML escaped: &amp; &quot; &lt; &gt;\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Basic interpolation should be HTML escaped.") } func testTripleMustache() throws { let templateString = "These characters should not be HTML escaped: {{{forbidden}}}\n" let contextJSON = "{\"forbidden\":\"& \\\" < >\"}".data(using: .utf8)! let expected = "These characters should not be HTML escaped: & \" < >\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Triple mustaches should interpolate without HTML escaping.") } func testAmpersand() throws { let templateString = "These characters should not be HTML escaped: {{&forbidden}}\n" let contextJSON = "{\"forbidden\":\"& \\\" < >\"}".data(using: .utf8)! let expected = "These characters should not be HTML escaped: & \" < >\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Ampersand should interpolate without HTML escaping.") } func testBasicIntegerInterpolation() throws { let templateString = "\"{{mph}} miles an hour!\"" let contextJSON = "{\"mph\":85}".data(using: .utf8)! let expected = "\"85 miles an hour!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Integers should interpolate seamlessly.") } func testTripleMustacheIntegerInterpolation() throws { let templateString = "\"{{{mph}}} miles an hour!\"" let contextJSON = "{\"mph\":85}".data(using: .utf8)! let expected = "\"85 miles an hour!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Integers should interpolate seamlessly.") } func testAmpersandIntegerInterpolation() throws { let templateString = "\"{{&mph}} miles an hour!\"" let contextJSON = "{\"mph\":85}".data(using: .utf8)! let expected = "\"85 miles an hour!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Integers should interpolate seamlessly.") } func testBasicDecimalInterpolation() throws { let templateString = "\"{{power}} jiggawatts!\"" let contextJSON = "{\"power\":1.21}".data(using: .utf8)! let expected = "\"1.21 jiggawatts!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Decimals should interpolate seamlessly with proper significance.") } func testTripleMustacheDecimalInterpolation() throws { let templateString = "\"{{{power}}} jiggawatts!\"" let contextJSON = "{\"power\":1.21}".data(using: .utf8)! let expected = "\"1.21 jiggawatts!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Decimals should interpolate seamlessly with proper significance.") } func testAmpersandDecimalInterpolation() throws { let templateString = "\"{{&power}} jiggawatts!\"" let contextJSON = "{\"power\":1.21}".data(using: .utf8)! let expected = "\"1.21 jiggawatts!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Decimals should interpolate seamlessly with proper significance.") } func testBasicNullInterpolation() throws { let templateString = "I ({{cannot}}) be seen!" let contextJSON = "{\"cannot\":null}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nulls should interpolate as the empty string.") } func testTripleMustacheNullInterpolation() throws { let templateString = "I ({{{cannot}}}) be seen!" let contextJSON = "{\"cannot\":null}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nulls should interpolate as the empty string.") } func testAmpersandNullInterpolation() throws { let templateString = "I ({{&cannot}}) be seen!" let contextJSON = "{\"cannot\":null}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nulls should interpolate as the empty string.") } func testBasicContextMissInterpolation() throws { let templateString = "I ({{cannot}}) be seen!" let contextJSON = "{}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Failed context lookups should default to empty strings.") } func testTripleMustacheContextMissInterpolation() throws { let templateString = "I ({{{cannot}}}) be seen!" let contextJSON = "{}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Failed context lookups should default to empty strings.") } func testAmpersandContextMissInterpolation() throws { let templateString = "I ({{&cannot}}) be seen!" let contextJSON = "{}".data(using: .utf8)! let expected = "I () be seen!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Failed context lookups should default to empty strings.") } func testDottedNames_BasicInterpolation() throws { let templateString = "\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\"" let contextJSON = "{\"person\":{\"name\":\"Joe\"}}".data(using: .utf8)! let expected = "\"Joe\" == \"Joe\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be considered a form of shorthand for sections.") } func testDottedNames_TripleMustacheInterpolation() throws { let templateString = "\"{{{person.name}}}\" == \"{{#person}}{{{name}}}{{/person}}\"" let contextJSON = "{\"person\":{\"name\":\"Joe\"}}".data(using: .utf8)! let expected = "\"Joe\" == \"Joe\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be considered a form of shorthand for sections.") } func testDottedNames_AmpersandInterpolation() throws { let templateString = "\"{{&person.name}}\" == \"{{#person}}{{&name}}{{/person}}\"" let contextJSON = "{\"person\":{\"name\":\"Joe\"}}".data(using: .utf8)! let expected = "\"Joe\" == \"Joe\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be considered a form of shorthand for sections.") } func testDottedNames_ArbitraryDepth() throws { let templateString = "\"{{a.b.c.d.e.name}}\" == \"Phil\"" let contextJSON = "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":{\"name\":\"Phil\"}}}}}}".data(using: .utf8)! let expected = "\"Phil\" == \"Phil\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be functional to any level of nesting.") } func testDottedNames_BrokenChains() throws { let templateString = "\"{{a.b.c}}\" == \"\"" let contextJSON = "{\"a\":{}}".data(using: .utf8)! let expected = "\"\" == \"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Any falsey value prior to the last part of the name should yield ''.") } func testDottedNames_BrokenChainResolution() throws { let templateString = "\"{{a.b.c.name}}\" == \"\"" let contextJSON = "{\"a\":{\"b\":{}},\"c\":{\"name\":\"Jim\"}}".data(using: .utf8)! let expected = "\"\" == \"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Each part of a dotted name should resolve only against its parent.") } func testDottedNames_InitialResolution() throws { let templateString = "\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\"" let contextJSON = "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":{\"name\":\"Phil\"}}}}},\"b\":{\"c\":{\"d\":{\"e\":{\"name\":\"Wrong\"}}}}}".data(using: .utf8)! let expected = "\"Phil\" == \"Phil\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "The first part of a dotted name should resolve as any other name.") } func testDottedNames_ContextPrecedence() throws { let templateString = "{{#a}}{{b.c}}{{/a}}" let contextJSON = "{\"b\":{\"c\":\"ERROR\"},\"a\":{\"b\":{}}}".data(using: .utf8)! let expected = "" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be resolved against former resolutions.") } func testImplicitIterators_BasicInterpolation() throws { let templateString = "Hello, {{.}}!\n" let contextJSON = "\"world\"".data(using: .utf8)! let expected = "Hello, world!\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Unadorned tags should interpolate content into the template.") } func testImplicitIterators_HTMLEscaping() throws { let templateString = "These characters should be HTML escaped: {{.}}\n" let contextJSON = "\"& \\\" < >\"".data(using: .utf8)! let expected = "These characters should be HTML escaped: &amp; &quot; &lt; &gt;\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Basic interpolation should be HTML escaped.") } func testImplicitIterators_TripleMustache() throws { let templateString = "These characters should not be HTML escaped: {{{.}}}\n" let contextJSON = "\"& \\\" < >\"".data(using: .utf8)! let expected = "These characters should not be HTML escaped: & \" < >\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Triple mustaches should interpolate without HTML escaping.") } func testImplicitIterators_Ampersand() throws { let templateString = "These characters should not be HTML escaped: {{&.}}\n" let contextJSON = "\"& \\\" < >\"".data(using: .utf8)! let expected = "These characters should not be HTML escaped: & \" < >\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Ampersand should interpolate without HTML escaping.") } func testImplicitIterators_BasicIntegerInterpolation() throws { let templateString = "\"{{.}} miles an hour!\"" let contextJSON = "85".data(using: .utf8)! let expected = "\"85 miles an hour!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Integers should interpolate seamlessly.") } func testInterpolation_SurroundingWhitespace() throws { let templateString = "| {{string}} |" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "| --- |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Interpolation should not alter surrounding whitespace.") } func testTripleMustache_SurroundingWhitespace() throws { let templateString = "| {{{string}}} |" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "| --- |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Interpolation should not alter surrounding whitespace.") } func testAmpersand_SurroundingWhitespace() throws { let templateString = "| {{&string}} |" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "| --- |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Interpolation should not alter surrounding whitespace.") } func testInterpolation_Standalone() throws { let templateString = " {{string}}\n" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = " ---\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone interpolation should not alter surrounding whitespace.") } func testTripleMustache_Standalone() throws { let templateString = " {{{string}}}\n" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = " ---\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone interpolation should not alter surrounding whitespace.") } func testAmpersand_Standalone() throws { let templateString = " {{&string}}\n" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = " ---\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone interpolation should not alter surrounding whitespace.") } func testInterpolationWithPadding() throws { let templateString = "|{{ string }}|" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "|---|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } func testTripleMustacheWithPadding() throws { let templateString = "|{{{ string }}}|" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "|---|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } func testAmpersandWithPadding() throws { let templateString = "|{{& string }}|" let contextJSON = "{\"string\":\"---\"}".data(using: .utf8)! let expected = "|---|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } } /** Inverted Section tags and End Section tags are used in combination to wrap a section of the template. These tags' content MUST be a non-whitespace character sequence NOT containing the current closing delimiter; each Inverted Section tag MUST be followed by an End Section tag with the same content within the same section. This tag's content names the data to replace the tag. Name resolution is as follows: 1) Split the name on periods; the first part is the name to resolve, any remaining parts should be retained. 2) Walk the context stack from top to bottom, finding the first context that is a) a hash containing the name as a key OR b) an object responding to a method with the given name. 3) If the context is a hash, the data is the value associated with the name. 4) If the context is an object and the method with the given name has an arity of 1, the method SHOULD be called with a String containing the unprocessed contents of the sections; the data is the value returned. 5) Otherwise, the data is the value returned by calling the method with the given name. 6) If any name parts were retained in step 1, each should be resolved against a context stack containing only the result from the former resolution. If any part fails resolution, the result should be considered falsey, and should interpolate as the empty string. If the data is not of a list type, it is coerced into a list as follows: if the data is truthy (e.g. `!!data == true`), use a single-element list containing the data, otherwise use an empty list. This section MUST NOT be rendered unless the data list is empty. Inverted Section and End Section tags SHOULD be treated as standalone when appropriate. */ final class InvertedTests: XCTestCase { static var allTests: [(String, (InvertedTests) -> () throws -> Void)] { return [ ("testFalsey", testFalsey), ("testTruthy", testTruthy), ("testNullisfalsey", testNullisfalsey), ("testContext", testContext), ("testList", testList), ("testEmptyList", testEmptyList), ("testDoubled", testDoubled), ("testNested_Falsey", testNested_Falsey), ("testNested_Truthy", testNested_Truthy), ("testContextMisses", testContextMisses), ("testDottedNames_Truthy", testDottedNames_Truthy), ("testDottedNames_Falsey", testDottedNames_Falsey), ("testDottedNames_BrokenChains", testDottedNames_BrokenChains), ("testSurroundingWhitespace", testSurroundingWhitespace), ("testInternalWhitespace", testInternalWhitespace), ("testIndentedInlineSections", testIndentedInlineSections), ("testStandaloneLines", testStandaloneLines), ("testStandaloneIndentedLines", testStandaloneIndentedLines), ("testStandaloneLineEndings", testStandaloneLineEndings), ("testStandaloneWithoutPreviousLine", testStandaloneWithoutPreviousLine), ("testStandaloneWithoutNewline", testStandaloneWithoutNewline), ("testPadding", testPadding), ] } func testFalsey() throws { let templateString = "\"{{^boolean}}This should be rendered.{{/boolean}}\"" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "\"This should be rendered.\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Falsey sections should have their contents rendered.") } func testTruthy() throws { let templateString = "\"{{^boolean}}This should not be rendered.{{/boolean}}\"" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Truthy sections should have their contents omitted.") } func testNullisfalsey() throws { let templateString = "\"{{^null}}This should be rendered.{{/null}}\"" let contextJSON = "{\"null\":null}".data(using: .utf8)! let expected = "\"This should be rendered.\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Null is falsey.") } func testContext() throws { let templateString = "\"{{^context}}Hi {{name}}.{{/context}}\"" let contextJSON = "{\"context\":{\"name\":\"Joe\"}}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Objects and hashes should behave like truthy values.") } func testList() throws { let templateString = "\"{{^list}}{{n}}{{/list}}\"" let contextJSON = "{\"list\":[{\"n\":1},{\"n\":2},{\"n\":3}]}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Lists should behave like truthy values.") } func testEmptyList() throws { let templateString = "\"{{^list}}Yay lists!{{/list}}\"" let contextJSON = "{\"list\":[]}".data(using: .utf8)! let expected = "\"Yay lists!\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Empty lists should behave like falsey values.") } func testDoubled() throws { let templateString = "{{^bool}}\n* first\n{{/bool}}\n* {{two}}\n{{^bool}}\n* third\n{{/bool}}\n" let contextJSON = "{\"two\":\"second\",\"bool\":false}".data(using: .utf8)! let expected = "* first\n* second\n* third\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Multiple inverted sections per template should be permitted.") } func testNested_Falsey() throws { let templateString = "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |" let contextJSON = "{\"bool\":false}".data(using: .utf8)! let expected = "| A B C D E |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nested falsey sections should have their contents rendered.") } func testNested_Truthy() throws { let templateString = "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |" let contextJSON = "{\"bool\":true}".data(using: .utf8)! let expected = "| A E |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Nested truthy sections should be omitted.") } func testContextMisses() throws { let templateString = "[{{^missing}}Cannot find key 'missing'!{{/missing}}]" let contextJSON = "{}".data(using: .utf8)! let expected = "[Cannot find key 'missing'!]" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Failed context lookups should be considered falsey.") } func testDottedNames_Truthy() throws { let templateString = "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"\"" let contextJSON = "{\"a\":{\"b\":{\"c\":true}}}".data(using: .utf8)! let expected = "\"\" == \"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be valid for Inverted Section tags.") } func testDottedNames_Falsey() throws { let templateString = "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"" let contextJSON = "{\"a\":{\"b\":{\"c\":false}}}".data(using: .utf8)! let expected = "\"Not Here\" == \"Not Here\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names should be valid for Inverted Section tags.") } func testDottedNames_BrokenChains() throws { let templateString = "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"" let contextJSON = "{\"a\":{}}".data(using: .utf8)! let expected = "\"Not Here\" == \"Not Here\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Dotted names that cannot be resolved should be considered falsey.") } func testSurroundingWhitespace() throws { let templateString = " | {{^boolean}}\t|\t{{/boolean}} | \n" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = " | \t|\t | \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Inverted sections should not alter surrounding whitespace.") } func testInternalWhitespace() throws { let templateString = " | {{^boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = " | \n | \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Inverted should not alter internal whitespace.") } func testIndentedInlineSections() throws { let templateString = " {{^boolean}}NO{{/boolean}}\n {{^boolean}}WAY{{/boolean}}\n" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = " NO\n WAY\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Single-line sections should not alter surrounding whitespace.") } func testStandaloneLines() throws { let templateString = "| This Is\n{{^boolean}}\n|\n{{/boolean}}\n| A Line\n" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "| This Is\n|\n| A Line\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone lines should be removed from the template.") } func testStandaloneIndentedLines() throws { let templateString = "| This Is\n {{^boolean}}\n|\n {{/boolean}}\n| A Line\n" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "| This Is\n|\n| A Line\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone indented lines should be removed from the template.") } func testStandaloneLineEndings() throws { let templateString = "|\r\n{{^boolean}}\r\n{{/boolean}}\r\n|" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "|\r\n|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "\"\r\n\" should be considered a newline for standalone tags.") } func testStandaloneWithoutPreviousLine() throws { let templateString = " {{^boolean}}\n^{{/boolean}}\n/" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "^\n/" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to precede them.") } func testStandaloneWithoutNewline() throws { let templateString = "^{{^boolean}}\n/\n {{/boolean}}" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "^\n/\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to follow them.") } func testPadding() throws { let templateString = "|{{^ boolean }}={{/ boolean }}|" let contextJSON = "{\"boolean\":false}".data(using: .utf8)! let expected = "|=|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } } /** Comment tags represent content that should never appear in the resulting output. The tag's content may contain any substring (including newlines) EXCEPT the closing delimiter. Comment tags SHOULD be treated as standalone when appropriate. */ final class CommentsTests: XCTestCase { static var allTests: [(String, (CommentsTests) -> () throws -> Void)] { return [ ("testInline", testInline), ("testMultiline", testMultiline), ("testStandalone", testStandalone), ("testIndentedStandalone", testIndentedStandalone), ("testStandaloneLineEndings", testStandaloneLineEndings), ("testStandaloneWithoutPreviousLine", testStandaloneWithoutPreviousLine), ("testStandaloneWithoutNewline", testStandaloneWithoutNewline), ("testMultilineStandalone", testMultilineStandalone), ("testIndentedMultilineStandalone", testIndentedMultilineStandalone), ("testIndentedInline", testIndentedInline), ("testSurroundingWhitespace", testSurroundingWhitespace), ] } func testInline() throws { let templateString = "12345{{! Comment Block! }}67890" let contextJSON = "{}".data(using: .utf8)! let expected = "1234567890" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Comment blocks should be removed from the template.") } func testMultiline() throws { let templateString = "12345{{!\n This is a\n multi-line comment...\n}}67890\n" let contextJSON = "{}".data(using: .utf8)! let expected = "1234567890\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Multiline comments should be permitted.") } func testStandalone() throws { let templateString = "Begin.\n{{! Comment Block! }}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All standalone comment lines should be removed.") } func testIndentedStandalone() throws { let templateString = "Begin.\n {{! Indented Comment Block! }}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All standalone comment lines should be removed.") } func testStandaloneLineEndings() throws { let templateString = "|\r\n{{! Standalone Comment }}\r\n|" let contextJSON = "{}".data(using: .utf8)! let expected = "|\r\n|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "\"\r\n\" should be considered a newline for standalone tags.") } func testStandaloneWithoutPreviousLine() throws { let templateString = " {{! I'm Still Standalone }}\n!" let contextJSON = "{}".data(using: .utf8)! let expected = "!" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to precede them.") } func testStandaloneWithoutNewline() throws { let templateString = "!\n {{! I'm Still Standalone }}" let contextJSON = "{}".data(using: .utf8)! let expected = "!\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to follow them.") } func testMultilineStandalone() throws { let templateString = "Begin.\n{{!\nSomething's going on here...\n}}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All standalone comment lines should be removed.") } func testIndentedMultilineStandalone() throws { let templateString = "Begin.\n {{!\n Something's going on here...\n }}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "All standalone comment lines should be removed.") } func testIndentedInline() throws { let templateString = " 12 {{! 34 }}\n" let contextJSON = "{}".data(using: .utf8)! let expected = " 12 \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Inline comments should not strip whitespace") } func testSurroundingWhitespace() throws { let templateString = "12345 {{! Comment Block! }} 67890" let contextJSON = "{}".data(using: .utf8)! let expected = "12345 67890" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Comment removal should preserve surrounding whitespace.") } } /** Partial tags are used to expand an external template into the current template. The tag's content MUST be a non-whitespace character sequence NOT containing the current closing delimiter. This tag's content names the partial to inject. Set Delimiter tags MUST NOT affect the parsing of a partial. The partial MUST be rendered against the context stack local to the tag. If the named partial cannot be found, the empty string SHOULD be used instead, as in interpolations. Partial tags SHOULD be treated as standalone when appropriate. If this tag is used standalone, any whitespace preceding the tag should treated as indentation, and prepended to each line of the partial before rendering. */ final class PartialsTests: XCTestCase { static var allTests: [(String, (PartialsTests) -> () throws -> Void)] { return [ ("testBasicBehavior", testBasicBehavior), ("testFailedLookup", testFailedLookup), ("testContext", testContext), ("testRecursion", testRecursion), ("testSurroundingWhitespace", testSurroundingWhitespace), ("testInlineIndentation", testInlineIndentation), ("testStandaloneLineEndings", testStandaloneLineEndings), ("testStandaloneWithoutPreviousLine", testStandaloneWithoutPreviousLine), ("testStandaloneWithoutNewline", testStandaloneWithoutNewline), ("testStandaloneIndentation", testStandaloneIndentation), ("testPaddingWhitespace", testPaddingWhitespace), ] } func testBasicBehavior() throws { let templateString = "\"{{>text}}\"" let contextJSON = "{}".data(using: .utf8)! let expected = "\"from partial\"" let partials = try [ "text": Template("from partial"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "The greater-than operator should expand to the named partial.") } func testFailedLookup() throws { let templateString = "\"{{>text}}\"" let contextJSON = "{}".data(using: .utf8)! let expected = "\"\"" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "The empty string should be used when the named partial is not found.") } func testContext() throws { let templateString = "\"{{>partial}}\"" let contextJSON = "{\"text\":\"content\"}".data(using: .utf8)! let expected = "\"*content*\"" let partials = try [ "partial": Template("*{{text}}*"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "The greater-than operator should operate within the current context.") } func testRecursion() throws { let templateString = "{{>node}}" let contextJSON = "{\"content\":\"X\",\"nodes\":[{\"content\":\"Y\",\"nodes\":[]}]}".data(using: .utf8)! let expected = "X<Y<>>" let partials = try [ "node": Template("{{content}}<{{#nodes}}{{>node}}{{/nodes}}>"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "The greater-than operator should properly recurse.") } func testSurroundingWhitespace() throws { let templateString = "| {{>partial}} |" let contextJSON = "{}".data(using: .utf8)! let expected = "| \t|\t |" let partials = try [ "partial": Template("\t|\t"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "The greater-than operator should not alter surrounding whitespace.") } func testInlineIndentation() throws { let templateString = " {{data}} {{> partial}}\n" let contextJSON = "{\"data\":\"|\"}".data(using: .utf8)! let expected = " | >\n>\n" let partials = try [ "partial": Template(">\n>"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Whitespace should be left untouched.") } func testStandaloneLineEndings() throws { let templateString = "|\r\n{{>partial}}\r\n|" let contextJSON = "{}".data(using: .utf8)! let expected = "|\r\n>|" let partials = try [ "partial": Template(">"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "\"\r\n\" should be considered a newline for standalone tags.") } func testStandaloneWithoutPreviousLine() throws { let templateString = " {{>partial}}\n>" let contextJSON = "{}".data(using: .utf8)! let expected = " >\n >>" let partials = try [ "partial": Template(">\n>"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to precede them.") } func testStandaloneWithoutNewline() throws { let templateString = ">\n {{>partial}}" let contextJSON = "{}".data(using: .utf8)! let expected = ">\n >\n >" let partials = try [ "partial": Template(">\n>"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to follow them.") } func testStandaloneIndentation() throws { let templateString = "\\n {{>partial}}\n/\n" let contextJSON = "{\"content\":\"<\n->\"}".data(using: .utf8)! let expected = "\\n |\n <\n->\n |\n/\n" let partials = try [ "partial": Template("|\n{{{content}}}\n|\n"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Each line of the partial should be indented before rendering.") } func testPaddingWhitespace() throws { let templateString = "|{{> partial }}|" let contextJSON = "{\"boolean\":true}".data(using: .utf8)! let expected = "|[]|" let partials = try [ "partial": Template("[]"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } } /** Set Delimiter tags are used to change the tag delimiters for all content following the tag in the current compilation unit. The tag's content MUST be any two non-whitespace sequences (separated by whitespace) EXCEPT an equals sign ('=') followed by the current closing delimiter. Set Delimiter tags SHOULD be treated as standalone when appropriate. */ final class DelimitersTests: XCTestCase { static var allTests: [(String, (DelimitersTests) -> () throws -> Void)] { return [ ("testPairBehavior", testPairBehavior), ("testSpecialCharacters", testSpecialCharacters), ("testSections", testSections), ("testInvertedSections", testInvertedSections), ("testPartialInheritence", testPartialInheritence), ("testPost_PartialBehavior", testPost_PartialBehavior), ("testSurroundingWhitespace", testSurroundingWhitespace), ("testOutlyingWhitespace_Inline", testOutlyingWhitespace_Inline), ("testStandaloneTag", testStandaloneTag), ("testIndentedStandaloneTag", testIndentedStandaloneTag), ("testStandaloneLineEndings", testStandaloneLineEndings), ("testStandaloneWithoutPreviousLine", testStandaloneWithoutPreviousLine), ("testStandaloneWithoutNewline", testStandaloneWithoutNewline), ("testPairwithPadding", testPairwithPadding), ] } func testPairBehavior() throws { let templateString = "{{=<% %>=}}(<%text%>)" let contextJSON = "{\"text\":\"Hey!\"}".data(using: .utf8)! let expected = "(Hey!)" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "The equals sign (used on both sides) should permit delimiter changes.") } func testSpecialCharacters() throws { let templateString = "({{=[ ]=}}[text])" let contextJSON = "{\"text\":\"It worked!\"}".data(using: .utf8)! let expected = "(It worked!)" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Characters with special meaning regexen should be valid delimiters.") } func testSections() throws { let templateString = "[\n{{#section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|#section|\n {{data}}\n |data|\n|/section|\n]\n" let contextJSON = "{\"section\":true,\"data\":\"I got interpolated.\"}".data(using: .utf8)! let expected = "[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Delimiters set outside sections should persist.") } func testInvertedSections() throws { let templateString = "[\n{{^section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|^section|\n {{data}}\n |data|\n|/section|\n]\n" let contextJSON = "{\"section\":false,\"data\":\"I got interpolated.\"}".data(using: .utf8)! let expected = "[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Delimiters set outside inverted sections should persist.") } func testPartialInheritence() throws { let templateString = "[ {{>include}} ]\n{{= | | =}}\n[ |>include| ]\n" let contextJSON = "{\"value\":\"yes\"}".data(using: .utf8)! let expected = "[ .yes. ]\n[ .yes. ]\n" let partials = try [ "include": Template(".{{value}}."), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Delimiters set in a parent template should not affect a partial.") } func testPost_PartialBehavior() throws { let templateString = "[ {{>include}} ]\n[ .{{value}}. .|value|. ]\n" let contextJSON = "{\"value\":\"yes\"}".data(using: .utf8)! let expected = "[ .yes. .yes. ]\n[ .yes. .|value|. ]\n" let partials = try [ "include": Template(".{{value}}. {{= | | =}} .|value|."), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Delimiters set in a partial should not affect the parent template.") } func testSurroundingWhitespace() throws { let templateString = "| {{=@ @=}} |" let contextJSON = "{}".data(using: .utf8)! let expected = "| |" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Surrounding whitespace should be left untouched.") } func testOutlyingWhitespace_Inline() throws { let templateString = " | {{=@ @=}}\n" let contextJSON = "{}".data(using: .utf8)! let expected = " | \n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Whitespace should be left untouched.") } func testStandaloneTag() throws { let templateString = "Begin.\n{{=@ @=}}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone lines should be removed from the template.") } func testIndentedStandaloneTag() throws { let templateString = "Begin.\n {{=@ @=}}\nEnd.\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Begin.\nEnd.\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Indented standalone lines should be removed from the template.") } func testStandaloneLineEndings() throws { let templateString = "|\r\n{{= @ @ =}}\r\n|" let contextJSON = "{}".data(using: .utf8)! let expected = "|\r\n|" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "\"\r\n\" should be considered a newline for standalone tags.") } func testStandaloneWithoutPreviousLine() throws { let templateString = " {{=@ @=}}\n=" let contextJSON = "{}".data(using: .utf8)! let expected = "=" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to precede them.") } func testStandaloneWithoutNewline() throws { let templateString = "=\n {{=@ @=}}" let contextJSON = "{}".data(using: .utf8)! let expected = "=\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Standalone tags should not require a newline to follow them.") } func testPairwithPadding() throws { let templateString = "|{{= @ @ =}}|" let contextJSON = "{}".data(using: .utf8)! let expected = "||" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Superfluous in-tag whitespace should be ignored.") } } /** Like partials, Parent tags are used to expand an external template into the current template. Unlike partials, Parent tags may contain optional arguments delimited by Block tags. For this reason, Parent tags may also be referred to as Parametric Partials. The Parent tags' content MUST be a non-whitespace character sequence NOT containing the current closing delimiter; each Parent tag MUST be followed by an End Section tag with the same content within the matching Parent tag. This tag's content names the Parent template to inject. Set Delimiter tags Preceding a Parent tag MUST NOT affect the parsing of the injected external template. The Parent MUST be rendered against the context stack local to the tag. If the named Parent cannot be found, the empty string SHOULD be used instead, as in interpolations. Parent tags SHOULD be treated as standalone when appropriate. If this tag is used standalone, any whitespace preceding the tag should be treated as indentation, and prepended to each line of the Parent before rendering. The Block tags' content MUST be a non-whitespace character sequence NOT containing the current closing delimiter. Each Block tag MUST be followed by an End Section tag with the same content within the matching Block tag. This tag's content determines the parameter or argument name. Block tags may appear both inside and outside of Parent tags. In both cases, they specify a position within the template that can be overridden; it is a parameter of the containing template. The template text between the Block tag and its matching End Section tag defines the default content to render when the parameter is not overridden from outside. In addition, when used inside of a Parent tag, the template text between a Block tag and its matching End Section tag defines content that replaces the default defined in the Parent template. This content is the argument passed to the Parent template. The practice of injecting an external template using a Parent tag is referred to as inheritance. If the Parent tag includes a Block tag that overrides a parameter of the Parent template, this may also be referred to as substitution. Parent templates are taken from the same namespace as regular Partial templates and in fact, injecting a regular Partial is exactly equivalent to injecting a Parent without making any substitutions. Parameter and arguments names live in a namespace that is distinct from both Partials and the context. */ final class InheritanceTests: XCTestCase { static var allTests: [(String, (InheritanceTests) -> () throws -> Void)] { return [ ("testDefault", testDefault), ("testVariable", testVariable), ("testTripleMustache", testTripleMustache), ("testSections", testSections), ("testNegativeSections", testNegativeSections), ("testMustacheInjection", testMustacheInjection), ("testInherit", testInherit), ("testOverriddencontent", testOverriddencontent), ("testDatadoesnotoverrideblock", testDatadoesnotoverrideblock), ("testDatadoesnotoverrideblockdefault", testDatadoesnotoverrideblockdefault), ("testOverriddenparent", testOverriddenparent), ("testTwooverriddenparents", testTwooverriddenparents), ("testOverrideparentwithnewlines", testOverrideparentwithnewlines), ("testInheritindentation", testInheritindentation), ("testOnlyoneoverride", testOnlyoneoverride), ("testParenttemplate", testParenttemplate), ("testRecursion", testRecursion), ("testMulti_levelinheritance", testMulti_levelinheritance), ("testMulti_levelinheritance_nosubchild", testMulti_levelinheritance_nosubchild), ("testTextinsideparent", testTextinsideparent), ("testTextinsideparent2", testTextinsideparent2), ] } func testDefault() throws { let templateString = "{{$title}}Default title{{/title}}\n" let contextJSON = "{}".data(using: .utf8)! let expected = "Default title\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Default content should be rendered if the block isn't overridden") } func testVariable() throws { let templateString = "{{$foo}}default {{bar}} content{{/foo}}\n" let contextJSON = "{\"bar\":\"baz\"}".data(using: .utf8)! let expected = "default baz content\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Default content renders variables") } func testTripleMustache() throws { let templateString = "{{$foo}}default {{{bar}}} content{{/foo}}\n" let contextJSON = "{\"bar\":\"<baz>\"}".data(using: .utf8)! let expected = "default <baz> content\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Default content renders triple mustache variables") } func testSections() throws { let templateString = "{{$foo}}default {{#bar}}{{baz}}{{/bar}} content{{/foo}}\n" let contextJSON = "{\"bar\":{\"baz\":\"qux\"}}".data(using: .utf8)! let expected = "default qux content\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Default content renders sections") } func testNegativeSections() throws { let templateString = "{{$foo}}default {{^bar}}{{baz}}{{/bar}} content{{/foo}}\n" let contextJSON = "{\"baz\":\"three\"}".data(using: .utf8)! let expected = "default three content\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Default content renders negative sections") } func testMustacheInjection() throws { let templateString = "{{$foo}}default {{#bar}}{{baz}}{{/bar}} content{{/foo}}\n" let contextJSON = "{\"bar\":{\"baz\":\"{{qux}}\"}}".data(using: .utf8)! let expected = "default {{qux}} content\n" let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context) XCTAssertEqual(rendered, expected, "Mustache injection in default content") } func testInherit() throws { let templateString = "{{<include}}{{/include}}\n" let contextJSON = "{}".data(using: .utf8)! let expected = "default content" let partials = try [ "include": Template("{{$foo}}default content{{/foo}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Default content rendered inside inherited templates") } func testOverriddencontent() throws { let templateString = "{{<super}}{{$title}}sub template title{{/title}}{{/super}}" let contextJSON = "{}".data(using: .utf8)! let expected = "...sub template title..." let partials = try [ "super": Template("...{{$title}}Default title{{/title}}..."), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Overridden content") } func testDatadoesnotoverrideblock() throws { let templateString = "{{<include}}{{$var}}var in template{{/var}}{{/include}}" let contextJSON = "{\"var\":\"var in data\"}".data(using: .utf8)! let expected = "var in template" let partials = try [ "include": Template("{{$var}}var in include{{/var}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Context does not override argument passed into parent") } func testDatadoesnotoverrideblockdefault() throws { let templateString = "{{<include}}{{/include}}" let contextJSON = "{\"var\":\"var in data\"}".data(using: .utf8)! let expected = "var in include" let partials = try [ "include": Template("{{$var}}var in include{{/var}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Context does not override default content of block") } func testOverriddenparent() throws { let templateString = "test {{<parent}}{{$stuff}}override{{/stuff}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "test override" let partials = try [ "parent": Template("{{$stuff}}...{{/stuff}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Overridden parent") } func testTwooverriddenparents() throws { let templateString = "test {{<parent}}{{$stuff}}override1{{/stuff}}{{/parent}} {{<parent}}{{$stuff}}override2{{/stuff}}{{/parent}}\n" let contextJSON = "{}".data(using: .utf8)! let expected = "test |override1 default| |override2 default|\n" let partials = try [ "parent": Template("|{{$stuff}}...{{/stuff}}{{$default}} default{{/default}}|"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Two overridden parents with different content") } func testOverrideparentwithnewlines() throws { let templateString = "{{<parent}}{{$ballmer}}\npeaked\n\n:(\n{{/ballmer}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "peaked\n\n:(\n" let partials = try [ "parent": Template("{{$ballmer}}peaking{{/ballmer}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Override parent with newlines") } func testInheritindentation() throws { let templateString = "{{<parent}}{{$nineties}}hammer time{{/nineties}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "stop:\n hammer time\n" let partials = try [ "parent": Template("stop:\n {{$nineties}}collaborate and listen{{/nineties}}\n"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Inherit indentation when overriding a parent") } func testOnlyoneoverride() throws { let templateString = "{{<parent}}{{$stuff2}}override two{{/stuff2}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "new default one, override two" let partials = try [ "parent": Template("{{$stuff}}new default one{{/stuff}}, {{$stuff2}}new default two{{/stuff2}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Override one parameter but not the other") } func testParenttemplate() throws { let templateString = "{{>parent}}|{{<parent}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "default content|default content" let partials = try [ "parent": Template("{{$foo}}default content{{/foo}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Parent templates behave identically to partials when called with no parameters") } func testRecursion() throws { let templateString = "{{<parent}}{{$foo}}override{{/foo}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "override override override don't recurse" let partials = try [ "parent2": Template("{{$foo}}parent2 default content{{/foo}} {{<parent}}{{$bar}}don't recurse{{/bar}}{{/parent}}"), "parent": Template("{{$foo}}default content{{/foo}} {{$bar}}{{<parent2}}{{/parent2}}{{/bar}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Recursion in inherited templates") } func testMulti_levelinheritance() throws { let templateString = "{{<parent}}{{$a}}c{{/a}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "c" let partials = try [ "grandParent": Template("{{$a}}g{{/a}}"), "older": Template("{{<grandParent}}{{$a}}o{{/a}}{{/grandParent}}"), "parent": Template("{{<older}}{{$a}}p{{/a}}{{/older}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Top-level substitutions take precedence in multi-level inheritance") } func testMulti_levelinheritance_nosubchild() throws { let templateString = "{{<parent}}{{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "p" let partials = try [ "grandParent": Template("{{$a}}g{{/a}}"), "older": Template("{{<grandParent}}{{$a}}o{{/a}}{{/grandParent}}"), "parent": Template("{{<older}}{{$a}}p{{/a}}{{/older}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Top-level substitutions take precedence in multi-level inheritance") } func testTextinsideparent() throws { let templateString = "{{<parent}} asdfasd {{$foo}}hmm{{/foo}} asdfasdfasdf {{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "hmm" let partials = try [ "parent": Template("{{$foo}}default content{{/foo}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Ignores text inside parent templates, but does parse $ tags") } func testTextinsideparent2() throws { let templateString = "{{<parent}} asdfasd asdfasdfasdf {{/parent}}" let contextJSON = "{}".data(using: .utf8)! let expected = "default content" let partials = try [ "parent": Template("{{$foo}}default content{{/foo}}"), ] let context = try JSONDecoder().decode(Context.self, from: contextJSON) let template = try Template(templateString) let rendered = template.render(with: context, partials: partials) XCTAssertEqual(rendered, expected, "Allows text inside a parent tag, but ignores it") } }
mit
b3c4da42dc58ed4919200f90d9bf2f72
43.848471
590
0.643737
4.536097
false
true
false
false
4faramita/TweeBox
TweeBox/UserTimelineParams.swift
1
804
// // UserTimelineParams.swift // TweeBox // // Created by 4faramita on 2017/7/31. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation class UserTimelineParams: TimelineParams { public var userID: String? // screenName init(of userID: String, sinceID: String? = nil, maxID: String? = nil, excludeReplies: Bool = false, includeRetweets: Bool = true) { self.userID = userID super.init(excludeReplies: nil, includeRetweets: nil) resourceURL = ResourceURL.statuses_user_timeline } override public func getParams() -> [String: Any] { var params = super.getParams() if userID != nil { params["user_id"] = userID } return params } }
mit
29a34ca0d83188e4ba308415430ef99e
22.558824
135
0.595506
4.128866
false
false
false
false
jiaxw32/ZRSwiftKit
ZRSwiftKit/Extension/Date+Extension.swift
1
3945
// // Date+Extension.swift // ZRSwiftKit // // Created by jiaxw-mac on 2017/9/7. // Copyright © 2017年 jiaxw32. All rights reserved. // import Foundation public let dateFormatYear = "yyyy" let dateFormatMonth = "MM" let dateFormatDay = "dd" public let dateFormatNormal = "yyyy-MM-dd" public let dateFormatSlash = "yyyy/MM/dd" public let datetimeFormatNormal = "yyyy-MM-dd HH:mm:ss" public let dateTimeFormatSlash = "yyyy/MM/dd HH:mm:ss" // MARK: - init extension Date{ init?(_ date: String, format: String = datetimeFormatNormal) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format if let formatDate = dateFormatter.date(from: date) { self.init(timeIntervalSince1970: formatDate.timeIntervalSince1970) } else { return nil } } init?(year: Int,month: Int,day: Int,hour:Int = 0,minute: Int = 0,second: Int = 0) { var components = DateComponents() components.year = year components.month = month components.day = day components.hour = hour components.minute = minute components.second = second if let date = Calendar.current.date(from: components) { self.init(timeIntervalSince1970: date.timeIntervalSince1970) } else { return nil } } } // MARK: - computer property extension Date{ var year: Int { return Calendar.current.component(.year, from: self) } var month: Int { return Calendar.current.component(.month, from: self) } var day: Int { return Calendar.current.component(.day, from: self) } var hour: Int { return Calendar.current.component(.hour, from: self) } var minute: Int { return Calendar.current.component(.minute, from: self) } var second: Int { return Calendar.current.component(.second, from: self) } var weekDay: Int { return Calendar.current.component(.weekday, from: self) } var cnWeekDay: String? { var result: String? switch weekDay { case 1: result = "星期天" case 2: result = "星期一" case 3: result = "星期二" case 4: result = "星期三" case 5: result = "星期四" case 6: result = "星期五" case 7: result = "星期六" default: break } return result } var weekOfMonth: Int { return Calendar.current.component(.weekOfMonth, from: self) } var weekOfYear: Int { return Calendar.current.component(.weekOfYear, from: self) } var firstDayOfMonth: Date { let calendar = Calendar.current var components = calendar.dateComponents([.day,.month,.year], from: self) components.day = 1 return calendar.date(from: components)! } var lastDayOfMonth: Date { let calendar = Calendar.current let dayRange = calendar.range(of: .day, in: .month, for: self) let dayCount = dayRange!.count var comp = calendar.dateComponents([.year, .month, .day], from: self) comp.day = dayCount return calendar.date(from: comp)! } } // MARK: - format and transfrom extension Date{ func toString(with format:String = datetimeFormatNormal) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } static func format(date: String,inFormat: String = dateTimeFormatSlash,outFormat: String = datetimeFormatNormal) -> String? { if let date = Date(date, format: inFormat){ return date.toString(with: outFormat) } else { return nil } } }
mit
bba383daeb4d793e3ecb8c4be5145c4e
24.16129
129
0.585128
4.257642
false
false
false
false
ngodacdu/SSSheetLayout
Example/SSSheetLayout/SheetLayout/SLSheetCell.swift
1
1311
// // SLSheetCell.swift // SLSheetLayout // // Created by Macbook on 6/29/17. // Copyright © 2017 Macbook. All rights reserved. // import UIKit class SLSheetCell: UICollectionViewCell { @IBOutlet weak var valueLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() valueLabel.text = nil backgroundColor = UIColor.white valueLabel.textColor = UIColor.black } func updateContent(value: String?) { valueLabel.text = value } func updateTopDockState() { backgroundColor = UIColor( red: 41/255.0, green: 56/255.0, blue: 74/255.0, alpha: 1.0 ) valueLabel.textColor = UIColor.white } func updateLeftDockState() { backgroundColor = UIColor( red: 41/255.0, green: 56/255.0, blue: 74/255.0, alpha: 1.0 ) valueLabel.textColor = UIColor.white } func updateCellState(indexPath: IndexPath) { if indexPath.section % 2 == 0 { backgroundColor = UIColor.groupTableViewBackground } else { backgroundColor = UIColor.white } } }
mit
0f893d1009bd6b520a8ac0701b1b9d74
21.586207
62
0.562595
4.532872
false
false
false
false
LawrenceHan/iOS-project-playground
iOS_programming_5th/WorldTrootter/WorldTrootter/ViewController.swift
1
902
// // ViewController.swift // WorldTrootter // // Created by Hanguang on 1/6/16. // Copyright © 2016 Hanguang. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) // let firstView = UIView(frame: firstFrame) // firstView.backgroundColor = UIColor.blueColor() // view.addSubview(firstView) // // let secondFrame = CGRect(x: 20, y: 30, width: 50, height: 50) // let secondView = UIView(frame: secondFrame) // secondView.backgroundColor = UIColor.greenColor() // firstView.addSubview(secondView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
af2fa140d5cee14ad4da1d0f0462423d
24.742857
74
0.629301
4.270142
false
false
false
false
vector-im/vector-ios
Riot/Modules/Common/Toasts/RoundedToastView.swift
1
4387
// // Copyright 2021 New Vector Ltd // // 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 UIKit import DesignKit class RoundedToastView: UIView, Themable { private struct ShadowStyle { let offset: CGSize let radius: CGFloat let opacity: Float } private struct Constants { static let padding = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12) static let activityIndicatorScale = CGFloat(0.75) static let imageViewSize = CGFloat(15) static let lightShadow = ShadowStyle(offset: .init(width: 0, height: 4), radius: 12, opacity: 0.1) static let darkShadow = ShadowStyle(offset: .init(width: 0, height: 4), radius: 4, opacity: 0.2) } private lazy var activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView() indicator.transform = .init(scaleX: Constants.activityIndicatorScale, y: Constants.activityIndicatorScale) indicator.startAnimating() return indicator }() private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: Constants.imageViewSize), imageView.heightAnchor.constraint(equalToConstant: Constants.imageViewSize) ]) return imageView }() private let stackView: UIStackView = { let stack = UIStackView() stack.axis = .horizontal stack.alignment = .center stack.spacing = 5 return stack }() private let label: UILabel = { return UILabel() }() init(viewState: ToastViewState) { super.init(frame: .zero) setup(viewState: viewState) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup(viewState: ToastViewState) { setupStackView() stackView.addArrangedSubview(toastView(for: viewState.style)) stackView.addArrangedSubview(label) label.text = viewState.label } private func setupStackView() { addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor, constant: Constants.padding.top), stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Constants.padding.bottom), stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.padding.left), stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.padding.right) ]) } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = layer.frame.height / 2 } func update(theme: Theme) { backgroundColor = theme.colors.background stackView.arrangedSubviews.first?.tintColor = theme.colors.primaryContent label.font = theme.fonts.subheadline label.textColor = theme.colors.primaryContent let shadowStyle = theme.identifier == ThemeIdentifier.dark.rawValue ? Constants.darkShadow : Constants.lightShadow layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = shadowStyle.offset layer.shadowRadius = shadowStyle.radius layer.shadowOpacity = shadowStyle.opacity } private func toastView(for style: ToastViewState.Style) -> UIView { switch style { case .loading: return activityIndicator case .success: imageView.image = Asset.Images.checkmark.image return imageView } } }
apache-2.0
4ac7d981d26aaecf9d5d5f4d17fe7acd
35.558333
122
0.674721
5.089327
false
false
false
false
SandcastleApps/partyup
PartyUP/SampleTastingContoller.swift
1
7757
// // SampleTastingContoller.swift // PartyUP // // Created by Fritz Vander Heide on 2015-09-22. // Copyright © 2015 Sandcastle Application Development. All rights reserved. // import UIKit class SampleTastingContoller: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { private enum PageContent { case Video(Tastable) case Ad(Advertisement) case Recruit } private var pages = [PageContent]() @IBOutlet weak var container: UIView! @IBOutlet weak var loadingProgress: UIActivityIndicatorView! @IBOutlet weak var nextPage: UIButton! @IBOutlet weak var previousPage: UIButton! private var navigationArrowsVisible: Bool = { return NSUserDefaults.standardUserDefaults().boolForKey(PartyUpPreferences.FeedNavigationArrows) }() override func viewDidLoad() { super.viewDidLoad() if venues != nil && observations.isEmpty { updateSampleDisplay() } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SampleTastingContoller.sieveOffensiveSamples), name: Defensive.OffensiveMuteUpdateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SampleTastingContoller.sieveOffensiveSamples), name: Sample.FlaggedUpdateNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } @IBAction func flipPage(sender: UIButton) { if let pvc = childViewControllers.first as? UIPageViewController { if let index = (pvc.viewControllers?.first as? PageProtocol)?.page { if let page = dequeTastePageController(index + sender.tag) { pvc.setViewControllers([page], direction: sender.tag > 0 ? UIPageViewControllerNavigationDirection.Forward : UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil) updateNavigationArrows(pvc) } } } } var venues: [Venue]? { didSet { let notify = NSNotificationCenter.defaultCenter() let stale = NSUserDefaults.standardUserDefaults().doubleForKey(PartyUpPreferences.StaleSampleInterval) let suppress = NSUserDefaults.standardUserDefaults().integerForKey(PartyUpPreferences.SampleSuppressionThreshold) if let venues = venues { for venue in venues { observations.insert(venue) notify.addObserver(self, selector: #selector(SampleTastingContoller.sampleFetchObserver(_:)), name: Venue.VitalityUpdateNotification, object: venue) venue.fetchSamples(withStaleInterval: stale, andSuppression: suppress, andTimeliness: 60) } } } } var ads: [Advertisement] = [] { didSet { for ad in ads { for page in ad.pages { switch ad.style { case .Page: adPages[page] = ad case .Overlay: adOvers[page] = ad } } } } } private var adPages = [Int:Advertisement]() private var adOvers = [Int:Advertisement]() private var samples = [Tastable]() private var observations = Set<Venue>() func sampleFetchObserver(note: NSNotification) { if let venue = note.object as? Venue { if observations.remove(venue) != nil, let local = venue.treats { samples.appendContentsOf(local) if observations.isEmpty { samples.sortInPlace { $0.time.compare($1.time) == .OrderedDescending } updateSampleDisplay() } } } } private func updateSampleDisplay() { loadingProgress?.stopAnimating() pages = samples.map { .Video($0) } adPages.forEach { page, ad in self.pages.insert(.Ad(ad), atIndex: min(page, self.pages.count)) } pages.append(.Recruit) if let page = dequeTastePageController(0), pvc = childViewControllers.first as? UIPageViewController { pvc.dataSource = self pvc.delegate = self pvc.setViewControllers([page], direction: .Forward, animated: false) { completed in if completed { self.updateNavigationArrows(pvc) } } } } func sieveOffensiveSamples() { let filtered = pages.filter { if case .Video(let treat) = $0, let sample = treat as? Votable { return !Defensive.shared.muted(sample.user) && !(sample.flag ?? false) } else { return true } } if filtered.count != pages.count { pages = filtered } if let pvc = childViewControllers.first as? UIPageViewController, visible = pvc.viewControllers?.first as? SampleTastePageController { let index = pages.indexOf { if case .Video(let sample) = $0 { return sample.time.compare(visible.sample.time) == .OrderedAscending } else { return false } } if let toVC = dequeTastePageController(index ?? pages.count - 1) { pvc.setViewControllers([toVC], direction: .Forward, animated: true) { completed in if completed { self.updateNavigationArrows(pvc) } } } } } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var toVC: UIViewController? if let fromVC = viewController as? PageProtocol { toVC = dequeTastePageController(fromVC.page + 1) } return toVC } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var toVC: UIViewController? if let fromVC = viewController as? PageProtocol { toVC = dequeTastePageController(fromVC.page - 1) } return toVC } func dequeTastePageController(page: Int) -> UIViewController? { if page >= 0 && page < pages.count { let over = adOvers[page].flatMap { NSURL(string: $0.media, relativeToURL: PartyUpPaths.AdvertisementUrl) } switch pages[page] { case .Video(let sample): let pageVC = storyboard?.instantiateViewControllerWithIdentifier("Sample Taste Page Controller") as? SampleTastePageController pageVC?.page = page pageVC?.sample = sample pageVC?.ad = over return pageVC case .Ad(let ad): let pageVC = storyboard?.instantiateViewControllerWithIdentifier("Advertising Page Controller") as? AdvertisingOverlayController pageVC?.page = page pageVC?.url = NSURL(string: ad.media, relativeToURL: PartyUpPaths.AdvertisementUrl) return pageVC case .Recruit: let pageVC = storyboard?.instantiateViewControllerWithIdentifier("Recruit Page Controller") as? RecruitPageController pageVC?.page = page pageVC?.ad = over return pageVC } } return nil } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { updateNavigationArrows(pageViewController) } } func updateNavigationArrows(pageViewController: UIPageViewController) { if navigationArrowsVisible, let index = (pageViewController.viewControllers?.first as? PageProtocol)?.page { let prev = !(index > 0) let next = !(index < pages.count - 1) if prev != previousPage.hidden { UIView.animateWithDuration(0.5, animations: { self.previousPage.transform = prev ? CGAffineTransformMakeScale(0.1, 0.1) : CGAffineTransformIdentity }, completion: { (done) in self.previousPage.hidden = prev }) } if next != nextPage.hidden { UIView.animateWithDuration(0.5, animations: { self.nextPage.transform = next ? CGAffineTransformMakeScale(0.1, 0.1) : CGAffineTransformIdentity }, completion: { (done) in self.nextPage.hidden = next }) } } } }
mit
b3ced1248270065f79b03631c3bd3337
36.650485
213
0.692367
4.426941
false
false
false
false
leotumwattana/WWC-Animations
WWC-Animations/Geometry+Extensions.swift
1
21543
// Copyright (c) 2014 Nikolaj Schumacher // // 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 CoreGraphics // MARK: CGPoint extension CGPoint { public init(_ x: CGFloat, _ y: CGFloat) { self.x = x self.y = y } public func with(# x: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) } public func with(# y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) } } // MARK: CGSize extension CGSize { public init(_ width: CGFloat, _ height: CGFloat) { self.width = width self.height = height } public func with(# width: CGFloat) -> CGSize { return CGSize(width: width, height: height) } public func with(# height: CGFloat) -> CGSize { return CGSize(width: width, height: height) } } // MARK: CGRect extension CGRect { public init(_ origin: CGPoint, _ size: CGSize) { self.origin = origin self.size = size } public init(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) { self.origin = CGPoint(x: x, y: y) self.size = CGSize(width: width, height: height) } // MARK: access shortcuts public var x: CGFloat { get {return origin.x} set {origin.x = newValue} } public var y: CGFloat { get {return origin.y} set {origin.y = newValue} } public var centerX: CGFloat { get {return x + width * 0.5} set {x = newValue - width * 0.5} } public var centerY: CGFloat { get {return y + height * 0.5} set {y = newValue - height * 0.5} } // MARK: edges public var left: CGFloat { get {return origin.x} set {origin.x = newValue} } public var right: CGFloat { get {return x + width} set {x = newValue - width} } #if os(iOS) public var top: CGFloat { get {return y} set {y = newValue} } public var bottom: CGFloat { get {return y + height} set {y = newValue - height} } #else public var top: CGFloat { get {return y + height} set {y = newValue - height} } public var bottom: CGFloat { get {return y} set {y = newValue} } #endif // MARK: points public var topLeft: CGPoint { get {return CGPoint(x: left, y: top)} set {left = newValue.x; top = newValue.y} } public var topCenter: CGPoint { get {return CGPoint(x: centerX, y: top)} set {centerX = newValue.x; top = newValue.y} } public var topRight: CGPoint { get {return CGPoint(x: right, y: top)} set {right = newValue.x; top = newValue.y} } public var centerLeft: CGPoint { get {return CGPoint(x: left, y: centerY)} set {left = newValue.x; centerY = newValue.y} } public var center: CGPoint { get {return CGPoint(x: centerX, y: centerY)} set {centerX = newValue.x; centerY = newValue.y} } public var centerRight: CGPoint { get {return CGPoint(x: right, y: centerY)} set {right = newValue.x; centerY = newValue.y} } public var bottomLeft: CGPoint { get {return CGPoint(x: left, y: bottom)} set {left = newValue.x; bottom = newValue.y} } public var bottomCenter: CGPoint { get {return CGPoint(x: centerX, y: bottom)} set {centerX = newValue.x; bottom = newValue.y} } public var bottomRight: CGPoint { get {return CGPoint(x: right, y: bottom)} set {right = newValue.x; bottom = newValue.y} } // MARK: with public func with(# origin: CGPoint) -> CGRect { return CGRect(origin: origin, size: size) } public func with(# x: CGFloat, y: CGFloat) -> CGRect { return with(origin: CGPoint(x: x, y: y)) } public func with(# x: CGFloat) -> CGRect { return with(x: x, y: y) } public func with(# y: CGFloat) -> CGRect { return with(x: x, y: y) } public func with(# size: CGSize) -> CGRect { return CGRect(origin: origin, size: size) } public func with(# width: CGFloat, height: CGFloat) -> CGRect { return with(size: CGSize(width: width, height: height)) } public func with(# width: CGFloat) -> CGRect { return with(width: width, height: height) } public func with(# height: CGFloat) -> CGRect { return with(width: width, height: height) } public func with(# x: CGFloat, width: CGFloat) -> CGRect { return CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height)) } public func with(# y: CGFloat, height: CGFloat) -> CGRect { return CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height)) } // MARK: offset public func rectByOffsetting(dx: CGFloat, _ dy: CGFloat) -> CGRect { return with(x: x + dx, y: y + dy) } public func rectByOffsetting(# dx: CGFloat) -> CGRect { return with(x: x + dx) } public func rectByOffsetting(# dy: CGFloat) -> CGRect { return with(y: y + dy) } public func rectByOffsetting(by: CGSize) -> CGRect { return with(x: x + by.width, y: y + by.height) } public mutating func offset(dx: CGFloat, _ dy: CGFloat) { offset(dx: dx, dy: dy) } public mutating func offset(dx: CGFloat = 0) { x += dx } public mutating func offset(dy: CGFloat = 0) { y += dy } public mutating func offset(by: CGSize) { offset(dx: by.width, dy: by.height) } // MARK: inset public func rectByInsetting(by: CGFloat) -> CGRect { return rectByInsetting(dx: by, dy: by) } public func rectByInsetting(# dx: CGFloat) -> CGRect { return with(x: x + dx, width: width - dx * 2) } public func rectByInsetting(# dy: CGFloat) -> CGRect { return with(y: y + dy, height: height - dy * 2) } public func rectByInsetting(minX: CGFloat = 0, minY: CGFloat = 0, maxX: CGFloat = 0, maxY: CGFloat = 0) -> CGRect { return CGRect(x: x + minX, y: y + minY, width: width - minX - maxX, height: height - minY - maxY) } public func rectByInsetting(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> CGRect { #if os(iOS) return CGRect(x: x + left, y: y + top, width: width - right - left, height: height - top - bottom) #else return CGRect(x: x + left, y: y + bottom, width: width - right - left, height: height - top - bottom) #endif } public func rectByInsetting(# topLeft: CGSize) -> CGRect { return rectByInsetting(top: topLeft.height, left: topLeft.width) } public func rectByInsetting(# topRight: CGSize) -> CGRect { return rectByInsetting(top: topRight.height, right: topRight.width) } public func rectByInsetting(# bottomLeft: CGSize) -> CGRect { return rectByInsetting(bottom: bottomLeft.height, left: bottomLeft.width) } public func rectByInsetting(# bottomRight: CGSize) -> CGRect { return rectByInsetting(bottom: bottomRight.height, right: bottomRight.width) } public mutating func inset(by: CGFloat) { inset(dx: by, dy: by) } public mutating func inset(# dx: CGFloat) { inset(dx: dx, dy: 0) } public mutating func inset(# dy: CGFloat) { inset(dx: 0, dy: dy) } public mutating func inset(minX: CGFloat = 0, minY: CGFloat = 0, maxX: CGFloat = 0, maxY: CGFloat = 0) { self = rectByInsetting(minX: minX, minY: minY, maxX: maxX, maxY: maxY) } public mutating func inset(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) { self = rectByInsetting(top: top, left: left, bottom: bottom, right: right) } public mutating func inset(# topLeft: CGSize) { self = rectByInsetting(topLeft: topLeft) } public mutating func inset(# topRight: CGSize) { self = rectByInsetting(topRight: topRight) } public mutating func inset(# bottomLeft: CGSize) { self = rectByInsetting(bottomLeft: bottomLeft) } public mutating func inset(# bottomRight: CGSize) { self = rectByInsetting(bottomRight: bottomRight) } // MARK: extending public func rectByExtending(#dx: CGFloat, dy: CGFloat = 0) -> CGRect { return rectByInsetting(dx: -dx, dy: -dy) } public func rectByExtending(# dy: CGFloat) -> CGRect { return rectByInsetting(dy: -dy) } public func rectByExtending(by: CGFloat) -> CGRect { return rectByInsetting(dx: -by, dy: -by) } public func rectByExtending(minX: CGFloat = 0, minY: CGFloat = 0, maxX: CGFloat = 0, maxY: CGFloat = 0) -> CGRect { return rectByInsetting(minX: -minX, minY: -minY, maxX: -maxX, maxY: -maxY) } public func rectByExtending(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> CGRect { return rectByInsetting(top: -top, left: -left, bottom: -bottom, right: -right) } public func rectByExtending(# topLeft: CGSize) -> CGRect { return rectByExtending(top: topLeft.height, left: topLeft.width) } public func rectByExtending(# topRight: CGSize) -> CGRect { return rectByInsetting(top: -topRight.height, right: -topRight.width) } public func rectByExtending(# bottomLeft: CGSize) -> CGRect { return rectByInsetting(bottom: -bottomLeft.height, left: -bottomLeft.width) } public func rectByExtending(# bottomRight: CGSize) -> CGRect { return rectByInsetting(bottom: -bottomRight.height, right: -bottomRight.width) } public mutating func extend(#dx: CGFloat, dy: CGFloat = 0) { self = rectByInsetting(dx: -dx, dy: -dy) } public mutating func extend(# dy: CGFloat) { self = rectByInsetting(dy: -dy) } public mutating func extend(by: CGFloat) { self = rectByInsetting(dx: -by, dy: -by) } public mutating func extend(minX: CGFloat = 0, minY: CGFloat = 0, maxX: CGFloat = 0, maxY: CGFloat = 0) { self = rectByInsetting(minX: -minX, minY: -minY, maxX: -maxX, maxY: -maxY) } public mutating func extend(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) { self = rectByInsetting(top: -top, left: -left, bottom: -bottom, right: -right) } public mutating func extend(# topLeft: CGSize) { self = rectByExtending(top: topLeft.height, left: topLeft.width) } public mutating func extend(# topRight: CGSize) { self = rectByInsetting(top: -topRight.height, right: -topRight.width) } public mutating func extend(# bottomLeft: CGSize) { self = rectByInsetting(bottom: -bottomLeft.height, left: -bottomLeft.width) } public mutating func extend(# bottomRight: CGSize) { self = rectByInsetting(bottom: -bottomRight.height, right: -bottomRight.width) } // MARK: sizes public func rectByCentering(size: CGSize) -> CGRect { let dx = width - size.width let dy = height - size.height return CGRect(x: x + dx * 0.5, y: y + dy * 0.5, width: size.width, height: size.height) } public func rectByCentering(size: CGSize, alignTo edge: CGRectEdge) -> CGRect { return CGRect(origin: alignedOrigin(size, edge: edge), size: size) } private func alignedOrigin(size: CGSize, edge: CGRectEdge) -> CGPoint { let dx = width - size.width let dy = height - size.height switch edge { case .MinXEdge: return CGPoint(x: x, y: y + dy * 0.5) case .MinYEdge: return CGPoint(x: x + dx * 0.5, y: y) case .MaxXEdge: return CGPoint(x: x + dx, y: y + dy * 0.5) case .MaxYEdge: return CGPoint(x: x + dx * 0.5, y: y + dy) } } public func rectByAligning(size: CGSize, corner e1: CGRectEdge, _ e2: CGRectEdge) -> CGRect { return CGRect(origin: alignedOrigin(size, corner: e1, e2), size: size) } private func alignedOrigin(size: CGSize, corner e1: CGRectEdge, _ e2: CGRectEdge) -> CGPoint { let dx = width - size.width let dy = height - size.height switch (e1, e2) { case (.MinXEdge, .MinYEdge), (.MinYEdge, .MinXEdge): return CGPoint(x: x, y: y) case (.MaxXEdge, .MinYEdge), (.MinYEdge, .MaxXEdge): return CGPoint(x: x + dx, y: y) case (.MinXEdge, .MaxYEdge), (.MaxYEdge, .MinXEdge): return CGPoint(x: x, y: y + dy) case (.MaxXEdge, .MaxYEdge), (.MaxYEdge, .MaxXEdge): return CGPoint(x: x + dx, y: y + dy) default: preconditionFailure("Cannot align to this combination of edges") } } public mutating func setSizeCentered(size: CGSize) { self = rectByCentering(size) } public mutating func setSizeCentered(size: CGSize, alignTo edge: CGRectEdge) { self = rectByCentering(size, alignTo: edge) } public mutating func setSizeAligned(size: CGSize, corner e1: CGRectEdge, _ e2: CGRectEdge) { self = rectByAligning(size, corner: e1, e2) } // ===================== // MARK: - Leo Additions // ===================== public func scaleAspectFittingRect(toRect:CGRect) -> CGFloat { let fromDim = min(self.width, self.height) let toDim = min(toRect.width, toRect.height) let scale = 1 - ((fromDim - toDim) / fromDim) return scale } public func rectAspectFittingRect(toRect:CGRect) -> CGRect { let scale = self.scaleAspectFittingRect(toRect) let width = self.width * scale let height = self.height * scale return CGRectMake(toRect.x, toRect.y, width, height) } } // MARK: transform extension CGAffineTransform: Equatable { } public func ==(t1: CGAffineTransform, t2: CGAffineTransform) -> Bool { return CGAffineTransformEqualToTransform(t1, t2) } extension CGAffineTransform: DebugPrintable { public var debugDescription: String { return "(\(a),\(b),\(c),\(d),\(tx),\(ty))" } } // MARK: operators public func +(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y) } public func +=(inout p1: CGPoint, p2: CGPoint) { p1.x += p2.x p1.y += p2.y } public func -(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x - p2.x, y: p1.y - p2.y) } public func -=(inout p1: CGPoint, p2: CGPoint) { p1.x -= p2.x p1.y -= p2.y } public func +(point: CGPoint, size: CGSize) -> CGPoint { return CGPoint(x: point.x + size.width, y: point.y + size.height) } public func +=(inout point: CGPoint, size: CGSize) { point.x += size.width point.y += size.height } public func -(point: CGPoint, size: CGSize) -> CGPoint { return CGPoint(x: point.x - size.width, y: point.y - size.height) } public func -=(inout point: CGPoint, size: CGSize) { point.x -= size.width point.y -= size.height } public func +(point: CGPoint, tuple: (CGFloat, CGFloat)) -> CGPoint { return CGPoint(x: point.x + tuple.0, y: point.y + tuple.1) } public func +=(inout point: CGPoint, tuple: (CGFloat, CGFloat)) { point.x += tuple.0 point.y += tuple.1 } public func -(point: CGPoint, tuple: (CGFloat, CGFloat)) -> CGPoint { return CGPoint(x: point.x - tuple.0, y: point.y - tuple.1) } public func -=(inout point: CGPoint, tuple: (CGFloat, CGFloat)) { point.x -= tuple.0 point.y -= tuple.1 } public func *(point: CGPoint, factor: CGFloat) -> CGPoint { return CGPoint(x: point.x * factor, y: point.y * factor) } public func *=(inout point: CGPoint, factor: CGFloat) { point.x *= factor point.y *= factor } public func *(point: CGPoint, tuple: (CGFloat, CGFloat)) -> CGPoint { return CGPoint(x: point.x * tuple.0, y: point.y * tuple.1) } public func *=(inout point: CGPoint, tuple: (CGFloat, CGFloat)) { point.x *= tuple.0 point.y *= tuple.1 } public func /(point: CGPoint, tuple: (CGFloat, CGFloat)) -> CGPoint { return CGPoint(x: point.x / tuple.0, y: point.y / tuple.1) } public func /=(inout point: CGPoint, tuple: (CGFloat, CGFloat)) { point.x /= tuple.0 point.y /= tuple.1 } public func /(point: CGPoint, factor: CGFloat) -> CGPoint { return CGPoint(x: point.x / factor, y: point.y / factor) } public func /=(inout point: CGPoint, factor: CGFloat) { point.x /= factor point.y /= factor } public func +(s1: CGSize, s2: CGSize) -> CGSize { return CGSize(width: s1.width + s2.width, height: s1.height + s2.height) } public func +=(inout s1: CGSize, s2: CGSize) { s1.width += s2.width s1.height += s2.height } public func -(s1: CGSize, s2: CGSize) -> CGSize { return CGSize(width: s1.width - s2.width, height: s1.height - s2.height) } public func -=(inout s1: CGSize, s2: CGSize) { s1.width -= s2.width s1.height -= s2.height } public func +(size: CGSize, tuple: (CGFloat, CGFloat)) -> CGSize { return CGSize(width: size.width + tuple.0, height: size.height + tuple.1) } public func +=(inout size: CGSize, tuple: (CGFloat, CGFloat)) { size.width += tuple.0 size.height += tuple.1 } public func -(size: CGSize, tuple: (CGFloat, CGFloat)) -> CGSize { return CGSize(width: size.width - tuple.0, height: size.height - tuple.1) } public func -=(inout size: CGSize, tuple: (CGFloat, CGFloat)) { size.width -= tuple.0 size.height -= tuple.1 } public func *(size: CGSize, factor: CGFloat) -> CGSize { return CGSize(width: size.width * factor, height: size.height * factor) } public func *=(inout size: CGSize, factor: CGFloat) { size.width *= factor size.height *= factor } public func *(size: CGSize, tuple: (CGFloat, CGFloat)) -> CGSize { return CGSize(width: size.width * tuple.0, height: size.height * tuple.1) } public func *=(inout size: CGSize, tuple: (CGFloat, CGFloat)) { size.width *= tuple.0 size.height *= tuple.1 } public func /(size: CGSize, factor: CGFloat) -> CGSize { return CGSize(width: size.width / factor, height: size.height / factor) } public func /=(inout size: CGSize, factor: CGFloat) { size.width /= factor size.height /= factor } public func /(size: CGSize, tuple: (CGFloat, CGFloat)) -> CGSize { return CGSize(width: size.width / tuple.0, height: size.height / tuple.1) } public func /=(inout size: CGSize, tuple: (CGFloat, CGFloat)) { size.width /= tuple.0 size.height /= tuple.1 } public func +(rect: CGRect, point: CGPoint) -> CGRect { return CGRect(origin: rect.origin + point, size: rect.size) } public func +=(inout rect: CGRect, point: CGPoint) { rect.origin += point } public func -(rect: CGRect, point: CGPoint) -> CGRect { return CGRect(origin: rect.origin - point, size: rect.size) } public func -=(inout rect: CGRect, point: CGPoint) { rect.origin -= point } public func +(rect: CGRect, size: CGSize) -> CGRect { return CGRect(origin: rect.origin, size: rect.size + size) } public func +=(inout rect: CGRect, size: CGSize) { rect.size += size } public func -(rect: CGRect, size: CGSize) -> CGRect { return CGRect(origin: rect.origin, size: rect.size - size) } public func -=(inout rect: CGRect, size: CGSize) { rect.size -= size } public func *(point: CGPoint, transform: CGAffineTransform) -> CGPoint { return CGPointApplyAffineTransform(point, transform) } public func *=(inout point: CGPoint, transform: CGAffineTransform) { point = CGPointApplyAffineTransform(point, transform) } public func *(size: CGSize, transform: CGAffineTransform) -> CGSize { return CGSizeApplyAffineTransform(size, transform) } public func *=(inout size: CGSize, transform: CGAffineTransform) { size = CGSizeApplyAffineTransform(size, transform) } public func *(rect: CGRect, transform: CGAffineTransform) -> CGRect { return CGRectApplyAffineTransform(rect, transform) } public func *=(inout rect: CGRect, transform: CGAffineTransform) { rect = CGRectApplyAffineTransform(rect, transform) } public func *(t1: CGAffineTransform, t2: CGAffineTransform) -> CGAffineTransform { return CGAffineTransformConcat(t1, t2) } public func *=(inout t1: CGAffineTransform, t2: CGAffineTransform) { t1 = CGAffineTransformConcat(t1, t2) }
bsd-3-clause
92696b6aa60fb1bea2cab7fa39170531
32.819466
121
0.616488
3.6971
false
false
false
false
DivineDominion/mac-multiproc-code
RelocationManager/BoxCreationWindowController.swift
1
1988
// // BoxCreationWindowController.swift // RelocationManager // // Created by Christian Tietze on 16/02/15. // Copyright (c) 2015 Christian Tietze. All rights reserved. // import Cocoa public protocol HandlesBoxCreationEvents { func order(boxOrder: BoxOrder) func cancel() } let kBoxCreationWindowControllerNibName = "BoxCreationWindowController" public class BoxCreationWindowController: NSWindowController, NSWindowDelegate { public var eventHandler: HandlesBoxCreationEvents? /// Initialize using the default Nib public override convenience init() { self.init(windowNibName: kBoxCreationWindowControllerNibName) } public override func loadWindow() { super.loadWindow() window?.level = kCGModalPanelWindowLevelKey } // MARK: Buttons @IBOutlet public var orderButton: NSButton! @IBAction public func order(sender: AnyObject) { if let eventHandler = eventHandler { let boxOrder = boxOrderFromForm() eventHandler.order(boxOrder) } } func boxOrderFromForm() -> BoxOrder { return BoxOrder(label: boxLabel(), capacity: boxCapacity()) } @IBOutlet public var cancelButton: NSButton! @IBAction public func cancel(sender: AnyObject) { self.close() } public func windowWillClose(notification: NSNotification) { if let eventHandler = eventHandler { eventHandler.cancel() } } // MARK: Data Input @IBOutlet public var capacityComboBox: NSComboBox! func boxCapacity() -> Int { return capacityComboBox.integerValue } @IBOutlet public var boxLabelTextField: NSTextField! func boxLabel() -> String { let labelText = boxLabelTextField.stringValue if labelText == "" { return "New Box" } return labelText } }
mit
13ad4cba137d6726ccf2bb7b32ec1596
22.388235
80
0.6333
5.190601
false
false
false
false
OneBusAway/onebusaway-iphone
OneBusAway/externals/PromiseKit/Sources/Promise.swift
3
25230
import class Dispatch.DispatchQueue import class Foundation.NSError import func Foundation.NSLog /** A *promise* represents the future value of a (usually) asynchronous task. To obtain the value of a promise we call `then`. Promises are chainable: `then` returns a promise, you can call `then` on that promise, which returns a promise, you can call `then` on that promise, et cetera. Promises start in a pending state and *resolve* with a value to become *fulfilled* or an `Error` to become rejected. - SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/docs/) */ open class Promise<T> { let state: State<T> /** Create a new, pending promise. func fetchAvatar(user: String) -> Promise<UIImage> { return Promise { fulfill, reject in MyWebHelper.GET("\(user)/avatar") { data, err in guard let data = data else { return reject(err) } guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) } guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) } fulfill(img) } } } - Parameter resolvers: The provided closure is called immediately on the active thread; commence your asynchronous task, calling either fulfill or reject when it completes. - Parameter fulfill: Fulfills this promise with the provided value. - Parameter reject: Rejects this promise with the provided error. - Returns: A new promise. - Note: If you are wrapping a delegate-based system, we recommend to use instead: `Promise.pending()` - SeeAlso: http://promisekit.org/docs/sealing-promises/ - SeeAlso: http://promisekit.org/docs/cookbook/wrapping-delegation/ - SeeAlso: pending() */ required public init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) { var resolve: ((Resolution<T>) -> Void)! do { state = UnsealedState(resolver: &resolve) try resolvers({ resolve(.fulfilled($0)) }, { error in #if !PMKDisableWarnings if self.isPending { resolve(Resolution(error)) } else { NSLog("PromiseKit: warning: reject called on already rejected Promise: \(error)") } #else resolve(Resolution(error)) #endif }) } catch { resolve(Resolution(error)) } } /** Create an already fulfilled promise. To create a resolved `Void` promise, do: `Promise(value: ())` */ required public init(value: T) { state = SealedState(resolution: .fulfilled(value)) } /** Create an already rejected promise. */ required public init(error: Error) { state = SealedState(resolution: Resolution(error)) } /** Careful with this, it is imperative that sealant can only be called once or you will end up with spurious unhandled-errors due to possible double rejections and thus immediately deallocated ErrorConsumptionTokens. */ init(sealant: (@escaping (Resolution<T>) -> Void) -> Void) { var resolve: ((Resolution<T>) -> Void)! state = UnsealedState(resolver: &resolve) sealant(resolve) } /** A `typealias` for the return values of `pending()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise(value: ())`s within the same scope, or when the promise initialization must occur outside of the caller's initialization. class Foo: BarDelegate { var task: Promise<Int>.PendingTuple? } - SeeAlso: pending() */ public typealias PendingTuple = (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) /** Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pending. class Foo: BarDelegate { let (promise, fulfill, reject) = Promise<Int>.pending() func barDidFinishWithResult(result: Int) { fulfill(result) } func barDidError(error: NSError) { reject(error) } } - Returns: A tuple consisting of: 1) A promise 2) A function that fulfills that promise 3) A function that rejects that promise */ public final class func pending() -> PendingTuple { var fulfill: ((T) -> Void)! var reject: ((Error) -> Void)! let promise = self.init { fulfill = $0; reject = $1 } return (promise, fulfill, reject) } /** The provided closure is executed when this promise is resolved. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise that is resolved with the value returned from the provided closure. For example: URLSession.GET(url).then { data -> Int in //… return data.length }.then { length in //… } */ @discardableResult public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> { return Promise<U> { resolve in state.then(on: q, else: resolve) { value in resolve(.fulfilled(try body(value))) } } } /** The provided closure executes when this promise resolves. This variant of `then` allows chaining promises, the promise returned by the provided closure is resolved before the promise returned by this closure resolves. - Parameter on: The queue to which the provided closure dispatches. - Parameter execute: The closure that executes when this promise fulfills. - Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example: URLSession.GET(url1).then { data in return CLLocationManager.promise() }.then { location in //… } */ @discardableResult public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> { var resolve: ((Resolution<U>) -> Void)! let rv = Promise<U>{ resolve = $0 } state.then(on: q, else: resolve) { value in let promise = try body(value) guard promise !== rv else { throw PMKError.returnedSelf } promise.state.pipe(resolve) } return rv } /** The provided closure executes when this promise resolves. This variant of `then` allows returning a tuple of promises within provided closure. All of the returned promises needs be fulfilled for this promise to be marked as resolved. - Note: At maximum 5 promises may be returned in a tuple - Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error. - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. - Parameter on: The queue to which the provided closure dispatches. - Parameter execute: The closure that executes when this promise fulfills. - Returns: A new promise that resolves when all promises returned from the provided closure resolve. For example: loginPromise.then { _ -> (Promise<Data>, Promise<UIImage>) return (URLSession.GET(userUrl), URLSession.dataTask(with: avatarUrl).asImage()) }.then { userData, avatarImage in //… } */ @discardableResult public func then<U, V>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>)) -> Promise<(U, V)> { return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1) } } /// This variant of `then` allows returning a tuple of promises within provided closure. @discardableResult public func then<U, V, X>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>)) -> Promise<(U, V, X)> { return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2) } } /// This variant of `then` allows returning a tuple of promises within provided closure. @discardableResult public func then<U, V, X, Y>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>)) -> Promise<(U, V, X, Y)> { return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) } } /// This variant of `then` allows returning a tuple of promises within provided closure. @discardableResult public func then<U, V, X, Y, Z>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>, Promise<Z>)) -> Promise<(U, V, X, Y, Z)> { return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) } } /// utility function to serve `then` implementations with `body` returning tuple of promises @discardableResult private func then<U, V>(on q: DispatchQueue, execute body: @escaping (T) throws -> V, when: @escaping (V) -> Promise<U>) -> Promise<U> { return Promise<U> { resolve in state.then(on: q, else: resolve) { value in let promise = try body(value) // since when(promise) switches to `zalgo`, we have to pipe back to `q` when(promise).state.pipe(on: q, to: resolve) } } } /** The provided closure executes when this promise rejects. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - Returns: `self` - SeeAlso: [Cancellation](http://promisekit.org/docs/) - Important: The promise that is returned is `self`. `catch` cannot affect the chain, in PromiseKit 3 no promise was returned to strongly imply this, however for PromiseKit 4 we started returning a promise so that you can `always` after a catch or return from a function that has an error handler. */ @discardableResult public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise { state.catch(on: q, policy: policy, else: { _ in }, execute: body) return self } /** The provided closure executes when this promise rejects. Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: CLLocationManager.promise().recover { error in guard error == CLError.unknownLocation else { throw error } return CLLocation.Chicago } - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ @discardableResult public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise { var resolve: ((Resolution<T>) -> Void)! let rv = Promise{ resolve = $0 } state.catch(on: q, policy: policy, else: resolve) { error in let promise = try body(error) guard promise !== rv else { throw PMKError.returnedSelf } promise.state.pipe(resolve) } return rv } /** The provided closure executes when this promise rejects. Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: CLLocationManager.promise().recover { error in guard error == CLError.unknownLocation else { throw error } return CLLocation.Chicago } - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ @discardableResult public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise { return Promise { resolve in state.catch(on: q, policy: policy, else: resolve) { error in resolve(.fulfilled(try body(error))) } } } /** The provided closure executes when this promise resolves. firstly { UIApplication.shared.networkActivityIndicatorVisible = true }.then { //… }.always { UIApplication.shared.networkActivityIndicatorVisible = false }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter execute: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ @discardableResult public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise { state.always(on: q) { resolution in body() } return self } /** Allows you to “tap” into a promise chain and inspect its result. The function you provide cannot mutate the chain. URLSession.GET(/*…*/).tap { result in print(result) } - Parameter on: The queue to which the provided closure dispatches. - Parameter execute: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ @discardableResult public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result<T>) -> Void) -> Promise { state.always(on: q) { resolution in body(Result(resolution)) } return self } /** Void promises are less prone to generics-of-doom scenarios. - SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code. */ public func asVoid() -> Promise<Void> { return then(on: zalgo) { _ in return } } //MARK: deprecations @available(*, unavailable, renamed: "always()") public func finally(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() } @available(*, unavailable, renamed: "always()") public func ensure(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() } @available(*, unavailable, renamed: "pending()") public class func `defer`() -> PendingTuple { fatalError() } @available(*, unavailable, renamed: "pending()") public class func `pendingPromise`() -> PendingTuple { fatalError() } @available(*, unavailable, message: "deprecated: use then(on: .global())") public func thenInBackground<U>(execute body: (T) throws -> U) -> Promise<U> { fatalError() } @available(*, unavailable, renamed: "catch") public func onError(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } @available(*, unavailable, renamed: "catch") public func errorOnQueue(_ on: DispatchQueue, policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } @available(*, unavailable, renamed: "catch") public func error(policy: CatchPolicy, execute body: (Error) -> Void) { fatalError() } @available(*, unavailable, renamed: "catch") public func report(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } @available(*, unavailable, renamed: "init(value:)") public init(_ value: T) { fatalError() } //MARK: disallow `Promise<Error>` @available(*, unavailable, message: "cannot instantiate Promise<Error>") public init<T: Error>(resolvers: (_ fulfill: (T) -> Void, _ reject: (Error) -> Void) throws -> Void) { fatalError() } @available(*, unavailable, message: "cannot instantiate Promise<Error>") public class func pending<T: Error>() -> (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) { fatalError() } //MARK: disallow returning `Error` @available (*, unavailable, message: "instead of returning the error; throw") public func then<U: Error>(on: DispatchQueue = .default, execute body: (T) throws -> U) -> Promise<U> { fatalError() } @available (*, unavailable, message: "instead of returning the error; throw") public func recover<T: Error>(on: DispatchQueue = .default, execute body: (Error) throws -> T) -> Promise { fatalError() } //MARK: disallow returning `Promise?` @available(*, unavailable, message: "unwrap the promise") public func then<U>(on: DispatchQueue = .default, execute body: (T) throws -> Promise<U>?) -> Promise<U> { fatalError() } @available(*, unavailable, message: "unwrap the promise") public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> Promise?) -> Promise { fatalError() } } extension Promise: CustomStringConvertible { public var description: String { return "Promise: \(state)" } } /** Judicious use of `firstly` *may* make chains more readable. Compare: URLSession.GET(url1).then { URLSession.GET(url2) }.then { URLSession.GET(url3) } With: firstly { URLSession.GET(url1) }.then { URLSession.GET(url2) }.then { URLSession.GET(url3) } */ public func firstly<T>(execute body: () throws -> Promise<T>) -> Promise<T> { return firstly(execute: body) { $0 } } /** Judicious use of `firstly` *may* make chains more readable. Firstly allows to return tuple of promises Compare: when(fulfilled: URLSession.GET(url1), URLSession.GET(url2)).then { URLSession.GET(url3) }.then { URLSession.GET(url4) } With: firstly { (URLSession.GET(url1), URLSession.GET(url2)) }.then { _, _ in URLSession.GET(url2) }.then { URLSession.GET(url3) } - Note: At maximum 5 promises may be returned in a tuple - Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error. */ public func firstly<T, U>(execute body: () throws -> (Promise<T>, Promise<U>)) -> Promise<(T, U)> { return firstly(execute: body) { when(fulfilled: $0.0, $0.1) } } /// Firstly allows to return tuple of promises public func firstly<T, U, V>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>)) -> Promise<(T, U, V)> { return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2) } } /// Firstly allows to return tuple of promises public func firstly<T, U, V, W>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>)) -> Promise<(T, U, V, W)> { return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) } } /// Firstly allows to return tuple of promises public func firstly<T, U, V, W, X>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>, Promise<X>)) -> Promise<(T, U, V, W, X)> { return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) } } /// utility function to serve `firstly` implementations with `body` returning tuple of promises fileprivate func firstly<U, V>(execute body: () throws -> V, when: (V) -> Promise<U>) -> Promise<U> { do { return when(try body()) } catch { return Promise(error: error) } } @available(*, unavailable, message: "instead of returning the error; throw") public func firstly<T: Error>(execute body: () throws -> T) -> Promise<T> { fatalError() } @available(*, unavailable, message: "use DispatchQueue.promise") public func firstly<T>(on: DispatchQueue, execute body: () throws -> Promise<T>) -> Promise<T> { fatalError() } ///** // - SeeAlso: `DispatchQueue.promise(group:qos:flags:execute:)` // */ //@available(*, deprecated: 4.0, renamed: "DispatchQueue.promise") //public func dispatch_promise<T>(_ on: DispatchQueue, _ body: @escaping () throws -> T) -> Promise<T> { // return Promise(value: ()).then(on: on, execute: body) //} /** The underlying resolved state of a promise. - Remark: Same as `Resolution<T>` but without the associated `ErrorConsumptionToken`. */ public enum Result<T> { /// Fulfillment case fulfilled(T) /// Rejection case rejected(Error) init(_ resolution: Resolution<T>) { switch resolution { case .fulfilled(let value): self = .fulfilled(value) case .rejected(let error, _): self = .rejected(error) } } /** - Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`. */ public var boolValue: Bool { switch self { case .fulfilled: return true case .rejected: return false } } } /** An object produced by `Promise.joint()`, along with a promise to which it is bound. Joining with a promise via `Promise.join(_:)` will pipe the resolution of that promise to the joint's bound promise. - SeeAlso: `Promise.joint()` - SeeAlso: `Promise.join(_:)` */ public class PMKJoint<T> { fileprivate var resolve: ((Resolution<T>) -> Void)! } extension Promise { /** Provides a safe way to instantiate a `Promise` and resolve it later via its joint and another promise. class Engine { static func make() -> Promise<Engine> { let (enginePromise, joint) = Promise<Engine>.joint() let cylinder: Cylinder = Cylinder(explodeAction: { // We *could* use an IUO, but there are no guarantees about when // this callback will be called. Having an actual promise is safe. enginePromise.then { engine in engine.checkOilPressure() } }) firstly { Ignition.default.start() }.then { plugs in Engine(cylinders: [cylinder], sparkPlugs: plugs) }.join(joint) return enginePromise } } - Returns: A new promise and its joint. - SeeAlso: `Promise.join(_:)` */ public final class func joint() -> (Promise<T>, PMKJoint<T>) { let pipe = PMKJoint<T>() let promise = Promise(sealant: { pipe.resolve = $0 }) return (promise, pipe) } /** Pipes the value of this promise to the promise created with the joint. - Parameter joint: The joint on which to join. - SeeAlso: `Promise.joint()` */ public func join(_ joint: PMKJoint<T>) { state.pipe(joint.resolve) } } extension Promise where T: Collection { /** Transforms a `Promise` where `T` is a `Collection` into a `Promise<[U]>` URLSession.shared.dataTask(url: /*…*/).asArray().map { result in return download(result) }.then { images in // images is `[UIImage]` } - Parameter on: The queue to which the provided closure dispatches. - Parameter transform: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ public func map<U>(on: DispatchQueue = .default, transform: @escaping (T.Iterator.Element) throws -> Promise<U>) -> Promise<[U]> { return Promise<[U]> { resolve in return state.then(on: zalgo, else: resolve) { tt in when(fulfilled: try tt.map(transform)).state.pipe(resolve) } } } } #if swift(>=3.1) public extension Promise where T == Void { convenience init() { self.init(value: ()) } } #endif
apache-2.0
6e9f585e74405f53372629b0a8839007
38.01548
339
0.624901
4.315015
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
18
3020
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return rxAbstractMethodWithMessage(dataSourceNotSet) } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return rxAbstractMethodWithMessage(dataSourceNotSet) } } // Please take a look at `DelegateProxyType.swift` class RxCollectionViewDataSourceProxy : DelegateProxy , UICollectionViewDataSource , DelegateProxyType { unowned let collectionView: UICollectionView unowned var dataSource: UICollectionViewDataSource = collectionViewDataSourceNotSet required init(parentObject: AnyObject) { self.collectionView = parentObject as! UICollectionView super.init(parentObject: parentObject) } // data source methods func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.collectionView(collectionView, numberOfItemsInSection: section) ?? 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return dataSource.collectionView(collectionView, cellForItemAtIndexPath: indexPath) } // proxy override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> { return _pointer(&dataSourceAssociatedTag) } class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UICollectionView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.dataSource } override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) { let dataSource: UICollectionViewDataSource? = castOptionalOrFatalError(forwardToDelegate) self.dataSource = dataSource ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } }
gpl-3.0
60f9fbf7090fb5c2f1f8a03cd655d32f
38.75
130
0.731126
6.593886
false
false
false
false
IBM-DTeam/swift-for-db2
Tests/IBMDBTests/ConnectTests.swift
1
2417
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest @testable import IBMDB #if os(Linux) import Glibc #else import Darwin #endif class ConnectTests : XCTestCase { static var allTests : [(String, (ConnectTests) -> () throws -> Void)] { return [ ("testConnectValidConfig", testConnectValidConfig), ("testConnectInvalidConfig", testConnectInvalidConfig), ] } let db = IBMDB() let connStringInvalid = "DRIVER={DB2};DATABASE=someDB;UID=someUID;PWD=somePWD;HOSTNAME=someHost;PORT=somePort" func testConnectValidConfig() { var connStringValid: String? = nil if getenv("DB2_CONN_STRING") != nil { connStringValid = String(validatingUTF8: getenv("DB2_CONN_STRING")) } if connStringValid == nil { XCTFail("Environment Variable DB2_CONN_STRING not set.") } let expectation = self.expectation(description: "Attempts to connect to the database and runs the callback closure") db.connect(info: connStringValid!) { (error, connection) -> Void in XCTAssertNil(error, "error is Nil") XCTAssertNotNil(connection, "connection is not Nil") expectation.fulfill() } self.waitForExpectations(timeout: 600) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testConnectInvalidConfig() { let expectation = self.expectation(description: "Attempts to connect to the database and runs the callback closure") db.connect(info: connStringInvalid) { (error, connection) -> Void in XCTAssertNotNil(error, "error is not Nil") XCTAssertNil(connection, "connection is Nil") expectation.fulfill() } self.waitForExpectations(timeout: 600) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } }
apache-2.0
b1a592d34e63bea116bce16600f0af58
27.104651
120
0.696731
4.247803
false
true
false
false
iOSWizards/AwesomeUIMagic
Example/Pods/AwesomeUIMagic/AwesomeUIMagic/Classes/Layer/UIView+Layer.swift
3
1522
// // UIView+Magic.swift // AwesomeUIMagic // // Created by Evandro Harrison Hoffmann on 2/9/18. // import UIKit @IBDesignable extension UIView { // MARK: - Associations private static let borderColorAssociation = ObjectAssociation<NSObject>() private static let borderWidthAssociation = ObjectAssociation<NSObject>() private static let cornerRadiusAssociation = ObjectAssociation<NSObject>() // MARK: - Inspectables @IBInspectable public var borderColor: UIColor { get { return UIView.borderColorAssociation[self] as? UIColor ?? .clear } set (borderColor) { UIView.borderColorAssociation[self] = borderColor as NSObject layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat { get { return UIView.borderWidthAssociation[self] as? CGFloat ?? 0 } set (borderWidth) { UIView.borderWidthAssociation[self] = borderWidth as NSObject layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat { get { return UIView.cornerRadiusAssociation[self] as? CGFloat ?? 0 } set (cornerRadius) { UIView.cornerRadiusAssociation[self] = cornerRadius as NSObject layer.cornerRadius = cornerRadius layer.masksToBounds = true } } }
mit
33c4adba252b9296cd594cbd7c3a4910
25.241379
78
0.606439
5.455197
false
false
false
false
JasdipChauhan/SceneIt
sceneIt-app/SceneIt/ProfileManager.swift
1
1058
// // ProfileManager.swift // SceneIt // // Created by Jasdip Chauhan on 2017-09-01. // Copyright © 2017 Jasdip Chauhan. All rights reserved. // import Foundation public class ProfileManager { private static var profileManager: ProfileManager? = nil public static func getProfileManager() -> ProfileManager { if (profileManager == nil) { profileManager = ProfileManager() } return profileManager! } private var currentUser: User? //PUBLIC METHODS public func setCurrentUser(id: Int, email: String, apiToken: String) { currentUser = User(id: id, email: email, apiToken: apiToken) } public func getCurrentUser() -> User? { return currentUser } //PRIVATE METHODS private init() {} private func isUserValid () -> Bool { guard let user = self.currentUser else { return false } return user.apiToken != nil && user.email != nil && user.id != nil } }
mit
26cd2e298d6a5a8f59859f12a27d2177
21.489362
74
0.586566
4.71875
false
false
false
false