repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
KrishMunot/swift
refs/heads/master
test/ClangModules/CoreServices_test.swift
apache-2.0
6
// RUN: %target-parse-verify-swift %clang-importer-sdk // REQUIRES: objc_interop import CoreServices func test(_ url: CFURL, ident: CSIdentity) { _ = CSBackupIsItemExcluded(url, nil) // okay _ = nil as TypeThatDoesNotExist? // expected-error {{use of undeclared type 'TypeThatDoesNotExist'}} _ = nil as CoreServices.Collection? // okay _ = kCollectionNoAttributes // expected-error{{use of unresolved identifier 'kCollectionNoAttributes'}} var name: Unmanaged<CFString>? = nil _ = LSCopyDisplayNameForURL(url, &name) as OSStatus // okay let unicharArray: [UniChar] = [ 0x61, 0x62, 0x63, 0x2E, 0x64 ] var extIndex: Int = 0 LSGetExtensionInfo(unicharArray.count, unicharArray, &extIndex) // okay _ = CSIdentityCreateCopy(nil, ident) // okay var vers: UInt32 = 0 _ = KCGetKeychainManagerVersion(&vers) as OSStatus// expected-error{{use of unresolved identifier 'KCGetKeychainManagerVersion'}} _ = CoreServices.KCGetKeychainManagerVersion(&vers) as OSStatus// okay }
36c366802acc619237d3068b1b72ce2b
35.962963
131
0.730461
false
false
false
false
Ferrari-lee/firefox-ios
refs/heads/master
Client/Frontend/Reader/ReadabilityService.swift
mpl-2.0
21
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit private let ReadabilityServiceSharedInstance = ReadabilityService() private let ReadabilityTaskDefaultTimeout = 15 private let ReadabilityServiceDefaultConcurrency = 1 enum ReadabilityOperationResult { case Success(ReadabilityResult) case Error(NSError) case Timeout } class ReadabilityOperation: NSOperation, WKNavigationDelegate, ReadabilityBrowserHelperDelegate { var url: NSURL var semaphore: dispatch_semaphore_t var result: ReadabilityOperationResult? var browser: Browser! init(url: NSURL) { self.url = url self.semaphore = dispatch_semaphore_create(0) } override func main() { if self.cancelled { return } // Setup a browser, attach a Readability helper. Kick all this off on the main thread since UIKit // and WebKit are not safe from other threads. dispatch_async(dispatch_get_main_queue(), { () -> Void in let configuration = WKWebViewConfiguration() self.browser = Browser(configuration: configuration) self.browser.createWebview() self.browser.navigationDelegate = self if let readabilityBrowserHelper = ReadabilityBrowserHelper(browser: self.browser) { readabilityBrowserHelper.delegate = self self.browser.addHelper(readabilityBrowserHelper, name: ReadabilityBrowserHelper.name()) } // Load the page in the webview. This either fails with a navigation error, or we get a readability // callback. Or it takes too long, in which case the semaphore times out. self.browser.loadRequest(NSURLRequest(URL: self.url)) }) if dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, Int64(Double(ReadabilityTaskDefaultTimeout) * Double(NSEC_PER_SEC)))) != 0 { result = ReadabilityOperationResult.Timeout } // Maybe this is where we should store stuff in the cache / run a callback? if let result = self.result { switch result { case .Timeout: // Don't do anything on timeout break case .Success(let readabilityResult): do { try ReaderModeCache.sharedInstance.put(url, readabilityResult) } catch let error as NSError { print("Failed to store readability results in the cache: \(error.localizedDescription)") // TODO Fail } case .Error(_): // TODO Not entitely sure what to do on error. Needs UX discussion and followup bug. break } } } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult readabilityResult: ReadabilityResult) { result = ReadabilityOperationResult.Success(readabilityResult) dispatch_semaphore_signal(semaphore) } } class ReadabilityService { class var sharedInstance: ReadabilityService { return ReadabilityServiceSharedInstance } var queue: NSOperationQueue init() { queue = NSOperationQueue() queue.maxConcurrentOperationCount = ReadabilityServiceDefaultConcurrency } func process(url: NSURL) { queue.addOperation(ReadabilityOperation(url: url)) } }
0739616b947ca578649f68db78ddd5d7
36.081818
156
0.667729
false
false
false
false
mitchtreece/Bulletin
refs/heads/master
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UIAnimation/UIAnimationGroup.swift
mit
1
// // UIAnimationGroup.swift // Espresso // // Created by Mitch Treece on 6/30/18. // import UIKit /** `UIAnimationGroup` is a container over a set of animations. Animations can be _chained_ to a group by using the `then()` function. ``` let view = UIView() view.frame = CGRect(x: 0, y: 0, width: 50, height: 50) view.alpha = 0 ... UIAnimation { view.alpha = 1 }.then { view.frame = CGRect(x: 0, y: 0, width: 100, height: 100) }.run() ``` */ public class UIAnimationGroup { internal private(set) var _animations: [UIAnimation] internal init(animations: [UIAnimation]) { self._animations = animations } /** Chains a new animation to the group with the specified parameters. - Parameter timingCurve: The animation's timing curve; _defaults to simple(easeInOut)_. - Parameter duration: The animation's duration; _defaults to 0.6_. - Parameter delay: The animation's start delay; _defaults to 0_. - Parameter animations: The animation block. - Returns: A `UIAnimationGroup` by appending the new animation. */ public func then(_ timingCurve: UIAnimation.TimingCurve = .simple(.easeInOut), duration: TimeInterval = 0.6, delay: TimeInterval = 0, _ animations: @escaping UIAnimationBlock) -> UIAnimationGroup { let animation = UIAnimation(timingCurve, duration: duration, delay: delay, animations) self._animations.append(animation) return self } /** Starts the group's animations. - Parameter completion: An optional completion handler; _defaults to nil_. */ public func run(completion: UIAnimationCompletion? = nil) { self._animations.run(completion: completion) } }
3a6897dde8c69d7d93c3a7498c3a971d
27.246154
94
0.626906
false
false
false
false
pahnev/Swift-tutorials
refs/heads/master
Stormy/Stormy/ViewController.swift
mit
1
// // ViewController.swift // Stormy // // Created by Kirill on 1/12/15. // Copyright (c) 2015 Kirill Pahnev. All rights reserved. // import UIKit class ViewController: UIViewController { // FIXME: Get our own key at http://developer.forecast.io/ !! private let apiKey = "XXXXXXXX" @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var precipitationLabel: UILabel! @IBOutlet weak var summaryLabel: UILabel! @IBOutlet weak var refreshButton: UIButton! @IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refreshActivityIndicator.hidden = true getCurrentWeatherData() } func getCurrentWeatherData() -> Void { let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/") let forecastURL = NSURL(string:"37.8267,-122.423", relativeToURL: baseURL) let sharedSession = NSURLSession.sharedSession() let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in if (error == nil) { let dataObject = NSData(contentsOfURL: location, options: nil, error: nil) let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary let currentWeather = Current(weatherDictionary: weatherDictionary) println(currentWeather.temperature) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.iconView.image = currentWeather.icon! // This is optional so we need to unwrap it self.temperatureLabel.text = "\(currentWeather.temperature)" self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is" // This is optional so we need to unwrap it self.humidityLabel.text = "\(currentWeather.humidity)" self.precipitationLabel.text = "\(currentWeather.precipProbability)" self.summaryLabel.text = "(currentWeather.summary)" }) } else { let networkIssueController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil) networkIssueController.addAction(okButton) let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) networkIssueController.addAction(cancelButton) self.presentViewController(networkIssueController, animated: true, completion: nil) } dispatch_async(dispatch_get_main_queue(), { () -> Void in //Stop refresh animation self.refreshActivityIndicator.stopAnimating() self.refreshActivityIndicator.hidden = true self.refreshButton.hidden = false }) }) downloadTask.resume() } @IBAction func refresh() { getCurrentWeatherData() refreshButton.hidden = true refreshActivityIndicator.hidden = false refreshActivityIndicator.startAnimating() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a706a9249bafa95bc3a7c9647ba80919
39.204082
194
0.62132
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/private/StdlibUnittest/RaceTest.swift
apache-2.0
5
//===--- RaceTest.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This file implements support for race tests. /// /// Race test harness executes the given operation in multiple threads over a /// set of shared data, trying to ensure that executions overlap in time. /// /// The name "race test" does not imply that the race actually happens in the /// harness or in the operation being tested. The harness contains all the /// necessary synchronization for its own data, and for publishing test data to /// threads. But if the operation under test is, in fact, racy, it should be /// easier to discover the bug in this environment. /// /// Every execution of a race test is called a trial. During a single trial /// the operation under test is executed multiple times in each thread over /// different data items (`RaceData` instances). Different threads process /// data in different order. Choosing an appropriate balance between the /// number of threads and data items, the harness uses the birthday paradox to /// increase the probability of "collisions" between threads. /// /// After performing the operation under test, the thread should observe the /// data in a test-dependent way to detect if presence of other concurrent /// actions disturbed the result. The observation should be as short as /// possible, and the results should be returned as `Observation`. Evaluation /// (cross-checking) of observations is deferred until the end of the trial. /// //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivateLibcExtras import SwiftPrivateThreadExtras #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #elseif os(WASI) import WASILibc #elseif os(Windows) import CRT import WinSDK #endif #if _runtime(_ObjC) import ObjectiveC #else func autoreleasepool(invoking code: () -> Void) { // Native runtime does not have autorelease pools. Execute the code // directly. code() } #endif /// Race tests that need a fresh set of data for every trial should implement /// this protocol. /// /// All racing threads execute the same operation, `thread1`. /// /// Types conforming to this protocol should be structs. (The type /// should be a struct to reduce unnecessary reference counting during /// the test.) The types should be stateless. public protocol RaceTestWithPerTrialData { /// Input for threads. /// /// This type should be a class. (The harness will not pass struct instances /// between threads correctly.) associatedtype RaceData : AnyObject /// Type of thread-local data. /// /// Thread-local data is newly created for every trial. associatedtype ThreadLocalData /// Results of the observation made after performing an operation. associatedtype Observation init() /// Creates a fresh instance of `RaceData`. func makeRaceData() -> RaceData /// Creates a fresh instance of `ThreadLocalData`. func makeThreadLocalData() -> ThreadLocalData /// Performs the operation under test and makes an observation. func thread1( _ raceData: RaceData, _ threadLocalData: inout ThreadLocalData) -> Observation /// Evaluates the observations made by all threads for a particular instance /// of `RaceData`. func evaluateObservations( _ observations: [Observation], _ sink: (RaceTestObservationEvaluation) -> Void) } /// The result of evaluating observations. /// /// Case payloads can carry test-specific data. Results will be grouped /// according to it. public enum RaceTestObservationEvaluation : Equatable, CustomStringConvertible { /// Normal 'pass'. case pass /// An unusual 'pass'. case passInteresting(String) /// A failure. case failure case failureInteresting(String) public var description: String { switch self { case .pass: return "Pass" case .passInteresting(let s): return "Pass(\(s))" case .failure: return "Failure" case .failureInteresting(let s): return "Failure(\(s))" } } } public func == ( lhs: RaceTestObservationEvaluation, rhs: RaceTestObservationEvaluation ) -> Bool { switch (lhs, rhs) { case (.pass, .pass), (.failure, .failure): return true case (.passInteresting(let s1), .passInteresting(let s2)): return s1 == s2 default: return false } } /// An observation result that consists of one `UInt`. public struct Observation1UInt : Equatable, CustomStringConvertible { public var data1: UInt public init(_ data1: UInt) { self.data1 = data1 } public var description: String { return "(\(data1))" } } public func == (lhs: Observation1UInt, rhs: Observation1UInt) -> Bool { return lhs.data1 == rhs.data1 } /// An observation result that consists of four `UInt`s. public struct Observation4UInt : Equatable, CustomStringConvertible { public var data1: UInt public var data2: UInt public var data3: UInt public var data4: UInt public init(_ data1: UInt, _ data2: UInt, _ data3: UInt, _ data4: UInt) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4))" } } public func == (lhs: Observation4UInt, rhs: Observation4UInt) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 } /// An observation result that consists of three `Int`s. public struct Observation3Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public init(_ data1: Int, _ data2: Int, _ data3: Int) { self.data1 = data1 self.data2 = data2 self.data3 = data3 } public var description: String { return "(\(data1), \(data2), \(data3))" } } public func == (lhs: Observation3Int, rhs: Observation3Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 } /// An observation result that consists of four `Int`s. public struct Observation4Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public init(_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4))" } } public func == (lhs: Observation4Int, rhs: Observation4Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 } /// An observation result that consists of five `Int`s. public struct Observation5Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public var data5: Int public init( _ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int ) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 self.data5 = data5 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4), \(data5))" } } public func == (lhs: Observation5Int, rhs: Observation5Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 && lhs.data5 == rhs.data5 } /// An observation result that consists of nine `Int`s. public struct Observation9Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public var data5: Int public var data6: Int public var data7: Int public var data8: Int public var data9: Int public init( _ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int, _ data6: Int, _ data7: Int, _ data8: Int, _ data9: Int ) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 self.data5 = data5 self.data6 = data6 self.data7 = data7 self.data8 = data8 self.data9 = data9 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4), \(data5), \(data6), \(data7), \(data8), \(data9))" } } public func == (lhs: Observation9Int, rhs: Observation9Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 && lhs.data5 == rhs.data5 && lhs.data6 == rhs.data6 && lhs.data7 == rhs.data7 && lhs.data8 == rhs.data8 && lhs.data9 == rhs.data9 } /// A helper that is useful to implement /// `RaceTestWithPerTrialData.evaluateObservations()` in race tests. public func evaluateObservationsAllEqual<T : Equatable>(_ observations: [T]) -> RaceTestObservationEvaluation { let first = observations.first! for x in observations { if x != first { return .failure } } return .pass } // WebAssembly/WASI doesn't support multi-threading yet #if os(WASI) public func runRaceTest<RT : RaceTestWithPerTrialData>( _: RT.Type, trials: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil ) {} public func runRaceTest<RT : RaceTestWithPerTrialData>( _ test: RT.Type, operations: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil ) {} public func consumeCPU(units amountOfWork: Int) {} public func runRaceTest( trials: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil, invoking body: @escaping () -> Void ) {} public func runRaceTest( operations: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil, invoking body: @escaping () -> Void ) {} #else struct _RaceTestAggregatedEvaluations : CustomStringConvertible { var passCount: Int = 0 var passInterestingCount = [String: Int]() var failureCount: Int = 0 var failureInterestingCount = [String: Int]() init() {} mutating func addEvaluation(_ evaluation: RaceTestObservationEvaluation) { switch evaluation { case .pass: passCount += 1 case .passInteresting(let s): if passInterestingCount[s] == nil { passInterestingCount[s] = 0 } passInterestingCount[s] = passInterestingCount[s]! + 1 case .failure: failureCount += 1 case .failureInteresting(let s): if failureInterestingCount[s] == nil { failureInterestingCount[s] = 0 } failureInterestingCount[s] = failureInterestingCount[s]! + 1 } } var isFailed: Bool { return failureCount != 0 || !failureInterestingCount.isEmpty } var description: String { var result = "" result += "Pass: \(passCount) times\n" for desc in passInterestingCount.keys.sorted() { let count = passInterestingCount[desc]! result += "Pass \(desc): \(count) times\n" } result += "Failure: \(failureCount) times\n" for desc in failureInterestingCount.keys.sorted() { let count = failureInterestingCount[desc]! result += "Failure \(desc): \(count) times\n" } return result } } // FIXME: protect this class against false sharing. class _RaceTestWorkerState<RT : RaceTestWithPerTrialData> { // FIXME: protect every element of 'raceData' against false sharing. var raceData: [RT.RaceData] = [] var raceDataShuffle: [Int] = [] var observations: [RT.Observation] = [] } class _RaceTestSharedState<RT : RaceTestWithPerTrialData> { var racingThreadCount: Int var stopNow = _stdlib_AtomicInt(0) var trialBarrier: _stdlib_Barrier var trialSpinBarrier = _stdlib_AtomicInt() var raceData: [RT.RaceData] = [] var workerStates: [_RaceTestWorkerState<RT>] = [] var aggregatedEvaluations: _RaceTestAggregatedEvaluations = _RaceTestAggregatedEvaluations() init(racingThreadCount: Int) { self.racingThreadCount = racingThreadCount self.trialBarrier = _stdlib_Barrier(threadCount: racingThreadCount + 1) self.workerStates.reserveCapacity(racingThreadCount) for _ in 0..<racingThreadCount { self.workerStates.append(_RaceTestWorkerState<RT>()) } } } func _masterThreadStopWorkers<RT>( _ sharedState: _RaceTestSharedState<RT>) { // Workers are proceeding to the first barrier in _workerThreadOneTrial. sharedState.stopNow.store(1) // Allow workers to proceed past that first barrier. They will then see // stopNow==true and stop. sharedState.trialBarrier.wait() } func _masterThreadOneTrial<RT>(_ sharedState: _RaceTestSharedState<RT>) { let racingThreadCount = sharedState.racingThreadCount let raceDataCount = racingThreadCount * racingThreadCount let rt = RT() sharedState.raceData.removeAll(keepingCapacity: true) sharedState.raceData.append(contentsOf: (0..<raceDataCount).lazy.map { _ in rt.makeRaceData() }) let identityShuffle = Array(0..<sharedState.raceData.count) sharedState.workerStates.removeAll(keepingCapacity: true) sharedState.workerStates.append(contentsOf: (0..<racingThreadCount).lazy.map { _ in let workerState = _RaceTestWorkerState<RT>() // Shuffle the data so that threads process it in different order. let shuffle = identityShuffle.shuffled() workerState.raceData = scatter(sharedState.raceData, shuffle) workerState.raceDataShuffle = shuffle workerState.observations = [] workerState.observations.reserveCapacity(sharedState.raceData.count) return workerState }) sharedState.trialSpinBarrier.store(0) sharedState.trialBarrier.wait() // Race happens. sharedState.trialBarrier.wait() // Collect and compare results. for i in 0..<racingThreadCount { let shuffle = sharedState.workerStates[i].raceDataShuffle sharedState.workerStates[i].raceData = gather(sharedState.workerStates[i].raceData, shuffle) sharedState.workerStates[i].observations = gather(sharedState.workerStates[i].observations, shuffle) } if true { // FIXME: why doesn't the bracket syntax work? // <rdar://problem/18305718> Array sugar syntax does not work when used // with associated types var observations: [RT.Observation] = [] observations.reserveCapacity(racingThreadCount) for i in 0..<raceDataCount { for j in 0..<racingThreadCount { observations.append(sharedState.workerStates[j].observations[i]) } let sink = { sharedState.aggregatedEvaluations.addEvaluation($0) } rt.evaluateObservations(observations, sink) observations.removeAll(keepingCapacity: true) } } } func _workerThreadOneTrial<RT>( _ tid: Int, _ sharedState: _RaceTestSharedState<RT> ) -> Bool { sharedState.trialBarrier.wait() if sharedState.stopNow.load() == 1 { return true } let racingThreadCount = sharedState.racingThreadCount let workerState = sharedState.workerStates[tid] let rt = RT() var threadLocalData = rt.makeThreadLocalData() do { let trialSpinBarrier = sharedState.trialSpinBarrier _ = trialSpinBarrier.fetchAndAdd(1) while trialSpinBarrier.load() < racingThreadCount {} } // Perform racy operations. // Warning: do not add any synchronization in this loop, including // any implicit reference counting of shared data. for raceData in workerState.raceData { workerState.observations.append(rt.thread1(raceData, &threadLocalData)) } sharedState.trialBarrier.wait() return false } /// One-shot sleep in one thread, allowing interrupt by another. #if os(Windows) class _InterruptibleSleep { let event: HANDLE? var completed: Bool = false init() { self.event = CreateEventW(nil, true, false, nil) precondition(self.event != nil) } deinit { CloseHandle(self.event) } func sleep(durationInSeconds duration: Int) { guard completed == false else { return } let result: DWORD = WaitForSingleObject(event, DWORD(duration * 1000)) precondition(result == WAIT_OBJECT_0) completed = true } func wake() { guard completed == false else { return } let result: Bool = SetEvent(self.event) precondition(result == true) } } #else class _InterruptibleSleep { let writeEnd: CInt let readEnd: CInt var completed = false init() { (readEnd: readEnd, writeEnd: writeEnd, _) = _stdlib_pipe() } deinit { close(readEnd) close(writeEnd) } /// Sleep for durationInSeconds or until another /// thread calls wake(), whichever comes first. func sleep(durationInSeconds duration: Int) { if completed { return } // WebAssembly/WASI on wasm32 is the only 32-bit platform with Int64 time_t, // needs an explicit conversion to `time_t` because of this. var timeout = timeval(tv_sec: time_t(duration), tv_usec: 0) var readFDs = _stdlib_fd_set() var writeFDs = _stdlib_fd_set() var errorFDs = _stdlib_fd_set() readFDs.set(readEnd) let ret = _stdlib_select(&readFDs, &writeFDs, &errorFDs, &timeout) precondition(ret >= 0) completed = true } /// Wake the thread in sleep(). func wake() { if completed { return } let buffer: [UInt8] = [1] let ret = write(writeEnd, buffer, 1) precondition(ret >= 0) } } #endif public func runRaceTest<RT : RaceTestWithPerTrialData>( _: RT.Type, trials: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil ) { let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency()) let sharedState = _RaceTestSharedState<RT>(racingThreadCount: racingThreadCount) // Alarm thread sets timeoutReached. // Master thread sees timeoutReached and tells worker threads to stop. let timeoutReached = _stdlib_AtomicInt(0) let alarmTimer = _InterruptibleSleep() let masterThreadBody = { () -> Void in for t in 0..<trials { // Check for timeout. // _masterThreadStopWorkers must run BEFORE the last _masterThreadOneTrial // to make the thread coordination barriers work // but we do want to run at least one trial even if the timeout occurs. if timeoutReached.load() == 1 && t > 0 { _masterThreadStopWorkers(sharedState) break } autoreleasepool { _masterThreadOneTrial(sharedState) } } } let racingThreadBody = { (tid: Int) -> Void in for _ in 0..<trials { let stopNow = _workerThreadOneTrial(tid, sharedState) if stopNow { break } } } let alarmThreadBody = { () -> Void in guard let timeoutInSeconds = timeoutInSeconds else { return } alarmTimer.sleep(durationInSeconds: timeoutInSeconds) _ = timeoutReached.fetchAndAdd(1) } var testTids = [ThreadHandle]() var alarmTid: ThreadHandle // Create the master thread. do { let (ret, tid) = _stdlib_thread_create_block(masterThreadBody, ()) expectEqual(0, ret) testTids.append(tid!) } // Create racing threads. for i in 0..<racingThreadCount { let (ret, tid) = _stdlib_thread_create_block(racingThreadBody, i) expectEqual(0, ret) testTids.append(tid!) } // Create the alarm thread that enforces the timeout. do { let (ret, tid) = _stdlib_thread_create_block(alarmThreadBody, ()) expectEqual(0, ret) alarmTid = tid! } // Join all testing threads. for tid in testTids { let (ret, _) = _stdlib_thread_join(tid, Void.self) expectEqual(0, ret) } // Tell the alarm thread to stop if it hasn't already, then join it. do { alarmTimer.wake() let (ret, _) = _stdlib_thread_join(alarmTid, Void.self) expectEqual(0, ret) } let aggregatedEvaluations = sharedState.aggregatedEvaluations expectFalse(aggregatedEvaluations.isFailed) print(aggregatedEvaluations) } internal func _divideRoundUp(_ lhs: Int, _ rhs: Int) -> Int { return (lhs + rhs) / rhs } public func runRaceTest<RT : RaceTestWithPerTrialData>( _ test: RT.Type, operations: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil ) { let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency()) // Each trial runs threads^2 operations. let operationsPerTrial = racingThreadCount * racingThreadCount let trials = _divideRoundUp(operations, operationsPerTrial) runRaceTest(test, trials: trials, timeoutInSeconds: timeoutInSeconds, threads: threads) } public func consumeCPU(units amountOfWork: Int) { for _ in 0..<amountOfWork { let scale = 16 for _ in 0..<scale { _blackHole(42) } } } internal struct ClosureBasedRaceTest : RaceTestWithPerTrialData { static var thread: () -> Void = {} class RaceData {} typealias ThreadLocalData = Void typealias Observation = Void func makeRaceData() -> RaceData { return RaceData() } func makeThreadLocalData() -> Void { return Void() } func thread1( _ raceData: RaceData, _ threadLocalData: inout ThreadLocalData ) { ClosureBasedRaceTest.thread() } func evaluateObservations( _ observations: [Observation], _ sink: (RaceTestObservationEvaluation) -> Void ) {} } public func runRaceTest( trials: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil, invoking body: @escaping () -> Void ) { ClosureBasedRaceTest.thread = body runRaceTest(ClosureBasedRaceTest.self, trials: trials, timeoutInSeconds: timeoutInSeconds, threads: threads) } public func runRaceTest( operations: Int, timeoutInSeconds: Int? = nil, threads: Int? = nil, invoking body: @escaping () -> Void ) { ClosureBasedRaceTest.thread = body runRaceTest(ClosureBasedRaceTest.self, operations: operations, timeoutInSeconds: timeoutInSeconds, threads: threads) } #endif // os(WASI)
80a739e7a2b4d4dda540d80eb220afec
27.077707
103
0.680731
false
true
false
false
xiawuacha/DouYuzhibo
refs/heads/master
DouYuzhibo/DouYuzhibo/Classses/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // DouYuzhibo // // Created by 汪凯 on 16/10/22. // Copyright © 2016年 汪凯. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = {[weak self] in // 1.确定内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) childVcs.append(GameViewController()) childVcs.append(AmuseViewController()) childVcs.append(funnyViewController()) let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self return contentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() } } // MARK:- 设置UI界面 extension HomeViewController { fileprivate func setupUI() { // 0.不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false // 1.设置导航栏 setupNavigationBar() // 2.添加TitleView view.addSubview(pageTitleView) // 3.添加ContentView view.addSubview(pageContentView) } fileprivate func setupNavigationBar() { // 1.设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2.设置右侧的Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate { func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(index) } } // MARK:- 遵守PageContentViewDelegate协议 extension HomeViewController : PageContentViewDelegate { func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
b5124e9ba46206d3845487c19c66710d
32.368421
125
0.664353
false
false
false
false
petrone/PetroneAPI_swift
refs/heads/master
PetroneAPI/Packets/PetronePacketResetHeading.swift
mit
1
// // PetronePacketResetHeading.swift // Petrone // // Created by Byrobot on 2017. 8. 7.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation class PetronePacketResetHeading : PetronePacketLedCommand { override init() { super.init() lightMode = PetroneLigthMode.ArmFlickerDouble lightColor = PetroneColors.Violet interval = 200 repeatCount = 2 command = PetroneCommand.ResetHeading } }
04f04c038d5f6c93c3302ffe5ca37acc
22.4
59
0.673077
false
false
false
false
SwiftKitz/Datez
refs/heads/master
Sources/Datez/Entity/DateView.swift
mit
1
// // Date.swift // Prayerz // // Created by Mazyad Alabduljaleel on 9/16/15. // Copyright (c) 2015 ArabianDevs. All rights reserved. // import Foundation /** A date associated with an `Calendar` */ public struct DateView: Equatable { // MARK: - Properties public let date: Date public let calendar: Calendar public var components: CalendarComponents { return calendar.dateComponents( Calendar.Component.all, from: date ).calendarComponents } // MARK: - Init & Dealloc public init(forDate date: Date, inCalendar calendar: Calendar) { self.calendar = calendar self.date = date } public init(forCalendarComponents calendarComponents: CalendarComponents, inCalendar calendar: Calendar) { self.init( forDate: calendar.date(from: calendarComponents.dateComponents)!, inCalendar: calendar ) } // MARK: - Public methods public func update( year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil ) -> DateView { let comps = components.update(year: year, month: month, day: day, hour: hour, minute: minute, second: second) return DateView(forCalendarComponents: comps, inCalendar: calendar) } }
442ea17f365e0ed13d0424b844df5c90
24.035088
117
0.594954
false
false
false
false
nghiaphunguyen/NKit
refs/heads/master
NKit/Source/Layout/OAStackView/OAStackView+NKit.swift
mit
1
// // OAStackView+NKit.swift // NKit // // Created by Nghia Nguyen on 3/13/17. // Copyright © 2017 Nghia Nguyen. All rights reserved. // import UIKit import OAStackView public extension OAStackView { @discardableResult public func nk_addArrangedSubview<T: UIView>(_ view: T, config: ((T) -> Void)? = nil) -> Self { self.addArrangedSubview(view) config?(view) return self } @discardableResult public static func nk_create(_ distribution: OAStackViewDistribution = .fill, alignment: OAStackViewAlignment = .fill, spacing: CGFloat = 0, axis: NSLayoutConstraint.Axis = .vertical) -> Self { let stackView = self.init() stackView.alignment = alignment stackView.distribution = distribution stackView.spacing = spacing stackView.axis = axis return stackView } @discardableResult public static func nk_row(_ distribution: OAStackViewDistribution = .fill, alignment: OAStackViewAlignment = .fill, spacing: CGFloat = 0) -> Self { return self.nk_create(distribution, alignment: alignment, spacing: spacing, axis: .horizontal) } @discardableResult public static func nk_column(_ distribution: OAStackViewDistribution = .fill, alignment: OAStackViewAlignment = .fill, spacing: CGFloat = 0) -> Self { return self.nk_create(distribution, alignment: alignment, spacing: spacing, axis: .vertical) } }
0ae96bfae664a37309a4570ccdf3dcfe
39.714286
216
0.688421
false
true
false
false
frodoking/GithubIOSClient
refs/heads/master
Github/Core/Module/Users/UsersViewModule.swift
apache-2.0
1
// // UserRankViewModule.swift // Github // // Created by frodo on 15/10/23. // Copyright © 2015年 frodo. All rights reserved. // import Foundation import Alamofire import SwiftyJSON public class UsersViewModule { var dataSource = DataSource() var totalCount: Int = 0 public func loadDataFromApiWithIsFirst(isFirst: Bool, location: String, language: String, handler: (users: NSArray) -> Void) { var q: String = "" var page:Int = 0 if (isFirst) { page = 1; } else { page = dataSource.page!+1; } if !language.isEmpty && !location.isEmpty { q = "location:\(location)+language:\(language)" } else if language.isEmpty && !location.isEmpty { q = "location:\(location)" } else if !language.isEmpty && location.isEmpty { q = "language:\(language)" } Server.shareInstance.searchUsersWithPage(page, q: q, sort: "followers", location: location, language: language, completoinHandler: { (users, page, totalCount) -> Void in if (page <= 1) { self.dataSource.reset() } self.dataSource.page = page self.totalCount = totalCount self.dataSource.dsArray?.addObjectsFromArray(users) handler(users: self.dataSource.dsArray!) }, errorHandler: { (errors) -> Void in // do nothing handler(users: NSArray()) }) } }
e0a569f933cf582fce20e4f415efbb7b
29.9
177
0.556995
false
false
false
false
hw3308/Swift3Basics
refs/heads/master
Swift3Basics/DataBase/RealmManager.swift
mit
2
// // RealmManager.swift // SwiftBasics // // Created by 侯伟 on 17/1/11. // Copyright © 2017年 侯伟. All rights reserved. // import Foundation import Realm import RealmSwift extension Realm { public static let rootPath = (Realm.Configuration.defaultConfiguration.fileURL!.path as NSString).deletingLastPathComponent //MARK:share fileprivate static var _sharedRealm: Realm! public static var sharedRealm: Realm { if _sharedRealm == nil { _sharedRealm = try! Realm(fileURL: NSURL(string:"\(rootPath)/shared.realm")! as URL) } return _sharedRealm } public static func setSharedRealm(_ realm: Realm) { _sharedRealm = realm } //MAKR:user fileprivate static var _userRealm: Realm! public static var userRealm: Realm { if _userRealm == nil { return Realm.sharedRealm } return _userRealm } public static func setUserRealm(_ realm: Realm) { _userRealm = realm } public static func setUerRealmWithString(_ idOrName:String){ _userRealm = try! Realm(fileURL: NSURL(string:"\(rootPath)/\(idOrName).realm")! as URL) } public static func resetUserRealm() { _userRealm = nil } }
6e3eed01c80c6aa6b379a917d48f82c3
22
127
0.607933
false
false
false
false
emaloney/CleanroomDateTime
refs/heads/master
Sources/Formatter.swift
mit
1
// // Formatter.swift // CleanroomDateTime // // Created by Nikita Korchagin on 22/09/2017. // Copyright © 2017 Gilt Groupe. All rights reserved. // import Foundation /** Formatters are expinsive to create. It's important to not unnecessarily create and destroy formatters that you're likely to need again. In WWDC 2012 video, iOS App Performance: Responsiveness, https://developer.apple.com/videos/wwdc/2012/?id=235 Apple explicitly encourages us to: - Cache one formatter per date format; - Add observer for NSLocale.currentLocaleDidChangeNotification through the NSNotificationCenter, and clearing resetting cached formatters if this occurs; - resetting a format is as expensive as recreating, so avoid repeatedly changing a formatter's format string. Bottom line, reuse date formatters wherever possible if you're using the same date format repeatedly. */ extension Date { public struct Formatter { //MARK: Fixed-format dates /** If using NSDateFormatter to parse date strings to be exchanged with a web service (or stored in a database), you should use en_US_POSIX locale to avoid problems with international users who might not be using Gregorian calendars. See Apple Technical Q&A #1480. https://developer.apple.com/library/content/qa/qa1480/_index.html */ private static func fixedDateFormatter(format: StandardDateFormat) -> DateFormatter { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = format.rawValue return formatter } public static let iso8601Date: DateFormatter = { return fixedDateFormatter(format: .iso8601Date) }() public static let iso8601DateTime: DateFormatter = { return fixedDateFormatter(format: .iso8601DateTime) }() public static let iso8601DateTimeMillis: DateFormatter = { return fixedDateFormatter(format: .iso8601DateTimeMillis) }() public static let rfc1123: DateFormatter = { return fixedDateFormatter(format: .rfc1123) }() } }
bba9a8882a640a746ac5c46d188fa5ed
35.734375
102
0.684815
false
false
false
false
hucool/XMImagePicker
refs/heads/master
Example/PROJECT/ViewController.swift
mit
1
// // ViewController.swift // PROJECT // // Created by PROJECT_OWNER on TODAYS_DATE. // Copyright (c) TODAYS_YEAR PROJECT_OWNER. All rights reserved. // import UIKit import XMImagePicker class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton() button.backgroundColor = .red button.frame = CGRect(x: 100, y: 100, width: 100, height: 100) button.addTarget(self, action: #selector(pushController), for: .touchUpInside) view.addSubview(button) } func pushController() { let nv = XMImagePickerController() nv.config = XMImagePickerOptions(imageLimit: 2) nv.config.isMarkImageURL = true nv.setFinishPickingHandle { (photos) in let images = photos.flatMap{ $0.original.image } print(images) } present(nv, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e8934f6d9fb9238f9eda753bb9483bea
25.5
86
0.632525
false
false
false
false
jopamer/swift
refs/heads/master
test/SILOptimizer/access_enforcement_selection.swift
apache-2.0
2
// RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s -Xllvm -debug-only=access-enforcement-selection -swift-version 3 2>&1 | %FileCheck %s // REQUIRES: asserts // This is a source-level test because it helps bring up the entire -Onone pipeline with the access markers. public func takesInout(_ i: inout Int) { i = 42 } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection10takesInoutyySizF // CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int // Helper taking a basic, no-escape closure. func takeClosure(_: ()->Int) {} // Helper taking a basic, no-escape closure. func takeClosureAndInout(_: inout Int, _: ()->Int) {} // Helper taking an escaping closure. func takeEscapingClosure(_: @escaping ()->Int) {} // Generate an alloc_stack that escapes into a closure. public func captureStack() -> Int { // Use a `var` so `x` isn't treated as a literal. var x = 3 takeClosure { return x } return x } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection12captureStackSiyF // Dynamic access for `return x`. Since the closure is non-escaping, using // dynamic enforcement here is more conservative than it needs to be -- static // is sufficient here. // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection12captureStackSiyFSiyXEfU_ // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // Generate an alloc_stack that does not escape into a closure. public func nocaptureStack() -> Int { var x = 3 takeClosure { return 5 } return x } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14nocaptureStackSiyF // Static access for `return x`. // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14nocaptureStackSiyFSiyXEfU_ // Generate an alloc_stack that escapes into a closure while an access is // in progress. public func captureStackWithInoutInProgress() -> Int { // Use a `var` so `x` isn't treated as a literal. var x = 3 takeClosureAndInout(&x) { return x } return x } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection31captureStackWithInoutInProgressSiyF // Static access for `&x`. // CHECK-DAG: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int // Static access for `return x`. // CHECK-DAG: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection31captureStackWithInoutInProgressSiyFSiyXEfU_ // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // Generate an alloc_box that escapes into a closure. // FIXME: `x` is eventually promoted to an alloc_stack even though it has dynamic enforcement. // We should ensure that alloc_stack variables are statically enforced. public func captureBox() -> Int { var x = 3 takeEscapingClosure { x = 4; return x } return x } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection10captureBoxSiyF // Dynamic access for `return x`. // CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int // CHECK-LABEL: $S28access_enforcement_selection10captureBoxSiyFSiycfU_ // Generate a closure in which the @inout_aliasing argument // escapes to an @inout function `bar`. public func recaptureStack() -> Int { var x = 3 takeClosure { takesInout(&x); return x } return x } // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14recaptureStackSiyF // // Static access for `return x`. // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14recaptureStackSiyFSiyXEfU_ // // The first [modify] access inside the closure is static. It enforces the // @inout argument. // CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int // // The second [read] access is static. Same as `captureStack` above. // // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
cd0af252f4e60c4af9d66b1edafe97af
42.37
183
0.703712
false
false
false
false
jorgeluis11/EmbalsesPR
refs/heads/master
Embalses/DetailViewController.swift
mit
1
// // ViewController.swift // Embalses // // Created by Jorge Perez on 9/28/15. // Copyright © 2015 Jorge Perez. All rights reserved. // import UIKit import Kanna import Charts class DetailViewController: UIViewController { @IBOutlet var barChartView: BarChartView! var county:String? var date:String? var meters:String? var niveles:[Double]? @IBOutlet var labelWater: UILabel! var chartData = [899.56] @IBOutlet var navigationBar: UINavigationBar! @IBAction func backButton(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) print("Sdf") } func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .TopAttached } override func unwindForSegue(unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) { } override func viewDidLoad() { super.viewDidLoad() // navigationBar.ba = backButton let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0] setChart(months, values: unitsSold) } func setChart(dataPoints: [String], values: [Double]) { barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0) if let niveles = niveles{ var ll = ChartLimitLine(limit: niveles[0], label: "Desborde") // ll.setLineColor(Color.RED); // // // ll.setLineWidth(4f); // ll.setTextColor(Color.BLACK); // ll.setTextSize(12f); barChartView.rightAxis.addLimitLine(ll) barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[1], label: "Seguridad")) barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[2], label: "Obervación")) barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[3], label: "Ajustes Operacionales")) barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[4], label: "Control")) // var xAxis:ChartYAxis = barChartView.getAxis(ChartYAxis(position: 34.34)) // LimitLine ll = new LimitLine(140f, "Critical Blood Pressure"); // ll.setLineColor(Color.RED); // ll.setLineWidth(4f); // ll.setTextColor(Color.BLACK); // ll.setTextSize(12f); // .. and more styling options // // leftAxis.addLimitLine(ll); } barChartView.noDataText = "You need to provide data for the chart." let meterDouble:Double = Double(self.meters!)! let dataEntries: [BarChartDataEntry] = [BarChartDataEntry(value: meterDouble, xIndex: 0)] let dataPoints2 = [self.county] let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Agua en Metros") let chartData = BarChartData(xVals: dataPoints2, dataSet: chartDataSet) barChartView.data = chartData } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { var newFrame:CGRect = labelWater.frame; newFrame.origin.y = newFrame.origin.y - 615; // newFrame.size.height = 181; newFrame.size.height = 665; UIView.animateWithDuration(3, animations: { self.labelWater.frame = newFrame }) } }
000727bcc43f6c33f0a60dfe24f17f39
31.367521
120
0.589385
false
false
false
false
pointfreeco/swift-web
refs/heads/main
Sources/HtmlPlainTextPrint/HtmlPlainTextPrint.swift
mit
1
import Foundation import Html import Prelude /// Naive transformation of HTML nodes into plain text. public func plainText(for nodes: [Node]) -> String { return nodes.map(plainText(for:)).joined() } /// Naive transformation of an HTML into plain text. public func plainText(for node: Node) -> String { switch node { case .comment, .doctype: return "" case let .element(tag, attributes, child): guard attributes .first(where: { $0.key == "style" })? .value? .range(of: "\\bdisplay:\\s*none\\b", options: .regularExpression) == nil else { return "" } return plainText(tag: tag, attributes: attributes, child: child) case let .raw(text): return text case let .text(text): return unencode(text) case let .fragment(children): return children.map(plainText(for:)).joined() } } private func plainText(tag: String, attributes: [(key: String, value: String?)], child: Node) -> String { switch tag.lowercased() { case "a": let content = plainText(for: child) let href = attributes.first(where: { $0.key == "href" })?.value return href.map { "\(content) <\($0)>" } ?? content case "b", "strong": return "**" + plainText(for: child) + "**" case "blockquote": return "> \(plainText(for: child))\n\n" case "br": return "\n" case "em", "i": return "_" + plainText(for: child) + "_" case "h1": let content = plainText(for: child) return """ \(content) \(String(repeating: "=", count: content.count)) """ case "h2": let content = plainText(for: child) return """ \(content) \(String(repeating: "-", count: content.count)) """ case "h3": return "### \(plainText(for: child))\n\n" case "h4": return "#### \(plainText(for: child))\n\n" case "h5": return "##### \(plainText(for: child))\n\n" case "h6": return "###### \(plainText(for: child))\n\n" case "head", "script", "style": return "" case "ol": return zip(1..., child.children(where: { $0.isLi })) .map { " \($0). \(plainText(for: $1))" }.joined(separator: "\n") + "\n" case "p": return "\(plainText(for: child))\n\n" case "q": return "\"\(plainText(for: child))\"" case "sub", "sup": return "[\(plainText(for: child))]" case "ul": return child .children(where: { $0.isLi }) .map { " - \(plainText(for: $0))" }.joined(separator: "\n") + "\n" case "abbr", "acronym", "bdo", "big", "button", "cite", "code", "dfn", "img", "input", "kbd", "label", "map", "object", "samp", "select", "small", "span", "textarea", "tt", "var": return plainText(for: child) default: return plainText(for: child) + "\n" } } private func unencode(_ encoded: String) -> String { return encoded .replacingOccurrences(of: "&amp;", with: "&") .replacingOccurrences(of: "&lt;", with: "<") .replacingOccurrences(of: "&gt;", with: ">") .replacingOccurrences(of: "&quot;", with: "\"") .replacingOccurrences(of: "&#39;", with: "'") .replacingOccurrences(of: "&nbsp;", with: " ") .replacingOccurrences(of: "&#8209;", with: "-") } fileprivate extension Node { func children(where isIncluded: (Node) -> Bool) -> [Node] { switch self { case let .element(_, _, node): return isIncluded(node) ? [node] : node.children(where: isIncluded) case let .fragment(nodes): return nodes.flatMap { isIncluded($0) ? [$0] : $0.children(where: isIncluded) } case .comment, .doctype, .raw, .text: return [] } } var isLi: Bool { switch self { case .element("li", _, _): return true default: return false } } }
05d66dde69826cdc5a2cb880917b9612
22.054217
105
0.552391
false
false
false
false
nextcloud/ios
refs/heads/master
Widget/Files/FilesWidgetView.swift
gpl-3.0
1
// // FilesWidgetView.swift // Widget // // Created by Marino Faggiana on 25/08/22. // Copyright © 2022 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <marino.faggiana@nextcloud.com> // // 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 SwiftUI import WidgetKit struct FilesWidgetView: View { var entry: FilesDataEntry var body: some View { let parameterLink = "&user=\(entry.userId)&url=\(entry.url)" let linkNoAction: URL = URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink)! : URL(string: NCGlobal.shared.widgetActionNoAction)! let linkActionUploadAsset: URL = URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink)! : URL(string: NCGlobal.shared.widgetActionUploadAsset)! let linkActionScanDocument: URL = URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionScanDocument)! let linkActionTextDocument: URL = URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionTextDocument)! let linkActionVoiceMemo: URL = URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink)! : URL(string: NCGlobal.shared.widgetActionVoiceMemo)! GeometryReader { geo in if entry.isEmpty { VStack(alignment: .center) { Image(systemName: "checkmark") .resizable() .scaledToFit() .frame(width: 50, height: 50) Text(NSLocalizedString("_no_items_", comment: "")) .font(.system(size: 25)) .padding() Text(NSLocalizedString("_check_back_later_", comment: "")) .font(.system(size: 15)) } .frame(width: geo.size.width, height: geo.size.height) } ZStack(alignment: .topLeading) { HStack() { Text(entry.tile) .font(.system(size: 12)) .fontWeight(.bold) .multilineTextAlignment(.center) .textCase(.uppercase) .lineLimit(1) } .frame(width: geo.size.width - 20) .padding([.top, .leading, .trailing], 10) if !entry.isEmpty { VStack(alignment: .leading) { VStack(spacing: 0) { ForEach(entry.datas, id: \.id) { element in Link(destination: element.url) { HStack { Image(uiImage: element.image) .resizable() .scaledToFill() .frame(width: 35, height: 35) .clipped() .cornerRadius(5) VStack(alignment: .leading, spacing: 2) { Text(element.title) .font(.system(size: 12)) .fontWeight(.regular) Text(element.subTitle) .font(.system(size: CGFloat(10))) .foregroundColor(Color(.systemGray)) } Spacer() } .padding(.leading, 10) .frame(height: 50) } Divider() .padding(.leading, 54) } } } .padding(.top, 30) .redacted(reason: entry.isPlaceholder ? .placeholder : []) } HStack(spacing: 0) { let sizeButton: CGFloat = 40 Link(destination: entry.isPlaceholder ? linkNoAction : linkActionUploadAsset, label: { Image("addImage") .resizable() .renderingMode(.template) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brandText)) .padding(11) .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) .clipShape(Circle()) .scaledToFit() .frame(width: geo.size.width / 4, height: sizeButton) }) Link(destination: entry.isPlaceholder ? linkNoAction : linkActionScanDocument, label: { Image("scan") .resizable() .renderingMode(.template) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brandText)) .padding(11) .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) .clipShape(Circle()) .scaledToFit() .frame(width: geo.size.width / 4, height: sizeButton) }) Link(destination: entry.isPlaceholder ? linkNoAction : linkActionTextDocument, label: { Image("note.text") .resizable() .renderingMode(.template) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brandText)) .padding(11) .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) .clipShape(Circle()) .scaledToFit() .frame(width: geo.size.width / 4, height: sizeButton) }) Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo, label: { Image("microphone") .resizable() .renderingMode(.template) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brandText)) .padding(11) .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) .clipShape(Circle()) .scaledToFit() .frame(width: geo.size.width / 4, height: sizeButton) }) } .frame(width: geo.size.width, height: geo.size.height - 25, alignment: .bottomTrailing) .redacted(reason: entry.isPlaceholder ? .placeholder : []) HStack { Image(systemName: entry.footerImage) .resizable() .scaledToFit() .frame(width: 15, height: 15) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) Text(entry.footerText) .font(.caption2) .lineLimit(1) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) } .padding(.horizontal, 15.0) .frame(maxWidth: geo.size.width, maxHeight: geo.size.height - 2, alignment: .bottomTrailing) } } } } struct FilesWidget_Previews: PreviewProvider { static var previews: some View { let datas = Array(filesDatasTest[0...4]) let entry = FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: true, userId: "", url: "", tile: "Good afternoon, Marino Faggiana", footerImage: "checkmark.icloud", footerText: "Nextcloud files") FilesWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) } }
ca879c38f7ccd959ca7304cc487bb3d4
49.14433
248
0.496608
false
false
false
false
artsy/eigen
refs/heads/main
ios/Artsy/View_Controllers/Live_Auctions/ViewModels/LiveAuctionViewModel.swift
mit
1
import Foundation import Interstellar /// Represents the whole auction, all the live biz, timings, watchers protocol LiveAuctionViewModelType: AnyObject { var startDate: Date { get } var lotCount: Int { get } var saleAvailabilitySignal: Observable<SaleAvailabilityState> { get } var currentLotSignal: Observable<LiveAuctionLotViewModelType?> { get } var auctionState: ARAuctionState { get } func distanceFromCurrentLot(_ lot: LiveAuctionLotViewModelType) -> Int? } class LiveAuctionViewModel: NSObject, LiveAuctionViewModelType { fileprivate var sale: LiveSale fileprivate var lastUpdatedSaleAvailability: SaleAvailabilityState let saleAvailabilitySignal = Observable<SaleAvailabilityState>() let currentLotSignal: Observable<LiveAuctionLotViewModelType?> // When the bidder status changes, we get a full object refresh let biddingCredentials: BiddingCredentials init(sale: LiveSale, currentLotSignal: Observable<LiveAuctionLotViewModelType?>, biddingCredentials: BiddingCredentials) { self.sale = sale self.lastUpdatedSaleAvailability = sale.saleAvailability saleAvailabilitySignal.update(lastUpdatedSaleAvailability) self.currentLotSignal = currentLotSignal self.biddingCredentials = biddingCredentials } var startDate: Date { return sale.startDate } var lotCount: Int { return sale.saleArtworks.count } var auctionState: ARAuctionState { return sale.auctionStateWithBidders(biddingCredentials.bidders) } /// A distance relative to the current lot, -x being that it precedded the current /// 0 being it is current and a positive number meaning it upcoming. func distanceFromCurrentLot(_ lot: LiveAuctionLotViewModelType) -> Int? { guard let _lastUpdatedCurrentLot = currentLotSignal.peek() else { return nil } guard let lastUpdatedCurrentLot = _lastUpdatedCurrentLot else { return nil } let lotIDs = sale.saleArtworks.map { $0.liveAuctionLotID } let currentIndex = lotIDs.firstIndex(of: lastUpdatedCurrentLot.lotID) let lotIndex = lotIDs.firstIndex(of: lot.liveAuctionLotID) guard let current = currentIndex, let lot = lotIndex else { return nil } return (current - lot) * -1 } } extension LiveSale: SaleAuctionStatusType { }
b377081dbdd669881c3e237bfe57c549
35.890625
126
0.736976
false
false
false
false
Candyroot/HanekeSwift
refs/heads/master
Haneke/Data.swift
apache-2.0
1
// // Data.swift // Haneke // // Created by Hermes Pique on 9/19/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit // See: http://stackoverflow.com/questions/25922152/not-identical-to-self public protocol DataConvertible { typealias Result static func convertFromData(data:NSData) -> Result? } public protocol DataRepresentable { func asData() -> NSData! } private let imageSync = NSLock() extension UIImage : DataConvertible, DataRepresentable { public typealias Result = UIImage static func safeImageWithData(data:NSData) -> Result? { imageSync.lock() let image = UIImage(data:data) imageSync.unlock() return image } public class func convertFromData(data:NSData) -> Result? { let image = UIImage.safeImageWithData(data) return image } public func asData() -> NSData! { return self.hnk_data() } } extension String : DataConvertible, DataRepresentable { public typealias Result = String public static func convertFromData(data:NSData) -> Result? { let string = NSString(data: data, encoding: NSUTF8StringEncoding) return string as? Result } public func asData() -> NSData! { return self.dataUsingEncoding(NSUTF8StringEncoding) } } extension NSData : DataConvertible, DataRepresentable { public typealias Result = NSData public class func convertFromData(data:NSData) -> Result? { return data } public func asData() -> NSData! { return self } } public enum JSONData : DataConvertible, DataRepresentable { public typealias Result = JSONData case Dictionary([String:AnyObject]) case Array([AnyObject]) public static func convertFromData(data:NSData) -> Result? { do { let object : AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) switch (object) { case let dictionary as [String:AnyObject]: return JSONData.Dictionary(dictionary) case let array as [AnyObject]: return JSONData.Array(array) default: return nil } } catch { Log.error("Invalid JSON data", error) return nil } } public func asData() -> NSData! { switch (self) { case .Dictionary(let dictionary): do { return try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions()) } catch _ { return nil } case .Array(let array): do { return try NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions()) } catch _ { return nil } } } public var array : [AnyObject]! { switch (self) { case .Dictionary(_): return nil case .Array(let array): return array } } public var dictionary : [String:AnyObject]! { switch (self) { case .Dictionary(let dictionary): return dictionary case .Array(_): return nil } } }
3ae362d8e6da42277aff85b771a3d0ad
24.007463
118
0.581916
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Notifications/NotificationCell.swift
mit
1
// // NotificationDetailsCell.swift // Freetime // // Created by Ryan Nystrom on 5/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit final class NotificationCell: SwipeSelectableCell { static let labelInset = UIEdgeInsets( top: Styles.Fonts.title.lineHeight + 2*Styles.Sizes.rowSpacing, left: Styles.Sizes.icon.width + 2*Styles.Sizes.columnSpacing, bottom: Styles.Sizes.rowSpacing, right: Styles.Sizes.gutter ) private let reasonImageView = UIImageView() private let dateLabel = ShowMoreDetailsLabel() private let titleLabel = UILabel() private let textLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) accessibilityTraits |= UIAccessibilityTraitButton isAccessibilityElement = true backgroundColor = .white titleLabel.numberOfLines = 1 titleLabel.font = Styles.Fonts.title titleLabel.textColor = Styles.Colors.Gray.light.color contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(Styles.Sizes.rowSpacing) make.left.equalTo(NotificationCell.labelInset.left) } dateLabel.backgroundColor = .clear dateLabel.numberOfLines = 1 dateLabel.font = Styles.Fonts.secondary dateLabel.textColor = Styles.Colors.Gray.light.color dateLabel.textAlignment = .right contentView.addSubview(dateLabel) dateLabel.snp.makeConstraints { make in make.right.equalTo(-Styles.Sizes.gutter) make.centerY.equalTo(titleLabel) make.left.equalTo(titleLabel.snp.right).offset(Styles.Sizes.gutter) } reasonImageView.backgroundColor = .clear reasonImageView.contentMode = .scaleAspectFit reasonImageView.tintColor = Styles.Colors.Blue.medium.color contentView.addSubview(reasonImageView) reasonImageView.snp.makeConstraints { make in make.size.equalTo(Styles.Sizes.icon) make.top.equalTo(NotificationCell.labelInset.top) make.left.equalTo(Styles.Sizes.rowSpacing) } textLabel.numberOfLines = 0 contentView.addSubview(textLabel) textLabel.snp.makeConstraints { make in make.edges.equalTo(contentView).inset(NotificationCell.labelInset) } contentView.addBorder(.bottom, left: NotificationCell.labelInset.left) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentViewForSafeAreaInsets() } // MARK: Public API var isRead = false { didSet { for view in [titleLabel, textLabel, reasonImageView] { view.alpha = isRead ? 0.5 : 1 } } } func configure(_ viewModel: NotificationViewModel) { var titleAttributes = [ NSAttributedStringKey.font: Styles.Fonts.title, NSAttributedStringKey.foregroundColor: Styles.Colors.Gray.light.color ] let title = NSMutableAttributedString(string: "\(viewModel.owner)/\(viewModel.repo) ", attributes: titleAttributes) titleAttributes[NSAttributedStringKey.font] = Styles.Fonts.secondary switch viewModel.identifier { case .number(let number): title.append(NSAttributedString(string: "#\(number)", attributes: titleAttributes)) default: break } titleLabel.attributedText = title textLabel.attributedText = viewModel.title.attributedText dateLabel.setText(date: viewModel.date) reasonImageView.image = viewModel.type.icon.withRenderingMode(.alwaysTemplate) accessibilityLabel = AccessibilityHelper .generatedLabel(forCell: self) .appending(".\n\(viewModel.type.localizedString)") } }
f82c7ee2086f66b99b2e7b2da568db09
33.973684
123
0.669927
false
false
false
false
qblu/MosaicCollectionViewLayout
refs/heads/master
MosaicCollectionViewLayoutTests/TestMosaicCollectionViewDelegate.swift
mit
1
// // TestMosaicCollectionViewDelegate.swift // TestMosaicCollectionViewDelegate // // Created by Rusty Zarse on 12/11/15. // Copyright © 2015 com.levous. All rights reserved. // import Foundation @testable import MosaicCollectionViewLayout class TestMosaicCollectionViewDelegate: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MosaicCollectionViewLayoutDelegate { var numberOfSections = 1 var numberOfRowsForSection = [Int: Int]() var interitemSpacing: CGFloat = 2.0 var sectionInsets = UIEdgeInsetsMake(0, 0, 0, 0) var headerSize = CGSizeZero var footerSize = CGSizeZero var sizeforIndexPath = [NSIndexPath: CGSize]() var allowedMosaicCellSizesForIndexPath: [NSIndexPath: [MosaicCollectionViewLayout.MosaicCellSize]] = [:] //MARK: UICollectionViewDataSource @objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfRowsForSection[section] ?? 10 } @objc func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numberOfSections } @objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return UICollectionViewCell() } @objc func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let frame = (kind == UICollectionElementKindSectionHeader) ? CGRectMake(0, 0, headerSize.width, headerSize.height) : CGRectMake(0, 0, footerSize.width, footerSize.height) return UICollectionReusableView(frame: frame) } //MARK: UICollectionViewDelegateFlowLayout @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return sectionInsets } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return interitemSpacing } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return interitemSpacing } @objc func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, referenceSizeForHeaderInSection: Int) -> CGSize { return headerSize } @objc func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, referenceSizeForFooterInSection: Int) -> CGSize { return footerSize } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return sizeforIndexPath[indexPath] ?? CGSize.zero } //Mark: MosaicCollectionViewLayoutDelegate func mosaicCollectionViewLayout(layout:MosaicCollectionViewLayout, allowedSizesForItemAtIndexPath indexPath:NSIndexPath) -> [MosaicCollectionViewLayout.MosaicCellSize]? { return allowedMosaicCellSizesForIndexPath[indexPath] } }
14bb4647ed558f7463f08c2ee8b16aca
35.181818
175
0.809928
false
false
false
false
SwiftKit/Torch
refs/heads/master
Source/Utils/TorchMetadata.swift
mit
1
// // TorchMetadata.swift // Torch // // Created by Filip Dolnik on 20.07.16. // Copyright © 2016 Brightify. All rights reserved. // import CoreData @objc(TorchMetadata) class TorchMetadata: NSManagedObject { static let NAME = "TorchSwift_TorchMetadata" @NSManaged var torchEntityName: String @NSManaged var lastAssignedId: NSNumber static func describeEntity(to registry: EntityRegistry) { let entity = NSEntityDescription() entity.name = NAME entity.managedObjectClassName = String(TorchMetadata) let name = NSAttributeDescription() name.name = "torchEntityName" name.attributeType = .StringAttributeType name.optional = false let id = NSAttributeDescription() id.name = "lastAssignedId" id.attributeType = .Integer64AttributeType id.optional = false entity.properties = [name, id] registry.describe(NAME, as: entity) } }
81ef36f02b622f016686d046848a2e3a
25.131579
61
0.652568
false
false
false
false
CodaFi/swift
refs/heads/main
benchmark/single-source/RangeOverlaps.swift
apache-2.0
20
//===--- RangeOverlaps.swift ----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let RangeOverlaps = [ BenchmarkInfo( name: "RangeOverlapsRange", runFunction: run_RangeOverlapsRange, tags: [.validation, .api], setUpFunction: buildRanges), BenchmarkInfo( name: "RangeOverlapsClosedRange", runFunction: run_RangeOverlapsClosedRange, tags: [.validation, .api], setUpFunction: buildRanges), BenchmarkInfo( name: "ClosedRangeOverlapsClosedRange", runFunction: run_ClosedRangeOverlapsClosedRange, tags: [.validation, .api], setUpFunction: buildRanges) ] private func buildRanges() { blackHole(ranges) blackHole(closedRanges) } private let ranges: [Range<Int>] = (-8...8).flatMap { a in (0...16).map { l in a..<(a+l) } } private let closedRanges: [ClosedRange<Int>] = (-8...8).flatMap { a in (0...16).map { l in a...(a+l) } } @inline(never) public func run_RangeOverlapsRange(_ N: Int) { var check: UInt64 = 0 for _ in 0..<N { for lhs in ranges { for rhs in ranges { if lhs.overlaps(rhs) { check += 1 } } } } CheckResults(check == 47872 * UInt64(N)) } @inline(never) public func run_RangeOverlapsClosedRange(_ N: Int) { var check: UInt64 = 0 for _ in 0..<N { for lhs in ranges { for rhs in closedRanges { if lhs.overlaps(rhs) { check += 1 } } } } CheckResults(check == 51680 * UInt64(N)) } @inline(never) public func run_ClosedRangeOverlapsClosedRange(_ N: Int) { var check: UInt64 = 0 for _ in 0..<N { for lhs in closedRanges { for rhs in closedRanges { if lhs.overlaps(rhs) { check += 1 } } } } CheckResults(check == 55777 * UInt64(N)) }
672f7ca0f4d93ae2a1dd28c1f3a36acd
26.807692
104
0.610881
false
false
false
false
Chris-Perkins/Lifting-Buddy
refs/heads/master
Lifting Buddy/ExercisesView.swift
mit
1
// // ExercisesView.swift // Lifting Buddy // // Created by Christopher Perkins on 10/29/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit import Realm import RealmSwift class ExercisesView: UIView { // MARK: View properties // Notified when we pick an exercise public var exercisePickerDelegate: ExercisePickerDelegate? // Whether or not we're simply selecting an exercise private let selectingExercise: Bool // Whether or not we've loaded the view private var loaded: Bool = false // The workouts for this view private let exerciseTableView: ExercisesTableView // The view where our buttons go private let footerView: UIView // The button to create this workout private let createExerciseButton: PrettyButton // A button to cancel this view (only visible if selecting exercise) private let cancelButton: PrettyButton // MARK: View inits required init(selectingExercise: Bool = false, frame: CGRect) { self.selectingExercise = selectingExercise let realm = try! Realm() let exercises = realm.objects(Exercise.self) exerciseTableView = ExercisesTableView(exercises: AnyRealmCollection(exercises), selectingExercise: selectingExercise, style: UITableView.Style.plain) footerView = UIView() createExerciseButton = PrettyButton() cancelButton = PrettyButton() super.init(frame: frame) addSubview(footerView) footerView.addSubview(createExerciseButton) footerView.addSubview(cancelButton) addSubview(exerciseTableView) createAndActivateFooterViewConstraints() createAndActivateCancelButtonConstraints() createAndActivateCreateExerciseButtonConstraints() createAndActivateExerciseTableViewConstraints() exerciseTableView.exercisePickerDelegate = self createExerciseButton.addTarget(self, action: #selector(showCreateExerciseView(sender:)), for: .touchUpInside) cancelButton.addTarget(self, action: #selector(removeSelf), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Overrides override func layoutSubviews() { super.layoutSubviews() backgroundColor = .lightestBlackWhiteColor createExerciseButton.setDefaultProperties() createExerciseButton.setTitle(NSLocalizedString("ExerciseView.Button.CreateExercise", comment: ""), for: .normal) if selectingExercise { cancelButton.setDefaultProperties() cancelButton.backgroundColor = .niceRed cancelButton.setTitle(NSLocalizedString("Button.Cancel", comment: ""), for: .normal) } else { cancelButton.alpha = 0 } exerciseTableView.reloadData() } // MARK: View functions // Just removes this view @objc func removeSelf() { removeSelfNicelyWithAnimation() } public func selectExercise(exercise: Exercise) { guard let indexOfExercise = exerciseTableView.getSortedData().index(of: exercise) else { fatalError("Exercise selected that did not exist!") } let indexPath = IndexPath(row: indexOfExercise, section: 0) exerciseTableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom) } // MARK: Event functions @objc func showCreateExerciseView(sender: PrettyButton) { let createExerciseView: CreateExerciseView = CreateExerciseView(frame: .zero) createExerciseView.dataDelegate = self showView(createExerciseView) } // MARK: Constraint functions // Cling to bottom, left, right of view ; height of default prettybutton height private func createAndActivateFooterViewConstraints() { footerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: footerView, withCopyView: self, attribute: .bottom).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: footerView, withCopyView: self, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: footerView, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: footerView, height: PrettyButton.defaultHeight).isActive = true } // Cling to top, left, right of this view ; bottom of this view @ createButton private func createAndActivateExerciseTableViewConstraints() { exerciseTableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: exerciseTableView, withCopyView: self, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: exerciseTableView, withCopyView: self, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: exerciseTableView, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint(item: footerView, attribute: .top, relatedBy: .equal, toItem: exerciseTableView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } // Cling to right, top, bottom of footer ; place to right of cancelbutton private func createAndActivateCreateExerciseButtonConstraints() { createExerciseButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: createExerciseButton, withCopyView: footerView, attribute: .right).isActive = true NSLayoutConstraint(item: cancelButton, attribute: .right, relatedBy: .equal, toItem: createExerciseButton, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: createExerciseButton, withCopyView: footerView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: createExerciseButton, withCopyView: footerView, attribute: .bottom).isActive = true } // cling to left, top, bottom of this view ; width 0.5 if selectingExercise else 0 private func createAndActivateCancelButtonConstraints() { cancelButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: footerView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: footerView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: footerView, attribute: .bottom).isActive = true if selectingExercise { NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: footerView, attribute: .width, multiplier: 0.5).isActive = true } else { NSLayoutConstraint.createWidthConstraintForView(view: cancelButton, width: 0).isActive = true } } } extension ExercisesView: ExercisePickerDelegate { // when we select an exercise, return it. func didSelectExercise(exercise: Exercise) { exercisePickerDelegate?.didSelectExercise(exercise: exercise) removeSelfNicelyWithAnimation() } } extension ExercisesView: CreateExerciseViewDelegate { // Called when a workout is created from this view func finishedWithExercise(exercise: Exercise) { // if we're selecting an exercise, return the one we just made. if selectingExercise { exercisePickerDelegate?.didSelectExercise(exercise: exercise) removeSelfNicelyWithAnimation() } else { exerciseTableView.reloadData() exerciseTableView.layoutSubviews() } } } extension ExercisesView: ShowViewDelegate { // Shows a view over this one func showView(_ view: UIView) { addSubview(view) UIView.slideView(view, overView: self) } }
5a703a4e64d1d3f3fc11e46211e4f6e4
43.570833
108
0.553987
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
SyncTelemetry/SyncTelemetryEvents.swift
mpl-2.0
6
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SwiftyJSON private let log = Logger.browserLogger public typealias IdentifierString = String public extension IdentifierString { func validate() -> Bool { // Regex located here: http://gecko.readthedocs.io/en/latest/toolkit/components/telemetry/telemetry/collection/events.html#limits let regex = try! NSRegularExpression(pattern: "^[a-zA-Z][a-zA-Z0-9_.]*[a-zA-Z0-9]$", options: []) return regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.count)).count > 0 } } // Telemetry Events // Documentation: http://gecko.readthedocs.io/en/latest/toolkit/components/telemetry/telemetry/collection/events.html#events public struct Event { let timestamp: Timestamp let category: IdentifierString let method: IdentifierString let object: IdentifierString let value: String? let extra: [String: String]? public init(category: IdentifierString, method: IdentifierString, object: IdentifierString, value: String? = nil, extra: [String: String]? = nil) { self.init(timestamp: .uptimeInMilliseconds(), category: category, method: method, object: object, value: value, extra: extra) } init(timestamp: Timestamp, category: IdentifierString, method: IdentifierString, object: IdentifierString, value: String? = nil, extra: [String: String]? = nil) { self.timestamp = timestamp self.category = category self.method = method self.object = object self.value = value self.extra = extra } public func validate() -> Bool { let results = [category, method, object].map { $0.validate() } // Fold down the results into false if any of the results is false. return results.reduce(true) { $0 ? $1 :$0 } } public func pickle() -> Data? { do { return try JSONSerialization.data(withJSONObject: toArray(), options: []) } catch let error { log.error("Error pickling telemetry event. Error: \(error), Event: \(self)") return nil } } public static func unpickle(_ data: Data) -> Event? { do { let array = try JSONSerialization.jsonObject(with: data, options: []) as! [Any] return Event( timestamp: Timestamp(array[0] as! UInt64), category: array[1] as! String, method: array[2] as! String, object: array[3] as! String, value: array[4] as? String, extra: array[5] as? [String: String] ) } catch let error { log.error("Error unpickling telemetry event: \(error)") return nil } } public func toArray() -> [Any] { return [timestamp, category, method, object, value ?? NSNull(), extra ?? NSNull()] } } extension Event: CustomDebugStringConvertible { public var debugDescription: String { return toArray().description } }
52b14fa1bab666d33198531cb48eebf1
33.612245
137
0.593455
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/IRGen/prespecialized-metadata/struct-inmodule-otherfile-1argument-run.swift
apache-2.0
3
// RUN: %target-run-simple-swift(%S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift %S/Inputs/struct-nonfrozen-1argument.swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // Executing on the simulator within __abort_with_payload with "No ABI plugin located for triple x86_64h-apple-ios -- shared libraries will not be registered!" // UNSUPPORTED: CPU=x86_64 && OS=ios // UNSUPPORTED: CPU=x86_64 && OS=tvos // UNSUPPORTED: CPU=x86_64 && OS=watchos // UNSUPPORTED: CPU=i386 && OS=watchos // UNSUPPORTED: use_os_stdlib func consume<First>(oneArgument: OneArgument<First>) { consume(oneArgument) } func doit() { // CHECK: [[METADATA_ADDRESS:[0-9a-f]+]] 3 @ 21 consume(OneArgument(3)) // CHECK: [[METADATA_ADDRESS]] 3 @ 23 consume(oneArgument: OneArgument(3)) }
1150509ca573fc0029be4ed50b5833fd
42.5
233
0.711686
false
false
false
false
remirobert/MNIST-machine-learning
refs/heads/master
draw-recognition/PredictionService.swift
mit
1
// // PredictionService.swift // draw-recognition // // Created by Rémi Robert on 02/06/2017. // Copyright © 2017 Rémi Robert. All rights reserved. // import UIKit let baseUrl = "" protocol Prediction { func predict(pixels: [UInt8], completion: @escaping (Int?) -> Void) } class PredictionService: Prediction { private func bodyData(pixels: [UInt8]) -> Data? { let json: [String: Any] = ["image" : pixels, "label": 0] let jsonData = try? JSONSerialization.data(withJSONObject: json) return jsonData } func predict(pixels: [UInt8], completion: @escaping (Int?) -> Void) { guard let url = URL(string: baseUrl) else { return } let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.httpBody = self.bodyData(pixels: pixels) URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in guard let data = data, let element = data.first else { completion(nil) return } let prediction = Int(element - 48) completion(prediction) }.resume() } }
042addbb53dea97f50dfadbe818a0e26
28.425
90
0.604928
false
false
false
false
oleander/bitbar
refs/heads/master
Tests/SharedTests/Matchers.swift
mit
1
import Nimble import Dollar import Cent import Foundation public func cyclicSubset<T: Equatable>(of cycle: [T]) -> Predicate<[T]> { return Predicate { (actual: Expression<[T]>) throws -> PredicateResult in let msg = ExpectationMessage.expectedActualValueTo("be cyclic") if let list = try actual.evaluate() { if list.isEmpty { return PredicateResult(bool: false, message: msg) } for (index, value) in cycle.enumerated() { switch (value, list.get(index: index % list.count)) { case let (that, .some(this)) where that == this: continue default: return PredicateResult(status: .fail, message: msg) } } return PredicateResult(bool: true, message: msg) } return PredicateResult(status: .fail, message: msg) } } public func beginWith<T: Equatable>(_ array: [T]) -> Predicate<[T]> { return Predicate { (actual: Expression<[T]>) throws -> PredicateResult in let msg = ExpectationMessage.expectedActualValueTo("begin with") let failed = PredicateResult(status: .fail, message: msg) guard let list = try actual.evaluate() else { return failed } if list.count < array.count { return failed } for (index, value) in array.enumerated() { if value != list[index] { return failed } } return PredicateResult(bool: true, message: msg) } } public func beCyclicSubset<T: Equatable>(of cycle: [T], from: Int = 0) -> Predicate<[T]> { return Predicate { (actual: Expression<[T]>) throws -> PredicateResult in let msg = ExpectationMessage.expectedActualValueTo("be cyclic") let failed = PredicateResult(status: .fail, message: msg) guard let list = try actual.evaluate() else { return failed } if (list.count - from) <= 0 { return failed } for (index, value) in list.enumerated() where index >= from { if value != cycle[(index - from) % cycle.count] { return failed } } return PredicateResult(bool: true, message: msg) } }
b072c7eb61b85204e79291786bff34e3
27.887324
90
0.636275
false
false
false
false
sseitov/WD-Content
refs/heads/master
WD Content TV/AddShareController.swift
gpl-2.0
1
// // AddShareController.swift // WD Content // // Created by Сергей Сейтов on 29.12.16. // Copyright © 2016 Sergey Seitov. All rights reserved. // import UIKit class ServiceHost : NSObject { var name:String = "" var host:String = "" var port:Int32 = 0 init(name:String, host:String, port:Int32) { super.init() self.name = name self.host = host self.port = port } } class AddShareController: UITableViewController { let serviceBrowser:NetServiceBrowser = NetServiceBrowser() var services:[NetService] = [] var hosts:[ServiceHost] = [] override func viewDidLoad() { super.viewDidLoad() self.title = "Devices" serviceBrowser.delegate = self serviceBrowser.searchForServices(ofType: "_smb._tcp.", inDomain: "local") } func updateInterface () { for service in self.services { if service.port == -1 { // print("service \(service.name) of type \(service.type)" + // " not yet resolved") service.delegate = self service.resolve(withTimeout:10) } else { // print("service \(service.name) of type \(service.type)," + // "port \(service.port), addresses \(service.addresses)") if let addresses = service.addresses { var ips: String = "" for address in addresses { let ptr = (address as NSData).bytes.bindMemory(to: sockaddr_in.self, capacity: address.count) var addr = ptr.pointee.sin_addr let buf = UnsafeMutablePointer<Int8>.allocate(capacity: Int(INET6_ADDRSTRLEN)) let family = ptr.pointee.sin_family if family == __uint8_t(AF_INET) { if let ipc:UnsafePointer<Int8> = inet_ntop(Int32(family), &addr, buf, __uint32_t(INET6_ADDRSTRLEN)) { ips = String(cString: ipc) } } } if !hostInList(address: ips) { hosts.append(ServiceHost(name: service.name, host: ips, port: Int32(service.port))) } tableView.reloadData() service.stop() } } } } func hostInList(address:String) -> Bool { for host in hosts { if host.host == address { return true } } return false } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hosts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel!.text = hosts[(indexPath as NSIndexPath).row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showDevice", sender: hosts[indexPath.row]) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDevice" { let controller = segue.destination as! DeviceController controller.target = sender as? ServiceHost } } } // MARK: - NSNetServiceDelegate extension AddShareController:NetServiceDelegate { func netServiceDidResolveAddress(_ sender: NetService) { updateInterface() sender.startMonitoring() } } // MARK: - NSNetServiceBrowserDelegate extension AddShareController:NetServiceBrowserDelegate { func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { services.append(service) if !moreComing { updateInterface() } } }
173d492a3718e7e098ee44ee3f9a8a4a
25.330827
109
0.678755
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/public/core/SliceBuffer.swift
apache-2.0
7
//===--- SliceBuffer.swift - Backing storage for ArraySlice<Element> ------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Buffer type for `ArraySlice<Element>`. @frozen @usableFromInline internal struct _SliceBuffer<Element> : _ArrayBufferProtocol, RandomAccessCollection { internal typealias NativeStorage = _ContiguousArrayStorage<Element> @usableFromInline internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> /// An object that keeps the elements stored in this buffer alive. @usableFromInline internal var owner: AnyObject @usableFromInline internal let subscriptBaseAddress: UnsafeMutablePointer<Element> /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @usableFromInline internal var startIndex: Int /// [63:1: 63-bit index][0: has a native buffer] @usableFromInline internal var endIndexAndFlags: UInt @inlinable internal init( owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>, startIndex: Int, endIndexAndFlags: UInt ) { self.owner = owner self.subscriptBaseAddress = subscriptBaseAddress self.startIndex = startIndex self.endIndexAndFlags = endIndexAndFlags } @inlinable internal init( owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>, indices: Range<Int>, hasNativeBuffer: Bool ) { self.owner = owner self.subscriptBaseAddress = subscriptBaseAddress self.startIndex = indices.lowerBound let bufferFlag = UInt(hasNativeBuffer ? 1 : 0) self.endIndexAndFlags = (UInt(indices.upperBound) << 1) | bufferFlag _invariantCheck() } @inlinable internal init() { let empty = _ContiguousArrayBuffer<Element>() self.owner = empty.owner self.subscriptBaseAddress = empty.firstElementAddress self.startIndex = empty.startIndex self.endIndexAndFlags = 1 _invariantCheck() } @inlinable internal init(_buffer buffer: NativeBuffer, shiftedToStartIndex: Int) { let shift = buffer.startIndex - shiftedToStartIndex self.init( owner: buffer.owner, subscriptBaseAddress: buffer.subscriptBaseAddress + shift, indices: shiftedToStartIndex..<shiftedToStartIndex + buffer.count, hasNativeBuffer: true) } @inlinable // FIXME(sil-serialize-all) internal func _invariantCheck() { let isNative = _hasNativeBuffer let isNativeStorage: Bool = owner is __ContiguousArrayStorageBase _internalInvariant(isNativeStorage == isNative) if isNative { _internalInvariant(count <= nativeBuffer.count) } } @inlinable internal var _hasNativeBuffer: Bool { return (endIndexAndFlags & 1) != 0 } @inlinable internal var nativeBuffer: NativeBuffer { _internalInvariant(_hasNativeBuffer) return NativeBuffer( owner as? __ContiguousArrayStorageBase ?? _emptyArrayStorage) } @inlinable internal var nativeOwner: AnyObject { _internalInvariant(_hasNativeBuffer, "Expect a native array") return owner } /// Replace the given subRange with the first newCount elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer` and `insertCount <= newValues.count`. @inlinable internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with insertCount: Int, elementsOf newValues: __owned C ) where C: Collection, C.Element == Element { _invariantCheck() _internalInvariant(insertCount <= newValues.count) _internalInvariant(_hasNativeBuffer) _internalInvariant(isUniquelyReferenced()) let eraseCount = subrange.count let growth = insertCount - eraseCount let oldCount = count var native = nativeBuffer let hiddenElementCount = firstElementAddress - native.firstElementAddress _internalInvariant(native.count + growth <= native.capacity) let start = subrange.lowerBound - startIndex + hiddenElementCount let end = subrange.upperBound - startIndex + hiddenElementCount native.replaceSubrange( start..<end, with: insertCount, elementsOf: newValues) self.endIndex = self.startIndex + oldCount + growth _invariantCheck() } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return subscriptBaseAddress + startIndex } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } //===--- Non-essential bits ---------------------------------------------===// @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> NativeBuffer? { _invariantCheck() // Note: with COW support it's already guaranteed to have a uniquely // referenced buffer. This check is only needed for backward compatibility. if _fastPath(isUniquelyReferenced()) { if capacity >= minimumCapacity { // Since we have the last reference, drop any inaccessible // trailing elements in the underlying storage. That will // tend to reduce shuffling of later elements. Since this // function isn't called for subscripting, this won't slow // down that case. var native = nativeBuffer let offset = self.firstElementAddress - native.firstElementAddress let backingCount = native.count let myCount = count if _slowPath(backingCount > myCount + offset) { native.replaceSubrange( (myCount+offset)..<backingCount, with: 0, elementsOf: EmptyCollection()) } _invariantCheck() return native } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { // This is a performance optimization that ensures that the copy of self // that occurs at -Onone is destroyed before we call // isUniquelyReferenced. This code used to be: // // return _hasNativeBuffer && isUniquelyReferenced() // // SR-6437 if !_hasNativeBuffer { return false } return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { _invariantCheck() if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) { return nativeBuffer } return nil } @inlinable @discardableResult internal __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _invariantCheck() _internalInvariant(bounds.lowerBound >= startIndex) _internalInvariant(bounds.upperBound >= bounds.lowerBound) _internalInvariant(bounds.upperBound <= endIndex) let c = bounds.count target.initialize(from: subscriptBaseAddress + bounds.lowerBound, count: c) return target + c } @inlinable internal __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { _invariantCheck() guard buffer.count > 0 else { return (makeIterator(), 0) } let c = Swift.min(self.count, buffer.count) buffer.baseAddress!.initialize( from: firstElementAddress, count: c) _fixLifetime(owner) return (IndexingIterator(_elements: self, _position: startIndex + c), c) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return _hasNativeBuffer } @inlinable internal var count: Int { get { return endIndex - startIndex } set { let growth = newValue - count if growth != 0 { nativeBuffer.mutableCount += growth self.endIndex += growth } _invariantCheck() } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `startIndex ≤ index < endIndex` @inlinable internal func _checkValidSubscript(_ index: Int) { _precondition( index >= startIndex && index < endIndex, "Index out of bounds") } @inlinable internal var capacity: Int { let count = self.count if _slowPath(!_hasNativeBuffer) { return count } let n = nativeBuffer let nativeEnd = n.firstElementAddress + n.count if (firstElementAddress + count) == nativeEnd { return count + (n.capacity - n.count) } return count } /// Returns `true` if this buffer's storage is uniquely-referenced; /// otherwise, returns `false`. /// /// This function should only be used for internal sanity checks and for /// backward compatibility. /// To guard a buffer mutation, use `beginCOWMutation`. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return isKnownUniquelyReferenced(&owner) } /// Returns `true` and puts the buffer in a mutable state if the buffer's /// storage is uniquely-referenced; otherwise, performs no action and returns /// `false`. /// /// - Precondition: The buffer must be immutable. /// /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer /// is mutated. @_alwaysEmitIntoClient internal mutating func beginCOWMutation() -> Bool { if !_hasNativeBuffer { return false } if Bool(Builtin.beginCOWMutation(&owner)) { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED nativeBuffer.isImmutable = false #endif return true } return false; } /// Puts the buffer in an immutable state. /// /// - Precondition: The buffer must be mutable or the empty array singleton. /// /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated /// until the next call of `beginCOWMutation`. @_alwaysEmitIntoClient @inline(__always) internal mutating func endCOWMutation() { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED nativeBuffer.isImmutable = true #endif Builtin.endCOWMutation(&owner) } @inlinable internal func getElement(_ i: Int) -> Element { _internalInvariant(i >= startIndex, "slice index is out of range (before startIndex)") _internalInvariant(i < endIndex, "slice index is out of range") return subscriptBaseAddress[i] } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable internal subscript(position: Int) -> Element { get { return getElement(position) } nonmutating set { _internalInvariant(position >= startIndex, "slice index is out of range (before startIndex)") _internalInvariant(position < endIndex, "slice index is out of range") subscriptBaseAddress[position] = newValue } } @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer { get { _internalInvariant(bounds.lowerBound >= startIndex) _internalInvariant(bounds.upperBound >= bounds.lowerBound) _internalInvariant(bounds.upperBound <= endIndex) return _SliceBuffer( owner: owner, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: _hasNativeBuffer) } set { fatalError("not implemented") } } //===--- Collection conformance -------------------------------------===// /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @inlinable internal var endIndex: Int { get { return Int(endIndexAndFlags >> 1) } set { endIndexAndFlags = (UInt(newValue) << 1) | (_hasNativeBuffer ? 1 : 0) } } @usableFromInline internal typealias Indices = Range<Int> //===--- misc -----------------------------------------------------------===// /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } @inlinable internal func unsafeCastElements<T>(to type: T.Type) -> _SliceBuffer<T> { _internalInvariant(_isClassOrObjCExistential(T.self)) let baseAddress = UnsafeMutableRawPointer(self.subscriptBaseAddress) .assumingMemoryBound(to: T.self) return _SliceBuffer<T>( owner: self.owner, subscriptBaseAddress: baseAddress, startIndex: self.startIndex, endIndexAndFlags: self.endIndexAndFlags) } } extension _SliceBuffer { @inlinable internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if _hasNativeBuffer { let n = nativeBuffer if count == n.count { return ContiguousArray(_buffer: n) } } let result = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: 0) result.firstElementAddress.initialize( from: firstElementAddress, count: count) return ContiguousArray(_buffer: result) } }
db0aa76abae3838ff99998b41444c3e7
30.233906
99
0.679973
false
false
false
false
google/swift-structural
refs/heads/main
Sources/StructuralExamples/MyDebugString.swift
apache-2.0
1
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 StructuralCore /// A duplicate protocol, similar to MyDebugStringConvertible public protocol MyDebugString { var debugString: String { get } } // Inductive cases. extension StructuralStruct: MyDebugString where Properties: MyDebugString { public var debugString: String { let name: String if let type = self.representedType { name = String(describing: type) } else { name = "" } return "\(name)(\(body.debugString))" } } extension StructuralCons: MyDebugString where Value: MyDebugString, Next: MyDebugString { public var debugString: String { let valueString = self.value.debugString let nextString = self.next.debugString if nextString == "" { return valueString } else { return "\(valueString), \(nextString)" } } } extension StructuralProperty: MyDebugString where Value: MyDebugString { public var debugString: String { if self.name.description == "" { return self.value.debugString } else { return "\(self.name): \(self.value.debugString)" } } } extension StructuralEnum: MyDebugString where Cases: MyDebugString { public var debugString: String { let name: String if let type = self.representedType { name = String(describing: type) } else { name = "" } return "\(name).\(self.body.debugString)" } } extension StructuralEither: MyDebugString where Left: MyDebugString, Right: MyDebugString { public var debugString: String { switch self { case .left(let left): return left.debugString case .right(let right): return right.debugString } } } extension StructuralCase: MyDebugString where AssociatedValues: MyDebugString { public var debugString: String { let valuesString = associatedValues.debugString if valuesString == "" { return name.description } else { return "\(name)(\(valuesString))" } } } // Base cases. extension StructuralEmpty: MyDebugString { public var debugString: String { return "" } } extension String: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Int: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Float: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Double: MyDebugString { public var debugString: String { return String(reflecting: self) } } // Sugar extension MyDebugString where Self: Structural, Self.StructuralRepresentation: MyDebugString { public var debugString: String { return self.structuralRepresentation.debugString } }
5ecbc36d2676a47f0a73a7bb7d58ae06
24.693431
75
0.651136
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Business/Constracts/ContractCell.swift
lgpl-2.1
2
// // ContractCell.swift // Neocom // // Created by Artem Shimanski on 2/13/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import CoreData import Expressible struct ContractCell: View { var contract: ESI.PersonalContracts.Element var contacts: [Int64: Contact] var locations: [Int64: EVELocation] var body: some View { let endDate: Date = contract.dateCompleted ?? { guard let date = contract.dateAccepted, let duration = contract.daysToComplete else {return nil} return date.addingTimeInterval(TimeInterval(duration) * 24 * 3600) }() ?? contract.dateExpired let currentStatus = contract.currentStatus let isActive = currentStatus == .outstanding || currentStatus == .inProgress let t = contract.dateExpired.timeIntervalSinceNow let status: Text if isActive { status = Text("\(currentStatus.title):").fontWeight(.semibold).foregroundColor(.primary) + Text(" \(TimeIntervalFormatter.localizedString(from: max(t, 0), precision: .minutes))") } else { status = Text("\(currentStatus.title):").fontWeight(.semibold) + Text(" \(DateFormatter.localizedString(from: endDate, dateStyle: .medium, timeStyle: .medium))") } return VStack(alignment: .leading) { HStack { Text(contract.type.title).foregroundColor(.accentColor) Text("[\(contract.availability.title)]").modifier(SecondaryLabelModifier()) } Group { contract.title.map{Text($0)} status contract.startLocationID.map { locationID in Text(locations[locationID] ?? .unknown(locationID)).modifier(SecondaryLabelModifier()) } // contacts[Int64(contract.issuerID)].map { issuer in // Text("Issued: ").fontWeight(.semibold).foregroundColor(.primary) + // Text(issuer.name ?? "") // } }.modifier(SecondaryLabelModifier()) }.accentColor(isActive ? .primary : .secondary) } } #if DEBUG struct ContractCell_Previews: PreviewProvider { static var previews: some View { let contact = Contact(entity: NSEntityDescription.entity(forEntityName: "Contact", in: Storage.testStorage.persistentContainer.viewContext)!, insertInto: nil) contact.name = "Artem Valiant" contact.contactID = 1554561480 let solarSystem = try! Storage.testStorage.persistentContainer.viewContext.from(SDEMapSolarSystem.self).first()! let location = EVELocation(solarSystem: solarSystem, id: Int64(solarSystem.solarSystemID)) let contract = ESI.PersonalContracts.Element(acceptorID: Int(contact.contactID), assigneeID: Int(contact.contactID), availability: .corporation, buyout: 1e6, collateral: 1e7, contractID: 1, dateAccepted: nil, dateCompleted: nil, dateExpired: Date(timeIntervalSinceNow: 3600 * 10), dateIssued: Date(timeIntervalSinceNow: -3600 * 10), daysToComplete: 16, endLocationID: nil, forCorporation: false, issuerCorporationID: 0, issuerID: Int(contact.contactID), price: 1e4, reward: 1e3, startLocationID: location.id, status: .outstanding, title: "Contract Title", type: .auction, volume: 1e10) return NavigationView { List { ContractCell(contract: contract, contacts: [1554561480: contact], locations: [location.id: location]) }.listStyle(GroupedListStyle()) } } } #endif
4fd7895d493afcc1a3d874e6a0ceaefc
46.178218
190
0.49276
false
false
false
false
derekli66/Learning-Core-Audio-Swift-SampleCode
refs/heads/master
CH07_AUGraphSineWave-Swfit/CH07_AUGraphSineWave-Swfit/main.swift
mit
1
// // main.swift // CH07_AUGraphSineWave-Swfit // // Created by LEE CHIEN-MING on 21/04/2017. // Copyright © 2017 derekli66. All rights reserved. // import Foundation import AudioToolbox private let sineFrequency: Double = 2200.0 class MySineWavePlayer { var outputUnit: AudioUnit? var startingFrameCount: Double = 0.0 } // MARK: Callback functions private let SineWaveRenderProc: AURenderCallback = { (inRefCon: UnsafeMutableRawPointer, ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, inTimeStamp: UnsafePointer<AudioTimeStamp>, inBusNumber: UInt32, inNumberFrames: UInt32, ioData: UnsafeMutablePointer<AudioBufferList>?) in var player = Unmanaged<MySineWavePlayer>.fromOpaque(inRefCon).takeUnretainedValue() var j = player.startingFrameCount let cycleLength = 44100.0 / sineFrequency guard let ioData_ = ioData else { debugPrint("No ioData for further processing") return kAudioUnitErr_InvalidOfflineRender } let abl = UnsafeMutableAudioBufferListPointer(ioData_) for frame in 0..<Int(inNumberFrames) { let buffer1 = abl[0] let buffer2 = abl[1] let capacity: Int = Int(buffer1.mDataByteSize / UInt32(MemoryLayout<Float32>.size)) let frameData: Float32 = Float32(sin(2 * Double.pi * (j / cycleLength))) if let data = abl[0].mData { var float32Data = data.bindMemory(to: Float32.self, capacity: capacity) float32Data[frame] = frameData } if let data = abl[1].mData { var float32Data = data.bindMemory(to: Float32.self, capacity: capacity) float32Data[frame] = frameData } j += 1.0 if (j > cycleLength) { j -= cycleLength } } player.startingFrameCount = j return noErr } func CreateAndConnectOutputUnit(with player: inout MySineWavePlayer) -> Void { var outputcd: AudioComponentDescription = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) let compOptional: AudioComponent? = AudioComponentFindNext(nil, &outputcd) guard let comp = compOptional else { debugPrint("Cannot get output unit") exit(-1) } CheckError(AudioComponentInstanceNew(comp, &player.outputUnit), "Couldn't open component for outputUnit") // registre render callback var input: AURenderCallbackStruct = AURenderCallbackStruct(inputProc: SineWaveRenderProc, inputProcRefCon: Unmanaged.passUnretained(player).toOpaque()) guard let outputUnit = player.outputUnit else { debugPrint("Cannot get output unit for setting render callback") exit(0) } // register render callback AudioUnitSetProperty(outputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, UInt32(MemoryLayout.size(ofValue: input))) // initialize unit CheckError(AudioUnitInitialize(outputUnit), "Couldn't initialize output unit") } // Start to play sine wave var player: MySineWavePlayer = MySineWavePlayer() // set up unit and callback CreateAndConnectOutputUnit(with: &player) guard let outputUnit = player.outputUnit else { debugPrint("Couldn't start output unit") exit(0) } CheckError(AudioOutputUnitStart(outputUnit), "Couldn't start output unit") debugPrint("[SineWave] playing") // play for 5 seconds sleep(5) AudioOutputUnitStop(outputUnit) AudioUnitUninitialize(outputUnit) AudioComponentInstanceDispose(outputUnit)
413fbfe986c4211bd711eeb3f663cc70
31.773438
124
0.621216
false
false
false
false
heitorgcosta/Quiver
refs/heads/master
Quiver/Validating/Extensions/Validator+Strings.swift
mit
1
// // Validator+Strings.swift // Quiver // // Created by Heitor Costa on 20/10/17. // Copyright © 2017 Heitor Costa. All rights reserved. // import Foundation // Strings public extension Validator { // Strings static func length(min: Int = 0, max: Int = Int.max, message: String? = nil) -> Validator { return LengthValidator(min: min, max: max).with(message: message) } static func regex(pattern: String, message: String? = nil) -> Validator { return RegexValidator(pattern: pattern).with(message: message) } static func email(message: String? = nil) -> Validator { return RegexValidator(pattern: "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$").with(message: message) } static func alphabetic(message: String? = nil) -> Validator { return RegexValidator(pattern: "^[A-Za-z]+$").with(message: message) } static func numeric(message: String? = nil) -> Validator { return RegexValidator(pattern: "^[0-9]+$").with(message: message) } static func alphaNumeric(message: String? = nil) -> Validator { return RegexValidator(pattern: "^[a-zA-Z0-9]+$").with(message: message) } }
9e0eec6f626600a7eda2fdaf8ff0128a
32.108108
133
0.613878
false
false
false
false
johnsextro/cycschedule
refs/heads/master
cycschedule/SeasonsViewController.swift
gpl-2.0
1
import Foundation import UIKit class SeasonsViewController: SelectionViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var activityView: UIView! override func viewDidLoad() { activityView.hidden = false activityIndicator.startAnimating() var postEndpoint: String = "http://x8-avian-bricolage-r.appspot.com/season/SeasonService.season" let timeout = 15 let url = NSURL(string: postEndpoint) var urlRequest = NSMutableURLRequest(URL: url!) urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.HTTPMethod = "POST" let queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest( urlRequest, queue: queue, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in if data.length > 0 && error == nil{ let json = NSString(data: data, encoding: NSASCIIStringEncoding) self.extract_json(json!) }else if data.length == 0 && error == nil{ println("Nothing was downloaded") } else if error != nil{ println("Error happened = \(error)") } } ) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toSchools") { var svc = segue.destinationViewController as! SchoolsViewController svc.season = TableData[lastSelectedIndexPath!.item] } } override func extract_json(data:NSString) { var parseError: NSError? let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)! let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) if (parseError == nil) { if let seasons_obj = json as? NSDictionary { if let seasons = seasons_obj["seasons"] as? NSArray { for (var i = 0; i < seasons.count ; i++ ) { if let season_obj = seasons[i] as? NSDictionary { if let season = season_obj["season"] as? String { super.TableData.append(season) } } } } } } do_table_refresh(); activityIndicator.stopAnimating() activityView.hidden = true } }
6e3a8c3e470b55b231a59192983f05df
36.69863
113
0.538881
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Post/FakePreviewBuilder.swift
gpl-2.0
2
import Foundation class FakePreviewBuilder: NSObject { let title: String? let content: String? let tags: [String] let categories: [String] let message: String? init(title: String?, content: String?, tags: [String], categories: [String], message: String?) { self.title = title self.content = content self.tags = tags self.categories = categories self.message = message super.init() } func build() -> String { let template = loadTemplate() let messageParagraph = message.map({ "<p>\($0)</p>" }) ?? "" return template .replacingOccurrences(of: "!$title$!", with: previewTitle) .replacingOccurrences(of: "!$text$!", with: previewContent) .replacingOccurrences(of: "!$mt_keywords$!", with: previewTags) .replacingOccurrences(of: "!$categories$!", with: previewCategories) .replacingOccurrences(of: "<div class=\"page\">", with: "<div class=\"page\">\(messageParagraph)") } private func loadTemplate() -> String { guard let path = Bundle.main.path(forResource: "defaultPostTemplate", ofType: "html"), let template = try? String(contentsOfFile: path, encoding: .utf8) else { assertionFailure("Unable to load preview template") return "" } return template } } // MARK: - Formatting Fields private extension FakePreviewBuilder { var previewTitle: String { return title?.nonEmptyString() ?? NSLocalizedString("(no title)", comment: "") } var previewContent: String { guard var contentText = content?.nonEmptyString() else { let placeholder = NSLocalizedString("No Description available for this Post", comment: "") return "<h1>\(placeholder)</h1>" } contentText = contentText.replacingOccurrences(of: "\n", with: "<br>") return "<p>\(contentText)</p><br />" } var previewTags: String { let tagsLabel = NSLocalizedString("Tags: %@", comment: "") return String(format: tagsLabel, tags.joined(separator: ", ")) } var previewCategories: String { let categoriesLabel = NSLocalizedString("Categories: %@", comment: "") return String(format: categoriesLabel, categories.joined(separator: ", ")) } } // MARK: - Processing AbstractPost extension FakePreviewBuilder { convenience init(apost: AbstractPost, message: String?) { let title = apost.postTitle let content = apost.content let tags: [String] let categories: [String] if let post = apost as? Post { tags = post.tags? .components(separatedBy: ",") .map({ $0.trim() }) ?? [] categories = post.categories? .map({ $0.categoryName }) ?? [] } else { tags = [] categories = [] } self.init(title: title, content: content, tags: tags, categories: categories, message: message) } }
1524ab54db9cbe04d664b5cd990cf5fa
33.010989
110
0.583845
false
false
false
false
AjayOdedara/CoreKitTest
refs/heads/master
CoreKit/CoreKit/Core.swift
mit
1
// // Core.swift // CllearWorksCoreKit // // Created by CllearWorks Dev on 5/20/15. // Copyright (c) 2015 CllearWorks. All rights reserved. // import Foundation public typealias JSONDictionary = [String:AnyObject] public typealias JSONArray = [AnyObject] public let ApiErrorDomain = "com.CllearWorks.core.error" public let NonBreakingSpace = "\0x00a0" public let ConnectLogUserOutNotification = "ConnectLogUserOutNotification" public let DidRegisterNotification = "DidRegisterNotification" public let DidRegisterNotificationFailedOnSend = "DidRegisterNotificationFailedOnSend" public let DidFailRegisterNotification = "DidFailRegisterNotification" public let ConnectSelectedPlaceChangedNotification = "ConnectSelectedPlaceChangedNotification" public let ConnectOpenedFromHandoff = "ConnectOpenedFromHandoff" public let ConnectOpenedFromNotification = "ConnectOpenedFromNotification" public let CWRequestDidTimeOutNotification = "CWRequestDidTimeOutNotification" public let CMLoginWasSuccessful = "CMLoginWasSuccessful" public let CMContinueAsGuestSuccessful = "CMContinueAsGuestSuccessful" public let CWLogoutWasSuccessful = "CWLogoutWasSuccessful" public let CWUserReAuth = "CWUserReAuth" public let CWUpdateUserPhoto = "CWUpdateUserPhoto" public let CWNoBeacons = "CWNoBeacons" public let CWUserLogout = "CWUserLogout" public let CWCheckedInTrack = "CWCheckedInTrack" public let CWCheckedOutTrack = "CWCheckedOutTrack" public let CWBeaconsUpdateLocation = "CWBeaconsUpdateLocation" public let CWBeaconsAppKill = "CWBeaconsAppKill" public let CWUserNotificationReminder = "CWUserNotificationReminder" public let CWApplyForLeaveNotification = "CWApplyForLeave" public let CWUserBluetoothStatus = "CWUserBluetoothStatus" public let CWUserBluetoothOn = "CWUserBluetoothOn"
eed391ff13a935cfab328ddd7e5b2628
41.428571
94
0.843996
false
false
false
false
colemancda/Pedido
refs/heads/master
CorePedidoServer/CorePedidoServer/User+Function.swift
mit
1
// // User+Function.swift // CorePedidoServer // // Created by Alsey Coleman Miller on 12/6/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import CoreData import NetworkObjects import CorePedido func UserEntityFunctions() -> [String] { return [UserFunction.ChangePassword.rawValue] } func UserPerformFunction(function: UserFunction, managedObject: User, context: NSManagedObjectContext, user: User?, recievedJsonObject: [String : AnyObject]?) -> (ServerFunctionCode, [String : AnyObject]?) { switch function { case .ChangePassword: if recievedJsonObject == nil { return (ServerFunctionCode.RecievedInvalidJSONObject, nil) } // get values from JSON let oldPassword = recievedJsonObject!["oldPassword"] as? String let newPassword = recievedJsonObject!["newPassword"] as? String if oldPassword == nil || newPassword == nil { return (ServerFunctionCode.RecievedInvalidJSONObject, nil) } var validOldPassword = false context.performBlockAndWait({ () -> Void in validOldPassword = (oldPassword == managedObject.password) }) if !validOldPassword { return (ServerFunctionCode.CannotPerformFunction, nil) } // change password... context.performBlockAndWait({ () -> Void in managedObject.password = newPassword! }) // return success return (ServerFunctionCode.PerformedSuccesfully, nil) } }
d7392d178a5bd460715f64d63753ce1b
26.836066
207
0.602239
false
false
false
false
radazzouz/firefox-ios
refs/heads/master
Client/Frontend/Browser/MailProviders.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared // mailto headers: subject, body, cc, bcc protocol MailProvider { var beginningScheme: String {get set} var supportedHeaders: [String] {get set} func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? } private func constructEmailURLString(_ beginningURLString: String, metadata: MailToMetadata, supportedHeaders: [String], bodyHName: String = "body", toHName: String = "to") -> String { var lowercasedHeaders = [String: String]() metadata.headers.forEach { (hname, hvalue) in lowercasedHeaders[hname.lowercased()] = hvalue } var toParam: String if let toHValue = lowercasedHeaders["to"] { let value = metadata.to.isEmpty ? toHValue : [metadata.to, toHValue].joined(separator: "%2C%20") lowercasedHeaders.removeValue(forKey: "to") toParam = "\(toHName)=\(value)" } else { toParam = "\(toHName)=\(metadata.to)" } var queryParams: [String] = [] lowercasedHeaders.forEach({ (hname, hvalue) in if supportedHeaders.contains(hname) { queryParams.append("\(hname)=\(hvalue)") } else if hname == "body" { queryParams.append("\(bodyHName)=\(hvalue)") } }) let stringParams = queryParams.joined(separator: "&") let finalURLString = beginningURLString + (stringParams.isEmpty ? toParam : [toParam, stringParams].joined(separator: "&")) return finalURLString } class ReaddleSparkIntegration: MailProvider { var beginningScheme = "readdle-spark://compose?" var supportedHeaders = [ "subject", "recipient", "textbody", "html", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "textbody", toHName: "recipient").asURL } } class AirmailIntegration: MailProvider { var beginningScheme = "airmail://compose?" var supportedHeaders = [ "subject", "from", "to", "cc", "bcc", "plainBody", "htmlBody" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "htmlBody").asURL } } class MyMailIntegration: MailProvider { var beginningScheme = "mymail-mailto://?" var supportedHeaders = [ "to", "subject", "body", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class MailRuIntegration: MyMailIntegration { override init() { super.init() self.beginningScheme = "mailru-mailto://?" } } class MSOutlookIntegration: MailProvider { var beginningScheme = "ms-outlook://emails/new?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } }
926b1b4b94d9d3969e0e049a10d0bbe5
30.424779
184
0.647705
false
false
false
false
kstaring/swift
refs/heads/upstream-master
test/SILGen/protocol_extensions.swift
apache-2.0
1
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | %FileCheck %s public protocol P1 { func reqP1a() subscript(i: Int) -> Int { get set } } struct Box { var number: Int } extension P1 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): final func extP1a() { // CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () reqP1a() // CHECK: return } // CHECK-LABEL: sil @_TFE19protocol_extensionsPS_2P16extP1b{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): public final func extP1b() { // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () extP1a() // CHECK: return } subscript(i: Int) -> Int { // materializeForSet can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance) get { return 0 } set {} } final func callSubscript() -> Int { // But here we have to do a witness method call: // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P113callSubscript{{.*}} // CHECK: bb0(%0 : $*Self): // CHECK: witness_method $Self, #P1.subscript!getter.1 // CHECK: return return self[0] } static var staticReadOnlyProperty: Int { return 0 } static var staticReadWrite1: Int { get { return 0 } set { } } static var staticReadWrite2: Box { get { return Box(number: 0) } set { } } } // ---------------------------------------------------------------------------- // Using protocol extension members with concrete types // ---------------------------------------------------------------------------- class C : P1 { func reqP1a() { } } // (materializeForSet test from above) // CHECK-LABEL: sil [transparent] [thunk] @_TTWC19protocol_extensions1CS_2P1S_FS1_m9subscriptFSiSi // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $Int, %3 : $*C): // CHECK: function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSiSi // CHECK: return class D : C { } struct S : P1 { func reqP1a() { } } struct G<T> : P1 { func reqP1a() { } } struct MetaHolder { var d: D.Type = D.self var s: S.Type = S.self } struct GenericMetaHolder<T> { var g: G<T>.Type = G<T>.self } func inout_func(_ n: inout Int) {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testDFTVS_10MetaHolder2ddMCS_1D1dS1__T_ : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> () // CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : $D): func testD(_ m: MetaHolder, dd: D.Type, d: D) { // CHECK: [[D2:%[0-9]+]] = alloc_box $@box D // CHECK: [[RESULT:%.*]] = project_box [[D2]] // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: [[DCOPY:%[0-9]+]] = alloc_stack $D // CHECK: store [[D]] to [init] [[DCOPY]] : $*D // CHECK: apply [[FN]]<D>([[RESULT]], [[DCOPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var d2: D = d.returnsSelf() // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = D.staticReadOnlyProperty // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si D.staticReadWrite1 = 1 // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack D.staticReadWrite1 += 1 // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box D.staticReadWrite2 = Box(number: 2) // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack D.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&D.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = dd.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si dd.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack dd.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box dd.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack dd.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&dd.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = m.d.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si m.d.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.d.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box m.d.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.d.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.d.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testSFTVS_10MetaHolder2ssMVS_1S_T_ func testS(_ m: MetaHolder, ss: S.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = S.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type S.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack S.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type S.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack S.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&S.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = ss.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type ss.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack ss.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type ss.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack ss.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&ss.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = m.s.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type m.s.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.s.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type m.s.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.s.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.s.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testG func testG<T>(_ m: GenericMetaHolder<T>, gg: G<T>.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = G<T>.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack G<T>.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack G<T>.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&G<T>.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = gg.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack gg.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack gg.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&gg.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = m.g.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.g.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.g.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.g.staticReadWrite2.number) // CHECK: return } // ---------------------------------------------------------------------------- // Using protocol extension members with existentials // ---------------------------------------------------------------------------- extension P1 { final func f1() { } final subscript (i: Int64) -> Bool { get { return true } } final var prop: Bool { get { return true } } final func returnsSelf() -> Self { return self } final var prop2: Bool { get { return true } set { } } final subscript (b: Bool) -> Bool { get { return b } set { } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials1 // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool, [[I:%[0-9]+]] : $Int64): func testExistentials1(_ p1: P1, b: Bool, i: Int64) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) // CHECK: [[F1:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P12f1{{.*}} // CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () p1.f1() // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFVs5Int64Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool // CHECK: destroy_addr [[POPENED_COPY]] // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b2 = p1[i] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g4propSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b3 = p1.prop } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials2 // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentials2(_ p1: P1) { // CHECK: [[P1A:%[0-9]+]] = alloc_box $@box P1 // CHECK: [[PB:%.*]] = project_box [[P1A]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1 // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var p1a: P1 = p1.returnsSelf() } // CHECK-LABEL: sil hidden @_TF19protocol_extensions23testExistentialsGetters // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentialsGetters(_ p1: P1) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g5prop2Sb // CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool let b: Bool = p1.prop2 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSbSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool let b2: Bool = p1[b] } // CHECK-LABEL: sil hidden @_TF19protocol_extensions22testExistentialSetters // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool): func testExistentialSetters(_ p1: P1, b: Bool) { var p1 = p1 // CHECK: [[PBOX:%[0-9]+]] = alloc_box $@box P1 // CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]] // CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr p1.prop2 = b // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s9subscriptFSbSb // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1 p1[b] = b // CHECK: return } struct HasAP1 { var p1: P1 var someP1: P1 { get { return p1 } set { p1 = newValue } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions29testLogicalExistentialSetters // CHECK: bb0([[HASP1:%[0-9]+]] : $*HasAP1, [[B:%[0-9]+]] : $Bool) func testLogicalExistentialSetters(_ hasAP1: HasAP1, _ b: Bool) { var hasAP1 = hasAP1 // CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box $@box HasAP1 // CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]] // CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1 // CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1 // CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1 // CHECK-NEXT: copy_addr [[PBHASP1]] to [initialization] [[HASP1_COPY]] : $*HasAP1 // CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1g6someP1PS_2P1_ : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], %8) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1s6someP1PS_2P1_ : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[PBHASP1]]) : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK-NOT: deinit_existential_addr hasAP1.someP1.prop2 = b // CHECK: return } func plusOneP1() -> P1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions38test_open_existential_semantics_opaque func test_open_existential_semantics_opaque(_ guaranteed: P1, immediate: P1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $@box P1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_addr %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) guaranteed.f1() // -- Need a guaranteed copy because it's immutable // CHECK: copy_addr [[PB]] to [initialization] [[IMMEDIATE:%.*]] : // CHECK: [[VALUE:%.*]] = open_existential_addr [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[IMMEDIATE]] // CHECK: dealloc_stack [[IMMEDIATE]] immediate.f1() // CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1 // CHECK: [[VALUE:%.*]] = open_existential_addr [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[PLUS_ONE]] // CHECK: dealloc_stack [[PLUS_ONE]] plusOneP1().f1() } protocol CP1: class {} extension CP1 { final func f1() { } } func plusOneCP1() -> CP1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions37test_open_existential_semantics_class func test_open_existential_semantics_class(_ guaranteed: CP1, immediate: CP1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $@box CP1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: copy_value %0 // CHECK: [[VALUE:%.*]] = open_existential_ref %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_value [[VALUE]] // CHECK-NOT: destroy_value %0 guaranteed.f1() // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[PB]] // CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[VALUE]] // CHECK-NOT: destroy_value [[IMMEDIATE]] immediate.f1() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1 // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[VALUE]] // CHECK-NOT: destroy_value [[PLUS_ONE]] plusOneCP1().f1() } protocol InitRequirement { init(c: C) } extension InitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(d: D) { // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]] // CHECK: apply [[DELEGATEE]]<Self>({{%.*}}, [[ARG_COPY_CAST]], [[SELF_TYPE]]) self.init(c: d) } // CHECK: } // end sil function '_TFE19protocol_extensionsPS_15InitRequirementC{{.*}}' // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} : $@convention(method) // CHECK: function_ref @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} // CHECK: } // end sil function '_TFE19protocol_extensionsPS_15InitRequirementC{{.*}}' init(d2: D) { self.init(d: d2) } } protocol ClassInitRequirement: class { init(c: C) } extension ClassInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_20ClassInitRequirementC{{.*}} : $@convention(method) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0 // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]] // CHECK: apply [[DELEGATEE]]<Self>([[ARG_COPY_CAST]], [[SELF_TYPE]]) // CHECK: } // end sil function '_TFE19protocol_extensionsPS_20ClassInitRequirementC{{.*}}' init(d: D) { self.init(c: d) } } @objc class OC {} @objc class OD: OC {} @objc protocol ObjCInitRequirement { init(c: OC, d: OC) } func foo(_ t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement { return t.init(c: OC(), d: OC()) } extension ObjCInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_19ObjCInitRequirementC{{.*}} : $@convention(method) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $OD, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]] // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self // CHECK: [[WITNESS:%.*]] = witness_method [volatile] $Self, #ObjCInitRequirement.init!initializer.1.foreign : $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[ARG_COPY_1:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_1_UPCAST:%.*]] = upcast [[ARG_COPY_1]] // CHECK: [[ARG_COPY_2:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_2_UPCAST:%.*]] = upcast [[ARG_COPY_2]] // CHECK: apply [[WITNESS]]<Self>([[ARG_COPY_1_UPCAST]], [[ARG_COPY_2_UPCAST]], [[SELF]]) // CHECK: } // end sil function '_TFE19protocol_extensionsPS_19ObjCInitRequirementC{{.*}}' init(d: OD) { self.init(c: d, d: d) } } // rdar://problem/21370992 - delegation from an initializer in a // protocol extension to an @objc initializer in a class. class ObjCInitClass { @objc init() { } } protocol ProtoDelegatesToObjC { } extension ProtoDelegatesToObjC where Self : ObjCInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_13ObjCInitClassxS_20ProtoDelegatesToObjCrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $@box Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[SELF_META]] : $@thick Self.Type to $@objc_metatype Self.Type // CHECK: [[SELF_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[SELF_META_OBJC]] : $@objc_metatype Self.Type, $Self // CHECK: [[SELF_ALLOC_C:%[0-9]+]] = upcast [[SELF_ALLOC]] : $Self to $ObjCInitClass // CHECK: [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_ALLOC_C]] : $ObjCInitClass, #ObjCInitClass.init!initializer.1 : (ObjCInitClass.Type) -> () -> ObjCInitClass , $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_ALLOC_C]]) : $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // Delegating from an initializer in a protocol extension where Self // has a superclass to a required initializer of that class. class RequiredInitClass { required init() { } } protocol ProtoDelegatesToRequired { } extension ProtoDelegatesToRequired where Self : RequiredInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_17RequiredInitClassxS_24ProtoDelegatesToRequiredrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $@box Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type // CHECK: [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator.1 : (RequiredInitClass.Type) -> () -> RequiredInitClass , $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // ---------------------------------------------------------------------------- // Default implementations via protocol extensions // ---------------------------------------------------------------------------- protocol P2 { associatedtype A func f1(_ a: A) func f2(_ a: A) var x: A { get } } extension P2 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f1{{.*}} // CHECK: witness_method $Self, #P2.f2!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f1(_ a: A) { f2(a) f3(a) } // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f2{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f2(_ a: A) { f1(a) f3(a) } func f3(_ a: A) {} // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f4{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: witness_method $Self, #P2.f2!1 // CHECK: return func f4() { f1(x) f2(x) } }
fa5e29f3ff00bbfc9cb4a010cc52276b
40.483294
280
0.647384
false
false
false
false
gobetti/Swift
refs/heads/master
SocialFrameworkTwitter/SocialFrameworkTwitter/SecondViewController.swift
mit
1
// // SecondViewController.swift // // Created by Carlos Butron on 11/11/14. // Copyright (c) 2014 Carlos Butron. // // 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 UIKit import Accounts import QuartzCore import Social import CoreGraphics import Foundation class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var table: UITableView! var refreshControl:UIRefreshControl! var tweetsArray = NSArray() var imageDictionary:NSMutableDictionary! override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshTimeLine:", forControlEvents: UIControlEvents.ValueChanged) self.refreshTimeLine() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refreshTimeLine(){ if(SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)){ let accountStore = ACAccountStore() let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: {(granted,error) in if(granted==true){ let arrayOfAccounts = accountStore.accountsWithAccountType(accountType) let tempAccount = arrayOfAccounts.last as! ACAccount let tweetURL = NSURL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json") let tweetRequest = SLRequest(forServiceType:SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: tweetURL, parameters: nil) tweetRequest.account = tempAccount tweetRequest.performRequestWithHandler({(responseData,urlResponse,error) in if(error == nil){ let responseJSON: NSArray? do { responseJSON = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as? NSArray self.tweetsArray = responseJSON! self.imageDictionary = NSMutableDictionary() dispatch_async(dispatch_get_main_queue(), {self.table.reloadData()}) } catch _ { print("JSON ERROR ") } // /*get tweets*/ // let jsonError:NSError? // let responseJSON = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) as! NSArray // if(jsonError != nil) { // print("JSON ERROR ") // } // else{ // self.tweetsArray = responseJSON // self.imageDictionary = NSMutableDictionary() // dispatch_async(dispatch_get_main_queue(), // {self.table.reloadData()}) // }} } else{ /*access Error*/ } }) } }) } else { /*Error: you need Twitter account*/ } refreshControl.endRefreshing() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tweetsArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("timelineCell") as! TimelineCell let currentTweet = self.tweetsArray.objectAtIndex(indexPath.row) as! NSDictionary let currentUser = currentTweet["user"] as! NSDictionary cell.userNameLabel!.text = currentUser["name"] as? String cell.tweetlabel!.text = currentTweet["text"] as! String let userName = cell.userNameLabel.text if((self.imageDictionary[userName!]) != nil){ cell.userImageView.image = (self.imageDictionary[userName!] as! UIImage) } else{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let imageURL = NSURL(string: currentUser.objectForKey("profile_image_url") as! String) let imageData = NSData(contentsOfURL: imageURL!) self.imageDictionary.setObject(UIImage(data: imageData!)!, forKey: userName!) (dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { cell.userImageView.image = (self.imageDictionary[cell.userNameLabel.text!] as! UIImage) }) }) } return cell } }
688f64103423dd868fe363d2f23074c9
42.788618
166
0.638693
false
false
false
false
fhchina/firefox-ios
refs/heads/master
Client/Frontend/Browser/SessionData.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class SessionData: NSObject, NSCoding { let currentPage: Int let urls: [NSURL] let lastUsedTime: Timestamp /** Creates a new SessionData object representing a serialized tab. :param: currentPage The active page index. Must be in the range of (-N, 0], where 1-N is the first page in history, and 0 is the last. :param: urls The sequence of URLs in this tab's session history. :param: lastUsedTime The last time this tab was modified. **/ init(currentPage: Int, urls: [NSURL], lastUsedTime: Timestamp) { self.currentPage = currentPage self.urls = urls self.lastUsedTime = lastUsedTime assert(urls.count > 0, "Session has at least one entry") assert(currentPage > -urls.count && currentPage <= 0, "Session index is valid") } required init(coder: NSCoder) { self.currentPage = coder.decodeObjectForKey("currentPage") as? Int ?? 0 self.urls = coder.decodeObjectForKey("urls") as? [NSURL] ?? [] self.lastUsedTime = UInt64(coder.decodeInt64ForKey("lastUsedTime")) ?? NSDate.now() } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(currentPage, forKey: "currentPage") coder.encodeObject(urls, forKey: "urls") coder.encodeInt64(Int64(lastUsedTime), forKey: "lastUsedTime") } }
09c1c17076d25e2bc62f527a6fe6fdd2
37.952381
91
0.64893
false
false
false
false
deanstone/swift-toolbox
refs/heads/master
AsyncSocket.swift
mit
1
// // AsyncSocket.swift // swift-toolbox // // Created by dean xu on 18/7/2016. // Copyright © 2016 com.runsdata. All rights reserved. // import Foundation import CocoaAsyncSocket class AsyncSocket :NSObject, GCDAsyncSocketDelegate{ var socket:GCDAsyncSocket? = nil let delegateQueue = dispatch_queue_create("delegateQueue", DISPATCH_QUEUE_SERIAL) let socketQueue = dispatch_queue_create("socketQueue", DISPATCH_QUEUE_SERIAL) let workQueue = dispatch_queue_create("workQueue", DISPATCH_QUEUE_SERIAL) let PH_TAG = 100 let PB_TAG = 200 var user_id:String = "" var auth_key:String = "" var host:String = "127.0.0.1" var port:UInt16 = 9080 var autoReconnect = true typealias status_cb_t = @convention(block) (status:String) -> Void typealias work_cb_t = @convention(block) (data:NSData) -> Void var scb:status_cb_t? = nil var wcb: work_cb_t? = nil init(userId:String, authKey: String,host: String,port:UInt16) { self.user_id = userId self.auth_key = authKey self.host = host self.port = port } func initCallback(scb:status_cb_t, wcb: work_cb_t) -> Void { self.scb = scb self.wcb = wcb } func connect() -> Void { socket = GCDAsyncSocket(delegate: self, delegateQueue: delegateQueue, socketQueue: socketQueue) try! socket?.connectToHost(self.host, onPort: self.port) } func socket(sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { scb?(status:"connected") sock.writeData("{\"user_id\":\"\(self.user_id)\",\"auth_key\":\"\(self.auth_key)\"}".dataUsingEncoding(NSUTF8StringEncoding)!, withTimeout: -1, tag: PH_TAG) sock.readDataToLength(4, withTimeout: -1, tag: PH_TAG) } func socketDidDisconnect(sock: GCDAsyncSocket, withError err: NSError?) { scb?(status:"disconnect") sock.disconnect() if autoReconnect { let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 5 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue(), { try! self.socket?.connectToHost(self.host, onPort: self.port) }) } } func socket(sock: GCDAsyncSocket, didReadData data: NSData, withTag tag: Int) { scb?(status:"readdata:\(data.length)") if tag == PH_TAG { var len: UInt32 = 0 data.getBytes(&len, length: 4) let length = CFSwapInt32BigToHost(len) sock.readDataToLength(UInt(length), withTimeout: -1, tag: PB_TAG) } else { sock.readDataToLength(4, withTimeout: -1, tag: PH_TAG) dispatch_async(workQueue, { let cpData = NSData.init(data: data) self.doWork(cpData) }) } } func doWork(data:NSData) -> Void { wcb?(data:data) } // Public API func writeJsonString(json: String) -> Void { socket?.writeData(json.dataUsingEncoding(NSUTF8StringEncoding)!, withTimeout: -1, tag: PH_TAG) } }
e46ae75b7f53f44d9b659f8607def06b
32.934783
164
0.608264
false
false
false
false
jurre/BPM
refs/heads/master
BPM/ViewController.swift
mit
1
// // ViewController.swift // BPM // // Created by Jurre Stender on 08/02/16. // Copyright © 2016 jurre. All rights reserved. // import UIKit class ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var background: UIView! @IBOutlet weak var bpmLabel: UILabel! @IBOutlet weak var beatCountLabel: UILabel! @IBOutlet weak var bpmPreciseLabel: UILabel! var counter = BPMCounter() override func viewDidLoad() { super.viewDidLoad() let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))) gestureRecognizer.delegate = self; background.addGestureRecognizer(gestureRecognizer) counter.resetTimer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func handleTap(_ recognizer: UITapGestureRecognizer) { counter.beat() updateView() } @IBAction func resetButtonTapped(_ sender: AnyObject) { counter.reset() updateView() } func updateView() { var bpmValue = "-" var bpmPreciseValue = "-" if counter.bpm > 0 && counter.beatCount > 3 { bpmValue = String(format: "%.0f", counter.bpm) bpmPreciseValue = String(format: "%.2f", counter.bpm) } bpmLabel.text = bpmValue bpmPreciseLabel.text = bpmPreciseValue beatCountLabel.text = "\(counter.beatCount) beats" } }
a6098704a13bc5ce3a5a5a589c9f16fb
25.910714
117
0.641009
false
false
false
false
Olinguito/YoIntervengoiOS
refs/heads/master
Yo Intervengo/Helpers/CallOut/CallOutTop.swift
mit
1
// // CallOutTop.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 1/13/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import Foundation import UIKit class CallOutTop: UIView{ required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(red:0.761, green:0.286, blue:0.000, alpha: 1) let imgIcon = UIImageView(frame: CGRect(x: 23, y: 10, width: 17, height: 55)) imgIcon.image = UIImage(named: "img1") self.addSubview(imgIcon) let title = UILabel(frame: CGRect(x: 70, y: 8, width: 112, height: 40)) title.numberOfLines = 2 title.font = UIFont(name: "Roboto-Light", size: 14) title.textColor = UIColor.whiteColor() title.text = "Puente Calle 33 con Av. López ..." self.addSubview(title) let subtitle = UILabel(frame: CGRect(x: 70, y: 50, width: 112, height: 10)) subtitle.font = UIFont(name: "Roboto-Light", size: 9) subtitle.textColor = UIColor.whiteColor() subtitle.text = "Nombre Subcategoría" self.addSubview(subtitle) let imgProject = UIImageView(frame: CGRect(x: 193, y: 0, width: 76, height: frame.height)) imgProject.image = UIImage(named: "bg1") self.addSubview(imgProject) } }
5f9f2e1711027295a554118f0da70053
33.512195
98
0.624735
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/CodeFragments/Category/Date+JCDate.swift
mit
3
// // Date+JCDate.swift // JCSwiftKitDemo // // Created by molin.JC on 2017/1/20. // Copyright © 2017年 molin. All rights reserved. // private let kDATE_MINUTE_SEC = 60; // 一分 = 60秒 private let kDATE_HOURS_SEC = 3600; // 一小时 = 60分 = 3600秒 private let kDATE_DAY_SEC = 86400; // 一天 = 24小时 = 86400秒 private let kDATE_WEEK_SEC = 604800; // 一周 = 7天 = 604800秒 import Foundation extension Date { var year: Int { get { return NSCalendar.current.component(Calendar.Component.year, from: self); } } var month: Int { get { return NSCalendar.current.component(Calendar.Component.month, from: self); } } var day: Int { get { return NSCalendar.current.component(Calendar.Component.day, from: self); } } var hour: Int { get { return NSCalendar.current.component(Calendar.Component.hour, from: self); } } var minute: Int { get { return NSCalendar.current.component(Calendar.Component.minute, from: self); } } var second: Int { get { return NSCalendar.current.component(Calendar.Component.second, from: self); } } var nanosecond: Int { get { return NSCalendar.current.component(Calendar.Component.nanosecond, from: self); } } var weekday: Int { get { return NSCalendar.current.component(Calendar.Component.weekday, from: self); } } var weekdayOrdinal: Int { get { return NSCalendar.current.component(Calendar.Component.weekdayOrdinal, from: self); } } var weekOfMonth: Int { get { return NSCalendar.current.component(Calendar.Component.weekOfMonth, from: self); } } var weekOfYear: Int { get { return NSCalendar.current.component(Calendar.Component.weekOfYear, from: self); } } var yearForWeekOfYear: Int { get { return NSCalendar.current.component(Calendar.Component.yearForWeekOfYear, from: self); } } var quarter: Int { get { return NSCalendar.current.component(Calendar.Component.quarter, from: self); } } /// 闰月 var isLeapMonth: Bool { get { return DateComponents.init().isLeapMonth!; } } /// 闰年 var isLeapYear: Bool { get { let year = self.year; return ((year % 400 == 0) || (year % 100 == 0) || (year % 4 == 0)); } } /// 今天 var isToday: Bool { get { if (fabs(self.timeIntervalSinceNow) >= Double(kDATE_DAY_SEC)) { return false; } return Date.init().day == self.day; } } } extension Date { static func dateWithString(_ stringDate: String) -> Date? { return Date.dateWithString(stringDate, "yyyy-MM-dd HH:mm:ss"); } static func dateWithString(_ stringDate: String, _ format: String) -> Date? { let formatter = DateFormatter.init(); formatter.locale = NSLocale.current; formatter.dateFormat = format; return formatter.date(from: stringDate); } func string() -> String { return self.stringWithFormat(format: "yyyy-MM-dd HH:mm:ss"); } func stringWithFormat(format: String) -> String { let formatter = DateFormatter.init(); formatter.locale = NSLocale.current; formatter.dateFormat = format; return formatter.string(from: self as Date); } /// 明天 static func dateTomorrow() -> Date { return Date.dateWithDaysFromNow(days: 1); } /// 后几天 static func dateWithDaysFromNow(days: NSInteger) -> Date { return Date.init().dateByAdding(days: days); } /// 昨天 static func dateYesterday() -> Date { return Date.dateWithDaysBeforeNow(days: 1); } /// 前几天 static func dateWithDaysBeforeNow(days: NSInteger) -> Date { return Date.init().dateByAdding(days: -(days)); } /// 当前小时后hours个小时 static func dateWithHoursFromNow(hours: NSInteger) -> Date { return Date.dateByAddingTimeInterval(ti: TimeInterval(kDATE_HOURS_SEC * hours)); } /// 当前小时前hours个小时 static func dateWithHoursBeforeNow(hours: NSInteger) -> Date { return Date.dateByAddingTimeInterval(ti: TimeInterval(-kDATE_HOURS_SEC * hours)); } /// 当前分钟后minutes个分钟 static func dateWithMinutesFromNow(minutes: NSInteger) -> Date { return Date.dateByAddingTimeInterval(ti: TimeInterval(kDATE_MINUTE_SEC * minutes)); } /// 当前分钟前minutes个分钟 static func dateWithMinutesBeforeNow(minutes: NSInteger) -> Date { return Date.dateByAddingTimeInterval(ti: TimeInterval(-kDATE_MINUTE_SEC * minutes)); } /// 追加天数,生成新的Date func dateByAdding(days: NSInteger) -> Date { var dateComponents = DateComponents.init(); dateComponents.day = days; let date = NSCalendar.current.date(byAdding: dateComponents, to: (self as Date?)!); return (date as Date?)!; } /// 追加秒数,生成新的Date static func dateByAddingTimeInterval(ti: TimeInterval) -> Date { let aTimeInterval = Date.init().timeIntervalSinceReferenceDate + ti; let date = Date.init(timeIntervalSinceReferenceDate: aTimeInterval); return date; } }
25a565f9ee12c86d4153527c87495dd4
26.765
98
0.584189
false
false
false
false
dnevera/ImageMetalling
refs/heads/master
ImageMetalling-02/ImageMetalling-02/IMPSHLView.swift
mit
1
// // IMPView.swift // ImageMetalling-02 // // Created by denis svinarchuk on 27.10.15. // Copyright © 2015 ImageMetalling. All rights reserved. // import UIKit import Metal import MetalKit /// /// Параметризация фильтра /// struct IMPShadowsHighLights { /// /// Степень фильтрации /// var level:Float; /// float3 - тип данных экспортируемых из Metal Framework /// .x - вес светов/теней 0-1 /// .y - тональная ширины светов/теней над которыми производим операцию >0-1 /// .w - степень подъема/наклона кривой воздействия [1-5] /// var shadows:float3; var highlights:float3; }; /** * Представление результатов обработки картинки в GCD. */ class IMPSHLView: UIView { private func updateUniform(){ var shadows:IMPShadowsHighLights = IMPShadowsHighLights( level: level, shadows: float3(1, shadowsWidth, 1), highlights: float3(1, highlightsWidth, 1) ) shadowsHighlightslUniform = shadowsHighlightslUniform ?? self.device.newBufferWithLength(sizeof(IMPShadowsHighLights), options: MTLResourceOptions.CPUCacheModeDefaultCache) memcpy(shadowsHighlightslUniform.contents(), &shadows, sizeof(IMPShadowsHighLights)) } var level:Float!{ didSet(oldValue){ updateUniform() } } var shadowsWidth:Float!{ didSet(oldValue){ if shadowsWidth<0.01 { shadowsWidth=0.01 } else if shadowsWidth>1 { shadowsWidth=1 } updateUniform() } } var highlightsWidth:Float!{ didSet(oldValue){ if highlightsWidth<0.01 { highlightsWidth=0.01 } else if highlightsWidth>1 { highlightsWidth=1 } updateUniform() } } private var shadowsHighlightslUniform:MTLBuffer!=nil private let device:MTLDevice! = MTLCreateSystemDefaultDevice() private var commandQueue:MTLCommandQueue!=nil private var metalView:MTKView!=nil private var imageTexture:MTLTexture!=nil private var pipeline:MTLComputePipelineState!=nil private let threadGroupCount = MTLSizeMake(8, 8, 1) private var threadGroups:MTLSize? func loadImage(file: String){ autoreleasepool { let textureLoader = MTKTextureLoader(device: self.device!) if let image = UIImage(named: file){ imageTexture = try! textureLoader.newTextureWithCGImage(image.CGImage!, options: nil) threadGroups = MTLSizeMake( (imageTexture.width+threadGroupCount.width)/threadGroupCount.width, (imageTexture.height+threadGroupCount.height)/threadGroupCount.height, 1) } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) metalView = MTKView(frame: self.bounds, device: self.device) metalView.autoResizeDrawable = true metalView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] metalView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI),1.0,0.0,0.0) self.addSubview(metalView) let scaleFactor:CGFloat! = metalView.contentScaleFactor metalView.drawableSize = CGSizeMake(self.bounds.width*scaleFactor, self.bounds.height*scaleFactor) commandQueue = device.newCommandQueue() let library:MTLLibrary! = self.device.newDefaultLibrary() let function:MTLFunction! = library.newFunctionWithName("kernel_adjustSHL") pipeline = try! self.device.newComputePipelineStateWithFunction(function) level = 1 shadowsWidth = 1 highlightsWidth = 1 updateUniform() } func refresh(){ if let actualImageTexture = imageTexture{ let commandBuffer = commandQueue.commandBuffer() let encoder = commandBuffer.computeCommandEncoder() encoder.setComputePipelineState(pipeline) encoder.setTexture(actualImageTexture, atIndex: 0) encoder.setTexture(metalView.currentDrawable!.texture, atIndex: 1) encoder.setBuffer(self.shadowsHighlightslUniform, offset: 0, atIndex: 0) encoder.dispatchThreadgroups(threadGroups!, threadsPerThreadgroup: threadGroupCount) encoder.endEncoding() commandBuffer.presentDrawable(metalView.currentDrawable!) commandBuffer.commit() } } }
3d590181ab7a5e4e4dfd961e286c5860
29.699346
106
0.622099
false
false
false
false
Ashok28/Kingfisher
refs/heads/acceptance
DYLive/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift
apache-2.0
23
// // SizeExtensions.swift // Kingfisher // // Created by onevcat on 2018/09/28. // // Copyright (c) 2019 Wei Wang <onevcat@gmail.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 CoreGraphics extension CGSize: KingfisherCompatibleValue {} extension KingfisherWrapper where Base == CGSize { /// Returns a size by resizing the `base` size to a target size under a given content mode. /// /// - Parameters: /// - size: The target size to resize to. /// - contentMode: Content mode of the target size should be when resizing. /// - Returns: The resized size under the given `ContentMode`. public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize { switch contentMode { case .aspectFit: return constrained(size) case .aspectFill: return filling(size) case .none: return size } } /// Returns a size by resizing the `base` size by making it aspect fitting the given `size`. /// /// - Parameter size: The size in which the `base` should fit in. /// - Returns: The size fitted in by the input `size`, while keeps `base` aspect. public func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } /// Returns a size by resizing the `base` size by making it aspect filling the given `size`. /// /// - Parameter size: The size in which the `base` should fill. /// - Returns: The size be filled by the input `size`, while keeps `base` aspect. public func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } /// Returns a `CGRect` for which the `base` size is constrained to an input `size` at a given `anchor` point. /// /// - Parameters: /// - size: The size in which the `base` should be constrained to. /// - anchor: An anchor point in which the size constraint should happen. /// - Returns: The result `CGRect` for the constraint operation. public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect { let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0), y: anchor.y.clamped(to: 0.0...1.0)) let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height let r = CGRect(x: x, y: y, width: size.width, height: size.height) let ori = CGRect(origin: .zero, size: base) return ori.intersection(r) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension CGRect { func scaled(_ scale: CGFloat) -> CGRect { return CGRect(x: origin.x * scale, y: origin.y * scale, width: size.width * scale, height: size.height * scale) } } extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } }
41ebb477eb5479c45de1052fbd07b828
41.145455
113
0.647541
false
false
false
false
XSega/Words
refs/heads/master
Words/Scenes/Trainings/TrainingRouter.swift
mit
1
// // SprintTrainingRouter.swift // Words // // Created by Sergey Ilyushin on 28/07/2017. // Copyright (c) 2017 Sergey Ilyushin. All rights reserved. // import UIKit @objc protocol ITrainingRouter { } protocol ITrainingDataPassing { var dataStore: ITrainingDataStore! { get } } class TrainingRouter: NSObject, ITrainingRouter, ITrainingDataPassing { weak var viewController: TrainingViewController! var dataStore: ITrainingDataStore! // MARK: Routing func routeToFinishTraining(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? FinishTrainingViewController, var destinationDS = destinationVC.router!.dataStore { passDataToFinishTraining(source: dataStore, destination: &destinationDS) } } // MARK: Passing data func passDataToFinishTraining(source: ITrainingDataStore, destination: inout IFinishTrainingDataStore) { destination.mistakes = source.mistakes destination.words = source.words destination.learnedIdentifiers = source.learnedIdentifiers } }
484f77627791ab1ef053c9c0c84f338d
26.769231
136
0.730379
false
false
false
false
fizker/mogenerator
refs/heads/master
test/MogenSwiftTest/MogenSwiftTestTests/MogenSwiftTestTests.swift
mit
5
import Cocoa import XCTest import MogenSwiftTest class MogenSwiftTestTests: XCTestCase { func newMoc() -> (NSManagedObjectContext) { let momURL : NSURL = NSBundle.mainBundle().URLForResource("MogenSwiftTest", withExtension: "momd") let mom : NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: momURL) let psc : NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: mom); let ps : NSPersistentStore = psc.addPersistentStoreWithType( NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: nil) let moc : NSManagedObjectContext = NSManagedObjectContext() moc.persistentStoreCoordinator = psc return moc } func testUnorderedToMany() { let moc = newMoc() let a = MyEntityMO(managedObjectContext: moc) println("^^before: \(a)") a.stringAttribute = "fred"; a.integerAttribute = 42 println("^^after 1: \(a)") a.integerAttribute = nil println("^^after 2: \(a)") XCTAssert(moc.save(nil), "") //-- var srcs = UnorderedToManySrcMO.fetchAllUnorderedToManySrcs(moc) XCTAssertEqual(srcs.count, 0, "") var dsts = UnorderedToManyDstMO.fetchAllUnorderedToManyDsts(moc) XCTAssertEqual(dsts.count, 0, "") //-- let src : UnorderedToManySrcMO = UnorderedToManySrcMO( entity: NSEntityDescription.entityForName_workaround("UnorderedToManySrc", inManagedObjectContext:moc), insertIntoManagedObjectContext: moc) //-- srcs = UnorderedToManySrcMO.fetchAllUnorderedToManySrcs(moc) XCTAssertEqual(srcs.count, 1, "") XCTAssert(moc.save(nil), "") //-- var dst1 : UnorderedToManyDstMO = UnorderedToManyDstMO( entity: NSEntityDescription.entityForName_workaround("UnorderedToManyDst", inManagedObjectContext:moc), insertIntoManagedObjectContext: moc) var dst2 : UnorderedToManyDstMO = UnorderedToManyDstMO( entity: NSEntityDescription.entityForName_workaround("UnorderedToManyDst", inManagedObjectContext:moc), insertIntoManagedObjectContext: moc) src.addRelationshipObject(dst1) src.addRelationshipObject(dst2) /*UnorderedToManyDstMO(managedObjectContext: moc) XCTAssert(moc.save(nil), "")*/ /* //-- var src = UnorderedToManyDstMO(managedObjectContext: moc) src.tag = 42 var dst = UnorderedToManyDestinationMO(managedObjectContext: moc) dst.tag = 43 src.addRelationshipObject(dst)*/ // //-- } } extension NSEntityDescription { class func entityForName_workaround(entityName: String!, inManagedObjectContext context: NSManagedObjectContext!) -> NSEntityDescription! { let entities = context.persistentStoreCoordinator.managedObjectModel.entitiesByName; let keys = Array(entities.keys) var result : NSEntityDescription? for (key, value) in entities { if key == entityName { result = value as? NSEntityDescription } } return result } }
fdadef74cb149b5d20e72955a3d411e1
33.27
143
0.618506
false
true
false
false
google/iosched-ios
refs/heads/master
Source/IOsched/Screens/Info/WifiInfoCollectionViewCell.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MaterialComponents /// Class does nothing but display static information on the venue wifi. class WifiInfoCollectionViewCell: MDCCollectionViewCell { struct Constants { // Horizontal inset is 16pt, vertical inset is 32. static let insets = CGPoint(x: 16, y: 32) static let interItemVerticalSpacing: CGFloat = 20 // These may change before ship. static let wifi = NSLocalizedString("Wifi network:", comment: "Wifi network name label") static let wifiName = "io2019" static let password = NSLocalizedString("Password", comment: "Wifi network password label") static let passwordValue = "makegoodthings" static func labelFont() -> UIFont { return UIFont.preferredFont(forTextStyle: .subheadline) } static func valueFont() -> UIFont { return UIFont.preferredFont(forTextStyle: .subheadline) } static let labelTextColor = UIColor(red: 66 / 255, green: 66 / 255, blue: 66 / 255, alpha: 1) static let valueTextColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1) } static let wifiPassword = Constants.passwordValue private let wifiLabel = UILabel() private let wifiNameLabel = UILabel() private let passwordLabel = UILabel() private let passwordValueLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(wifiLabel) setupWifiLabel() contentView.addSubview(passwordLabel) setupPasswordLabel() contentView.addSubview(wifiNameLabel) setupWifiNameLabel() contentView.addSubview(passwordValueLabel) setupPasswordValueLabel() setupViewConstraints() } static var minimumHeightForContents: CGFloat { let wifiSize = Constants.wifiName.size(withAttributes: [NSAttributedString.Key.font: Constants.valueFont()]) let passwordSize = Constants.passwordValue.size(withAttributes: [NSAttributedString.Key.font: Constants.valueFont()]) return CGFloat(Constants.insets.y * 2 + wifiSize.height + Constants.interItemVerticalSpacing + passwordSize.height) } // MARK: - layout code private func setupWifiLabel() { wifiLabel.text = Constants.wifi wifiLabel.font = Constants.labelFont() wifiLabel.textColor = Constants.labelTextColor wifiLabel.numberOfLines = 1 wifiLabel.allowsDefaultTighteningForTruncation = true wifiLabel.translatesAutoresizingMaskIntoConstraints = false wifiLabel.enableAdjustFontForContentSizeCategory() } private func setupPasswordLabel() { passwordLabel.text = Constants.password passwordLabel.font = Constants.labelFont() passwordLabel.textColor = Constants.labelTextColor passwordLabel.numberOfLines = 1 passwordLabel.allowsDefaultTighteningForTruncation = true passwordLabel.translatesAutoresizingMaskIntoConstraints = false passwordLabel.enableAdjustFontForContentSizeCategory() } private func setupWifiNameLabel() { wifiNameLabel.text = Constants.wifiName wifiNameLabel.font = Constants.valueFont() wifiNameLabel.textColor = Constants.valueTextColor wifiNameLabel.numberOfLines = 1 wifiNameLabel.allowsDefaultTighteningForTruncation = true wifiNameLabel.translatesAutoresizingMaskIntoConstraints = false wifiNameLabel.enableAdjustFontForContentSizeCategory() } private func setupPasswordValueLabel() { passwordValueLabel.text = Constants.passwordValue passwordValueLabel.font = Constants.valueFont() passwordValueLabel.textColor = Constants.valueTextColor passwordValueLabel.numberOfLines = 1 passwordValueLabel.allowsDefaultTighteningForTruncation = true passwordValueLabel.translatesAutoresizingMaskIntoConstraints = false passwordValueLabel.enableAdjustFontForContentSizeCategory() } private func setupViewConstraints() { var constraints = [NSLayoutConstraint]() // wifi label top constraints.append(NSLayoutConstraint(item: wifiLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 32)) // wifi label left constraints.append(NSLayoutConstraint(item: wifiLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 16)) // password label top constraints.append(NSLayoutConstraint(item: passwordLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -32)) // password label left constraints.append(NSLayoutConstraint(item: passwordLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 16)) // wifi name label bottom constraints.append(NSLayoutConstraint(item: wifiNameLabel, attribute: .centerY, relatedBy: .equal, toItem: wifiLabel, attribute: .centerY, multiplier: 1, constant: 0)) // wifi name label top constraints.append(NSLayoutConstraint(item: wifiNameLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -16)) // password value label bottom constraints.append(NSLayoutConstraint(item: passwordValueLabel, attribute: .centerY, relatedBy: .equal, toItem: passwordLabel, attribute: .centerY, multiplier: 1, constant: 0)) // password value label top constraints.append(NSLayoutConstraint(item: passwordValueLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -16)) wifiLabel.setContentCompressionResistancePriority(.required, for: .vertical) passwordLabel.setContentCompressionResistancePriority(.required, for: .vertical) contentView.addConstraints(constraints) } @available(*, unavailable) required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported for cell of type \(WifiInfoCollectionViewCell.self)") } } // MARK: - Accessibility extension WifiInfoCollectionViewCell { override var isAccessibilityElement: Bool { get { return true } set {} } override var accessibilityLabel: String? { get { return NSLocalizedString( "IO event wifi password. Network name: io2018. Password: makegoodthings. Double-tap to copy password to clipboard.", comment: "Accessible description for the wifi info cell. Visually-impaired users will hear this text read to them via VoiceOver" ) } set {} } }
dc2b11c448eba1d4dcabe71af79ebe48
39.746606
136
0.581122
false
false
false
false
mpatelCAS/MDAlamofireCheck
refs/heads/master
Pods/Alamofire/Source/Alamofire.swift
mit
2
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(method, URLString, headers: headers, destination: destination) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
76fcb121e50a3955167878f9e919b4fb
32.658263
118
0.710969
false
false
false
false
sjrmanning/Birdsong
refs/heads/master
Source/Presence.swift
mit
1
// // Presence.swift // Pods // // Created by Simon Manning on 6/07/2016. // // import Foundation public final class Presence { // MARK: - Convenience typealiases public typealias PresenceState = [String: [Meta]] public typealias Diff = [String: [String: Any]] public typealias Meta = [String: Any] // MARK: - Properties fileprivate(set) public var state: PresenceState // MARK: - Callbacks public var onJoin: ((_ id: String, _ meta: Meta) -> ())? public var onLeave: ((_ id: String, _ meta: Meta) -> ())? public var onStateChange: ((_ state: PresenceState) -> ())? // MARK: - Initialisation init(state: PresenceState = Presence.PresenceState()) { self.state = state } // MARK: - Syncing func sync(_ diff: Response) { // Initial state event if diff.event == "presence_state" { diff.payload.forEach{ id, entry in if let entry = entry as? [String: Any] { if let metas = entry["metas"] as? [Meta] { state[id] = metas } } } } else if diff.event == "presence_diff" { if let leaves = diff.payload["leaves"] as? Diff { syncLeaves(leaves) } if let joins = diff.payload["joins"] as? Diff { syncJoins(joins) } } onStateChange?(state) } func syncLeaves(_ diff: Diff) { defer { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { metas.forEach { onLeave?(id, $0) } } } } for (id, entry) in diff where state[id] != nil { guard var existing = state[id] else { continue } // If there's only one entry for the id, just remove it. if existing.count == 1 { state.removeValue(forKey: id) continue } // Otherwise, we need to find the phx_ref keys to delete. let metas = entry["metas"] as? [Meta] if let refsToDelete = metas?.flatMap({ $0["phx_ref"] as? String }) { existing = existing.filter { if let phxRef = $0["phx_ref"] as? String { return !refsToDelete.contains(phxRef) } return true } state[id] = existing } } } func syncJoins(_ diff: Diff) { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { if var existing = state[id] { state[id] = existing + metas } else { state[id] = metas } metas.forEach { onJoin?(id, $0) } } } } // MARK: - Presence access convenience public func metas(id: String) -> [Meta]? { return state[id] } public func firstMeta(id: String) -> Meta? { return state[id]?.first } public func firstMetas() -> [String: Meta] { var result = [String: Meta]() state.forEach { id, metas in result[id] = metas.first } return result } public func firstMetaValue<T>(id: String, key: String) -> T? { guard let meta = state[id]?.first, let value = meta[key] as? T else { return nil } return value } public func firstMetaValues<T>(key: String) -> [T] { var result = [T]() state.forEach { id, metas in if let meta = metas.first, let value = meta[key] as? T { result.append(value) } } return result } }
6b572f974cdebc85cb8b32799eb937ea
25.705479
80
0.469608
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/core/Map.swift
apache-2.0
2
//===--- Map.swift - Lazily map over a Sequence ---------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A `Sequence` whose elements consist of those in a `Base` /// `Sequence` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. @_fixed_layout public struct LazyMapSequence<Base : Sequence, Element> { public typealias Elements = LazyMapSequence @usableFromInline internal var _base: Base @usableFromInline internal let _transform: (Base.Element) -> Element /// Creates an instance with elements `transform(x)` for each element /// `x` of base. @inlinable internal init(_base: Base, transform: @escaping (Base.Element) -> Element) { self._base = _base self._transform = transform } } extension LazyMapSequence { @_fixed_layout public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal let _transform: (Base.Element) -> Element @inlinable public var base: Base.Iterator { return _base } @inlinable internal init( _base: Base.Iterator, _transform: @escaping (Base.Element) -> Element ) { self._base = _base self._transform = _transform } } } extension LazyMapSequence.Iterator: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Element? { return _base.next().map(_transform) } } extension LazyMapSequence: LazySequenceProtocol { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _transform: _transform) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return _base.underestimatedCount } } /// A `Collection` whose elements consist of those in a `Base` /// `Collection` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. @_fixed_layout public struct LazyMapCollection<Base: Collection, Element> { @usableFromInline internal var _base: Base @usableFromInline internal let _transform: (Base.Element) -> Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable internal init(_base: Base, transform: @escaping (Base.Element) -> Element) { self._base = _base self._transform = transform } } extension LazyMapCollection: Sequence { public typealias Iterator = LazyMapSequence<Base,Element>.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _transform: _transform) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public var underestimatedCount: Int { return _base.underestimatedCount } } extension LazyMapCollection: LazyCollectionProtocol { public typealias Index = Base.Index public typealias Indices = Base.Indices public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element> @inlinable public var startIndex: Base.Index { return _base.startIndex } @inlinable public var endIndex: Base.Index { return _base.endIndex } @inlinable public func index(after i: Index) -> Index { return _base.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _base.formIndex(after: &i) } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable public subscript(position: Base.Index) -> Element { return _transform(_base[position]) } @inlinable public subscript(bounds: Range<Base.Index>) -> SubSequence { return SubSequence(_base: _base[bounds], transform: _transform) } @inlinable public var indices: Indices { return _base.indices } /// A Boolean value indicating whether the collection is empty. @inlinable public var isEmpty: Bool { return _base.isEmpty } /// The number of elements in the collection. /// /// To check whether the collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; O(*n*) /// otherwise. @inlinable public var count: Int { return _base.count } @inlinable public var first: Element? { return _base.first.map(_transform) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _base.index(i, offsetBy: n) } @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _base.index(i, offsetBy: n, limitedBy: limit) } @inlinable public func distance(from start: Index, to end: Index) -> Int { return _base.distance(from: start, to: end) } } extension LazyMapCollection : BidirectionalCollection where Base : BidirectionalCollection { /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public func index(before i: Index) -> Index { return _base.index(before: i) } @inlinable public func formIndex(before i: inout Index) { _base.formIndex(before: &i) } @inlinable public var last: Element? { return _base.last.map(_transform) } } extension LazyMapCollection : RandomAccessCollection where Base : RandomAccessCollection { } //===--- Support for s.lazy -----------------------------------------------===// extension LazySequenceProtocol { /// Returns a `LazyMapSequence` over this `Sequence`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @inlinable public func map<U>( _ transform: @escaping (Elements.Element) -> U ) -> LazyMapSequence<Self.Elements, U> { return LazyMapSequence(_base: self.elements, transform: transform) } } extension LazyCollectionProtocol { /// Returns a `LazyMapCollection` over this `Collection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @inlinable public func map<U>( _ transform: @escaping (Elements.Element) -> U ) -> LazyMapCollection<Self.Elements, U> { return LazyMapCollection(_base: self.elements, transform: transform) } } extension LazyMapCollection { // This overload is needed to re-enable Swift 3 source compatibility related // to a bugfix in ranking behavior of the constraint solver. @available(swift, obsoleted: 4.0) public static func + < Other : LazyCollectionProtocol >(lhs: LazyMapCollection, rhs: Other) -> [Element] where Other.Element == Element { var result: [Element] = [] result.reserveCapacity(numericCast(lhs.count + rhs.count)) result.append(contentsOf: lhs) result.append(contentsOf: rhs) return result } } extension LazyMapSequence { @inlinable @available(swift, introduced: 5) public func map<ElementOfResult>( _ transform: @escaping (Element) -> ElementOfResult ) -> LazyMapSequence<Base, ElementOfResult> { return LazyMapSequence<Base, ElementOfResult>( _base: _base, transform: {transform(self._transform($0))}) } } extension LazyMapCollection { @inlinable @available(swift, introduced: 5) public func map<ElementOfResult>( _ transform: @escaping (Element) -> ElementOfResult ) -> LazyMapCollection<Base, ElementOfResult> { return LazyMapCollection<Base, ElementOfResult>( _base: _base, transform: {transform(self._transform($0))}) } } // @available(*, deprecated, renamed: "LazyMapSequence.Iterator") public typealias LazyMapIterator<T, E> = LazyMapSequence<T, E>.Iterator where T: Sequence @available(*, deprecated, renamed: "LazyMapCollection") public typealias LazyMapBidirectionalCollection<T, E> = LazyMapCollection<T, E> where T : BidirectionalCollection @available(*, deprecated, renamed: "LazyMapCollection") public typealias LazyMapRandomAccessCollection<T, E> = LazyMapCollection<T, E> where T : RandomAccessCollection
c2d4cb66feb399e305a386e696c92612
31.531148
113
0.688672
false
false
false
false
wanghdnku/Whisper
refs/heads/master
MyPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" NSNumber(value: NSDate().timeIntervalSince1970) Double(NSDate().timeIntervalSince1970) // 获取当前时间的 timestamp let timestamp = String(Date().timeIntervalSince1970) NSNumber(value: Int(Date().timeIntervalSince1970)) var dict = [String: Bool]() dict["1"] = true dict["2"] = true dict["2"] //let string = String(string: timestamp) let date = Date(timeIntervalSince1970: Double(timestamp)!) var dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm a 'on' MMMM dd, yyyy" var dateString = dateFormatter.string(from: date) var df = DateFormatter() df.dateFormat = "'Last Message: 'MM/dd hh:mm a" var ds = df.string(from: date) let a: NSNumber = 33333 let b = String(describing: a)
6e770b9749035e0b16f6d28976463674
21.055556
58
0.72796
false
false
false
false
kildevaeld/location
refs/heads/master
Pod/Classes/address-cache.swift
mit
1
// // address-cache.swift // Pods // // Created by Rasmus Kildevæld on 11/10/2015. // // import Foundation // // Cache.swift // Pods // // Created by Rasmus Kildevæld on 25/06/15. // // import Foundation import MapKit class CacheItem : Equatable { var address: Address var key: String init(address: Address) { self.address = address self.key = "\(address.city.name), \(address.country.name)" } init(key: String, address: Address) { self.address = address self.key = key } func check(location:CLLocation) -> Bool { return self.address.location.compare(location, precision: 100) } func check(key: String) -> Bool { if self.key == key { return true } return false } } func ==(lhs:CacheItem, rhs: CacheItem) -> Bool { return lhs.address.location == rhs.address.location } class AddressCache { var store: [CacheItem] = [] var storePath : String { return (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("address_cache.lm") } init () { self.load() } func set (address: Address) { let item = CacheItem(address: address) if self.store.contains(item) { return } self.store.append(item) } func set (key: String, address: Address) { let addr = self.get(key) if addr == nil { let item = CacheItem(key: key, address: address) self.store.append(item) } } func get (location: CLLocation) -> Address? { return self.get(location, precision: 20) } func get (location: CLLocation, precision: CLLocationDistance) -> Address? { for item in self.store { if item.check(location) { return item.address } } return nil } func get(key: String) -> Address? { for item in self.store { if item.check(key) { return item.address } } return nil } func save() { var dict = Dictionary<String,Address>() for item in self.store { dict[item.key] = item.address } NSKeyedArchiver.archiveRootObject(dict, toFile: self.storePath) } func load () { let fm = NSFileManager.defaultManager() if !fm.isReadableFileAtPath(self.storePath) { return } let data: AnyObject? do { data = try NSKeyedUnarchiver.location_unarchiveObjectWithFilePath(self.storePath); } catch { data = nil do { try fm.removeItemAtPath(self.storePath) } catch {} } //NSKeyedUnarchiver.unarchiveObjectWithFile(<#T##path: String##String#>) if let dict = data as? Dictionary<String, Address> { for (key, item) in dict { self.set(key, address: item) } } } }
a3c33447c43e6900931725efc7cb0b5e
21.103448
102
0.515445
false
false
false
false
danielsaidi/iExtra
refs/heads/master
iExtra/UI/Themes/ThemedButton.swift
mit
1
// // ThemedButton.swift // iExtra // // Created by Daniel Saidi on 2018-05-09. // Copyright © 2018 Daniel Saidi. All rights reserved. // /* This class can be used to easily apply custom button themes. Instead of overriding its initializers, just override setup. */ import UIKit import Foundation open class ThemedButton: UIButton { // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open func setup() { } open override func didMoveToWindow() { super.didMoveToWindow() updateAppearance() } // MARK: - Appearance @objc open dynamic var disabledBackgroundColor: UIColor? @objc open dynamic var highlightedBackgroundColor: UIColor? @objc open dynamic var normalBackgroundColor: UIColor? { didSet { backgroundColor = normalBackgroundColor } } @objc open dynamic var themedFont: UIFont? { get { return titleLabel?.font } set { titleLabel?.font = newValue } } // MARK: - Properties open var backgroundColorForCurrentState: UIColor? { if isDisabled, let color = disabledBackgroundColor { return color } if isHighlighted, let color = highlightedBackgroundColor { return color } return normalBackgroundColor ?? backgroundColor } open override var isEnabled: Bool { didSet { updateAppearance() } } open var isDisabled: Bool { return !isEnabled || isSoftDisabled } open override var isHighlighted: Bool { didSet { updateAppearance() } } open var isSoftDisabled: Bool = false { didSet { updateAppearance() } } fileprivate var allStates: [UIControl.State] { return [.normal, .highlighted, .disabled] } // MARK: - Public Functions open func updateAppearance() { backgroundColor = backgroundColorForCurrentState } }
e54466eb833e22eaaa4362e249feb096
22.184783
81
0.621191
false
false
false
false
kedu/FULL_COPY
refs/heads/master
xingLangWeiBo/xingLangWeiBo/Classes/Modeul/Home/HOmeTableViewCell.swift
mit
1
// // HOmeTableViewCell.swift // xingLangWeiBo // // Created by Apple on 16/10/18. // Copyright © 2016年 lkb-求工作qq:1218773641. All rights reserved. // import UIKit class HOmeTableViewCell: UITableViewCell { @IBOutlet weak var for_other_conView: UIView! @IBOutlet weak var for_other: UILabel! @IBOutlet weak var for_other_height: NSLayoutConstraint! //配图容器 @IBOutlet weak var collectView: UICollectionView! //配图高度 @IBOutlet weak var phontoHeight: NSLayoutConstraint! @IBOutlet weak var verImageview: UIImageView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var vip: UIImageView! @IBOutlet weak var creat_time: UILabel! @IBOutlet weak var source: UILabel! @IBOutlet weak var contentText: UILabel! @IBOutlet weak var unlike_btn: UIButton! @IBOutlet weak var commont_btn: UIButton! @IBOutlet weak var for_other_button: UIButton! @IBOutlet weak var bottomViewHeight: NSLayoutConstraint! @IBOutlet weak var weibocellheigeht: NSLayoutConstraint! //转发容器 @IBOutlet weak var for_other_collectView: UICollectionView! //转发配图高度 @IBOutlet weak var for_other_phontoHeight: NSLayoutConstraint! var isFor_other : Bool? var homeModel_tmp : HomeModel? //数据模型 var homeModel : HomeModel? { set{ homeModel_tmp = newValue if homeModel_tmp != nil { //头像 let url = NSURL(string: (homeModel_tmp?.profile_image_url)!) icon.layer.masksToBounds = true icon.layer.cornerRadius = 25 icon.layer.borderWidth = 0.2 icon.layer.borderColor = UIColor.whiteColor().CGColor icon.setImageWithURL(url!, placeholderImage: UIImage(named:"compose_keyboardbutton_background_highlighted" )) //昵称 name.text = homeModel_tmp!.name //会员图标 vip.hidden = false let tORf = homeModel_tmp?.isVip() if (tORf != false) { let rangk = homeModel_tmp?.mbrank let nameStr = NSString(string: "common_icon_membership_level\(rangk!)") vip.image = UIImage(named: nameStr as String) name.textColor = UIColor.orangeColor() }else if (tORf == false){ // let nameStr = NSString(string: "common_icon_membership_expired") vip.hidden = true // // vip.image = UIImage(named: nameStr as String) name.textColor = UIColor.grayColor() } //认证 verImageview.hidden = false switch(Int((homeModel_tmp?.verified_level)!)){ case 0://个人 verImageview.image = UIImage(named: "avatar_vip") break case 2: verImageview.image = UIImage(named: "avatar_enterprise_vip") break case 3: verImageview.image = UIImage(named: "avatar_enterprise_vip") break case 5: verImageview.image = UIImage(named: "avatar_enterprise_vip") break case 220: verImageview.image = UIImage(named: "avatar_grassroot") break default: verImageview.hidden = true break } //时间 creat_time.text = dealwith((homeModel_tmp?.created_at)!) // 需要先处理一下 //正文 contentText.text = homeModel_tmp?.text contentText.sizeToFit() // print(contentText.text) //来源 if ( homeModel_tmp?.source != ""){ source.text = dealwithSource( (homeModel_tmp?.source)!) as String}else{ source.text = "未通过审核应用" } // print(source.text! + "是source") //正文的高度 let conHeight = contentText.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height //原创微博的高度 weibocellheigeht.constant = contentText.frame.origin.y + conHeight //配图 if (homeModel_tmp?.pic_urls?.count > 0){ let count = homeModel_tmp?.pic_urls?.count var row = 0 //行数 if (count! % 3 == 0){ row = count!/3 }else { row = count!/3+1 } //高度 let tmp = (row*70 + (row-1)*10) phontoHeight.constant = CGFloat(tmp) weibocellheigeht.constant = weibocellheigeht.constant + phontoHeight.constant + 10 //加载 collectView.reloadData() }else{ //没有 phontoHeight.constant = 0 } //转发微博 //是否转发 let iszf = (homeModel_tmp!.retweeted_status == nil) if ((iszf) == true){ for_other.hidden = true for_other_height.constant = 0 isFor_other = false }else { isFor_other = true for_other.hidden = false let str = homeModel_tmp!.retweeted_status?["user"]!["name"] as! String + ":" + ((homeModel_tmp!.retweeted_status?["text"])! as! String) as! String for_other.text = str print(for_other.text) //高度 for_other_height.constant = for_other.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 10 //转发配图 let source = homeModel_tmp?.retweeted_status?["pic_urls"] if (source!.count > 0){ let count = source!.count var row = 0 //行数 if (count! % 3 == 0){ row = count!/3 }else { row = count!/3+1 } //高度 let tmp = (row*70 + (row-1)*10) for_other_phontoHeight.constant = CGFloat(tmp) for_other_height.constant = for_other_height.constant + for_other_phontoHeight.constant + 10 //加载 for_other_collectView.reloadData() }else{ //没有 for_other_phontoHeight.constant = 0 } //底部视图 for_other_button.addTarget(self, action: "didclick", forControlEvents: .TouchUpInside) if (homeModel_tmp?.comments_count?.longLongValue > 0){ commont_btn.setTitle(homeModel_tmp?.comments_count?.description, forState: .Normal) }else { commont_btn.setTitle("评论", forState: .Normal) } if (homeModel_tmp?.reposts_count?.longLongValue > 0){ for_other_button.setTitle(homeModel_tmp?.reposts_count?.description, forState: .Normal) }else { for_other_button.setTitle("转发", forState: .Normal) } if (homeModel_tmp?.attitudes_count?.longLongValue > 0){ unlike_btn.setTitle(homeModel_tmp?.attitudes_count?.description, forState: .Normal) }else { unlike_btn.setTitle("赞", forState: .Normal) } bringSubviewToFront(for_other_button) bringSubviewToFront(commont_btn) bringSubviewToFront(unlike_btn) } } } get{ return nil } } func didclick(){ print("我被点击了") } func dealwithSource(var source_str:NSString) -> NSString{ // 1.计算从什么地方开始截取 let startRange = source_str.rangeOfString(">") let startIndex = startRange.location + 1 // 2.计算截取的长度 //#warning rangeOfString方法会从字符串的开头开始查找, 只要查找到第一个就不会继续查找 let endRange = source_str.rangeOfString("</") let length = endRange.location - startIndex // 3.截取字符串 if (startRange.location != NSNotFound && endRange.location != NSNotFound) { let resultStr = source_str .substringWithRange(NSMakeRange(startIndex, length) ) source_str = resultStr; } return source_str } func dealwith(string : String) -> String { // let formatter = NSDateFormatter() // #warning 注意: 如果是真机, 还需要设置时间所属的区域 formatter.locale = NSLocale(localeIdentifier: "en_US") // // 指定服务器返回时间的格式 // // Mon Feb 02 18:15:20 +0800 2015 formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" // 1.将服务器返回的字符串转换为NSDate let createdDate = formatter.dateFromString(string)! // // 2.判断服务器返回的时间, 根据时间返回对应的字符串 if createdDate.isThisYear() { if createdDate.isToday(){ let comps = createdDate.deltaWithNow if comps().hour >= 1 { return "\(comps().hour)小时前" }else if comps().minute > 1 { return "\(comps().minute )分钟以前" }else { return "刚刚" } }else if createdDate.isYesterday() { formatter.dateFormat = "昨天 HH时:mm分" return formatter.stringFromDate(createdDate) }else { formatter.dateFormat = "MM月dd日 HH时:mm分" return formatter.stringFromDate(createdDate) } }else{ formatter.dateFormat = "yy年MM月dd日 HH时:mm分" return formatter.stringFromDate(createdDate) } } var status : IWStatus? override func awakeFromNib() { super.awakeFromNib() // Initialization code //设置原创微博正文最大的宽度 let screenWith = UIScreen.mainScreen().bounds.size.width contentText.preferredMaxLayoutWidth = screenWith - 10 for_other.preferredMaxLayoutWidth = screenWith - 10 // UITableViewCellSelectionStyleNone self.selectionStyle = UITableViewCellSelectionStyle(rawValue: 0)! } //获取指定行数据cell的高度 func cellHeightWithHomeModel(homeModel:HomeModel?) -> CGFloat{ self.homeModel = homeModel layoutIfNeeded() //计算高度 let iszf = (homeModel_tmp!.retweeted_status == nil) if ((iszf) == true){ return weibocellheigeht.constant + bottomViewHeight.constant }else{ let height = for_other_conView.frame.origin.y + for_other_height.constant + 10+bottomViewHeight.constant-10 return height } } //为重用cell做准备 override func prepareForReuse() { homeModel = nil } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension HOmeTableViewCell: UICollectionViewDelegate,UICollectionViewDataSource{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let source = homeModel_tmp?.retweeted_status?["pic_urls"] if (isFor_other == true){ return source!.count }else { if (homeModel_tmp?.pic_urls != nil){ return (homeModel_tmp?.pic_urls?.count)! }else { return 0 } } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let source = homeModel_tmp?.retweeted_status?["pic_urls"] let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as! photoCell if (isFor_other == true){ let urlStr = source![indexPath.item]["thumbnail_pic"] as! String cell.imageUrl = NSURL(string: urlStr ) }else{ if (homeModel_tmp?.pic_urls != nil){ let urlStr = homeModel_tmp?.pic_urls![indexPath.item]["thumbnail_pic"] as! String // print(urlStr) cell.imageUrl = NSURL(string: urlStr ) } } return cell } }
f30c5170c37497a6f7b66e7bf0c81655
33.653944
166
0.489537
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/RelativeFormatter+Style.swift
apache-2.0
1
// // Style.swift // SwiftDate // // Created by Daniele Margutti on 08/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation /// Languages table. /// In order to be fully compatible with Linux environment we need to /// handle directly with .swift files instead of plain text files. public protocol RelativeFormatterLang { /// Table with the data of the language. /// Data is structured in: /// { flavour: { unit : { data } } } var flavours: [String: Any] { get } /// Identifier of the language. /// Must be the languageIdentifier of the `Locale` instance. static var identifier: String { get } /// This is the rule to return singular or plural forms /// based upon the CDLC specs. Must return the appropriate /// value (other, few, none...) /// /// - Parameter value: quantity to evaluate func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? /// Init init() } // MARK: - Style public extension RelativeFormatter { public enum PluralForm: String { case zero, one, two, few, many, other } /// Style for formatter public struct Style { /// Flavours supported by the style, specified in order. /// The first available flavour for specified locale is used. /// If no flavour is available `.long` is used instead (this flavour /// MUST be part of every lang structure). public var flavours: [Flavour] /// Gradation specify how the unit are evaluated in order to get the /// best one to represent a given amount of time interval. /// By default `convenient()` is used. public var gradation: Gradation = .convenient() /// Allowed time units the style can use. Some styles may not include /// some time units (ie. `.quarter`) because they are not useful for /// a given representation. /// If not specified all the following units are set: /// `.now, .minute, .hour, .day, .week, .month, .year` public var allowedUnits: [Unit]? /// Create a new style. /// /// - Parameters: /// - flavours: flavours of the style. /// - gradation: gradation rules. /// - units: allowed units. public init(flavours: [Flavour], gradation: Gradation, allowedUnits units: [Unit]? = nil) { self.flavours = flavours self.gradation = gradation self.allowedUnits = (units ?? [.now, .minute, .hour, .day, .week, .month, .year]) } } /// Return the default style for relative formatter. /// /// - Returns: style instance. public static func defaultStyle() -> Style { return Style(flavours: [.longConvenient, .long], gradation: .convenient()) } /// Return the time-only style for relative formatter. /// /// - Returns: style instance. public static func timeStyle() -> Style { return Style(flavours: [.longTime], gradation: .convenient()) } /// Return the twitter style for relative formatter. /// /// - Returns: style instance. public static func twitterStyle() -> Style { return Style(flavours: [.tiny, .shortTime, .narrow, .shortTime], gradation: .twitter()) } } // MARK: - Flavour public extension RelativeFormatter { /// Supported flavours public enum Flavour: String { case long = "long" case longTime = "long_time" case longConvenient = "long_convenient" case short = "short" case shortTime = "short_time" case shortConvenient = "short_convenient" case narrow = "narrow" case tiny = "tiny" case quantify = "quantify" } } // MARK: - Gradation public extension RelativeFormatter { /// Gradation is used to define a set of rules used to get the best /// representation of a given elapsed time interval (ie. the best /// representation for 300 seconds is in minutes, 5 minutes specifically). /// Rules are executed in order by the parser and the best one (< elapsed interval) /// is returned to be used by the formatter. public struct Gradation { /// A single Gradation rule specification // swiftlint:disable nesting public struct Rule { public enum ThresholdType { case value(_: Double?) case function(_: ((TimeInterval) -> (Double?))) func evaluateForTimeInterval(_ elapsed: TimeInterval) -> Double? { switch self { case .value(let value): return value case .function(let function): return function(elapsed) } } } /// The time unit to which the rule refers. /// It's used to evaluate the factor. public var unit: Unit /// Threhsold value of the unit. When a difference between two dates /// is less than the threshold the unit before this is the best /// candidate to represent the time interval. public var threshold: ThresholdType? /// Granuality threshold of the unit public var granularity: Double? /// Relation with a previous threshold public var thresholdPrevious: [Unit: Double]? /// You can specify a custom formatter for a rule which return the /// string representation of a data with your own pattern. // swiftlint:disable nesting public typealias CustomFormatter = ((DateRepresentable) -> (String)) public var customFormatter: CustomFormatter? /// Create a new rule. /// /// - Parameters: /// - unit: target time unit. /// - threshold: threshold value. /// - granularity: granularity value. /// - prev: relation with a previous rule in gradation lsit. /// - formatter: custom formatter. public init(_ unit: Unit, threshold: ThresholdType?, granularity: Double? = nil, prev: [Unit: Double]? = nil, formatter: CustomFormatter? = nil ) { self.unit = unit self.threshold = threshold self.granularity = granularity self.thresholdPrevious = prev self.customFormatter = formatter } } /// Gradation rules var rules: [Rule] /// Number of gradation rules var count: Int { return self.rules.count } /// Subscript by unit. /// Return the first rule for given unit. /// /// - Parameter unit: unit to get. public subscript(_ unit: Unit) -> Rule? { return self.rules.first(where: { $0.unit == unit }) } /// Subscript by index. /// Return the rule at given index, `nil` if index is invalid. /// /// - Parameter index: index public subscript(_ index: Int) -> Rule? { guard index < self.rules.count, index >= 0 else { return nil } return self.rules[index] } /// Create a new gradition with a given set of ordered rules. /// /// - Parameter rules: ordered rules. public init(_ rules: [Rule]) { self.rules = rules } /// Create a new gradation by removing the units from receiver which are not part of the given array. /// /// - Parameter units: units to keep. /// - Returns: a new filtered `Gradation` instance. public func filtered(byUnits units: [Unit]) -> Gradation { return Gradation(self.rules.filter { units.contains($0.unit) }) } /// Canonical gradation rules public static func canonical() -> Gradation { return Gradation([ Rule(.now, threshold: .value(0)), Rule(.second, threshold: .value(0.5)), Rule(.minute, threshold: .value(59.5)), Rule(.hour, threshold: .value(59.5 * 60.0)), Rule(.day, threshold: .value(23.5 * 60 * 60)), Rule(.week, threshold: .value(6.5 * Unit.day.factor)), Rule(.month, threshold: .value(3.5 * 7 * Unit.day.factor)), Rule(.year, threshold: .value(1.5 * Unit.month.factor)) ]) } /// Convenient gradation rules public static func convenient() -> Gradation { let list = Gradation([ Rule(.now, threshold: .value(0)), Rule(.second, threshold: .value(1), prev: [.now: 1]), Rule(.minute, threshold: .value(45)), Rule(.minute, threshold: .value(2.5 * 60), granularity: 5), Rule(.halfHour, threshold: .value(22.5 * 60), granularity: 5), Rule(.hour, threshold: .value(42.5 * 60), prev: [.minute: 52.5 * 60]), Rule(.day, threshold: .value((20.5 / 24) * Unit.day.factor)), Rule(.week, threshold: .value(5.5 * Unit.day.factor)), Rule(.month, threshold: .value(3.5 * 7 * Unit.day.factor)), Rule(.year, threshold: .value(10.5 * Unit.month.factor)) ]) return list } /// Twitter gradation rules public static func twitter() -> Gradation { return Gradation([ Rule(.now, threshold: .value(0)), Rule(.second, threshold: .value(1), prev: [.now: 1]), Rule(.minute, threshold: .value(45)), Rule(.hour, threshold: .value(59.5 * 60.0)), Rule(.hour, threshold: .value((1.days.timeInterval - 0.5 * 1.hours.timeInterval))), Rule(.day, threshold: .value((20.5 / 24) * Unit.day.factor)), Rule(.other, threshold: .function({ now in // Jan 1st of the next year. let nextYear = (Date(timeIntervalSince1970: now) + 1.years).dateAtStartOf(.year) return (nextYear.timeIntervalSince1970 - now) }), formatter: { date in // "Apr 11, 2017" return date.toFormat("MMM dd, yyyy") }) ]) } } } // MARK: - Unit public extension RelativeFormatter { /// Units for relative formatter public enum Unit: String { case now = "now" case second = "second" case minute = "minute" case hour = "hour" case halfHour = "half_hour" case day = "day" case week = "week" case month = "month" case year = "year" case quarter = "quarter" case other = "" /// Factor of conversion of the unit to seconds public var factor: Double { switch self { case .now, .second: return 1 case .minute: return 1.minutes.timeInterval case .hour: return 1.hours.timeInterval case .halfHour: return (1.hours.timeInterval * 0.5) case .day: return 1.days.timeInterval case .week: return 1.weeks.timeInterval case .month: return 1.months.timeInterval case .year: return 1.years.timeInterval case .quarter: return (91.days.timeInterval + 6.hours.timeInterval) case .other: return 0 } } } } internal extension Double { /// Return -1 if number is negative, 1 if positive var sign: Int { return (self < 0 ? -1 : 1) } }
6c4e3d2af0b1ab613119cef1cbfd97b2
29.564815
103
0.656771
false
false
false
false
matthewca/SwiftyCloudant
refs/heads/master
SwiftyCloudant.swift
mit
1
// // SwiftyCloudant.swift // Swifty Cloudant // // Created by Matthew Smith on 2015-06-20. // import Foundation class SwiftyCloudant { var username = "" var apiPassword = "" var apiKey = "" var database = "" var urlBase:String { return "https://\(apiKey):\(apiPassword)@\(username).cloudant.com/\(database)" } init(username: String, apiPassword: String, apiKey: String, database: String) { self.username = username self.apiPassword = apiPassword self.apiKey = apiKey self.database = database } func getAllDocuments(completion: (result: JSON) -> Void) -> Void { let url = urlBase + "/_all_docs?include_docs=true" println(url) var request = NSURLRequest(URL: NSURL(string: url)!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } func getDocument(id: String, completion:(result: JSON) -> Void) -> Void { let url = urlBase + "/" + id println(url) var request = NSURLRequest(URL: NSURL(string: url)!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } func deleteDocument(id:String, rev:String, completion:(result: JSON) -> Void) -> Void { let url = urlBase + "/" + id + "?rev=" + rev println(url) var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "DELETE" var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } func updateDocument(id:String, rev:String, json:JSON, completion:(result: JSON) -> Void) -> Void { let url = urlBase + "/" + id println(url) var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "PUT" request.HTTPBody = json.rawData() var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } func createDocument(json:JSON, completion:(result: JSON) -> Void) -> Void { let url = urlBase println(url) var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = json.rawData() var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } func searchIndex(designDocument:String, indexName:String, luceneQuery:String, completion:(result: JSON) -> Void) -> Void { let url = urlBase + "/_design/" + designDocument + "/_search/" + indexName + "?q=" + luceneQuery + "&include_docs=true" println(url) var request = NSURLRequest(URL: NSURL(string: url)!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var json = JSON("") if data != nil { json = JSON(data: data!) } return completion(result: json) } }
c7136400fee9e273d74273732703adec
35.104762
127
0.593404
false
false
false
false
Coderian/SwiftedKML
refs/heads/master
SwiftedKML/Elements/IconStyle.swift
mit
1
// // IconStyle.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML IconStyle /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="IconStyle" type="kml:IconStyleType" substitutionGroup="kml:AbstractColorStyleGroup"/> public class IconStyle :SPXMLElement, AbstractColorStyleGroup, HasXMLElementValue { public static var elementName: String = "IconStyle" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Style: v.value.iconStyle = self default: break } } } } public var value : IconStyleType public required init(attributes:[String:String]){ self.value = IconStyleType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } public var abstractSubStyle : AbstractSubStyleType { return self.value } public var abstractColorStyle : AbstractColorStyleType { return self.value } } /// KML IconStyleType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="IconStyleType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractColorStyleType"> /// <sequence> /// <element ref="kml:scale" minOccurs="0"/> /// <element ref="kml:heading" minOccurs="0"/> /// <element name="Icon" type="kml:BasicLinkType" minOccurs="0"/> /// <element ref="kml:hotSpot" minOccurs="0"/> /// <element ref="kml:IconStyleSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:IconStyleObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="IconStyleSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="IconStyleObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class IconStyleType: AbstractColorStyleType { public var scale : Scale! // = 0.0 public var heading: Heading! // = 0.0 /// Iconが複数あるのでStyleIconとしている public class Icon :SPXMLElement, HasXMLElementValue { public static var elementName:String = "Icon" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as IconStyle: v.value.icon = self default:break } } } } public var value: BasicLinkType = BasicLinkType() } public var icon: Icon! public var hotSpot: HotSpot! public var iconStyleSimpleExtensionGroup: [AnyObject] = [] public var iconStyleObjectExtensionGroup: [AbstractObjectGroup] = [] }
82bb62bffa5d9141d452be7b3c3dd13a
38.192771
115
0.632954
false
false
false
false
CodaFi/swift
refs/heads/master
test/attr/attributes.swift
apache-2.0
12
// RUN: %target-typecheck-verify-swift -enable-objc-interop @unknown func f0() {} // expected-error{{unknown attribute 'unknown'}} @unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}} enum binary { case Zero case One init() { self = .Zero } } func f5(x: inout binary) {} //===--- //===--- IB attributes //===--- @IBDesignable class IBDesignableClassTy { @IBDesignable func foo() {} // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{3-17=}} } @IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}} struct IBDesignableStructTy {} @IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}} protocol IBDesignableProtTy {} @IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}} extension IBDesignableStructTy {} class IBDesignableClassExtensionTy {} @IBDesignable // okay extension IBDesignableClassExtensionTy {} class Inspect { @IBInspectable var value : Int = 0 // okay @GKInspectable var value2: Int = 0 // okay @IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}} @GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}} @IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}} @GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}} } @IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}} @GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}} func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}} func foo(x: @convention(block) (Int) -> Int) {} @_transparent func zim() {} @_transparent func zung<T>(_: T) {} @_transparent // expected-error{{'@_transparent' attribute cannot be applied to stored properties}} {{1-15=}} var zippity : Int func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}} protocol ProtoWithTransparent { @_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within protocols}} {{3-16=}} func transInProto() } class TestTranspClass : ProtoWithTransparent { @_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} init () {} @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{3-17=}} deinit {} @_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} class func transStatic() {} @_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-16=}} func transInProto() {} } struct TestTranspStruct : ProtoWithTransparent{ @_transparent init () {} @_transparent init <T> (x : T) { } @_transparent static func transStatic() {} @_transparent func transInProto() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} struct CannotHaveTransparentStruct { func m1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension TestTranspClass { func tr1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension TestTranspStruct { func tr1() {} } @_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}} extension binary { func tr1() {} } class transparentOnClassVar { @_transparent var max: Int { return 0xFF }; // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}} func blah () { var _: Int = max } }; class transparentOnClassVar2 { var max: Int { @_transparent // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{5-19=}} get { return 0xFF } } func blah () { var _: Int = max } }; @thin // expected-error {{attribute can only be applied to types, not declarations}} func testThinDecl() -> () {} protocol Class : class {} protocol NonClass {} @objc class Ty0 : Class, NonClass { init() { } } // Attributes that should be reported by parser as unknown // See rdar://19533915 @__setterAccess struct S__accessibility {} // expected-error{{unknown attribute '__setterAccess'}} @__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}} @__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}} weak var weak0 : Ty0? weak var weak0x : Ty0? weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned var weak3 : Ty0 unowned var weak3a : Ty0 unowned(safe) var weak3b : Ty0 unowned(unsafe) var weak3c : Ty0 unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak var weak6 : Int? // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} unowned var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}} weak var weak8 : Class? = Ty0() // expected-warning@-1 {{instance will be immediately deallocated because variable 'weak8' is 'weak'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'weak8' declared here}} unowned var weak9 : Class = Ty0() // expected-warning@-1 {{instance will be immediately deallocated because variable 'weak9' is 'unowned'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'weak9' declared here}} weak var weak10 : NonClass? = Ty0() // expected-error {{'weak' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak11 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak12 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak13 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} weak var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}} weak var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}} weak var weak16 : Class! @weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}} @_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} // Function result type attributes. var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}} func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}} return 4 } func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected parameter type following ':'}} func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected ',' separator}} {{47-47=,}} expected-error {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }} func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren. // @thin and @pseudogeneric are not supported except in SIL. var thinFunc : @thin () -> () // expected-error {{unknown attribute 'thin'}} var pseudoGenericFunc : @pseudogeneric () -> () // expected-error {{unknown attribute 'pseudogeneric'}} @inline(never) func nolineFunc() {} @inline(never) var noinlineVar : Int { return 0 } @inline(never) class FooClass { // expected-error {{'@inline(never)' attribute cannot be applied to this declaration}} {{1-16=}} } @inline(__always) func AlwaysInlineFunc() {} @inline(__always) var alwaysInlineVar : Int { return 0 } @inline(__always) class FooClass2 { // expected-error {{'@inline(__always)' attribute cannot be applied to this declaration}} {{1-19=}} } @_optimize(speed) func OspeedFunc() {} @_optimize(speed) var OpeedVar : Int // expected-error {{'@_optimize(speed)' attribute cannot be applied to stored properties}} {{1-19=}} @_optimize(speed) class OspeedClass { // expected-error {{'@_optimize(speed)' attribute cannot be applied to this declaration}} {{1-19=}} } class A { @inline(never) init(a : Int) {} var b : Int { @inline(never) get { return 42 } @inline(never) set { } } } class B { @inline(__always) init(a : Int) {} var b : Int { @inline(__always) get { return 42 } @inline(__always) set { } } } class C { @_optimize(speed) init(a : Int) {} var b : Int { @_optimize(none) get { return 42 } @_optimize(size) set { } } @_optimize(size) var c : Int // expected-error {{'@_optimize(size)' attribute cannot be applied to stored properties}} } class HasStorage { @_hasStorage var x : Int = 42 // ok, _hasStorage is allowed here } @_show_in_interface protocol _underscored {} @_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}} // Error recovery after one invalid attribute @_invalid_attribute_ // expected-error {{unknown attribute '_invalid_attribute_'}} @inline(__always) public func sillyFunction() {} // rdar://problem/45732251: unowned/unowned(unsafe) optional lets are permitted func unownedOptionals(x: C) { unowned let y: C? = x unowned(unsafe) let y2: C? = x _ = y _ = y2 } // @_nonEphemeral attribute struct S1<T> { func foo(@_nonEphemeral _ x: String) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func bar(@_nonEphemeral _ x: T) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func baz<U>(@_nonEphemeral _ x: U) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}} func qux(@_nonEphemeral _ x: UnsafeMutableRawPointer) {} func quux(@_nonEphemeral _ x: UnsafeMutablePointer<Int>?) {} } @_nonEphemeral struct S2 {} // expected-error {{@_nonEphemeral may only be used on 'parameter' declarations}} protocol P {} extension P { // Allow @_nonEphemeral on the protocol Self type, as the protocol could be adopted by a pointer type. func foo(@_nonEphemeral _ x: Self) {} func bar(@_nonEphemeral _ x: Self?) {} } enum E1 { case str(@_nonEphemeral _: String) // expected-error {{expected parameter name followed by ':'}} case ptr(@_nonEphemeral _: UnsafeMutableRawPointer) // expected-error {{expected parameter name followed by ':'}} func foo() -> @_nonEphemeral UnsafeMutableRawPointer? { return nil } // expected-error {{attribute can only be applied to declarations, not types}} }
e16dba5392504bbab46ff458d2c4eeb5
39.967949
256
0.695431
false
false
false
false
longsirhero/DinDinShop
refs/heads/master
DinDinShopDemo/DinDinShopDemo/接口/WCInterface.swift
mit
1
// // WCInterface.swift // DinDinShopDemo // // Created by longsirHERO on 2017/8/18. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import Foundation import XCGLogger let base_Url = "http://service.dindin.com/" // MARK: 海外 // 请求海外轮播图片 let overseas_slideshow_Url = base_Url + "overseas/overseasRollPic?" // 请求海外国家展示数据 let overseas_countryCalss_Url = base_Url + "ycd/ycdList" // 精品折扣 let overseas_Boutique_Url = base_Url + "goods/goodsHotSale?" // APP海外馆首页接口 let overseas_area = base_Url + "newIndex/findOverseasIndex" // 商品详情 let product_detail_Url = base_Url + "goods/goodsDetail?" // MARK: 分类 let classify_Url = base_Url + "category/goodsCategory?" // MARK: 首页 let home_category_second_Url = base_Url + "goods/goodsList?" let home_banner_Url = base_Url + "goods/rollPic?" // 分类 let home_category_url = base_Url + "newIndex/findNewIndexGoodsType" // 抢购 let home_purchase_url = base_Url + "xsqg/timeList" // 1: 随便逛逛 let home_stroll_url = base_Url + "goods/indexGoodList?" // MARK: 购物车 // MARK: 个人中心 // 查询个人信息(头像、昵称) let personalDatas_Url = base_Url + "userInfo/searchPersionInfo?" // MARK: 登陆 let login_Url = base_Url + "user/login?"
20fa861cdc139ecf24daf702d2cc16e6
18.111111
86
0.700997
false
false
false
false
kenwilcox/cute-possum-parser
refs/heads/master
cute-possum-parser/CutePossumParser.swift
mit
1
// // CutePossumParser.swift // // Json parser for Swift. Handy for converting JSON into Swift structs. // // Demo and examples: // // https://github.com/exchangegroup/cute-possum-parser // // Created by Evgenii Neumerzhitckii on 18/12/2014. // Copyright (c) 2014 The Exchange Group Pty Ltd. All rights reserved. // import Foundation private let cutePossumTopLevelObjectKey = "kutePossumTopLevelObjectKey#&" public class CutePossumParser { var parent: CutePossumParser? private let data: NSDictionary public init(json: String) { let encoded = json.dataUsingEncoding(NSUTF8StringEncoding) if let currentEncoded = encoded { var error: NSError? let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(currentEncoded, options: .MutableContainers | .AllowFragments, error: &error) if error != nil { data = NSDictionary() reportFailure() return } if let parsed = parsedObject as? NSDictionary { data = parsed } else { if let parsed: AnyObject = parsedObject { data = [cutePossumTopLevelObjectKey: parsed] } else { data = NSDictionary() reportFailure() } } } else { data = NSDictionary() reportFailure() } } init(data: NSDictionary, parent: CutePossumParser? = nil) { self.data = data self.parent = parent } init(array: NSArray, parent: CutePossumParser? = nil) { data = [cutePossumTopLevelObjectKey: array] self.parent = parent } // Returns parser for the attribute public subscript(name: String) -> CutePossumParser { if let subData = data[name] as? NSDictionary { return CutePossumParser(data: subData, parent: self) } else { reportFailure() return CutePossumParser(data: NSDictionary(), parent: self) } } private var amISuccessful = true // Was parsing successful? public var success: Bool { get { if let currentParent = parent { return currentParent.success } return amISuccessful } } private func reportFailure() { parent?.reportFailure() amISuccessful = false } // Parses primitive value: String, Int, [String] etc. public func parse<T>(name: String, miss: T, canBeMissing: Bool = false) -> T { if !success { return miss } if let parsed = data[name] as? T { return parsed } else { if !canBeMissing { reportFailure() } } return miss } // Parses a top-level value: String, Int, [String] etc. public func parseTopLevelValue<T: CollectionType>(miss: T, canBeMissing: Bool = false) -> T { if !success { return miss } return parse(cutePossumTopLevelObjectKey, miss: miss, canBeMissing: canBeMissing) } // Parses a value that is assigned to a Swift optional. public func parseOptional<T>(name: String, miss: T? = nil) -> T? { if !success { return miss } if let parsed = data[name] as? T { return parsed } return miss } // Parses an optional with custom parser. public func parseOptional<T>(name: String, miss: T? = nil, parser: (CutePossumParser) -> T) -> T? { if !success { return miss } if let currentData = data[name] as? NSDictionary { let itemParser = CutePossumParser(data: currentData, parent: self) return parser(itemParser) } return miss } // Parses a top-level array of items with custom parser function. public func parseArray<T: CollectionType>(miss: T, canBeMissing: Bool = false, parser: (CutePossumParser)->(T.Generator.Element)) -> T { return parseArray(cutePossumTopLevelObjectKey, miss: miss, parser: parser) } // Parses an array of items with custom parser function. public func parseArray<T: CollectionType>(name: String, miss: T, canBeMissing: Bool = false, parser: (CutePossumParser)->(T.Generator.Element)) -> T { if let items = data[name] as? NSArray { var parsedItems = Array<T.Generator.Element>() for item in items { var itemParser: CutePossumParser if let currentData = item as? NSDictionary { itemParser = CutePossumParser(data: currentData, parent: self) } else if let currentArray = item as? NSArray { itemParser = CutePossumParser(array: currentArray, parent: self) } else { if !canBeMissing { reportFailure() } return miss } let parsedValue = parser(itemParser) if success { parsedItems.append(parsedValue) } else { if !canBeMissing { reportFailure() } return miss } } if let result = parsedItems as? T { return result } } else { if !canBeMissing { reportFailure() } } return miss } }
11299d3cd9782fed62bb2f16443a9fc9
26.655367
101
0.628192
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Room/EmojiPicker/Data/Store/EmojiItem.swift
apache-2.0
2
/* Copyright 2019 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 struct EmojiItem { // MARK: - Properties /// The commonly-agreed short name for the emoji, as supported in GitHub and others via the :short_name: syntax (e.g. "grinning" for 😀). let shortName: String /// The emoji string (e.g. 😀) let value: String /// The offical Unicode name (e.g. "Grinning Face" for 😀) let name: String /// An array of all the other known short names (e.g. ["running"] for 🏃‍♂️). let shortNames: [String] /// Associated emoji keywords (e.g. ["face","smile","happy"] for 😀). let keywords: [String] /// For emoji with multiple skin tone variations, a list of alternative emoji items. let variations: [EmojiItem] // MARK: - Setup init(shortName: String, value: String, name: String, shortNames: [String] = [], keywords: [String] = [], variations: [EmojiItem] = []) { self.shortName = shortName self.value = value self.name = name self.shortNames = shortNames self.keywords = keywords self.variations = variations } }
6d80d09b42938685651d0a75519da21a
29.45614
140
0.639977
false
false
false
false
ryanbaldwin/Restivus
refs/heads/master
Tests/Person.swift
apache-2.0
1
// // Person.swift // RestivusTests // // Created by Ryan Baldwin on 2017-08-23. // Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Foundation struct Person: Codable { let firstName: String let lastName: String let age: Int } extension Person: Equatable { static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.age == rhs.age } }
bf54c4c079ae3fd4c44011496c865a00
21.217391
90
0.634051
false
false
false
false
galacemiguel/bluehacks2017
refs/heads/master
Project Civ-1/Project Civ/ViewController.swift
mit
1
// // ViewController.swift // Project Civ // // Created by Carlos Arcenas on 2/18/17. // Copyright © 2017 Rogue Three. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! let picker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() picker.delegate = self // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func callLibraryPressed(_ sender: Any) { picker.allowsEditing = false picker.sourceType = .photoLibrary picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)! present(picker, animated: true, completion: nil) } // For camera itself @IBAction func callCameraPressed(_ sender: Any) { picker.allowsEditing = false picker.sourceType = .camera picker.cameraCaptureMode = .photo picker.modalPresentationStyle = .fullScreen present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage imageView.contentMode = .scaleAspectFit imageView.image = chosenImage dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // here dismiss(animated: true, completion: nil) } }
6d835c06ad6d54c9c84881d47a690dfb
30.754386
119
0.685635
false
false
false
false
Adorkable-forkable/SwiftRecord
refs/heads/master
Example-iOS/SwiftRecordExample/SwiftRecordExample/AppDelegate.swift
mit
1
// // AppDelegate.swift // SwiftRecordExample // // Created by Zaid on 5/8/15. // Copyright (c) 2015 ark. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ark.SwiftRecordExample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftRecordExample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftRecordExample.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
6a0655d1bb482f65042a3023bcd18d3c
54.333333
290
0.716542
false
false
false
false
patricksan/desaparecidosBR
refs/heads/master
DesaparecidosBR/MyFunctions.swift
mit
1
// // MyFunctions.swift // DesaparecidosBR // // Created by hussan on 09/06/14. // Copyright (c) 2014 susieyy. All rights reserved. // import Foundation func colorWithHexString (hex:String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(1) } if (countElements(cString) != 6) { return UIColor.grayColor() } var rString = cString.substringFromIndex(0).substringToIndex(2) var gString = cString.substringFromIndex(2).substringToIndex(4) var bString = cString.substringFromIndex(4).substringToIndex(6) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner.scannerWithString(rString).scanHexInt(&r) NSScanner.scannerWithString(gString).scanHexInt(&g) NSScanner.scannerWithString(bString).scanHexInt(&b) return UIColor(red: Float(r) / 255.0, green: Float(g) / 255.0, blue: Float(b) / 255.0, alpha: Float(1)) }
b938680ffa440ed715492ed9d79aa6d8
31.058824
127
0.693297
false
false
false
false
edx/edx-app-ios
refs/heads/master
Source/CutomePlayer/CustomSlider.swift
apache-2.0
2
// // CustomSlider.swift // edX // // Created by Salman on 25/03/2018. // Copyright © 2018 edX. All rights reserved. // import UIKit class CustomSlider: UISlider { private var progressView = UIProgressView() override init(frame: CGRect) { super.init(frame: CGRect.zero) loadSubViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var secondaryTrackColor : UIColor { set { progressView.progressTintColor = newValue } get { return progressView.progressTintColor ?? UIColor.clear } } var secondaryProgress: Float { set { progressView.progress = newValue } get { return progressView.progress } } private func loadSubViews() { progressView.progress = 0.7 backgroundColor = UIColor.clear maximumTrackTintColor = UIColor.clear addSubview(progressView) } override func layoutSubviews() { super.layoutSubviews() progressView.frame = CGRect(x: 2, y: frame.size.height / 2 - 1, width: frame.size.width - 2, height: frame.size.height); } }
200f4c7e316b259e61c22051623db5cb
22.277778
128
0.589499
false
false
false
false
schrismartin/dont-shoot-the-messenger
refs/heads/master
Sources/Library/Services/SCMMessageHandler.swift
mit
1
// // SCMMessageHandler.swift // the-narrator // // Created by Chris Martin on 11/12/16. // // import Foundation import Dispatch import Vapor import HTTP import MongoKitten public class SCMMessageHandler { // Properties fileprivate var drop: Droplet fileprivate let messageSendQueue = DispatchQueue(label: "MessageSendQueue") public init(app: Droplet? = nil) { self.drop = app ?? Droplet() } enum HandlerErrors: Error { case entryParseError case unexpectedEventFormat } } // MARK: Handle Recipt extension SCMMessageHandler { /// Handle an incoming Messenger JSON Payload and delegate the handling of resulting events asyncronously. /// - Parameter json: JSON payload containing all data returned by a Facebook message /// - Parameter callback: Closure containing all game logic. @available(*, deprecated) public func handleAsync(json: JSON, callback: @escaping (FBIncomingMessage) throws -> Void) { // Run Asyncronously DispatchQueue(label: "Handler").async { do { try self.handle(json: json, callback: callback) } catch { console.log("Issue encountered in handling. Error: \(error)") } } } /// Handle an incoming Messenger JSON Payload and delegate the handling of resulting events. /// - Parameter json: JSON payload containing all data returned by a Facebook message /// - Parameter callback: Closure containing all game logic. public func handle(json: JSON, callback: @escaping (FBIncomingMessage) throws -> Void) throws { // Print JSON output let output = try! Data(json.makeBody().bytes!).toString() // console.log(output) // Extract top-level components guard let type = json["object"]?.string, type == "page", let entries = json["entry"]?.array as? [JSON] else { throw Abort.custom(status: .badRequest, message: "Unexpected Message Entry") } // Extract all events in all messaging arrays into one JSON array let events = entries .flatMap { $0["messaging"]?.array as? [JSON] } .flatMap { $0 } // Traverse each event and activate callback handler for each for data in events { // Extract payload, skip if failure guard let event = FBIncomingMessage(json: data) else { continue } // User feedback _ = try? FBOutgoingMessage.sendIndicator(type: .seen, to: event.recipientId) try callback(event) } } } // MARK: Message Sending Functions extension SCMMessageHandler { /// Send a group of messages to the user at a delay, where the last message is able to be read /// by the time the next one sends /// - Parameter messages: Array of messages to be sent public func sendGroupedMessages(_ messages: [FBOutgoingMessage]) { // Send with delays var sendDelay: Double = 0 for message in messages { // Apply delay and send messages message.delay = sendDelay message.send(handler: { (response) -> (Void) in print(response ?? "No response was received from message sent in grouped message") }) sendDelay += getMessageSendDelay(for: message) + 2 } } } // MARK: Utility Functions extension SCMMessageHandler { /// Calculate the time it takes to read a message /// - Parameter message: FBOutgoing with message to determine the time for fileprivate func getMessageSendDelay(for message: FBOutgoingMessage) -> Double { let charactersPerSecond: Double = 24 let messageLength = Double(message.messageText.characters.count) return messageLength / charactersPerSecond } }
0b475917ccaf5deef34b214c742d8f46
32.15
110
0.618904
false
false
false
false
liuchuo/Swift-practice
refs/heads/master
20150608-5.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var intResult = 1 + 2 println(intResult) intResult = intResult - 1 println(intResult) intResult = intResult * 2 println(intResult) intResult = intResult / 2 println(intResult) intResult = intResult + 8 intResult = intResult % 7 println(intResult) println("-----------") var doubleResult = 10.0 println(doubleResult) doubleResult = doubleResult - 1 println(doubleResult) doubleResult = doubleResult * 2 println(doubleResult) doubleResult = doubleResult / 2 println(doubleResult) doubleResult = doubleResult + 8 doubleResult = doubleResult % 7 println(doubleResult) var s1tr = "Hello, playground" println(s1tr) var value1 = 1 var value2 = 2 if value1 == value2{ println("value1 == value2") } else{ println("value != value2") } let name1 = "world" let name2 = "world" if name1 == name2{ println("name1 == name2") } let a1 = [1,2] let a2 = [1,2] if a1 == a2 { println("a1 == a2") } var i = 0 var a = 10 var b = 9 if(a > b) || (i++ == 1){ println("或运算为true") } else { println("或运算为false") } println("i = \(i)") i++ println("i = \(i)")
94511fc4bdd3df643ea69e4553d71721
13.6625
52
0.659847
false
false
false
false
lacyrhoades/GLSlideshow
refs/heads/master
GLSlideshow/SlideModel.swift
mit
1
// // SlideModel.swift // GLSlideshow // // Created by Lacy Rhoades on 8/12/16. // Copyright © 2016 Colordeaf. All rights reserved. // import GLKit typealias Color = (GLfloat, GLfloat, GLfloat, GLfloat) typealias Point = (GLfloat, GLfloat, GLfloat) typealias Coordinate = (GLfloat, GLfloat) struct Vertex { var position: Point var color: Color var textureCoordinate: Coordinate } class SlideModel { var texture: GLKTextureInfo? var vertices: [Vertex] { let color = Color(1.0, 0, 1.0 , 1.0) return [ Vertex( position: (-x, y + dy, z), color: color, textureCoordinate: Coordinate(0, 0) ), Vertex( position: (x, y + dy, z), color: color, textureCoordinate: Coordinate(1, 0) ), Vertex( position: (x, -y + dy, z), color: color, textureCoordinate: Coordinate(1, 1) ), Vertex( position: (-x, y + dy, z), color: color, textureCoordinate: Coordinate(0, 0) ), Vertex( position: (-x, -y + dy, z), color: color, textureCoordinate: Coordinate(0, 1) ), Vertex( position: (x, -y + dy, z), color: color, textureCoordinate: Coordinate(1, 1) ) ] } var indices: [GLubyte] { return [ 0, 1, 2, 3, 4, 5 ] } var x: GLfloat { return (self.scale / 2.0) * self.aspectRatio } var dy: GLfloat = 0 var y: GLfloat { return self.scale / 2.0 } var z: GLfloat = -1 var scale: GLfloat = 1.0 var image: UIImage init(image: UIImage) { self.image = image } var aspectRatio: GLfloat { return abs(Float(self.image.size.width) / Float(self.image.size.height)) } func reset() { self.dy = 0.0 self.z = -1.0 } }
0c3c7c45d123657d6c9bc1399ad3bb37
21.357143
80
0.457534
false
false
false
false
18775134221/SwiftBase
refs/heads/1.0.0
06-Touch ID /Pods/Alamofire/Source/NetworkReachabilityManager.swift
agpl-3.0
324
// // NetworkReachabilityManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) import Foundation import SystemConfiguration /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and /// WiFi network interfaces. /// /// Reachability can be used to determine background information about why a network operation failed, or to retry /// network requests when a connection is established. It should not be used to prevent a user from initiating a network /// request, as it's possible that an initial request may be required to establish reachability. public class NetworkReachabilityManager { /// Defines the various states of network reachability. /// /// - unknown: It is unknown whether the network is reachable. /// - notReachable: The network is not reachable. /// - reachable: The network is reachable. public enum NetworkReachabilityStatus { case unknown case notReachable case reachable(ConnectionType) } /// Defines the various connection types detected by reachability flags. /// /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. /// - wwan: The connection type is a WWAN connection. public enum ConnectionType { case ethernetOrWiFi case wwan } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void // MARK: - Properties /// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } /// Whether the network is currently reachable over Ethernet or WiFi interface. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } /// The current network reachability status. public var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. public var listenerQueue: DispatchQueue = DispatchQueue.main /// A closure executed when the network reachability status changes. public var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability private var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /// Creates a `NetworkReachabilityManager` instance with the specified host. /// /// - parameter host: The host used to evaluate network reachability. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. /// /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing /// status of the device, both IPv4 and IPv6. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?() { var address = sockaddr_in() address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) address.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(to: &address, { pointer in return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) { return SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability self.previousFlags = SCNetworkReachabilityFlags() } deinit { stopListening() } // MARK: - Listening /// Starts listening for changes in network reachability status. /// /// - returns: `true` if listening was started successfully, `false` otherwise. @discardableResult public func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = Unmanaged.passUnretained(self).toOpaque() let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) listenerQueue.async { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } return callbackEnabled && queueEnabled } /// Stops listening for changes in network reachability status. public func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(_ flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard flags.contains(.reachable) else { return .notReachable } var networkStatus: NetworkReachabilityStatus = .notReachable if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) { if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } } #if os(iOS) if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } #endif return networkStatus } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /// Returns whether the two network reachability status values are equal. /// /// - parameter lhs: The left-hand side value to compare. /// - parameter rhs: The right-hand side value to compare. /// /// - returns: `true` if the two values are equal, `false` otherwise. public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.notReachable, .notReachable): return true case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif
3d982f6573ddd42ea1dbd850a880fe41
37.447826
122
0.701685
false
false
false
false
billdonner/sheetcheats9
refs/heads/master
TinyConsole/TinyConsoleController.swift
apache-2.0
1
// // TinyConsoleController.swift // TinyConsole // // Created by Devran Uenal on 28.11.16. // // import UIKit open class TinyConsoleController: UIViewController { /// the kind of window modes that are supported by TinyConsole /// /// - collapsed: the console is hidden /// - expanded: the console is shown enum WindowMode { case collapsed case expanded } // MARK: - Private Properties - private var rootViewController: UIViewController private var consoleViewController: TinyConsoleViewController = { return TinyConsoleViewController() }() private lazy var consoleViewHeightConstraint: NSLayoutConstraint? = { if #available(iOS 9, *) { return self.consoleViewController.view.heightAnchor.constraint(equalToConstant: 0) } else { return NSLayoutConstraint(item: self.consoleViewController.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0) } }() private let consoleFrameHeight: CGFloat = 120 private let expandedHeight: CGFloat = 140 private lazy var consoleFrame: CGRect = { var consoleFrame = self.view.bounds consoleFrame.size.height -= self.consoleFrameHeight return consoleFrame }() private var consoleWindowMode: WindowMode = .collapsed { didSet { consoleViewHeightConstraint?.isActive = false consoleViewHeightConstraint?.constant = consoleWindowMode == .collapsed ? 0 : self.expandedHeight consoleViewHeightConstraint?.isActive = true } } // MARK: - Initializer - public init(rootViewController: UIViewController) { self.rootViewController = rootViewController super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { assertionFailure("Interface Builder is not supported") self.rootViewController = UIViewController() super.init(coder: aDecoder) } // MARK: - Public Methods - override open func viewDidLoad() { super.viewDidLoad() addChildViewController(consoleViewController) consoleViewController.view.frame = consoleFrame view.addSubview(consoleViewController.view) consoleViewController.didMove(toParentViewController: self) addChildViewController(rootViewController) rootViewController.view.frame = CGRect(x: consoleFrame.minX, y: consoleFrame.maxY, width: view.bounds.width, height: 120) view.addSubview(rootViewController.view) rootViewController.didMove(toParentViewController: self) setupConstraints() } open override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { if (motion == UIEventSubtype.motionShake) { consoleWindowMode = consoleWindowMode == .collapsed ? .expanded : .collapsed UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } } // MARK: - Private Methods - private func setupConstraints() { rootViewController.view.attach(anchor: .top, to: view) consoleViewController.view.attach(anchor: .bottom, to: view) consoleViewHeightConstraint?.isActive = true if #available(iOS 9, *) { rootViewController.view.bottomAnchor.constraint(equalTo: consoleViewController.view.topAnchor).isActive = true } else { NSLayoutConstraint(item: (rootViewController.view)!, attribute: .bottom, relatedBy: .equal, toItem: consoleViewController.view, attribute: .top, multiplier: 1.0, constant: 0) .isActive = true } } } fileprivate extension UIView { enum Anchor { case top case bottom } func attach(anchor: Anchor, to view: UIView) { translatesAutoresizingMaskIntoConstraints = false if #available(iOS 9, *) { switch anchor { case .top: topAnchor.constraint(equalTo: view.topAnchor).isActive = true case .bottom: bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true } else { switch anchor { case .top: NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0) .isActive = true case .bottom: NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0) .isActive = true } // left anchor NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0) .isActive = true // right anchor NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: 0) .isActive = true } } }
47e8dd3ce579323213ed7cf047690c3c
34.043243
186
0.523215
false
false
false
false
chourobin/GPUImage2
refs/heads/develop
framework/Source/iOS/MovieOutput.swift
bsd-3-clause
1
import AVFoundation public protocol AudioEncodingTarget { func activateAudioTrack() func processAudioBuffer(_ sampleBuffer:CMSampleBuffer) } public class MovieOutput: ImageConsumer, AudioEncodingTarget { public let sources = SourceContainer() public let maximumInputs:UInt = 1 public var transform: CGAffineTransform = CGAffineTransform.identity { didSet { assetWriterVideoInput.transform = transform } } let assetWriter:AVAssetWriter let assetWriterVideoInput:AVAssetWriterInput var assetWriterAudioInput:AVAssetWriterInput? let assetWriterPixelBufferInput:AVAssetWriterInputPixelBufferAdaptor let size:Size let colorSwizzlingShader:ShaderProgram private var isRecording = false private var videoEncodingIsFinished = false private var audioEncodingIsFinished = false private var startTime:CMTime? private var previousFrameTime = kCMTimeNegativeInfinity private var previousAudioTime = kCMTimeNegativeInfinity private var encodingLiveVideo:Bool var pixelBuffer:CVPixelBuffer? = nil var renderFramebuffer:Framebuffer! public init(URL:Foundation.URL, size:Size, fileType:String = AVFileTypeQuickTimeMovie, liveVideo:Bool = false, settings:[String:AnyObject]? = nil) throws { if sharedImageProcessingContext.supportsTextureCaches() { self.colorSwizzlingShader = sharedImageProcessingContext.passthroughShader } else { self.colorSwizzlingShader = crashOnShaderCompileFailure("MovieOutput"){try sharedImageProcessingContext.programForVertexShader(defaultVertexShaderForInputs(1), fragmentShader:ColorSwizzlingFragmentShader)} } self.size = size assetWriter = try AVAssetWriter(url:URL, fileType:fileType) // Set this to make sure that a functional movie is produced, even if the recording is cut off mid-stream. Only the last second should be lost in that case. assetWriter.movieFragmentInterval = CMTimeMakeWithSeconds(1.0, 1000) var localSettings:[String:AnyObject] if let settings = settings { localSettings = settings } else { localSettings = [String:AnyObject]() } localSettings[AVVideoWidthKey] = localSettings[AVVideoWidthKey] ?? NSNumber(value:size.width) localSettings[AVVideoHeightKey] = localSettings[AVVideoHeightKey] ?? NSNumber(value:size.height) localSettings[AVVideoCodecKey] = localSettings[AVVideoCodecKey] ?? AVVideoCodecH264 as NSString assetWriterVideoInput = AVAssetWriterInput(mediaType:AVMediaTypeVideo, outputSettings:localSettings) assetWriterVideoInput.expectsMediaDataInRealTime = liveVideo encodingLiveVideo = liveVideo // You need to use BGRA for the video in order to get realtime encoding. I use a color-swizzling shader to line up glReadPixels' normal RGBA output with the movie input's BGRA. let sourcePixelBufferAttributesDictionary:[String:AnyObject] = [kCVPixelBufferPixelFormatTypeKey as String:NSNumber(value:Int32(kCVPixelFormatType_32BGRA)), kCVPixelBufferWidthKey as String:NSNumber(value:size.width), kCVPixelBufferHeightKey as String:NSNumber(value:size.height)] assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput:assetWriterVideoInput, sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary) assetWriter.add(assetWriterVideoInput) } public func startRecording() { startTime = nil sharedImageProcessingContext.runOperationSynchronously{ self.isRecording = self.assetWriter.startWriting() CVPixelBufferPoolCreatePixelBuffer(nil, self.assetWriterPixelBufferInput.pixelBufferPool!, &self.pixelBuffer) /* AVAssetWriter will use BT.601 conversion matrix for RGB to YCbCr conversion * regardless of the kCVImageBufferYCbCrMatrixKey value. * Tagging the resulting video file as BT.601, is the best option right now. * Creating a proper BT.709 video is not possible at the moment. */ CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferColorPrimariesKey, kCVImageBufferColorPrimaries_ITU_R_709_2, .shouldPropagate) CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_601_4, .shouldPropagate) CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferTransferFunctionKey, kCVImageBufferTransferFunction_ITU_R_709_2, .shouldPropagate) let bufferSize = GLSize(self.size) var cachedTextureRef:CVOpenGLESTexture? = nil let _ = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, sharedImageProcessingContext.coreVideoTextureCache, self.pixelBuffer!, nil, GLenum(GL_TEXTURE_2D), GL_RGBA, bufferSize.width, bufferSize.height, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), 0, &cachedTextureRef) let cachedTexture = CVOpenGLESTextureGetName(cachedTextureRef!) self.renderFramebuffer = try! Framebuffer(context:sharedImageProcessingContext, orientation:.portrait, size:bufferSize, textureOnly:false, overriddenTexture:cachedTexture) } } public func finishRecording(_ completionCallback:(() -> Void)? = nil) { sharedImageProcessingContext.runOperationSynchronously{ self.isRecording = false if (self.assetWriter.status == .completed || self.assetWriter.status == .cancelled || self.assetWriter.status == .unknown) { sharedImageProcessingContext.runOperationAsynchronously{ completionCallback?() } return } if ((self.assetWriter.status == .writing) && (!self.videoEncodingIsFinished)) { self.videoEncodingIsFinished = true self.assetWriterVideoInput.markAsFinished() } if ((self.assetWriter.status == .writing) && (!self.audioEncodingIsFinished)) { self.audioEncodingIsFinished = true self.assetWriterAudioInput?.markAsFinished() } // Why can't I use ?? here for the callback? if let callback = completionCallback { self.assetWriter.finishWriting(completionHandler: callback) } else { self.assetWriter.finishWriting{} } } } public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) { defer { framebuffer.unlock() } guard isRecording else { return } // Ignore still images and other non-video updates (do I still need this?) guard let frameTime = framebuffer.timingStyle.timestamp?.asCMTime else { return } // If two consecutive times with the same value are added to the movie, it aborts recording, so I bail on that case guard (frameTime != previousFrameTime) else { return } if (startTime == nil) { if (assetWriter.status != .writing) { assetWriter.startWriting() } assetWriter.startSession(atSourceTime: frameTime) startTime = frameTime } // TODO: Run the following on an internal movie recording dispatch queue, context guard (assetWriterVideoInput.isReadyForMoreMediaData || (!encodingLiveVideo)) else { debugPrint("Had to drop a frame at time \(frameTime)") return } if !sharedImageProcessingContext.supportsTextureCaches() { let pixelBufferStatus = CVPixelBufferPoolCreatePixelBuffer(nil, assetWriterPixelBufferInput.pixelBufferPool!, &pixelBuffer) guard ((pixelBuffer != nil) && (pixelBufferStatus == kCVReturnSuccess)) else { return } } renderIntoPixelBuffer(pixelBuffer!, framebuffer:framebuffer) if (!assetWriterPixelBufferInput.append(pixelBuffer!, withPresentationTime:frameTime)) { debugPrint("Problem appending pixel buffer at time: \(frameTime)") } CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0))) if !sharedImageProcessingContext.supportsTextureCaches() { pixelBuffer = nil } } func renderIntoPixelBuffer(_ pixelBuffer:CVPixelBuffer, framebuffer:Framebuffer) { if !sharedImageProcessingContext.supportsTextureCaches() { renderFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:framebuffer.orientation, size:GLSize(self.size)) renderFramebuffer.lock() } renderFramebuffer.activateFramebufferForRendering() clearFramebufferWithColor(Color.black) CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0))) renderQuadWithShader(colorSwizzlingShader, uniformSettings:ShaderUniformSettings(), vertices:standardImageVertices, inputTextures:[framebuffer.texturePropertiesForOutputRotation(.noRotation)]) if sharedImageProcessingContext.supportsTextureCaches() { glFinish() } else { glReadPixels(0, 0, renderFramebuffer.size.width, renderFramebuffer.size.height, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), CVPixelBufferGetBaseAddress(pixelBuffer)) renderFramebuffer.unlock() } } // MARK: - // MARK: Audio support public func activateAudioTrack() { // TODO: Add ability to set custom output settings assetWriterAudioInput = AVAssetWriterInput(mediaType:AVMediaTypeAudio, outputSettings:nil) assetWriter.add(assetWriterAudioInput!) assetWriterAudioInput?.expectsMediaDataInRealTime = encodingLiveVideo } public func processAudioBuffer(_ sampleBuffer:CMSampleBuffer) { guard let assetWriterAudioInput = assetWriterAudioInput else { return } sharedImageProcessingContext.runOperationSynchronously{ let currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer) if (self.startTime == nil) { if (self.assetWriter.status != .writing) { self.assetWriter.startWriting() } self.assetWriter.startSession(atSourceTime: currentSampleTime) self.startTime = currentSampleTime } guard (assetWriterAudioInput.isReadyForMoreMediaData || (!self.encodingLiveVideo)) else { return } if (!assetWriterAudioInput.append(sampleBuffer)) { print("Trouble appending audio sample buffer") } } } } public extension Timestamp { public init(_ time:CMTime) { self.value = time.value self.timescale = time.timescale self.flags = TimestampFlags(rawValue:time.flags.rawValue) self.epoch = time.epoch } public var asCMTime:CMTime { get { return CMTimeMakeWithEpoch(value, timescale, epoch) } } }
344b55425b9b735c88c3d5cf5687a141
48.316239
295
0.674783
false
false
false
false
joearms/joearms.github.io
refs/heads/master
includes/swift/closures1.swift
mit
1
class Demo { var call: () -> Bool = {() -> Bool in true} } let x = Demo() print(x.call()) var i = 10 var f = {() -> Bool in print("hello I'm a callback and i =", i); return true} x.call = f print(x.call()) i = 20 print(x.call())
d914073d6621f5004f13b7dbec894232
18.5
77
0.551282
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat.ShareExtension/Rooms/SERoomCell.swift
mit
1
// // SERoomTableViewCell.swift // Rocket.Chat.ShareExtension // // Created by Matheus Cardoso on 3/7/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit class SERoomCell: UITableViewCell, SECell { @IBOutlet weak var avatarView: SEAvatarView! @IBOutlet weak var nameLabel: UILabel! override func prepareForReuse() { super.prepareForReuse() avatarView.prepareForReuse() nameLabel.text = "" cellModel = .emptyState } var cellModel: SERoomCellModel = .emptyState { didSet { nameLabel.text = cellModel.name avatarView.name = cellModel.name guard !cellModel.name.isEmpty else { return } if cellModel.room.type == .directMessage, let name = cellModel.name.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { avatarView.setImageUrl("\(cellModel.avatarBaseUrl)/\(name)") } } } }
d13fee86f318ca4ae537b43007178cec
26.583333
118
0.639476
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00140-swift-nominaltypedecl-computetype.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck } class p { u _ = q() { } } u l = r u s: k -> k = { n $h: m.j) { } } o l() { ({}) } struct m<t> { let p: [(t, () -> ())] = [] } protocol p : p { } protocol m { o u() -> String } class j { o m() -> String { n "" } } class h: j, m { q o m() -> String { n "" } o u() -> S, q> { } protocol u { typealias u } class p { typealias u = u
cfe20bb9358940e6b0e5bd14fae694ba
16.777778
79
0.54375
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCFittingFightersViewController.swift
lgpl-2.1
2
// // NCFittingFightersViewController.swift // Neocom // // Created by Artem Shimanski on 10.03.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import CloudData import Dgmpp class NCFittingFightersViewController: UIViewController, TreeControllerDelegate, NCFittingEditorPage { @IBOutlet weak var treeController: TreeController! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var droneBayLabel: NCResourceLabel! @IBOutlet weak var dronesCountLabel: UILabel! private var observer: NotificationObserver? override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCActionTableViewCell.default, Prototype.NCFittingDroneTableViewCell.default, Prototype.NCHeaderTableViewCell.default ]) tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension treeController.delegate = self droneBayLabel.unit = .cubicMeter } private var needsReload = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.treeController.content == nil { self.treeController.content = TreeNode() DispatchQueue.main.async { self.reload() } } else if needsReload { DispatchQueue.main.async { self.reload() } } if observer == nil { observer = NotificationCenter.default.addNotificationObserver(forName: .NCFittingFleetDidUpdate, object: fleet, queue: nil) { [weak self] (note) in guard self?.view.window != nil else { self?.needsReload = true return } self?.reload() } } } //MARK: - TreeControllerDelegate func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { treeController.deselectCell(for: node, animated: true) if let node = node as? NCFittingDroneRow { guard let fleet = fleet else {return} Router.Fitting.DroneActions(node.drones, fleet: fleet).perform(source: self, sender: treeController.cell(for: node)) } else if node is NCActionRow { guard let ship = fleet?.active?.ship ?? fleet?.structure?.0 else {return} guard let typePickerViewController = typePickerViewController else {return} let category = NCDBDgmppItemCategory.category(categoryID: ship is DGMStructure ? .structureFighter : .fighter) typePickerViewController.category = category typePickerViewController.completionHandler = { [weak typePickerViewController, weak self] (_, type) in let typeID = Int(type.typeID) let tag = -1 do { let drone = try DGMDrone(typeID: typeID) try ship.add(drone, squadronTag: tag) for _ in 1..<drone.squadronSize { try ship.add(DGMDrone(typeID: typeID), squadronTag: tag) } NotificationCenter.default.post(name: Notification.Name.NCFittingFleetDidUpdate, object: self?.fleet) } catch { } typePickerViewController?.dismiss(animated: true) if self?.editorViewController?.traitCollection.horizontalSizeClass == .compact || self?.traitCollection.userInterfaceIdiom == .phone { typePickerViewController?.dismiss(animated: true) } } Route(kind: .popover, viewController: typePickerViewController).perform(source: self, sender: treeController.cell(for: node)) } } func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? { guard let node = node as? NCFittingDroneRow else {return nil} let deleteAction = UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: "")) { [weak self] (_, _) in let drones = node.drones guard let ship = drones.first?.parent as? DGMShip else {return} drones.forEach { ship.remove($0) } NotificationCenter.default.post(name: Notification.Name.NCFittingFleetDidUpdate, object: self?.fleet) } return [deleteAction] } //MARK: - Private private func update() { guard let ship = fleet?.active?.ship ?? fleet?.structure?.0 else {return} let droneSquadron = (ship.usedFighterLaunchTubes, ship.totalFighterLaunchTubes) self.droneBayLabel.value = ship.usedFighterHangar self.droneBayLabel.maximumValue = ship.totalFighterHangar self.dronesCountLabel.text = "\(droneSquadron.0)/\(droneSquadron.1)" self.dronesCountLabel.textColor = droneSquadron.0 > droneSquadron.1 ? .red : .white } private func reload() { guard let ship = fleet?.active?.ship ?? fleet?.structure?.0 else {return} var drones = Dictionary(uniqueKeysWithValues: ship.drones.map { i -> (Int, Int, String, Int, DGMDrone) in return (i.squadron.rawValue, i.squadronTag, i.type?.typeName ?? "", i.isActive ? 0 : 1, i) } // .sorted {$0 < $1} .group { $0.0 == $1.0 } .map { i -> (DGMDrone.Squadron, NCFittingDroneSection) in let rows = Array(i).group { ($0.1, $0.2, $0.3) == ($1.1, $1.2, $1.3) } .map {NCFittingDroneRow(drones: $0.map{$0.4})} let squadron = DGMDrone.Squadron(rawValue: i.first!.0)! return (squadron, NCFittingDroneSection(squadron: squadron, ship: ship, children: rows)) }) let squadrons: [DGMDrone.Squadron] = ship is DGMStructure ? [.standupHeavy, .standupLight, .standupSupport] : [.heavy, .light, .support] squadrons.forEach { i in if drones[i] == nil { drones[i] = NCFittingDroneSection(squadron: i, ship: ship, children: []) } } var sections: [TreeNode] = drones.sorted {$0.key.rawValue < $1.key.rawValue}.map{$0.value} sections.append(NCActionRow(title: NSLocalizedString("Add Drone", comment: "").uppercased())) treeController.content?.children = sections update() needsReload = false } }
dd75094abe67196bc40d269f18e92621
34.068323
150
0.710592
false
false
false
false
kstaring/swift
refs/heads/upstream-master
test/SILGen/dynamic_self_reference_storage.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { // CHECK-LABEL: sil hidden @_TFC30dynamic_self_reference_storage3Foo11dynamicSelf func dynamicSelf() -> Self { // CHECK: debug_value {{%.*}} : $Foo let managedSelf = self // CHECK: alloc_box $@box @sil_unmanaged Foo unowned(unsafe) let unmanagedSelf = self // CHECK: alloc_box $@box @sil_unowned Foo unowned(safe) let unownedSelf = self // CHECK: alloc_box $@box @sil_weak Optional<Foo> weak var weakSelf = self // CHECK: debug_value {{%.*}} : $Optional<Foo> let optionalSelf = Optional(self) // CHECK: alloc_box $@box @sil_unowned Foo let f: () -> () = {[unowned self] in ()} // CHECK: alloc_box $@box @sil_weak Optional<Foo> let g: () -> () = {[weak self] in ()} } }
c6f80aec0351a24b707e5b261e9eb872
35.727273
83
0.613861
false
false
false
false
sarahspins/Loop
refs/heads/master
Loop/View Controllers/AuthenticationViewController.swift
apache-2.0
1
// // AuthenticationViewController.swift // Loop // // Created by Nate Racklyeft on 7/2/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit final class AuthenticationViewController<T: ServiceAuthentication>: UITableViewController, IdentifiableClass, UITextFieldDelegate { typealias AuthenticationObserver = (authentication: T) -> Void var authenticationObserver: AuthenticationObserver? var authentication: T private var state: AuthenticationState = .Empty { didSet { switch (oldValue, state) { case let (x, y) where x == y: break case (_, .Verifying): let titleView = ValidatingIndicatorView(frame: CGRect.zero) UIView.animateWithDuration(0.25) { self.navigationItem.hidesBackButton = true self.navigationItem.titleView = titleView } tableView.reloadSections(NSIndexSet(indexesInRange: NSRange(0...1)), withRowAnimation: .Automatic) authentication.verify { [unowned self] (success, error) in dispatch_async(dispatch_get_main_queue()) { UIView.animateWithDuration(0.25) { self.navigationItem.titleView = nil self.navigationItem.hidesBackButton = false } if success { self.state = .Authorized } else { if let error = error { self.presentAlertControllerWithError(error) } self.state = .Unauthorized } } } case (_, .Authorized), (_, .Unauthorized): authenticationObserver?(authentication: authentication) tableView.reloadSections(NSIndexSet(indexesInRange: NSRange(0...1)), withRowAnimation: .Automatic) default: break } } } init(authentication: T) { self.authentication = authentication state = authentication.isAuthorized ? .Authorized : .Unauthorized super.init(style: .Grouped) title = authentication.title } override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(AuthenticationTableViewCell.nib(), forCellReuseIdentifier: AuthenticationTableViewCell.className) tableView.registerNib(ButtonTableViewCell.nib(), forCellReuseIdentifier: ButtonTableViewCell.className) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Section.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .Credentials: switch state { case .Authorized: return authentication.credentials.filter({ !$0.isSecret }).count default: return authentication.credentials.count } case .Button: return 1 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .Button: let cell = tableView.dequeueReusableCellWithIdentifier(ButtonTableViewCell.className, forIndexPath: indexPath) as! ButtonTableViewCell switch state { case .Authorized: cell.button.setTitle(NSLocalizedString("Delete Account", comment: "The title of the button to remove the credentials for a service"), forState: .Normal) cell.button.setTitleColor(UIColor.deleteColor, forState: .Normal) case .Empty, .Unauthorized, .Verifying: cell.button.setTitle(NSLocalizedString("Add Account", comment: "The title of the button to add the credentials for a service"), forState: .Normal) cell.button.setTitleColor(nil, forState: .Normal) } if case .Verifying = state { cell.button.enabled = false } else { cell.button.enabled = true } cell.button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside) return cell case .Credentials: let cell = tableView.dequeueReusableCellWithIdentifier(AuthenticationTableViewCell.className, forIndexPath: indexPath) as! AuthenticationTableViewCell let credential = authentication.credentials[indexPath.row] cell.titleLabel.text = credential.title cell.textField.tag = indexPath.row cell.textField.keyboardType = credential.keyboardType cell.textField.secureTextEntry = credential.isSecret cell.textField.returnKeyType = (indexPath.row < authentication.credentials.count - 1) ? .Next : .Done cell.textField.text = credential.value cell.textField.placeholder = credential.placeholder ?? NSLocalizedString("Required", comment: "The default placeholder string for a credential") cell.textField.delegate = self switch state { case .Authorized, .Verifying, .Empty: cell.textField.enabled = false case .Unauthorized: cell.textField.enabled = true } return cell } } private func validate() { state = .Verifying } // MARK: - Actions @objc private func buttonPressed(_: AnyObject) { tableView.endEditing(false) switch state { case .Authorized: authentication.reset() state = .Unauthorized case .Unauthorized: validate() default: break } } // MARK: - UITextFieldDelegate func textFieldDidEndEditing(textField: UITextField) { authentication.credentials[textField.tag].value = textField.text } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.returnKeyType == .Done { textField.resignFirstResponder() } else { let point = tableView.convertPoint(textField.frame.origin, fromView: textField.superview) if let indexPath = tableView.indexPathForRowAtPoint(point), cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)) as? AuthenticationTableViewCell { cell.textField.becomeFirstResponder() validate() } } return true } } private enum Section: Int { case Credentials case Button static let count = 2 } enum AuthenticationState { case Empty case Authorized case Verifying case Unauthorized }
140e1fcf8849f2adeb79122b747a5aa0
33.604878
168
0.601917
false
false
false
false
KloversOrg/Drupal812
refs/heads/gh-pages
cordova/plugins/cordova-plugin-iosrtc/src/PluginUtils.swift
agpl-3.0
20
import Foundation class PluginUtils { class func randomInt(min: Int, max: Int) -> Int { return Int(arc4random_uniform(UInt32(max - min))) + min } // class func randomString(len: Int) -> String { // let letters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // var randomString: NSMutableString = NSMutableString(capacity: len) // for (var i = 0; i < len; i++) { // var length = UInt32(letters.length) // var rand = arc4random_uniform(length) // randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) // } // return randomString as String // } // class func delay(delay: Double, closure: () -> ()) { // dispatch_after( // dispatch_time( // DISPATCH_TIME_NOW, // Int64(delay * Double(NSEC_PER_SEC)) // ), // dispatch_get_main_queue(), // closure // ) // } }
eb3c1c690eba4626e46b9e5061cab282
25.875
93
0.64186
false
false
false
false
xxxAIRINxxx/ViewPagerController
refs/heads/master
Sources/PagerContainerView.swift
mit
1
// // PagerContainerView.swift // ViewPagerController // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } public final class PagerContainerView: UIView { // MARK: - Public Handler Properties public var didShowViewControllerHandler : ((UIViewController) -> Void)? public var startSyncHandler : ((Int) -> Void)? public var syncOffsetHandler : ((_ currentIndex: Int, _ percentComplete: CGFloat, _ scrollingTowards: Bool) -> Void)? public var finishSyncHandler : ((Int) -> Void)? // MARK: - Private Properties fileprivate lazy var scrollView : InfiniteScrollView = { var scrollView = InfiniteScrollView(frame: self.bounds) scrollView.infiniteDataSource = self scrollView.infiniteDelegate = self scrollView.backgroundColor = UIColor.clear return scrollView }() // Contents fileprivate var contents : [UIViewController] = [] // Sync ContainerView Scrolling public var scrollingIncrementalRatio: CGFloat = 1.1 fileprivate var startDraggingOffsetX : CGFloat? fileprivate var startDraggingIndex : Int? // MARK: - Constructor public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } fileprivate func commonInit() { self.addSubview(self.scrollView) self.scrollView.isPagingEnabled = true self.scrollView.scrollsToTop = false self.setupConstraint() } // MARK: - Override override public func layoutSubviews() { super.layoutSubviews() self.scrollView.frame = self.bounds } // MARK: - Public Functions public func addViewController(_ viewController: UIViewController) { self.contents.append(viewController) self.scrollView.reloadViews() } public func indexFromViewController(_ viewController: UIViewController) -> Int? { return self.contents.index(of: viewController) } public func removeContent(_ viewController: UIViewController) { if let content = self.contents.filter({ $0 === viewController }).first { self.contents = self.contents.filter() { $0 !== content } self.scrollView.reset() self.reload() } } public func scrollToCenter(_ index: Int, animated: Bool, animation: (() -> Void)?, completion: (() -> Void)?) { if !self.scrollView.isDragging { let _index = self.currentIndex() if _index == index { return } if _index > index { self.scrollView.resetWithIndex(index + 1) } else { self.scrollView.resetWithIndex(index - 1) } self.scrollView.scrollToCenter(index, animated: animated, animation: animation) { [weak self] in self?.scrollView.resetWithIndex(index) completion?() } } } public func currentIndex() -> Int? { guard let currentItem = self.scrollView.itemAtCenterPosition() else { return nil } return currentItem.index } public func reload() { self.scrollView.resetWithIndex(0) } public func currentContent() -> UIViewController? { guard let _index = self.currentIndex() , _index != Int.min else { return nil } return self.contents[self.scrollView.convertIndex(_index)] } } // MARK: - Layout extension PagerContainerView { fileprivate func setupConstraint() { self.allPin(self.scrollView) } } // MARK: - Sync ContainerView Scrolling extension PagerContainerView { fileprivate func finishSyncViewScroll(_ index: Int) { self.finishSyncHandler?(index) self.startDraggingOffsetX = nil self.scrollView.setNeedsLayout() self.scrollView.layoutIfNeeded() } } // MARK: - InfiniteScrollViewDataSource extension PagerContainerView: InfiniteScrollViewDataSource { public func totalItemCount() -> Int { return self.contents.count } public func viewForIndex(_ index: Int) -> UIView { let controller = self.contents[index] return controller.view } public func thicknessForIndex(_ index: Int) -> CGFloat { return self.frame.size.width } } // MARK: - InfiniteScrollViewDelegate extension PagerContainerView: InfiniteScrollViewDelegate { public func updateContentOffset(_ delta: CGFloat) { self.startDraggingOffsetX? += delta } public func infiniteScrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {} public func infiniteScrollViewWillBeginDragging(_ scrollView: UIScrollView) { if let _currentItem = self.scrollView.itemAtCenterPosition() { if self.startDraggingOffsetX == nil { self.startSyncHandler?(_currentItem.index) } else { self.finishSyncViewScroll(_currentItem.index) } } } public func infinitScrollViewDidScroll(_ scrollView: UIScrollView) { if let _startDraggingOffsetX = self.startDraggingOffsetX { let offsetX = scrollView.contentOffset.x let scrollingTowards = _startDraggingOffsetX > offsetX let percent = (offsetX - _startDraggingOffsetX) / scrollView.bounds.width * self.scrollingIncrementalRatio let percentComplete = scrollingTowards == false ? percent : (1.0 - percent) - 1.0 let _percentComplete = min(1.0, percentComplete) if let _currentItem = self.scrollView.itemAtCenterPosition() { self.syncOffsetHandler?(_currentItem.index, _percentComplete, scrollingTowards) } } else { if scrollView.isDragging { self.startDraggingOffsetX = ceil(scrollView.contentOffset.x) } } } public func infiniteScrollViewDidEndCenterScrolling(_ item: InfiniteItem) { guard self.startDraggingOffsetX != nil else { return } if let _currentItem = self.scrollView.itemAtCenterPosition() { self.scrollView.scrollToCenter(_currentItem.index, animated: false, animation: nil, completion: nil) self.finishSyncViewScroll(_currentItem.index) } } public func infiniteScrollViewDidShowCenterItem(_ item: InfiniteItem) { guard let controller = self.contents.filter({ $0.view === item.view }).first else { return } self.didShowViewControllerHandler?(controller) } }
3dbf24be05764e0c60593855827fd3ef
30.117391
121
0.629174
false
false
false
false
ZhangHangwei/100_days_Swift
refs/heads/master
Project_36/Project_36/AppDelegate.swift
mit
1
// // AppDelegate.swift // Project_36 // // Created by 章航伟 on 09/02/2017. // Copyright © 2017 Harvie. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CAAnimationDelegate { var window: UIWindow? var imageView: UIImageView? var mask: CALayer? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window!.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1) let rootView = window!.rootViewController!.view! mask = CALayer() mask?.contents = UIImage(named: "twitterLogo")?.cgImage mask?.position = rootView.center mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) rootView.layer.mask = mask animateMask() UIApplication.shared.isStatusBarHidden = true return true } func animateMask() { let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 1 keyFrameAnimation.beginTime = CACurrentMediaTime() + 1 keyFrameAnimation.isRemovedOnCompletion = false keyFrameAnimation.fillMode = kCAFillModeBoth let initalBounds = NSValue(cgRect: mask!.bounds) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 80, height: 64)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 2000, height: 2000)) keyFrameAnimation.values = [initalBounds, secondBounds, finalBounds] keyFrameAnimation.keyTimes = [0, 0.3, 1] keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] mask!.add(keyFrameAnimation, forKey: "bounds") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { let rootView = window!.rootViewController!.view! rootView.layer.mask = nil } 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:. } }
db3b975d61cbe3fd251f5523dc4dfee6
43.597701
285
0.695103
false
false
false
false
Shopify/mobile-buy-sdk-ios
refs/heads/main
Buy/Generated/Storefront/SellingPlanCheckoutChargePercentageValue.swift
mit
1
// // SellingPlanCheckoutChargePercentageValue.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The percentage value of the price used for checkout charge. open class SellingPlanCheckoutChargePercentageValueQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = SellingPlanCheckoutChargePercentageValue /// The percentage value of the price used for checkout charge. @discardableResult open func percentage(alias: String? = nil) -> SellingPlanCheckoutChargePercentageValueQuery { addField(field: "percentage", aliasSuffix: alias) return self } } /// The percentage value of the price used for checkout charge. open class SellingPlanCheckoutChargePercentageValue: GraphQL.AbstractResponse, GraphQLObject, SellingPlanCheckoutChargeValue { public typealias Query = SellingPlanCheckoutChargePercentageValueQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "percentage": guard let value = value as? Double else { throw SchemaViolationError(type: SellingPlanCheckoutChargePercentageValue.self, field: fieldName, value: fieldValue) } return value default: throw SchemaViolationError(type: SellingPlanCheckoutChargePercentageValue.self, field: fieldName, value: fieldValue) } } /// The percentage value of the price used for checkout charge. open var percentage: Double { return internalGetPercentage() } func internalGetPercentage(alias: String? = nil) -> Double { return field(field: "percentage", aliasSuffix: alias) as! Double } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { return [] } } }
e82bb195ac41db6e8ae949c03a22e79d
39.013699
127
0.758987
false
false
false
false
jtauber/minilight-swift
refs/heads/master
Minilight/camera.swift
bsd-3-clause
1
// // camera.swift // Minilight // // Created by James Tauber on 6/14/14. // Copyright (c) 2014 James Tauber. See LICENSE. // import Foundation let MIN_ANGLE = 10.0 let MAX_ANGLE = 160.0 struct Camera { let viewPosition: Vector let viewDirection: Vector let viewAngle: Double let right: Vector let up: Vector init(position: Vector, direction:Vector, angle: Double) { self.viewPosition = position self.viewDirection = direction.unitize() self.viewAngle = min(max(angle, MIN_ANGLE), MAX_ANGLE) * (M_PI / 180) if viewDirection == ZERO { viewDirection = Vector(x:0.0, y:0.0, z:1.0) } // calculate right and up self.right = Vector(x:0.0, y:1.0, z:0.0).cross(viewDirection).unitize() if right == ZERO { if viewDirection.y > 0 { up = Vector(x: 0.0, y: 0.0, z: 1.0) } else { up = Vector(x: 0.0, y: 0.0, z: -1.0) } right = up.cross(viewDirection).unitize() } else { up = viewDirection.cross(right).unitize() } } func getFrame(scene: Scene, image: Image) { let raytracer = RayTracer(scene: scene) let aspect = Double(image.height) / Double(image.width) for y in 0..<image.height { for x in 0..<image.width { // convert x, y into sample_direction let xCoefficient = ((Double(x) + drand48()) * 2.0 / Double(image.width)) - 1.0 let yCoefficient = ((Double(y) + drand48()) * 2.0 / Double(image.height)) - 1.0 let offset = right * xCoefficient + up * (yCoefficient * aspect) let sampleDirection = (viewDirection + (offset * tan(viewAngle * 0.5))).unitize() // calculate radiance from that direction let radiance = raytracer.getRadiance(rayOrigin: viewPosition, rayDirection: sampleDirection, lastHit: nil) // and add to image image.addRadiance(x: x, y: y, radiance: radiance) } } } }
3cb8042287a786225d07875ab10d3052
31.385714
122
0.51368
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/Search/153_FindMinimumInRotatedSortedArray.swift
mit
1
// // 151_FindMinimumInRotatedSortedArray.swift // LeetcodeSwift // // Created by yansong li on 2016-09-03. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:153 Find Minimum in Rotated Sorted Array URL: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ Space: O(1) Time: O(lgn) */ class FindMinimumInRotatedSortedArray_Solution { // Set the right most element as this rotated sorted array's target. // Then we want to find the first element that less that right most element. func findMin(_ nums: [Int]) -> Int { guard nums.count > 1 else { return nums.count == 1 ? nums[0] : -1 } var left = 0 var right = nums.count - 1 let target = nums[right] while left + 1 < right { let mid = left + (right - left) / 2 if nums[mid] > target { left = mid } else { right = mid } } if nums[left] > nums[right] { return nums[right] } else { return nums[left] } } }
9d4bc9ef5e447ab7d4ded3aac09ea2ac
23.285714
78
0.617647
false
false
false
false
wupingzj/YangRepoApple
refs/heads/master
TryCoreData/TryCoreData/vcMain.swift
gpl-2.0
1
// // vcMain.swift // TryCoreData // // Created by Ping on 11/07/2014. // Copyright (c) 2014 Yang Ltd. All rights reserved. // import UIKit import CoreData class vcMain: UIViewController { @IBOutlet var txtUsername: UITextField! @IBOutlet var txtPassword: UITextField! @IBAction func btnSave() { //println("Save button pressed \(txtUsername.text)") var appDel : AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject newUser.setValue(txtUsername.text, forKey: "username") newUser.setValue(txtPassword.text, forKey: "password") // TODO - error handling context.save(nil) println(newUser) println("New user saved") } @IBAction func btnLoad() { //println("Load button pressed \(txtPassword.text)") var appDel : AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext var request = NSFetchRequest(entityName: "Users") request.returnsObjectsAsFaults = false request.predicate = NSPredicate(format: "username = %@", txtUsername.text) // context.deleteObject(<#object: NSManagedObject?#>) // TODO -- error handling var results: NSArray = context.executeFetchRequest(request, error: nil) println("Totally \(results.count) records found") if (results.count > 0) { var result = results[0] as NSManagedObject txtUsername.text = result.valueForKey("username") as String txtPassword.text = result.valueForKey("password") as String // for result in results { // println(result) // } } else { // We say potential error because we didn't do error-handling println("No user found. Potential Error.") } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e7a188acf5084502a9052a5ec2bc2c1f
31.618421
134
0.629286
false
false
false
false
relayr/apple-sdk
refs/heads/master
Sources/common/public/Cloud.swift
mit
1
import Utils import ReactiveSwift import Foundation /// Representation of a relayr cloud installation (platform). /// /// It allows high level interaction with the relayr platform. For example, checking if the platform is available or if the connection is broken. public struct Cloud { /// The environment/addresses for this representation of the relayr cloud. public var environment: Cloud.Environment { return services.environment } /// Instance containing the services used on the global cloud calls. internal let services: Cloud.Services } extension Cloud { /// relayr cloud representation pointing to a specific installation. /// - parameter environment: relayr platform. By default, it is the *Production* environment. public init(environment: Cloud.Environment = Cloud.Environment.production) { self.services = Cloud.Services(withEnvironment: environment) } /// Checks if the relayr cloud platform is reachable and whether the services are up or not. /// - returns: Signal Producer returning a single value event and completing, or returning an error if the platform was not reachable. public func isReachable() -> SignalProducer<(),Error> { return self.services.api.isRelayrCloudReachable().mapError(Error.transform) } /// Returns a stream of the relayr-accepted platform's meanings. /// - note: Meanings are free form. relayr provides *a bunch* of universal meanings; however, you can add your custom ones. /// - returns: Signal Producer returning multiple value events; each one containing a single meaning (with the identifier and the human descriptor). public func pullMeanings() -> SignalProducer<(key: String, value: String),Error> { return self.services.api.meanings().mapError(Error.transform) } /// Returns a stream of all device-models supported by the platform. /// - note: There is *a lot* of device models within the platform. This endpoint will take a sizeable amount of time to complete. /// - returns: Signal Producer returning multiple value events; each one containing a device-model. public func pullDeviceModels() -> SignalProducer<DeviceModel,Error> { return self.services.api.deviceModels().mapError(Error.transform) } } extension Cloud { /// Retrieves basic information for all publishers hosted on the relayr platform. /// - returns: Signal Producer returning multiple value events; each one containing a publisher entity.. public func pullPublishers() -> SignalProducer<Publisher,Error> { return self.services.api.publishers().mapError(Error.transform).map(Publisher.init) } /// Retrieves basic information for all projects hosted on the relayr platform. /// - returns: Signal Producer returning multiple value events; each one containing a project entity. public func pullProjects() -> SignalProducer<Project,Error> { return self.services.api.projects().mapError(Error.transform).map(Project.init) } /// Retrieves information from a specific project from the relayr cloud or the internal database. /// - parameter projectIdentifier: Project's unique identifier on the relayr platform. public func pullProject(withIdentifier projectIdentifier: String) -> SignalProducer<Project,Error> { return self.services.api.projectInfo(withID: projectIdentifier).mapError(Error.transform).map(Project.init) } /// Retrieves information from a specific project and user from the relayr cloud. /// - parameter token: The relayr OAuth token identifying a relayr project and user. public func pullProjectUserPair(withToken token: String) -> SignalProducer<(Project,User),Error> { let environment = self.environment let api = API(withURLs: environment.api, token: token) return api.currentProjectInfo().flatMap(.latest) { (projectData) in api.currentUserInfo().map { (userData) in let project = Project(data: projectData) var user = User(data: userData) user.services = User.Services(withEnvironment: environment, token: token) return (project, user) } }.mapError(Error.transform) } } extension Cloud { /// Retrieves information from a specific project from the local database (if exists). /// - parameter projectIdentifier: Project's unique identifier on the relayr platform. public func pullProjectFromDatabase(withIdentifier projectIdentifier: String, loadingLoggedUsers: Bool = false) -> SignalProducer<(Project,[User]),Error> { guard loadingLoggedUsers else { return DB.project(withIdentifier: projectIdentifier).map { (projectData) -> (Project,[User]) in return (Project(data: projectData), []) }.mapError(Error.transform) } let environment = self.environment return DB.tokensData(withProjectIdentifier: projectIdentifier).iterate { (data) -> SignalProducer<User,DB.Error> in DB.user(withIdentifier: data.userID).map { var user = User(data: $0) user.services = User.Services(withEnvironment: environment, token: data.token) return user } }.flatMapError { (error) -> SignalProducer<[User],DB.Error> in if case .resourceNotFound = error { return SignalProducer(value: [User]()) } else { return SignalProducer(error: error) } }.flatMap(.latest) { (users) in DB.project(withIdentifier: projectIdentifier).map { (projectData) -> (Project,[User]) in let project = Project(data: projectData) return (project, users) } }.mapError(Error.transform) } /// Retrieves a project/user pair from the local database (if exists) and initializes the user´s communication services. /// - parameter token: The relayr OAuth token identifying a relayr project and user. public func pullProjectUserPairFromDatabase(withToken token: String) -> SignalProducer<(Project,User),Error> { let environment = self.environment return DB.tokenData(with: token).flatMap(.latest) { (tokenData) in DB.project(withIdentifier: tokenData.projectID).flatMap(.latest) { (projectData) in DB.user(withIdentifier: tokenData.userID).map{ (userData) in let project = Project(data: projectData) var user = User(data: userData) user.services = User.Services(withEnvironment: environment, token: token) return (project, user) } } }.mapError(Error.transform) } } extension Cloud { /// Class containing communication handlers such as API, MQTT, BLE... internal final class Services { /// The relayr installation addresses. let environment: Cloud.Environment /// Service in charge of communicating with relayr's HTTPS endpoints. lazy var api: API = API(withURLs: self.environment.api) /// Designated initialier specifying the routes for the core cloud services. /// - parameter environment: High-level environment defining the routes for the communication services. The routes should work together as a platform. init(withEnvironment environment: Cloud.Environment) { self.environment = environment } } /// relayr's environment defining the addresses of the core communication services. public struct Environment { /// Routes for the API service. public let api: API.Addresses /// Routes for the MQTT service. public let mqtt: MQTT.Addresses } /// It returns a String identifying the Relayr SDK version and the system running the SDK. public static let userAgent: String = { let os = Info.System.OS() let osVersion = os.version.map { " " + $0 } ?? "" let osBuild = os.build.map { "_" + $0 } ?? "" guard let sdkInfo = Info.Framework(withIdentifier: "io.relayr.sdk.\(os.description.lowercased())") else { fatalError("No framework info could be retrieved") } return sdkInfo.identifier + "/" + sdkInfo.version + "_" + sdkInfo.build + " (" + os.description + osVersion + osBuild + ")" }() /// It fetchs from the CPU the current date and transform it into a String. fileprivate static var currentDate: String { return dateFormatter.string(from: Date()) } /// It creates a date formatter following the conventions that the Cloud isntance needs. private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }() } extension Cloud.Environment { /// relayr's production environment. static let production = Cloud.Environment( api: API.Addresses(root: "https://api.relayr.io", broker: "https://broker.relayr.com"), mqtt: MQTT.Addresses(broker: "ssl://mqtt.relayr.io", port: 8883)) /// relayr's development environment. static let development = Cloud.Environment( api: API.Addresses(root: "https://dev-api.relayr.io", broker: "https://dev-broker.relayr.com"), mqtt: MQTT.Addresses(broker: "ssl://dev-mqtt.relayr.io", port: 8883)) }
67730806ea5affc79390429b50949795
50.869565
166
0.672569
false
false
false
false
johnno1962d/swift
refs/heads/master
test/Prototypes/MutableIndexableDict.swift
apache-2.0
1
// RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control %s -o %t.out // RUN: %target-run %t.out | FileCheck %s // REQUIRES: executable_test // General Mutable, Collection, Value-Type Collections // ================================================= // // Basic copy-on-write (COW) requires a container's data to be copied // into new storage before it is modified, to avoid changing the data // of other containers that may share the data. There is one // exception: when we know the container has the only reference to the // data, we can elide the copy. This COW optimization is crucial for // the performance of mutating algorithms. // // Some container elements (Characters in a String, key/value pairs in // an open-addressing hash table) are not traversable with a fixed // size offset, so incrementing/decrementing indices requires looking // at the contents of the container. The current interface for // incrementing/decrementing indices of an Collection is the usual ++i, // --i. Therefore, for memory safety, the indices need to keep a // reference to the container's underlying data so that it can be // inspected. But having multiple outstanding references to the // underlying data defeats the COW optimization. // // The way out is to count containers referencing the data separately // from indices that reference the data. When deciding to elide the // copy and modify the data directly---as long as we don't violate // memory safety of any outstanding indices---we only need to be // sure that no other containers are referencing the data. // // Implementation // -------------- // // Currently we use a data structure like this: // // Dictionary<K,V> (a struct) // +---+ // | * | // +-|-+ // | // V DictionaryBufferOwner<K,V> // +----------------+ // | * [refcount#1] | // +-|--------------+ // | // V FixedSizedRefArrayOfOptional<Pair<K,V>> // +-----------------------------------------+ // | [refcount#2] [...element storage...] | // +-----------------------------------------+ // ^ // +-|-+ // | * | Dictionary<K,V>.Index (a struct) // +---+ // // // In reality, we'd optimize by allocating the DictionaryBufferOwner // /inside/ the FixedSizedRefArrayOfOptional, and override the dealloc // method of DictionaryBufferOwner to do nothing but release its // reference. // // Dictionary<K,V> (a struct) // +---+ // | * | // +-|-+ // | +---+ // | | | // | | V FixedSizeRefArrayOfOptional<Pair<K,V>> // +---|--|-------------------------------------------+ // | | | | // | | | [refcount#2] [...element storage...] | // | | | | // | V | DictionaryBufferOwner<K,V> | // | +----|--------------+ | // | | * [refcount#1] | | // | +-------------------+ | // +--------------------------------------------------+ // ^ // +-|-+ // | * | Dictionary<K,V>.Index (a struct) // +---+ // // Index Invalidation // ------------------ // // Indexing a container, "c[i]", uses the integral offset stored in // the index to access the elements referenced by the container. The // buffer referenced by the index is only used to increment and // decrement the index. Most of the time, these two buffers will be // identical, but they need not always be. For example, if one // ensures that a Dictionary has sufficient capacity to avoid // reallocation on the next element insertion, the following works // // var (i, found) = d.find(k) // i is associated with d's buffer // if found { // var e = d // now d is sharing its data with e // e[newKey] = newValue // e now has a unique copy of the data // return e[i] // use i to access e // } // // The result should be a set of iterator invalidation rules familiar // to anyone familiar with the C++ standard library. Note that // because all accesses to a dictionary buffer are bounds-checked, // this scheme never compromises memory safety. import Swift class FixedSizedRefArrayOfOptionalStorage<T> : _HeapBufferStorage<Int, T?> { deinit { let buffer = Buffer(self) for i in 0..<buffer.value { (buffer.baseAddress + i).deinitialize() } } } struct FixedSizedRefArrayOfOptional<T> { typealias Storage = FixedSizedRefArrayOfOptionalStorage<T> let buffer: Storage.Buffer init(capacity: Int) { buffer = Storage.Buffer(Storage.self, capacity, capacity) for i in 0 ..< capacity { (buffer.baseAddress + i).initialize(with: .none) } buffer.value = capacity } subscript(i: Int) -> T? { get { assert(i >= 0 && i < buffer.value) return (buffer.baseAddress + i).pointee } nonmutating set { assert(i >= 0 && i < buffer.value) (buffer.baseAddress + i).pointee = newValue } } var count: Int { get { return buffer.value } nonmutating set(newValue) { buffer.value = newValue } } } struct DictionaryElement<Key: Hashable, Value> { var key: Key var value: Value } class DictionaryBufferOwner<Key: Hashable, Value> { typealias Element = DictionaryElement<Key, Value> typealias Buffer = FixedSizedRefArrayOfOptional<Element> init(minimumCapacity: Int = 2) { // Make sure there's a representable power of 2 >= minimumCapacity assert(minimumCapacity <= (Int.max >> 1) + 1) var capacity = 2 while capacity < minimumCapacity { capacity <<= 1 } buffer = Buffer(capacity: capacity) } var buffer: Buffer } func == <Element>(lhs: DictionaryIndex<Element>, rhs: DictionaryIndex<Element>) -> Bool { return lhs.offset == rhs.offset } struct DictionaryIndex<Element> : BidirectionalIndex { typealias Index = DictionaryIndex<Element> func predecessor() -> Index { var j = self.offset while j > 1 { j -= 1 if buffer[j] != nil { return Index(buffer: buffer, offset: j) } } return self } func successor() -> Index { var i = self.offset + 1 // FIXME: Can't write the simple code pending // <rdar://problem/15484639> Refcounting bug while i < buffer.count /*&& !buffer[i]*/ { // FIXME: workaround for <rdar://problem/15484639> if buffer[i] != nil { break } // end workaround i += 1 } return Index(buffer: buffer, offset: i) } var buffer: FixedSizedRefArrayOfOptional<Element> var offset: Int } struct Dictionary<Key: Hashable, Value> : Collection, Sequence { typealias _Self = Dictionary<Key, Value> typealias BufferOwner = DictionaryBufferOwner<Key, Value> typealias Buffer = BufferOwner.Buffer typealias Element = BufferOwner.Element typealias Index = DictionaryIndex<Element> /// \brief Create a dictionary with at least the given number of /// elements worth of storage. The actual capacity will be the /// smallest power of 2 that's >= minimumCapacity. init(minimumCapacity: Int = 2) { _owner = BufferOwner(minimumCapacity: minimumCapacity) } var startIndex: Index { return Index(buffer: _buffer, offset: -1).successor() } var endIndex: Index { return Index(buffer: _buffer, offset: _buffer.count) } subscript(i: Index) -> Element { get { return _buffer[i.offset]! } set(keyValue) { assert(keyValue.key == self[i].key) _buffer[i.offset] = .some(keyValue) } } var _maxLoadFactorInverse = 1.0 / 0.75 var maxLoadFactor : Double { get { return 1.0 / _maxLoadFactorInverse } mutating set(newValue) { // 1.0 might be useful for testing purposes; anything more is // crazy assert(newValue <= 1.0) _maxLoadFactorInverse = 1.0 / newValue } } subscript(key: Key) -> Value { get { return self[find(key).0].value } mutating set(value) { var (i, found) = find(key) // count + 2 below ensures that we don't fill in the last hole var minCapacity = found ? capacity : Swift.max(Int(Double(count + 1) * _maxLoadFactorInverse), count + 2) if (_ensureUniqueBuffer(minCapacity)) { i = find(key).0 } _buffer[i.offset] = Element(key: key, value: value) if !found { _count += 1 } } } var capacity : Int { return _buffer.count } var _bucketMask : Int { return capacity - 1 } /// \brief Ensure this Dictionary holds a unique reference to its /// buffer having at least minimumCapacity elements. Return true /// iff this results in a change of capacity. mutating func _ensureUniqueBuffer(_ minimumCapacity: Int) -> Bool { var isUnique: Bool = isUniquelyReferencedNonObjC(&_owner) if !isUnique || capacity < minimumCapacity { var newOwner = _Self(minimumCapacity: minimumCapacity) print("reallocating with isUnique: \(isUnique) and capacity \(capacity)=>\(newOwner.capacity)") for i in 0..<capacity { var x = _buffer[i] if x != nil { if capacity == newOwner.capacity { newOwner._buffer[i] = x } else { newOwner[x!.key] = x!.value } } } newOwner._count = count Swift.swap(&self, &newOwner) return self.capacity != newOwner.capacity } return false } func _bucket(_ k: Key) -> Int { return k.hashValue & _bucketMask } func _next(_ bucket: Int) -> Int { return (bucket + 1) & _bucketMask } func _prev(_ bucket: Int) -> Int { return (bucket - 1) & _bucketMask } func _find(_ k: Key, startBucket: Int) -> (Index,Bool) { var bucket = startBucket // The invariant guarantees there's always a hole, so we just loop // until we find one. assert(count < capacity) while true { var keyVal = _buffer[bucket] if (keyVal == nil) || keyVal!.key == k { return (Index(buffer: _buffer, offset: bucket), keyVal != nil) } bucket = _next(bucket) } } func find(_ k: Key) -> (Index,Bool) { return _find(k, startBucket: _bucket(k)) } mutating func deleteKey(_ k: Key) -> Bool { var start = _bucket(k) var (pos, found) = _find(k, startBucket: start) if !found { return false } // remove the element _buffer[pos.offset] = .none _count -= 1 // If we've put a hole in a chain of contiguous elements, some // element after the hole may belong where the new hole is. var hole = pos.offset // Find the last bucket in the contiguous chain var lastInChain = hole var b = _next(lastInChain) while _buffer[b] != nil { lastInChain = b b = _next(b) } // Relocate out-of-place elements in the chain, repeating until // none are found. while hole != lastInChain { // Walk backwards from the end of the chain looking for // something out-of-place. var b = lastInChain while b != hole { var idealBucket = _bucket(_buffer[b]!.key) // Does this element belong between start and hole? We need // two separate tests depending on whether [start,hole] wraps // around the end of the buffer var c0 = idealBucket >= start var c1 = idealBucket <= hole if start < hole ? (c0 && c1) : (c0 || c1) { break // found it } } if b == hole { // No out-of-place elements found; we're done adjusting break } // Move the found element into the hole _buffer[hole] = _buffer[b] _buffer[b] = .none hole = b b = _prev(b) } return true } var count : Int { return _count } var _count: Int = 0 var _owner: BufferOwner var _buffer: Buffer { return _owner.buffer } } func == <K: Equatable, V: Equatable>( lhs: Dictionary<K,V>, rhs: Dictionary<K,V> ) -> Bool { if lhs.count != rhs.count { return false } for lhsElement in lhs { var (pos, found) = rhs.find(lhsElement.key) // FIXME: Can't write the simple code pending // <rdar://problem/15484639> Refcounting bug /* if !found || rhs[pos].value != lhsElement.value { return false } */ if !found { return false } if rhs[pos].value != lhsElement.value { return false } } return true } func != <K: Equatable, V: Equatable>( lhs: Dictionary<K,V>, rhs: Dictionary<K,V> ) -> Bool { return !(lhs == rhs) } // // Testing // // CHECK: testing print("testing") var d0 = Dictionary<Int, String>() d0[0] = "zero" print("Inserting #2") // CHECK-NEXT: Inserting #2 d0[1] = "one" // CHECK-NEXT: reallocating with isUnique: true and capacity 2=>4 d0[2] = "two" var d1 = d0 print("copies are equal: \(d1 == d0)") // CHECK-NEXT: copies are equal: true d1[3] = "three" // CHECK-NEXT: reallocating with isUnique: false and capacity 4=>8 print("adding a key to one makes them unequal: \(d1 != d0)") // CHECK-NEXT: adding a key to one makes them unequal: true d1.deleteKey(3) print("deleting that key makes them equal again: \(d1 == d0)") // --------- class X : CustomStringConvertible { var constructed : Bool var id = 0 init() {print("X()"); constructed = true} init(_ anID : Int) { print("X(\(anID))") id = anID; constructed = true } deinit { print("~X(\(id))") constructed = false } var description: String { return "X(\(id))" } } extension String { init(_ x: X) { self = "X(\(x.id))" } } func display(_ v : Dictionary<Int, X>) { print("[ ", terminator: "") var separator = "" for p in v { print("\(separator) \(p.key) : \(p.value)", terminator: "") separator = ", " } print(" ]") } func test() { var v = Dictionary<Int, X>() v[1] = X(1) // CHECK: X(1) display(v) // CHECK-NEXT: [ 1 : X(1) ] v[2] = X(2) // CHECK-NEXT: X(2) // CHECK-NEXT: reallocating with isUnique: true and capacity 2=>4 display(v) // CHECK-NEXT: [ 1 : X(1), 2 : X(2) ] v[3] = X(3) // CHECK-NEXT: X(3) display(v) // CHECK-NEXT: [ 1 : X(1), 2 : X(2), 3 : X(3) ] v[4] = X(4) // CHECK-NEXT: X(4) // CHECK-NEXT: reallocating with isUnique: true and capacity 4=>8 display(v) // CHECK-NEXT: [ 1 : X(1), 2 : X(2), 3 : X(3), 4 : X(4) ] // CHECK: ~X(1) // CHECK: ~X(2) // CHECK: ~X(3) // CHECK: ~X(4) } test()
ee11a5c0bcd48f1c778ea5d95076eb00
25.558608
101
0.583408
false
false
false
false
yo-op/sketchcachecleaner
refs/heads/master
Sketch Cache Cleaner/Utils/Share.swift
mit
1
// // Share.swift // Sketch Cache Cleaner // // Created by Sasha Prokhorenko on 29.01.18. // Copyright © 2018 Sasha Prokhorenko. All rights reserved. // enum Share { static func twitterMessage(_ text: String) -> URL { let tweet = "https://twitter.com/intent/tweet?text=Just%20cleared%20" + "\(text.urlEncode())%20of%20space%20on%20my%20disk%20thanks%20" + "to%20Sketch%20Cache%20Cleaner!%20Check%20it%20out:%20" + "https%3A%2F%2Fyo-op.github.io%2Fsketchcachecleaner%2F%0A" guard let url = URL(string: tweet) else { return URL(string: Environment.webPage)! } return url } static func facebookMessage(_ text: String) -> URL { let facebook = "https://www.facebook.com/dialog/share?%20app_id=1778148252492778" + "&href=https%3A%2F%2Fyo-op.github.io%2Fsketchcachecleaner%2F%0A" + "&quote=Just%20cleared%20" + "\(text.urlEncode())%20of%20space%20on%20my%20disk%20thanks%20" + "to%20Sketch%20Cache%20Cleaner!%20Check%20it%20out:%20" + "&redirect_uri=https%3A%2F%2F.facebook.com" guard let url = URL(string: facebook) else { return URL(string: Environment.webPage)! } return url } }
9220ccc090482abcbb41d87f2cae8fb2
37.818182
91
0.615144
false
false
false
false
optimizely/swift-sdk
refs/heads/master
Sources/Extensions/OptimizelyClient+Extension.swift
apache-2.0
1
// // Copyright 2019-2021, Optimizely, Inc. and contributors // // 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 extension OptimizelyClient { func registerServices(sdkKey: String, logger: OPTLogger, eventDispatcher: OPTEventDispatcher, datafileHandler: OPTDatafileHandler, decisionService: OPTDecisionService, notificationCenter: OPTNotificationCenter) { // Register my logger service. Bind it as a non-singleton. So, we will create an instance anytime injected. // we don't associate the logger with a sdkKey at this time because not all components are sdkKey specific. HandlerRegistryService.shared.registerBinding(binder: Binder<OPTLogger>(service: OPTLogger.self, factory: type(of: logger).init)) // This is bound a reusable singleton. so, if we re-initalize, we will keep this. HandlerRegistryService.shared.registerBinding(binder: Binder<OPTNotificationCenter>(sdkKey: sdkKey, service: OPTNotificationCenter.self, strategy: .reUse, isSingleton: true, inst: notificationCenter)) // The decision service is also a singleton that will reCreate on re-initalize HandlerRegistryService.shared.registerBinding(binder: Binder<OPTDecisionService>(sdkKey: sdkKey, service: OPTDecisionService.self, strategy: .reUse, isSingleton: true, inst: decisionService)) // An event dispatcher. We use a singleton and use the same Event dispatcher for all // projects. If you change the event dispatcher, you can potentially lose data if you // don't use the same backingstore. HandlerRegistryService.shared.registerBinding(binder: Binder<OPTEventDispatcher>(sdkKey: sdkKey, service: OPTEventDispatcher.self, strategy: .reUse, isSingleton: true, inst: eventDispatcher)) // This is a singleton and might be a good candidate for reuse. The handler supports mulitple // sdk keys without having to be created for every key. HandlerRegistryService.shared.registerBinding(binder: Binder<OPTDatafileHandler>(sdkKey: sdkKey, service: OPTDatafileHandler.self, strategy: .reUse, isSingleton: true, inst: datafileHandler)) } /// OptimizelyClient init /// /// - Parameters: /// - sdkKey: sdk key /// - logger: custom Logger /// - eventDispatcher: custom EventDispatcher (optional) /// - datafileHandler: custom datafile handler (optional) /// - userProfileService: custom UserProfileService (optional) /// - periodicDownloadInterval: interval in secs for periodic background datafile download. /// The recommended value is 10 * 60 secs (you can also set this to nil to use the recommended value). /// Set this to 0 to disable periodic downloading. /// - defaultLogLevel: default log level (optional. default = .info) /// - defaultDecisionOptions: default decision optiopns (optional) /// - settings: SDK configuration (optional) public convenience init(sdkKey: String, logger: OPTLogger? = nil, eventDispatcher: OPTEventDispatcher? = nil, datafileHandler: OPTDatafileHandler? = nil, userProfileService: OPTUserProfileService? = nil, periodicDownloadInterval: Int?, defaultLogLevel: OptimizelyLogLevel? = nil, defaultDecideOptions: [OptimizelyDecideOption]? = nil, settings: OptimizelySdkSettings? = nil) { self.init(sdkKey: sdkKey, logger: logger, eventDispatcher: eventDispatcher, datafileHandler: datafileHandler, userProfileService: userProfileService, defaultLogLevel: defaultLogLevel, defaultDecideOptions: defaultDecideOptions, settings: settings) let interval = periodicDownloadInterval ?? 10 * 60 if interval > 0 { self.datafileHandler?.setPeriodicInterval(sdkKey: sdkKey, interval: interval) } } }
8ff6f154d7155f6bb588e0eb8ab81f10
55.529412
208
0.659313
false
false
false
false
laurrenreed/WWCodeDFW
refs/heads/develop
WWCodeDFW/WWCodeDFW/UIViewControllerExtensions.swift
mit
1
// // UIViewControllerExtensions.swift // WWCodeDFW // // Created by Val Osipenko on 10/10/17. // Copyright © 2017 WWCode. All rights reserved. // import UIKit extension UIViewController { func setupNavigationBar() { let tintColor = UIColor(red: 0.06, green: 0.48, blue: 0.48, alpha: 1.0) self.navigationController?.navigationBar.tintColor = tintColor self.navigationController?.view.backgroundColor = .white let rightButton = UIBarButtonItem(title: "Donate", style: .plain, target: self, action: #selector(donate)) self.navigationItem.rightBarButtonItem = rightButton } func donate() { let donateVC = DonationsViewController() donateVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(donateVC, animated: true) } }
cd9619b7265aed8c7b5a40720875a42e
29.678571
114
0.676368
false
false
false
false
duming91/Hear-You
refs/heads/master
Pods/AlamofireImage/Source/Request+AlamofireImage.swift
gpl-3.0
1
// Request+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(OSX) import Cocoa #endif extension Request { static var acceptableImageContentTypes: Set<String> = [ "image/jpg", "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-ms-bmp", "image/x-win-bitmap" ] /** Adds the content types specified to the list of acceptable images content types for validation. - parameter contentTypes: The additional content types. */ public class func addAcceptableImageContentTypes(contentTypes: Set<String>) { Request.acceptableImageContentTypes.unionInPlace(contentTypes) } // MARK: - iOS, tvOS and watchOS #if os(iOS) || os(tvOS) || os(watchOS) /** Creates a response serializer that returns an image initialized from the response data using the specified image options. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - returns: An image response serializer. */ public class func imageResponseSerializer( imageScale imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true) -> ResponseSerializer<UIImage, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { return .Failure(error!) } guard let validData = data where validData.length > 0 else { return .Failure(Request.imageDataError()) } guard Request.validateContentTypeForRequest(request, response: response) else { return .Failure(Request.contentTypeValidationError()) } do { let image = try Request.imageFromResponseData(validData, imageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .Success(image) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage( imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true, completionHandler: Response<Image, NSError> -> Void) -> Self { return response( responseSerializer: Request.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } private class func imageFromResponseData(data: NSData, imageScale: CGFloat) throws -> UIImage { if let image = UIImage.af_threadSafeImageWithData(data, scale: imageScale) { return image } throw imageDataError() } private class var imageScale: CGFloat { #if os(iOS) || os(tvOS) return UIScreen.mainScreen().scale #elseif os(watchOS) return WKInterfaceDevice.currentDevice().screenScale #endif } #elseif os(OSX) // MARK: - OSX /** Creates a response serializer that returns an image initialized from the response data. - returns: An image response serializer. */ public class func imageResponseSerializer() -> ResponseSerializer<NSImage, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { return .Failure(error!) } guard let validData = data where validData.length > 0 else { return .Failure(Request.imageDataError()) } guard Request.validateContentTypeForRequest(request, response: response) else { return .Failure(Request.contentTypeValidationError()) } guard let bitmapImage = NSBitmapImageRep(data: validData) else { return .Failure(Request.imageDataError()) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .Success(image) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage(completionHandler: Response<Image, NSError> -> Void) -> Self { return response( responseSerializer: Request.imageResponseSerializer(), completionHandler: completionHandler ) } #endif // MARK: - Private - Shared Helper Methods private class func validateContentTypeForRequest( request: NSURLRequest?, response: NSHTTPURLResponse?) -> Bool { if let URL = request?.URL where URL.fileURL { return true } if let mimeType = response?.MIMEType where Request.acceptableImageContentTypes.contains(mimeType) { return true } return false } private class func contentTypeValidationError() -> NSError { let failureReason = "Failed to validate response due to unacceptable content type" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } private class func imageDataError() -> NSError { let failureReason = "Failed to create a valid Image from the response data" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } }
67786aa10b8e488175906c3cb68bf6ac
40.793249
121
0.616052
false
false
false
false
niklasberglund/SwiftChinese
refs/heads/develop
SwiftChinese/SwiftChinese/DictionaryExport.swift
mit
1
// // DictionaryExport.swift // SwiftChinese // // Created by Niklas Berglund on 2016-12-11. // Copyright © 2016 Klurig. All rights reserved. // import Foundation import SSZipArchive /// Holds a dictionary export's data - the raw dump and also meta info parsed from the dump. public class DictionaryExport: NSObject { var exportInfo: DictionaryExportInfo var content: String? var version: String? var numberOfEntries: Int? var exportDate: Date? public var hasDownloaded: Bool { get { return content != nil } } public enum ExportError: Error { case DownloadInfoFailed case DownloadFailed case UnzipFailed } public typealias DownloadCompleteClosure = (_ databaseDump: String?, _ error: ExportError?) -> Void public init(exportInfo: DictionaryExportInfo) { self.exportInfo = exportInfo } /// Intended for debugging/development only. When developing you can use this initializer instead to initiate from a local CC-CEDICT export file (cedict_ts.u8). This way you don't have to download and unzip it. /// /// - Parameter localFile: File URL where the unzipped CC-CEDICT export is located(cedict_ts.u8) init(localFile: URL) { self.exportInfo = DictionaryExportInfo(releaseDate: Date(), numberOfEntries: 123123, zipArchive: URL(string: "http://dummy-domain.com/dummy.zip")!) do { self.content = try String(contentsOf: localFile) } catch { self.content = nil } } /// Triggers download of this dictionary export. The database export is returned in the `onCompletion` closure and also stored in `self.content` /// /// - Parameter onCompletion: Closure invoked after download is done, or when it has failed. public func download(onCompletion: @escaping DownloadCompleteClosure) -> Void { let request = URLRequest(url: self.exportInfo.zipArchiveUrl) URLSession.shared.downloadTask(with: request, completionHandler: { (dataUrl, _ response, error) -> Void in guard error == nil else { onCompletion(nil, ExportError.DownloadFailed) return } do { let unzipDirPath = NSTemporaryDirectory() let unzippedFilePath = unzipDirPath + "cedict_ts.u8" SSZipArchive.unzipFile(atPath: dataUrl!.path, toDestination: unzipDirPath) self.content = try String(contentsOfFile: unzippedFilePath, encoding: String.Encoding.utf8) self.readMetadata() DispatchQueue.main.async { onCompletion(self.content, nil) // Success } } catch { DispatchQueue.main.async { onCompletion(nil, ExportError.UnzipFailed) } } }).resume() } /// Read the meta data from this export file func readMetadata() -> Void { let scanner = Scanner(string: self.content!) var versionResult: NSString? let versionStart = "#! version=" scanner.scanUpTo(versionStart, into: nil) scanner.scanLocation = scanner.scanLocation + versionStart.characters.count scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &versionResult) var subVersionResult: NSString? let subVersionStart = "#! subversion=" scanner.scanUpTo(subVersionStart, into: nil) scanner.scanLocation = scanner.scanLocation + subVersionStart.characters.count scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &subVersionResult) var numberOfEntriesResult: NSString? let numberOfEntriesStart = "#! entries=" scanner.scanUpTo(numberOfEntriesStart, into: nil) scanner.scanLocation = scanner.scanLocation + numberOfEntriesStart.characters.count scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &numberOfEntriesResult) var exportDateResult: NSString? let exportDateStart = "#! date=" scanner.scanUpTo(exportDateStart, into: nil) scanner.scanLocation = scanner.scanLocation + exportDateStart.characters.count scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &exportDateResult) self.version = (versionResult as! String) + "." + (subVersionResult as! String) self.numberOfEntries = Int(numberOfEntriesResult!.intValue) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" self.exportDate = dateFormatter.date(from: exportDateResult as! String) } }
e28005db2fa3285bba29ab0b14c8ba8d
37.338583
214
0.63319
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
refs/heads/master
ShepardAppearanceConverter/ShepardAppearanceConverter/Views/Common/Faux Row/FauxRow/FauxRow.swift
mit
1
// // FauxRow.swift // ShepardAppearanceConverter // // Created by Emily Ivie on 8/9/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit @IBDesignable public class FauxRow: UIView { @IBInspectable public var title: String = "Label" { didSet { if oldValue != title { setupRow() } } } @IBInspectable public var isFirst: Bool = false { didSet { if oldValue != isFirst { setupRow() } } } @IBInspectable public var isLast: Bool = false { didSet { if oldValue != isLast { setupRow() } } } @IBInspectable public var hideArrow: Bool = false { didSet { if oldValue != hideArrow { setupRow() } } } @IBInspectable public var highlight: UIColor = Styles.Colors.RowHighlightColor { didSet { if oldValue != highlight { setupRow() } } } public var onClick: (()->Void)? { didSet { setupRow() } } internal var didSetup = false private var hideAutolayout = HideAutolayoutUtility() private var nib: FauxRowNib? public override func layoutSubviews() { if !didSetup { setupRow() } super.layoutSubviews() } internal func setupRow() { if nib == nil, let view = FauxRowNib.loadNib() { insertSubview(view, atIndex: 0) view.translatesAutoresizingMaskIntoConstraints = false view.constraintAllEdgesEqualTo(self) nib = view } if let view = nib { view.titleLabel.text = title if hideArrow { hideAutolayout.hide(view.disclosureImageView, key: "disclosureImageView") } else { hideAutolayout.show(view.disclosureImageView, key: "disclosureImageView") } view.fauxContentRow.highlight = highlight view.fauxContentRow.isFirst = isFirst view.fauxContentRow.isLast = isLast view.fauxContentRow.onClick = { self.onClick?() } didSetup = true } } public func clickRow() { onClick?() } } @IBDesignable public class FauxRowNib: UIView { @IBOutlet weak var fauxContentRow: FauxContentRow! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var disclosureImageView: UIImageView! public class func loadNib() -> FauxRowNib? { let bundle = NSBundle(forClass: FauxRowNib.self) if let view = bundle.loadNibNamed("FauxRowNib", owner: self, options: nil)?.first as? FauxRowNib { return view } return nil } }
3bba23fcad0fccf9f73e010e19d8e22e
25.570093
106
0.546094
false
false
false
false
rringham/swift-promises
refs/heads/master
promises/Promise.swift
mit
1
// // Promise.swift // promises // // Created by Rob Ringham on 6/7/14. // Copyright (c) 2014, Rob Ringham // // 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 protocol Finishable { func done(done: (() -> ())) -> () } class Promise : Finishable { // An array of callbacks (Void -> Void) to iterate through at resolve time. var pending: (() -> ())[] = [] // A callback to call when we're completely done. var done: (() -> ()) = {} // A callback to invoke in the event of failure. var fail: (() -> ()) = {} // A simple way to track rejection. var rejected: Bool = false // Class ("static") method to return a new promise. class func defer() -> Promise { return Promise() } // Resolve method. // // Returns a resolve function that loops through pending callbacks, // invoking each in sequence. // // Invokes fail callback in case of rejection (and swiftly abandons ship). func resolve() -> (() -> ()) { func resolve() -> () { for f in self.pending { if self.rejected { fail() return } f() } if self.rejected { fail() return } done() } return resolve } // Reject method. // // Sets rejection flag to true to halt execution of subsequent callbacks. func reject() -> () { self.rejected = true } // Then method. // // This lets us chain callbacks together; it accepts one parameter, a Void -> Void // callback - can either be a function itself, or a Swift closure. func then(callback: (() -> ())) -> Promise { self.pending.append(callback) return self } // Then method override. // // This also lets us chain callbacks together; it accepts one parameter, // but unlike the previous implementation of then(), it accepts a Promise -> Void // callback (which can either be a function itself, or a Swift closure). // // This method then wraps that callback in a Void -> Void callback that // passes in this Promise object when invoking the callback() function. // // This allows users of our Promise library to have access to the Promise object, // so that they can reject a Promise within their then() clauses. Not the cleanest // way, but hey, this whole thing is a proof of concept, right? :) func then(callback: ((promise: Promise) -> ())) -> Promise { func thenWrapper() -> () { callback(promise: self) } self.pending.append(thenWrapper) return self } // Fail method. // // This lets us chain a fail() method at the end of a set of then() clauses. // // Note that unlike then(), this does not return a Promise object. It returns // a "Finishable" object, which locks users down to only being able to specify // a done() clause after a fail() clause. This is to prevent users from being // able to do something like this: // // promise.then({}).fail({}).then({}).fail({}) // func fail(fail: (() -> ())) -> Finishable { self.fail = fail let finishablePromise : Finishable = self return finishablePromise } // Done method. // // This lets us specify a done() callback to be invoked at the end of a set // of then() clauses (provided the promise hasn't been rejected). func done(done: (() -> ())) -> () { self.done = done } }
84d97ca4f52bef12454b18a8f2595fec
33.807407
86
0.607493
false
false
false
false
polkahq/PLKSwift
refs/heads/master
Sources/polka/ui/PLKLoader.swift
mit
1
// // PLKLoader.swift // // Created by Alvaro Talavera on 5/12/16. // Copyright © 2016 Polka. All rights reserved. // import UIKit public class PLKLoader: NSObject { public static let shared = PLKLoader() private var completionHandler: (()->Void)? private var overlay:UIView? private var window:UIWindow? public func show(style:UIBlurEffectStyle, cancellable completion:(()->Void)?) { if let overlay = self.overlay { if overlay.superview != nil { return; } } completionHandler = completion let screen = UIScreen.main.bounds overlay = UIView(frame: screen) self.overlay!.alpha = 0 if window == nil { window = UIWindow(frame: screen) } if (!UIAccessibilityIsReduceTransparencyEnabled()) { overlay!.backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = overlay!.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlay!.addSubview(blurEffectView) } else { overlay!.backgroundColor = UIColor.black } var tint:UIColor = UIColor.black window!.backgroundColor = UIColor(white: 1, alpha: 0.02) if(style == UIBlurEffectStyle.dark) { tint = UIColor.white window!.backgroundColor = UIColor(white: 0, alpha: 0.02) } let indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) indicator.color = tint indicator.translatesAutoresizingMaskIntoConstraints = false overlay!.addSubview(indicator) overlay!.addConstraint(NSLayoutConstraint(item: overlay!, attribute: .centerX, relatedBy: .equal, toItem: indicator, attribute: .centerX, multiplier: 1, constant: 0)) overlay!.addConstraint(NSLayoutConstraint(item: overlay!, attribute: .centerY, relatedBy: .equal, toItem: indicator, attribute: .centerY, multiplier: 1, constant: 0)) indicator.startAnimating() if(completionHandler != nil) { let button:UIButton = UIButton(type: .system) button.tintColor = tint button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(NSLocalizedString("CANCELAR", comment:""), for: .normal) overlay!.addSubview(button) overlay!.addConstraint(NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: indicator, attribute: .centerX, multiplier: 1, constant: 0)) overlay!.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: indicator, attribute: .bottom, multiplier: 1, constant: 64)) button.addTarget(self, action: #selector(buttonHandler), for: .touchUpInside) } window!.rootViewController = UIViewController() self.overlay?.alpha = 0.1 window!.rootViewController!.view = self.overlay; window!.windowLevel = UIWindowLevelNormal window!.makeKeyAndVisible() UIView.animate(withDuration: 0.3, animations: { self.overlay?.alpha = 1 }) } public func hide(_ completion:(()->Void)? = nil) { if let window = self.window { if !window.isHidden { UIView.animate(withDuration: 0.3, animations: { self.overlay?.alpha = 0 }) { (success) in self.overlay?.removeFromSuperview() self.window?.isHidden = true DispatchQueue.main.async { completion?() } } return } } DispatchQueue.main.async { completion?() } } @objc private func buttonHandler() { self.hide() DispatchQueue.main.async { self.completionHandler?() } } }
45c316215adb3253bca54bb6c3dd0cb7
33.798387
176
0.574739
false
false
false
false
knomi/Allsorts
refs/heads/master
Allsorts/Sorting.swift
mit
1
// // Sorting.swift // Allsorts // // Copyright (c) 2015 Pyry Jahkola. All rights reserved. // extension Sequence { /// Make a sorted copy of `self` using a stable sort algorithm and the given /// 3-way comparator `ordering`. /// /// - FIXME: We wouldn't really need `@escaping` here but there's no way to tell the compiler. public func sorted(ordering: @escaping (Iterator.Element, Iterator.Element) -> Ordering) -> [Iterator.Element] { var array = Array(self) array.sort(ordering: ordering) return array } } extension Array { /// Sort `self` in place using a stable sort algorithm and the given 3-way /// comparator `ordering`. /// /// - FIXME: We wouldn't really need `@escaping` here but there's no way to tell the compiler. public mutating func sort(ordering: @escaping (Element, Element) -> Ordering) { var newIndices = indices.sorted {a, b -> Bool in return (ordering(self[a], self[b]) || (a <=> b)) == .less } self.permute(toIndices: &newIndices) } /// Reorder `self` into the permutation defined by `indices`. /// /// This function can be used to reorder multiple arrays according to the /// same permutation of `indices`: /// /// var xs = ["d", "a", "c", "b"] /// var ys = [10, 20, 30, 40] /// var js = [1, 3, 2, 0] /// xs.permuteInPlace(toIndices: &js) /// print(xs, js) //=> ["a", "b", "c", "d"] [-2, -4, -3, -1] /// ys.permuteInPlace(toIndices: &js) /// print(ys, js) //=> [20, 40, 30, 10] [1, 2, 3, 0] /// /// - Remark: The bits of each `Int` of `indices` are inverted (i.e. `~i`) /// during the process, but the resulting array of `indices` can be used /// for further passes. /// /// - Precondition: `indices` must be either: /// /// 1. a permutation of every number in the range `array.indices`, or /// 2. a permutation of every number in `-array.count ..< -1`, /// /// and in either case it must hold that `array.count == indices.count`. public mutating func permute(toIndices indices: inout [Int]) { precondition(count == indices.count) if let first = indices.first, first < 0 { for i in indices.indices where indices[i] < 0 { var j = i while ~indices[j] != i { let k = ~indices[j] swap(&self[j], &self[k]) (j, indices[j]) = (k, k) } indices[j] = i } } else { for i in indices.indices where indices[i] >= 0 { var j = i while indices[j] != i { let k = indices[j] swap(&self[j], &self[k]) (j, indices[j]) = (k, ~k) } indices[j] = ~i } } } }
b661f3d04f6d30138c33875294888a38
35.419753
98
0.513559
false
false
false
false