repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
IBM-MIL/IBM-Ready-App-for-Healthcare
|
iOS/Healthcare/Controllers/FormsViewController.swift
|
1
|
5778
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2014, 2015. All Rights Reserved.
*/
import UIKit
/**
This view controller presents a Questionnaire for the user to answer when they arrive at the Doctor's office. These questions can
be easily updated by changing the 'questions' variable. The table view has been setup to automatically expand based on the size of the question
so if the question is very long it will all be displayed.
*/
class FormsViewController: HealthcareUIViewController, UITableViewDelegate, UITableViewDataSource {
var formsDataManager = FormsDataManager.formsDataManager
var thePatient = DataManager.dataManager.currentPatient
var currentForms: [Forms]!
// local questions in case server retrieves no data
var questions = [
NSLocalizedString("Had tests for this condition", comment: "n/a"),
NSLocalizedString("Had similar condition before", comment: "n/a"),
NSLocalizedString("Symptoms have worsened", comment: "n/a"),
NSLocalizedString("Pain at rest", comment: "n/a"),
NSLocalizedString("Pain with activity", comment: "n/a"),
NSLocalizedString("Pain wakes you up at night", comment: "n/a"),
NSLocalizedString("Smoke tobacco", comment: "n/a"),
]
@IBOutlet weak var tableView: UITableView!
var tapGestureRecognizer: UITapGestureRecognizer!
// MARK: Lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
SVProgressHUD.showWithMaskType(SVProgressHUDMaskType.Gradient)
formsDataManager.getQuestionnaireForUser(thePatient.userID, callback: formsDataGathered)
Utils.rootViewMenu(self.parentViewController!, disablePanning: true)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
tapGestureRecognizer.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer.enabled = false
self.tableView.estimatedRowHeight = 55.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.tableFooterView = UIView(frame: CGRectZero) // eliminates any empty cells at the bottom of the table view
//send notification to challenge handler
let userInfo:Dictionary<String,UIViewController!> = ["FormsViewController" : self]
NSNotificationCenter.defaultCenter().postNotificationName("viewController", object: nil, userInfo: userInfo)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
/**
Notifies the ReadyAppsChallengeHandler that another view controller has been placed on top of the forms view controller
*/
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
let userInfo:Dictionary<String,Bool!> = ["FormsViewController" : false]
NSNotificationCenter.defaultCenter().postNotificationName("disappear", object: nil, userInfo: userInfo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Callback method that gets called when data has been returned from server
- parameter result: the result stating if the database call was successful
*/
func formsDataGathered(result: FormsResultType) {
SVProgressHUD.dismiss()
if result == FormsResultType.Success {
currentForms = FormsDataManager.formsDataManager.forms
tableView.reloadData()
}
}
/**
Method to open the side panel
*/
func openSideMenu() {
let container = self.navigationController?.parentViewController as! ContainerViewController
container.toggleLeftPanel()
self.tableView.userInteractionEnabled = false
tapGestureRecognizer.enabled = true
}
/**
Method to handle taps when the side menu is open
- parameter recognizer: tap gesture used to call method
*/
func handleTap(recognizer: UITapGestureRecognizer) {
let container = self.navigationController?.parentViewController as! ContainerViewController
container.toggleLeftPanel()
self.tableView.userInteractionEnabled = true
tapGestureRecognizer.enabled = false
}
// MARK: UITableView delegate methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questions.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("questionCell") as! FormQuestionTableViewCell
if var forms = self.currentForms {
let form = forms[indexPath.row]
cell.questionLabel.text = form.textDescription
} else {
cell.questionLabel.text = questions[indexPath.row]
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath) as! FormQuestionTableViewCell
cell.selectedCell()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goToPainFromNext" {
let vc: PainLocationViewController = segue.destinationViewController as! PainLocationViewController
vc.useBlueColor = true
}
}
}
|
epl-1.0
|
1b95613347b2a409d45d08574b60afa3
| 39.398601 | 144 | 0.70296 | 5.52823 | false | false | false | false |
FengDeng/RxGitHubAPI
|
RxGitHubAPI/RxGitHubAPI/YYEventOrg.swift
|
1
|
510
|
//
// YYEventOrg.swift
// RxGitHubAPI
//
// Created by 邓锋 on 16/2/2.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
public class YYEventOrg : NSObject{
public private(set) var id = 0
public private(set) var login = ""
public private(set) var gravatar = ""
public private(set) var avatar = ""
//api
var url = ""
public var org : Requestable<YYOrganization>{
return Requestable(mothod: .GET, url: self.url.yy_clear)
}
}
|
apache-2.0
|
0d0e5d088b83d7ef12bfcde68ffa7b5a
| 20.913043 | 64 | 0.624254 | 3.567376 | false | false | false | false |
victorlin/ReactiveCocoa
|
ReactiveCocoaTests/Swift/SignalProducerSpec.swift
|
1
|
60981
|
//
// SignalProducerSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import Result
import Nimble
import Quick
import ReactiveCocoa
class SignalProducerSpec: QuickSpec {
override func spec() {
describe("init") {
it("should run the handler once per start()") {
var handlerCalledTimes = 0
let signalProducer = SignalProducer<String, NSError>() { observer, disposable in
handlerCalledTimes += 1
return
}
signalProducer.start()
signalProducer.start()
expect(handlerCalledTimes) == 2
}
it("should not release signal observers when given disposable is disposed") {
var disposable: Disposable!
let producer = SignalProducer<Int, NoError> { observer, innerDisposable in
disposable = innerDisposable
innerDisposable += {
// This is necessary to keep the observer long enough to
// even test the memory management.
observer.sendNext(0)
}
}
weak var objectRetainedByObserver: NSObject?
producer.startWithSignal { signal, _ in
let object = NSObject()
objectRetainedByObserver = object
signal.observeNext { _ in _ = object }
}
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
// https://github.com/ReactiveCocoa/ReactiveCocoa/pull/2959
//
// Before #2959, this would be `nil` as the input observer is not
// retained, and observers would not retain the signal.
//
// After #2959, the object is still retained, since the observation
// keeps the signal alive.
expect(objectRetainedByObserver).toNot(beNil())
}
it("should dispose of added disposables upon completion") {
let addedDisposable = SimpleDisposable()
var observer: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError>() { incomingObserver, disposable in
disposable += addedDisposable
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendCompleted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon error") {
let addedDisposable = SimpleDisposable()
var observer: Signal<(), TestError>.Observer!
let producer = SignalProducer<(), TestError>() { incomingObserver, disposable in
disposable += addedDisposable
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendFailed(.default)
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon interruption") {
let addedDisposable = SimpleDisposable()
var observer: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError>() { incomingObserver, disposable in
disposable += addedDisposable
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendInterrupted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon start() disposal") {
let addedDisposable = SimpleDisposable()
let producer = SignalProducer<(), TestError>() { _, disposable in
disposable += addedDisposable
return
}
let startDisposable = producer.start()
expect(addedDisposable.isDisposed) == false
startDisposable.dispose()
expect(addedDisposable.isDisposed) == true
}
}
describe("init(signal:)") {
var signal: Signal<Int, TestError>!
var observer: Signal<Int, TestError>.Observer!
beforeEach {
// Cannot directly assign due to compiler crash on Xcode 7.0.1
let (signalTemp, observerTemp) = Signal<Int, TestError>.pipe()
signal = signalTemp
observer = observerTemp
}
it("should emit values then complete") {
let producer = SignalProducer<Int, TestError>(signal: signal)
var values: [Int] = []
var error: TestError?
var completed = false
producer.start { event in
switch event {
case let .next(value):
values.append(value)
case let .failed(err):
error = err
case .completed:
completed = true
default:
break
}
}
expect(values) == []
expect(error).to(beNil())
expect(completed) == false
observer.sendNext(1)
expect(values) == [ 1 ]
observer.sendNext(2)
observer.sendNext(3)
expect(values) == [ 1, 2, 3 ]
observer.sendCompleted()
expect(completed) == true
}
it("should emit error") {
let producer = SignalProducer<Int, TestError>(signal: signal)
var error: TestError?
let sentError = TestError.default
producer.start { event in
switch event {
case let .failed(err):
error = err
default:
break
}
}
expect(error).to(beNil())
observer.sendFailed(sentError)
expect(error) == sentError
}
}
describe("init(value:)") {
it("should immediately send the value then complete") {
let producerValue = "StringValue"
let signalProducer = SignalProducer<String, NSError>(value: producerValue)
expect(signalProducer).to(sendValue(producerValue, sendError: nil, complete: true))
}
}
describe("init(error:)") {
it("should immediately send the error") {
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let signalProducer = SignalProducer<Int, NSError>(error: producerError)
expect(signalProducer).to(sendValue(nil, sendError: producerError, complete: false))
}
}
describe("init(result:)") {
it("should immediately send the value then complete") {
let producerValue = "StringValue"
let producerResult = .success(producerValue) as Result<String, NSError>
let signalProducer = SignalProducer(result: producerResult)
expect(signalProducer).to(sendValue(producerValue, sendError: nil, complete: true))
}
it("should immediately send the error") {
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let producerResult = .failure(producerError) as Result<String, NSError>
let signalProducer = SignalProducer(result: producerResult)
expect(signalProducer).to(sendValue(nil, sendError: producerError, complete: false))
}
}
describe("init(values:)") {
it("should immediately send the sequence of values") {
let sequenceValues = [1, 2, 3]
let signalProducer = SignalProducer<Int, NSError>(values: sequenceValues)
expect(signalProducer).to(sendValues(sequenceValues, sendError: nil, complete: true))
}
}
describe("SignalProducer.empty") {
it("should immediately complete") {
let signalProducer = SignalProducer<Int, NSError>.empty
expect(signalProducer).to(sendValue(nil, sendError: nil, complete: true))
}
}
describe("SignalProducer.never") {
it("should not send any events") {
let signalProducer = SignalProducer<Int, NSError>.never
expect(signalProducer).to(sendValue(nil, sendError: nil, complete: false))
}
}
describe("trailing closure") {
it("receives next values") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
var values = [Int]()
producer.startWithNext { next in
values.append(next)
}
observer.sendNext(1)
expect(values) == [1]
}
}
describe("SignalProducer.attempt") {
it("should run the operation once per start()") {
var operationRunTimes = 0
let operation: () -> Result<String, NSError> = {
operationRunTimes += 1
return .success("OperationValue")
}
SignalProducer.attempt(operation).start()
SignalProducer.attempt(operation).start()
expect(operationRunTimes) == 2
}
it("should send the value then complete") {
let operationReturnValue = "OperationValue"
let operation: () -> Result<String, NSError> = {
return .success(operationReturnValue)
}
let signalProducer = SignalProducer.attempt(operation)
expect(signalProducer).to(sendValue(operationReturnValue, sendError: nil, complete: true))
}
it("should send the error") {
let operationError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let operation: () -> Result<String, NSError> = {
return .failure(operationError)
}
let signalProducer = SignalProducer.attempt(operation)
expect(signalProducer).to(sendValue(nil, sendError: operationError, complete: false))
}
}
describe("startWithSignal") {
it("should invoke the closure before any effects or events") {
var started = false
var value: Int?
SignalProducer<Int, NoError>(value: 42)
.on(started: {
started = true
}, next: {
value = $0
})
.startWithSignal { _ in
expect(started) == false
expect(value).to(beNil())
}
expect(started) == true
expect(value) == 42
}
it("should dispose of added disposables if disposed") {
let addedDisposable = SimpleDisposable()
var disposable: Disposable!
let producer = SignalProducer<Int, NoError>() { _, disposable in
disposable += addedDisposable
return
}
producer.startWithSignal { _, innerDisposable in
disposable = innerDisposable
}
expect(addedDisposable.isDisposed) == false
disposable.dispose()
expect(addedDisposable.isDisposed) == true
}
it("should send interrupted if disposed") {
var interrupted = false
var disposable: Disposable!
SignalProducer<Int, NoError>(value: 42)
.start(on: TestScheduler())
.startWithSignal { signal, innerDisposable in
signal.observeInterrupted {
interrupted = true
}
disposable = innerDisposable
}
expect(interrupted) == false
disposable.dispose()
expect(interrupted) == true
}
it("should release signal observers if disposed") {
weak var objectRetainedByObserver: NSObject?
var disposable: Disposable!
let producer = SignalProducer<Int, NoError>.never
producer.startWithSignal { signal, innerDisposable in
let object = NSObject()
objectRetainedByObserver = object
signal.observeNext { _ in _ = object.description }
disposable = innerDisposable
}
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
expect(objectRetainedByObserver).to(beNil())
}
it("should not trigger effects if disposed before closure return") {
var started = false
var value: Int?
SignalProducer<Int, NoError>(value: 42)
.on(started: {
started = true
}, next: {
value = $0
})
.startWithSignal { _, disposable in
expect(started) == false
expect(value).to(beNil())
disposable.dispose()
}
expect(started) == false
expect(value).to(beNil())
}
it("should send interrupted if disposed before closure return") {
var interrupted = false
SignalProducer<Int, NoError>(value: 42)
.startWithSignal { signal, disposable in
expect(interrupted) == false
signal.observeInterrupted {
interrupted = true
}
disposable.dispose()
}
expect(interrupted) == true
}
it("should dispose of added disposables upon completion") {
let addedDisposable = SimpleDisposable()
var observer: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError>() { incomingObserver, disposable in
disposable += addedDisposable
observer = incomingObserver
}
producer.startWithSignal { _ in }
expect(addedDisposable.isDisposed) == false
observer.sendCompleted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon error") {
let addedDisposable = SimpleDisposable()
var observer: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError>() { incomingObserver, disposable in
disposable += addedDisposable
observer = incomingObserver
}
producer.startWithSignal { _ in }
expect(addedDisposable.isDisposed) == false
observer.sendFailed(.default)
expect(addedDisposable.isDisposed) == true
}
}
describe("start") {
it("should immediately begin sending events") {
let producer = SignalProducer<Int, NoError>(values: [1, 2])
var values: [Int] = []
var completed = false
producer.start { event in
switch event {
case let .next(value):
values.append(value)
case .completed:
completed = true
default:
break
}
}
expect(values) == [1, 2]
expect(completed) == true
}
it("should send interrupted if disposed") {
let producer = SignalProducer<(), NoError>.never
var interrupted = false
let disposable = producer.startWithInterrupted {
interrupted = true
}
expect(interrupted) == false
disposable.dispose()
expect(interrupted) == true
}
it("should release observer when disposed") {
weak var objectRetainedByObserver: NSObject?
var disposable: Disposable!
let test = {
let producer = SignalProducer<Int, NoError>.never
let object = NSObject()
objectRetainedByObserver = object
disposable = producer.startWithNext { _ in _ = object }
}
test()
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
expect(objectRetainedByObserver).to(beNil())
}
describe("trailing closure") {
it("receives next values") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
var values = [Int]()
producer.startWithNext { next in
values.append(next)
}
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendCompleted()
expect(values) == [1, 2, 3]
}
it("receives results") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
var results: [Result<Int, TestError>] = []
producer.startWithResult { results.append($0) }
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendFailed(.default)
observer.sendCompleted()
expect(results).to(haveCount(4))
expect(results[0].value) == 1
expect(results[1].value) == 2
expect(results[2].value) == 3
expect(results[3].error) == .default
}
}
}
describe("lift") {
describe("over unary operators") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2])
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> Signal<Int, NoError> in
counter += 1
return signal
}
let producer = baseProducer.lift(transform)
expect(counter) == 0
producer.start()
expect(counter) == 1
producer.start()
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2, 3, 4])
let producer = baseProducer.lift { signal in
return signal.map { $0 * $0 }
}
let result = producer.collect().single()
expect(result?.value) == [1, 4, 9, 16]
}
}
describe("over binary operators") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2])
let otherProducer = SignalProducer<Int, NoError>(values: [3, 4])
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<(Int, Int), NoError> in
return { otherSignal in
counter += 1
return Signal.zip(signal, otherSignal)
}
}
let producer = baseProducer.lift(transform)(otherProducer)
expect(counter) == 0
producer.start()
expect(counter) == 1
producer.start()
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2, 3])
let otherProducer = SignalProducer<Int, NoError>(values: [4, 5, 6])
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<Int, NoError> in
return { otherSignal in
return Signal.zip(signal, otherSignal).map { first, second in first + second }
}
}
let producer = baseProducer.lift(transform)(otherProducer)
let result = producer.collect().single()
expect(result?.value) == [5, 7, 9]
}
}
describe("over binary operators with signal") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2])
let (otherSignal, otherSignalObserver) = Signal<Int, NoError>.pipe()
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<(Int, Int), NoError> in
return { otherSignal in
counter += 1
return Signal.zip(signal, otherSignal)
}
}
let producer = baseProducer.lift(transform)(otherSignal)
expect(counter) == 0
producer.start()
otherSignalObserver.sendNext(1)
expect(counter) == 1
producer.start()
otherSignalObserver.sendNext(2)
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3 ])
let (otherSignal, otherSignalObserver) = Signal<Int, NoError>.pipe()
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<Int, NoError> in
return { otherSignal in
return Signal.zip(signal, otherSignal).map(+)
}
}
let producer = baseProducer.lift(transform)(otherSignal)
var result: [Int] = []
var completed: Bool = false
producer.start { event in
switch event {
case .next(let value): result.append(value)
case .completed: completed = true
default: break
}
}
otherSignalObserver.sendNext(4)
expect(result) == [ 5 ]
otherSignalObserver.sendNext(5)
expect(result) == [ 5, 7 ]
otherSignalObserver.sendNext(6)
expect(result) == [ 5, 7, 9 ]
expect(completed) == true
}
}
}
describe("combineLatest") {
it("should combine the events to one array") {
let (producerA, observerA) = SignalProducer<Int, NoError>.pipe()
let (producerB, observerB) = SignalProducer<Int, NoError>.pipe()
let producer = SignalProducer.combineLatest([producerA, producerB])
var values = [[Int]]()
producer.startWithNext { next in
values.append(next)
}
observerA.sendNext(1)
observerB.sendNext(2)
observerA.sendNext(3)
observerA.sendCompleted()
observerB.sendCompleted()
expect(values as NSArray) == [[1, 2], [3, 2]]
}
it("should start signal producers in order as defined") {
var ids = [Int]()
let createProducer = { (id: Int) -> SignalProducer<Int, NoError> in
return SignalProducer { observer, disposable in
ids.append(id)
observer.sendNext(id)
observer.sendCompleted()
}
}
let producerA = createProducer(1)
let producerB = createProducer(2)
let producer = SignalProducer.combineLatest([producerA, producerB])
var values = [[Int]]()
producer.startWithNext { next in
values.append(next)
}
expect(ids) == [1, 2]
expect(values as NSArray) == [[1, 2]] as NSArray
}
}
describe("zip") {
it("should zip the events to one array") {
let producerA = SignalProducer<Int, NoError>(values: [ 1, 2 ])
let producerB = SignalProducer<Int, NoError>(values: [ 3, 4 ])
let producer = SignalProducer.zip([producerA, producerB])
let result = producer.collect().single()
expect(result?.value.map { $0 as NSArray }) == [[1, 3], [2, 4]] as NSArray
}
it("should start signal producers in order as defined") {
var ids = [Int]()
let createProducer = { (id: Int) -> SignalProducer<Int, NoError> in
return SignalProducer { observer, disposable in
ids.append(id)
observer.sendNext(id)
observer.sendCompleted()
}
}
let producerA = createProducer(1)
let producerB = createProducer(2)
let producer = SignalProducer.zip([producerA, producerB])
var values = [[Int]]()
producer.startWithNext { next in
values.append(next)
}
expect(ids) == [1, 2]
expect(values as NSArray) == [[1, 2]] as NSArray
}
}
describe("timer") {
it("should send the current date at the given interval") {
let scheduler = TestScheduler()
let producer = timer(interval: 1, on: scheduler, leeway: 0)
let startDate = scheduler.currentDate
let tick1 = startDate.addingTimeInterval(1)
let tick2 = startDate.addingTimeInterval(2)
let tick3 = startDate.addingTimeInterval(3)
var dates: [Date] = []
producer.startWithNext { dates.append($0) }
scheduler.advance(by: 0.9)
expect(dates) == []
scheduler.advance(by: 1)
expect(dates) == [tick1]
scheduler.advance()
expect(dates) == [tick1]
scheduler.advance(by: 0.2)
expect(dates) == [tick1, tick2]
scheduler.advance(by: 1)
expect(dates) == [tick1, tick2, tick3]
}
it("should release the signal when disposed") {
let scheduler = TestScheduler()
let producer = timer(interval: 1, on: scheduler, leeway: 0)
var interrupted = false
weak var weakSignal: Signal<Date, NoError>?
producer.startWithSignal { signal, disposable in
weakSignal = signal
scheduler.schedule {
disposable.dispose()
}
signal.observeInterrupted { interrupted = true }
}
expect(weakSignal).toNot(beNil())
expect(interrupted) == false
scheduler.run()
expect(weakSignal).to(beNil())
expect(interrupted) == true
}
}
describe("on") {
it("should attach event handlers to each started signal") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
var starting = 0
var started = 0
var event = 0
var next = 0
var completed = 0
var terminated = 0
let producer = baseProducer
.on(starting: {
starting += 1
}, started: {
started += 1
}, event: { e in
event += 1
}, next: { n in
next += 1
}, completed: {
completed += 1
}, terminated: {
terminated += 1
})
producer.start()
expect(starting) == 1
expect(started) == 1
producer.start()
expect(starting) == 2
expect(started) == 2
observer.sendNext(1)
expect(event) == 2
expect(next) == 2
observer.sendCompleted()
expect(event) == 4
expect(completed) == 2
expect(terminated) == 2
}
it("should attach event handlers for disposal") {
let (baseProducer, _) = SignalProducer<Int, TestError>.pipe()
var disposed: Bool = false
let producer = baseProducer
.on(disposed: { disposed = true })
let disposable = producer.start()
expect(disposed) == false
disposable.dispose()
expect(disposed) == true
}
it("should invoke the `started` action of the inner producer first") {
let (baseProducer, _) = SignalProducer<Int, TestError>.pipe()
var numbers = [Int]()
_ = baseProducer
.on(started: { numbers.append(1) })
.on(started: { numbers.append(2) })
.on(started: { numbers.append(3) })
.start()
expect(numbers) == [1, 2, 3]
}
it("should invoke the `starting` action of the outer producer first") {
let (baseProducer, _) = SignalProducer<Int, TestError>.pipe()
var numbers = [Int]()
_ = baseProducer
.on(starting: { numbers.append(1) })
.on(starting: { numbers.append(2) })
.on(starting: { numbers.append(3) })
.start()
expect(numbers) == [3, 2, 1]
}
}
describe("startOn") {
it("should invoke effects on the given scheduler") {
let scheduler = TestScheduler()
var invoked = false
let producer = SignalProducer<Int, NoError>() { _ in
invoked = true
}
producer.start(on: scheduler).start()
expect(invoked) == false
scheduler.advance()
expect(invoked) == true
}
it("should forward events on their original scheduler") {
let startScheduler = TestScheduler()
let testScheduler = TestScheduler()
let producer = timer(interval: 2, on: testScheduler, leeway: 0)
var next: Date?
producer.start(on: startScheduler).startWithNext { next = $0 }
startScheduler.advance(by: 2)
expect(next).to(beNil())
testScheduler.advance(by: 1)
expect(next).to(beNil())
testScheduler.advance(by: 1)
expect(next) == testScheduler.currentDate
}
}
describe("flatMapError") {
it("should invoke the handler and start new producer for an error") {
let (baseProducer, baseObserver) = SignalProducer<Int, TestError>.pipe()
var values: [Int] = []
var completed = false
baseProducer
.flatMapError { (error: TestError) -> SignalProducer<Int, TestError> in
expect(error) == TestError.default
expect(values) == [1]
return .init(value: 2)
}
.start { event in
switch event {
case let .next(value):
values.append(value)
case .completed:
completed = true
default:
break
}
}
baseObserver.sendNext(1)
baseObserver.sendFailed(.default)
expect(values) == [1, 2]
expect(completed) == true
}
it("should interrupt the replaced producer on disposal") {
let (baseProducer, baseObserver) = SignalProducer<Int, TestError>.pipe()
var (disposed, interrupted) = (false, false)
let disposable = baseProducer
.flatMapError { (error: TestError) -> SignalProducer<Int, TestError> in
return SignalProducer<Int, TestError> { _, disposable in
disposable += ActionDisposable { disposed = true }
}
}
.startWithInterrupted { interrupted = true }
baseObserver.sendFailed(.default)
disposable.dispose()
expect(interrupted) == true
expect(disposed) == true
}
}
describe("flatten") {
describe("FlattenStrategy.concat") {
describe("sequencing") {
var completePrevious: (() -> Void)!
var sendSubsequent: (() -> Void)!
var completeOuter: (() -> Void)!
var subsequentStarted = false
beforeEach {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
let (previousProducer, previousObserver) = SignalProducer<Int, NoError>.pipe()
subsequentStarted = false
let subsequentProducer = SignalProducer<Int, NoError> { _ in
subsequentStarted = true
}
completePrevious = { previousObserver.sendCompleted() }
sendSubsequent = { outerObserver.sendNext(subsequentProducer) }
completeOuter = { outerObserver.sendCompleted() }
outerProducer.flatten(.concat).start()
outerObserver.sendNext(previousProducer)
}
it("should immediately start subsequent inner producer if previous inner producer has already completed") {
completePrevious()
sendSubsequent()
expect(subsequentStarted) == true
}
context("with queued producers") {
beforeEach {
// Place the subsequent producer into `concat`'s queue.
sendSubsequent()
expect(subsequentStarted) == false
}
it("should start subsequent inner producer upon completion of previous inner producer") {
completePrevious()
expect(subsequentStarted) == true
}
it("should start subsequent inner producer upon completion of previous inner producer and completion of outer producer") {
completeOuter()
completePrevious()
expect(subsequentStarted) == true
}
}
}
it("should forward an error from an inner producer") {
let errorProducer = SignalProducer<Int, TestError>(error: TestError.default)
let outerProducer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: errorProducer)
var error: TestError?
(outerProducer.flatten(.concat)).startWithFailed { e in
error = e
}
expect(error) == TestError.default
}
it("should forward an error from the outer producer") {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
var error: TestError?
outerProducer.flatten(.concat).startWithFailed { e in
error = e
}
outerObserver.sendFailed(TestError.default)
expect(error) == TestError.default
}
describe("completion") {
var completeOuter: (() -> Void)!
var completeInner: (() -> Void)!
var completed = false
beforeEach {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
let (innerProducer, innerObserver) = SignalProducer<Int, NoError>.pipe()
completeOuter = { outerObserver.sendCompleted() }
completeInner = { innerObserver.sendCompleted() }
completed = false
outerProducer.flatten(.concat).startWithCompleted {
completed = true
}
outerObserver.sendNext(innerProducer)
}
it("should complete when inner producers complete, then outer producer completes") {
completeInner()
expect(completed) == false
completeOuter()
expect(completed) == true
}
it("should complete when outer producers completes, then inner producers complete") {
completeOuter()
expect(completed) == false
completeInner()
expect(completed) == true
}
}
}
describe("FlattenStrategy.merge") {
describe("behavior") {
var completeA: (() -> Void)!
var sendA: (() -> Void)!
var completeB: (() -> Void)!
var sendB: (() -> Void)!
var outerCompleted = false
var recv = [Int]()
beforeEach {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
let (producerA, observerA) = SignalProducer<Int, NoError>.pipe()
let (producerB, observerB) = SignalProducer<Int, NoError>.pipe()
completeA = { observerA.sendCompleted() }
completeB = { observerB.sendCompleted() }
var a = 0
sendA = { observerA.sendNext(a); a += 1 }
var b = 100
sendB = { observerB.sendNext(b); b += 1 }
outerProducer.flatten(.merge).start { event in
switch event {
case let .next(i):
recv.append(i)
case .completed:
outerCompleted = true
default:
break
}
}
outerObserver.sendNext(producerA)
outerObserver.sendNext(producerB)
outerObserver.sendCompleted()
}
it("should forward values from any inner signals") {
sendA()
sendA()
sendB()
sendA()
sendB()
expect(recv) == [0, 1, 100, 2, 101]
}
it("should complete when all signals have completed") {
completeA()
expect(outerCompleted) == false
completeB()
expect(outerCompleted) == true
}
}
describe("error handling") {
it("should forward an error from an inner signal") {
let errorProducer = SignalProducer<Int, TestError>(error: TestError.default)
let outerProducer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: errorProducer)
var error: TestError?
outerProducer.flatten(.merge).startWithFailed { e in
error = e
}
expect(error) == TestError.default
}
it("should forward an error from the outer signal") {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
var error: TestError?
outerProducer.flatten(.merge).startWithFailed { e in
error = e
}
outerObserver.sendFailed(TestError.default)
expect(error) == TestError.default
}
}
}
describe("FlattenStrategy.latest") {
it("should forward values from the latest inner signal") {
let (outer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
let (firstInner, firstInnerObserver) = SignalProducer<Int, TestError>.pipe()
let (secondInner, secondInnerObserver) = SignalProducer<Int, TestError>.pipe()
var receivedValues: [Int] = []
var errored = false
var completed = false
outer.flatten(.latest).start { event in
switch event {
case let .next(value):
receivedValues.append(value)
case .completed:
completed = true
case .failed:
errored = true
case .interrupted:
break
}
}
outerObserver.sendNext(SignalProducer(value: 0))
outerObserver.sendNext(firstInner)
firstInnerObserver.sendNext(1)
outerObserver.sendNext(secondInner)
secondInnerObserver.sendNext(2)
outerObserver.sendCompleted()
expect(receivedValues) == [ 0, 1, 2 ]
expect(errored) == false
expect(completed) == false
firstInnerObserver.sendNext(3)
firstInnerObserver.sendCompleted()
secondInnerObserver.sendNext(4)
secondInnerObserver.sendCompleted()
expect(receivedValues) == [ 0, 1, 2, 4 ]
expect(errored) == false
expect(completed) == true
}
it("should forward an error from an inner signal") {
let inner = SignalProducer<Int, TestError>(error: .default)
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
let result = outer.flatten(.latest).first()
expect(result?.error) == TestError.default
}
it("should forward an error from the outer signal") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(error: .default)
let result = outer.flatten(.latest).first()
expect(result?.error) == TestError.default
}
it("should complete when the original and latest signals have completed") {
let inner = SignalProducer<Int, TestError>.empty
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
var completed = false
outer.flatten(.latest).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should complete when the outer signal completes before sending any signals") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>.empty
var completed = false
outer.flatten(.latest).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should not deadlock") {
let producer = SignalProducer<Int, NoError>(value: 1)
.flatMap(.latest) { _ in SignalProducer(value: 10) }
let result = producer.take(first: 1).last()
expect(result?.value) == 10
}
}
describe("interruption") {
var innerObserver: Signal<(), NoError>.Observer!
var outerObserver: Signal<SignalProducer<(), NoError>, NoError>.Observer!
var execute: ((FlattenStrategy) -> Void)!
var interrupted = false
var completed = false
beforeEach {
let (innerProducer, incomingInnerObserver) = SignalProducer<(), NoError>.pipe()
let (outerProducer, incomingOuterObserver) = SignalProducer<SignalProducer<(), NoError>, NoError>.pipe()
innerObserver = incomingInnerObserver
outerObserver = incomingOuterObserver
execute = { strategy in
interrupted = false
completed = false
outerProducer
.flatten(strategy)
.start { event in
switch event {
case .interrupted:
interrupted = true
case .completed:
completed = true
default:
break
}
}
}
incomingOuterObserver.sendNext(innerProducer)
}
describe("Concat") {
it("should drop interrupted from an inner producer") {
execute(.concat)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.concat)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
describe("Latest") {
it("should drop interrupted from an inner producer") {
execute(.latest)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.latest)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
describe("Merge") {
it("should drop interrupted from an inner producer") {
execute(.merge)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.merge)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
}
describe("disposal") {
var completeOuter: (() -> Void)!
var disposeOuter: (() -> Void)!
var execute: ((FlattenStrategy) -> Void)!
var innerDisposable = SimpleDisposable()
var interrupted = false
beforeEach {
execute = { strategy in
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
innerDisposable = SimpleDisposable()
let innerProducer = SignalProducer<Int, NoError> { $1.add(innerDisposable) }
interrupted = false
let outerDisposable = outerProducer.flatten(strategy).startWithInterrupted {
interrupted = true
}
completeOuter = outerObserver.sendCompleted
disposeOuter = outerDisposable.dispose
outerObserver.sendNext(innerProducer)
}
}
describe("Concat") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.concat)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.concat)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
}
describe("Latest") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.latest)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.latest)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
}
describe("Merge") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.merge)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.merge)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
}
}
}
}
describe("times") {
it("should start a signal N times upon completion") {
let original = SignalProducer<Int, NoError>(values: [ 1, 2, 3 ])
let producer = original.times(3)
let result = producer.collect().single()
expect(result?.value) == [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
}
it("should produce an equivalent signal producer if count is 1") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.times(1)
let result = producer.collect().single()
expect(result?.value) == [ 1 ]
}
it("should produce an empty signal if count is 0") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.times(0)
let result = producer.first()
expect(result).to(beNil())
}
it("should not repeat upon error") {
let results: [Result<Int, TestError>] = [
.success(1),
.success(2),
.failure(.default)
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.times(3)
let events = producer
.materialize()
.collect()
.single()
let result = events?.value
let expectedEvents: [Event<Int, TestError>] = [
.next(1),
.next(2),
.failed(.default)
]
// TODO: if let result = result where result.count == expectedEvents.count
if result?.count != expectedEvents.count {
fail("Invalid result: \(result)")
} else {
// Can't test for equality because Array<T> is not Equatable,
// and neither is Event<Value, Error>.
expect(result![0] == expectedEvents[0]) == true
expect(result![1] == expectedEvents[1]) == true
expect(result![2] == expectedEvents[2]) == true
}
}
it("should evaluate lazily") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.times(Int.max)
let result = producer.take(first: 1).single()
expect(result?.value) == 1
}
}
describe("retry") {
it("should start a signal N times upon error") {
let results: [Result<Int, TestError>] = [
.failure(.error1),
.failure(.error2),
.success(1)
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.value) == 1
}
it("should forward errors that occur after all retries") {
let results: [Result<Int, TestError>] = [
.failure(.default),
.failure(.error1),
.failure(.error2),
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.error) == TestError.error2
}
it("should not retry upon completion") {
let results: [Result<Int, TestError>] = [
.success(1),
.success(2),
.success(3)
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.value) == 1
}
}
describe("then") {
it("should start the subsequent producer after the completion of the original") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
var subsequentStarted = false
let subsequent = SignalProducer<Int, NoError> { observer, _ in
subsequentStarted = true
}
let producer = original.then(subsequent)
producer.start()
expect(subsequentStarted) == false
observer.sendCompleted()
expect(subsequentStarted) == true
}
it("should forward errors from the original producer") {
let original = SignalProducer<Int, TestError>(error: .default)
let subsequent = SignalProducer<Int, TestError>.empty
let result = original.then(subsequent).first()
expect(result?.error) == TestError.default
}
it("should forward errors from the subsequent producer") {
let original = SignalProducer<Int, TestError>.empty
let subsequent = SignalProducer<Int, TestError>(error: .default)
let result = original.then(subsequent).first()
expect(result?.error) == TestError.default
}
it("should forward interruptions from the original producer") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
var subsequentStarted = false
let subsequent = SignalProducer<Int, NoError> { observer, _ in
subsequentStarted = true
}
var interrupted = false
let producer = original.then(subsequent)
producer.startWithInterrupted {
interrupted = true
}
expect(subsequentStarted) == false
observer.sendInterrupted()
expect(interrupted) == true
}
it("should complete when both inputs have completed") {
let (original, originalObserver) = SignalProducer<Int, NoError>.pipe()
let (subsequent, subsequentObserver) = SignalProducer<String, NoError>.pipe()
let producer = original.then(subsequent)
var completed = false
producer.startWithCompleted {
completed = true
}
originalObserver.sendCompleted()
expect(completed) == false
subsequentObserver.sendCompleted()
expect(completed) == true
}
}
describe("first") {
it("should start a signal then block on the first value") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let forwardingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
forwardingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
forwardingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(signal: _signal.delay(0.1, on: forwardingScheduler))
let observingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
observingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
observingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
var result: Int?
observingScheduler.schedule {
result = producer.first()?.value
}
expect(result).to(beNil())
observer.sendNext(1)
expect(result).toEventually(equal(1), timeout: 5.0)
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.first()
expect(result).to(beNil())
}
it("should return the first value if more than one value is sent") {
let result = SignalProducer<Int, NoError>(values: [ 1, 2 ]).first()
expect(result?.value) == 1
}
it("should return an error if one occurs before the first value") {
let result = SignalProducer<Int, TestError>(error: .default).first()
expect(result?.error) == TestError.default
}
}
describe("single") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let forwardingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
forwardingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
forwardingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(signal: _signal.delay(0.1, on: forwardingScheduler))
let observingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
observingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
observingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
var result: Int?
observingScheduler.schedule {
result = producer.single()?.value
}
expect(result).to(beNil())
observer.sendNext(1)
Thread.sleep(forTimeInterval: 3.0)
expect(result).to(beNil())
observer.sendCompleted()
expect(result).toEventually(equal(1))
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.single()
expect(result).to(beNil())
}
it("should return a nil result if more than one value is sent before completion") {
let result = SignalProducer<Int, NoError>(values: [ 1, 2 ]).single()
expect(result).to(beNil())
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).single()
expect(result?.error) == TestError.default
}
}
describe("last") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let scheduler: QueueScheduler
if #available(*, OSX 10.10) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(signal: _signal.delay(0.1, on: scheduler))
var result: Result<Int, NoError>?
let group = DispatchGroup()
let globalQueue: DispatchQueue
if #available(*, OSX 10.10) {
globalQueue = DispatchQueue.global()
} else {
globalQueue = DispatchQueue.global(priority: .default)
}
globalQueue.async(group: group, flags: []) {
result = producer.last()
}
expect(result).to(beNil())
observer.sendNext(1)
observer.sendNext(2)
expect(result).to(beNil())
observer.sendCompleted()
group.wait()
expect(result?.value) == 2
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.last()
expect(result).to(beNil())
}
it("should return the last value if more than one value is sent") {
let result = SignalProducer<Int, NoError>(values: [ 1, 2 ]).last()
expect(result?.value) == 2
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).last()
expect(result?.error) == TestError.default
}
}
describe("wait") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let scheduler: QueueScheduler
if #available(*, OSX 10.10) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(signal: _signal.delay(0.1, on: scheduler))
var result: Result<(), NoError>?
let group = DispatchGroup()
let globalQueue: DispatchQueue
if #available(*, OSX 10.10) {
globalQueue = DispatchQueue.global()
} else {
globalQueue = DispatchQueue.global(priority: .default)
}
globalQueue.async(group: group, flags: []) {
result = producer.wait()
}
expect(result).to(beNil())
observer.sendCompleted()
group.wait()
expect(result?.value).toNot(beNil())
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).wait()
expect(result.error) == TestError.default
}
}
describe("observeOn") {
it("should immediately cancel upstream producer's work when disposed") {
var upstreamDisposable: Disposable!
let producer = SignalProducer<(), NoError>{ _, innerDisposable in
upstreamDisposable = innerDisposable
}
var downstreamDisposable: Disposable!
producer
.observe(on: TestScheduler())
.startWithSignal { signal, innerDisposable in
downstreamDisposable = innerDisposable
}
expect(upstreamDisposable.isDisposed) == false
downstreamDisposable.dispose()
expect(upstreamDisposable.isDisposed) == true
}
}
describe("take") {
it("Should not start concat'ed producer if the first one sends a value when using take(1)") {
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
// Delaying producer1 from sending a value to test whether producer2 is started in the mean-time.
let producer1 = SignalProducer<Int, NoError>() { handler, _ in
handler.sendNext(1)
handler.sendCompleted()
}.start(on: scheduler)
var started = false
let producer2 = SignalProducer<Int, NoError>() { handler, _ in
started = true
handler.sendNext(2)
handler.sendCompleted()
}
let result = producer1.concat(producer2).take(first: 1).collect().first()
expect(result?.value) == [1]
expect(started) == false
}
}
describe("replayLazily") {
var producer: SignalProducer<Int, TestError>!
var observer: SignalProducer<Int, TestError>.ProducedSignal.Observer!
var replayedProducer: SignalProducer<Int, TestError>!
beforeEach {
let (producerTemp, observerTemp) = SignalProducer<Int, TestError>.pipe()
producer = producerTemp
observer = observerTemp
replayedProducer = producer.replayLazily(upTo: 2)
}
context("subscribing to underlying producer") {
it("emits new values") {
var last: Int?
replayedProducer
.assumeNoErrors()
.startWithNext { last = $0 }
expect(last).to(beNil())
observer.sendNext(1)
expect(last) == 1
observer.sendNext(2)
expect(last) == 2
}
it("emits errors") {
var error: TestError?
replayedProducer.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.sendFailed(.default)
expect(error) == TestError.default
}
}
context("buffers past values") {
it("emits last value upon subscription") {
let disposable = replayedProducer
.start()
observer.sendNext(1)
disposable.dispose()
var last: Int?
replayedProducer
.assumeNoErrors()
.startWithNext { last = $0 }
expect(last) == 1
}
it("emits previous failure upon subscription") {
let disposable = replayedProducer
.start()
observer.sendFailed(.default)
disposable.dispose()
var error: TestError?
replayedProducer
.startWithFailed { error = $0 }
expect(error) == TestError.default
}
it("emits last n values upon subscription") {
var disposable = replayedProducer
.start()
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
disposable.dispose()
var values: [Int] = []
disposable = replayedProducer
.assumeNoErrors()
.startWithNext { values.append($0) }
expect(values) == [ 3, 4 ]
observer.sendNext(5)
expect(values) == [ 3, 4, 5 ]
disposable.dispose()
values = []
replayedProducer
.assumeNoErrors()
.startWithNext { values.append($0) }
expect(values) == [ 4, 5 ]
}
}
context("starting underying producer") {
it("starts lazily") {
var started = false
let producer = SignalProducer<Int, NoError>(value: 0)
.on(started: { started = true })
expect(started) == false
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(started) == false
replayedProducer.start()
expect(started) == true
}
it("shares a single subscription") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>.never
.on(started: { startedTimes += 1 })
expect(startedTimes) == 0
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start()
expect(startedTimes) == 1
replayedProducer.start()
expect(startedTimes) == 1
}
it("does not start multiple times when subscribing multiple times") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>(value: 0)
.on(started: { startedTimes += 1 })
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start().dispose()
expect(startedTimes) == 1
replayedProducer.start().dispose()
expect(startedTimes) == 1
}
it("does not start again if it finished") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>.empty
.on(started: { startedTimes += 1 })
expect(startedTimes) == 0
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start()
expect(startedTimes) == 1
replayedProducer.start()
expect(startedTimes) == 1
}
}
context("lifetime") {
it("does not dispose underlying subscription if the replayed producer is still in memory") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(disposed) == false
let disposable = replayedProducer.start()
expect(disposed) == false
disposable.dispose()
expect(disposed) == false
}
it("does not dispose if it has active subscriptions") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
var replayedProducer = ImplicitlyUnwrappedOptional(producer.replayLazily(upTo: 1))
expect(disposed) == false
let disposable1 = replayedProducer?.start()
let disposable2 = replayedProducer?.start()
expect(disposed) == false
replayedProducer = nil
expect(disposed) == false
disposable1?.dispose()
expect(disposed) == false
disposable2?.dispose()
expect(disposed) == true
}
it("disposes underlying producer when the producer is deallocated") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
var replayedProducer = ImplicitlyUnwrappedOptional(producer.replayLazily(upTo: 1))
expect(disposed) == false
let disposable = replayedProducer?.start()
expect(disposed) == false
disposable?.dispose()
expect(disposed) == false
replayedProducer = nil
expect(disposed) == true
}
it("does not leak buffered values") {
final class Value {
private let deinitBlock: () -> Void
init(deinitBlock: @escaping () -> Void) {
self.deinitBlock = deinitBlock
}
deinit {
self.deinitBlock()
}
}
var deinitValues = 0
var producer: SignalProducer<Value, NoError>! = SignalProducer(value: Value {
deinitValues += 1
})
expect(deinitValues) == 0
var replayedProducer: SignalProducer<Value, NoError>! = producer
.replayLazily(upTo: 1)
let disposable = replayedProducer
.start()
disposable.dispose()
expect(deinitValues) == 0
producer = nil
expect(deinitValues) == 0
replayedProducer = nil
expect(deinitValues) == 1
}
}
describe("log events") {
it("should output the correct event") {
let expectations: [(String) -> Void] = [
{ event in expect(event) == "[] started" },
{ event in expect(event) == "[] next 1" },
{ event in expect(event) == "[] completed" },
{ event in expect(event) == "[] terminated" },
{ event in expect(event) == "[] disposed" }
]
let logger = TestLogger(expectations: expectations)
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
producer
.logEvents(logger: logger.logEvent)
.start()
observer.sendNext(1)
observer.sendCompleted()
}
}
describe("init(values) ambiguity") {
it("should not be a SignalProducer<SignalProducer<Int, NoError>, NoError>") {
let producer1: SignalProducer<Int, NoError> = SignalProducer.empty
let producer2: SignalProducer<Int, NoError> = SignalProducer.empty
// This expression verifies at compile time that the type is as expected.
let _: SignalProducer<Int, NoError> = SignalProducer(values: [producer1, producer2])
.flatten(.merge)
}
}
}
}
}
// MARK: - Helpers
extension SignalProducer {
internal static func pipe() -> (SignalProducer, ProducedSignal.Observer) {
let (signal, observer) = ProducedSignal.pipe()
let producer = SignalProducer(signal: signal)
return (producer, observer)
}
/// Creates a producer that can be started as many times as elements in `results`.
/// Each signal will immediately send either a value or an error.
fileprivate static func attemptWithResults<C: Collection>(_ results: C) -> SignalProducer<Value, Error> where C.Iterator.Element == Result<Value, Error>, C.IndexDistance == C.Index, C.Index == Int {
let resultCount = results.count
var operationIndex = 0
precondition(resultCount > 0)
let operation: () -> Result<Value, Error> = {
if operationIndex < resultCount {
defer {
operationIndex += 1
}
return results[results.index(results.startIndex, offsetBy: operationIndex)]
} else {
fail("Operation started too many times")
return results[results.startIndex]
}
}
return SignalProducer.attempt(operation)
}
}
|
mit
|
efdb406d4a338a2f8c22d86b974a74c1
| 26.018609 | 199 | 0.646152 | 4.009797 | false | true | false | false |
ZHSD/ZHZB
|
ZHZB/ZHZB/Classes/Home/Controller/HomeViewController.swift
|
1
|
3566
|
//
// HomeViewController.swift
// ZHZB
//
// Created by 张浩 on 2016/11/15.
// Copyright © 2016年 张浩. All rights reserved.
//
import UIKit
fileprivate let ZHTitleViewH: CGFloat = 40
class HomeViewController: UIViewController {
//MARK: -懒加载属性
fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in
let titleframe = CGRect(x: 0, y: ZHStatusBarH+ZHNavigationBarH, width: ZHScreenW, height: ZHTitleViewH )
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleframe, titles: titles)
titleView.delegate = self
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
//1.确定pageContentView的frame
let contentViewH = ZHScreenH - ZHStatusBarH - ZHNavigationBarH - ZHTitleViewH - ZHTabbarH
let ContentFrame = CGRect(x: 0, y: ZHStatusBarH+ZHNavigationBarH+ZHTitleViewH, width: ZHScreenW, height: contentViewH)
//2.添加ContentView的子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
for _ in 0..<3 {
let Vc = UIViewController()
Vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(Vc)
}
let contentView = PageContentView(frame: ContentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
}
}
//MARK: -设置UI界面
extension HomeViewController {
fileprivate func setupUI() {
//0.不需要调整uiscrollView的内边距(有导航栏系统自动设置64的内边距)
automaticallyAdjustsScrollViewInsets = false
//1.设置导航栏
setupNavigationBar()
//2.添加titleView
view.addSubview(pageTitleView)
//3.添加内容contentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.blue
}
private func setupNavigationBar(){
//1.1设置左侧item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//1.2设置右侧items
let size = CGSize(width: 40, height: 40);
let hister = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
let search = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcode = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
navigationItem.rightBarButtonItems = [hister,search,qrcode]
}
}
//MARK: -遵守PageTitleViewDelegate协议
extension HomeViewController : PageTitleViewDelegate {
func pagetitleView(titleView: PageTitleView, selectIndex index: Int) {
pageContentView.setCurrentIndent(currentIndex: index)
}
}
//MARK: -遵守pageContentViewDelegate协议
extension HomeViewController : pageContentViewDelegate {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
|
mit
|
7a91df38ea985cd9eeb3fd4851298060
| 33.622449 | 156 | 0.662246 | 4.758766 | false | false | false | false |
Leo19/swift_begin
|
test-swift/optional.playground/Contents.swift
|
1
|
616
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var optInt:Int?
optInt = 49
print("\(optInt)")
print("thats true")
print("this is my house")
let intValue:Int = 10
var sum:Int = optInt! + intValue
print("\(sum)")
var optStr:String?
optStr = "hi siri"
var name:String = "zhang san"
var fullName = optStr! + name
print("\(fullName)")
// optional可用于if判断如果有值就是true否则是false
var optValue: Double = 10
if optValue == 10{
print("true")
}else{
print("false")
}
var st:String = "100"
var value:Int = Int(st)!
|
gpl-2.0
|
71a2ab2acb63ddd10ebc1c9448a908c9
| 15.828571 | 53 | 0.644558 | 3.266667 | false | false | false | false |
pawanpoudel/CompositeValidation
|
CompositeValidation/Validators/EmailValidator/EmailFormatValidator.swift
|
1
|
1255
|
import Foundation
class EmailFormatValidator : Validator {
func validateValue(value: String?, error: NSErrorPointer?) -> Bool {
if isEmailFormatValid(value) {
return true
}
if let error = error {
error.memory = invalidEmailFormatError()
}
return false
}
private func isEmailFormatValid(email: String?) -> Bool {
if let email = email {
let expression = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let regex = NSRegularExpression(pattern: expression, options: .CaseInsensitive, error: nil)
let matches = regex?.matchesInString(email, options: .allZeros, range: NSMakeRange(0, count(email)))
return matches?.count > 0
}
return false
}
private func invalidEmailFormatError() -> NSError {
let errorCode = EmailValidatorErrorCode.InvalidFormat
let errorMessage = NSLocalizedString("Please enter a valid email address.", comment: "")
let userInfo = [NSLocalizedDescriptionKey: errorMessage]
let error = NSError(domain: EmailValidatorErrorDomain, code: errorCode.rawValue, userInfo: userInfo)
return error
}
}
|
mit
|
0e0ababbc8fc5e387693ec3719643777
| 35.911765 | 116 | 0.610359 | 5 | false | false | false | false |
aipeople/PokeIV
|
Pods/PGoApi/PGoApi/Classes/PGoRpcApi.swift
|
1
|
8308
|
//
// RPC.swift
// pgomap
//
// Based on https://github.com/tejado/pgoapi/blob/master/pgoapi/rpc_api.py
//
// Created by Luke Sapan on 7/20/16.
// Copyright © 2016 Coadstal. All rights reserved.
//
import Foundation
import Alamofire
import ProtocolBuffers
class PGoRpcApi {
let intent: PGoApiIntent
var auth: PGoAuth
let delegate: PGoApiDelegate?
let subrequests: [PGoApiMethod]
let api: PGoApiRequest
let encrypt: PGoEncrypt
private var timeSinceStart:UInt64 = 0
private var locationHex: NSData
private var requestId: UInt64 = 0
private var manager: Manager? = nil
internal init(subrequests: [PGoApiMethod], intent: PGoApiIntent, auth: PGoAuth, api: PGoApiRequest, delegate: PGoApiDelegate?) {
manager = auth.manager
manager!.session.configuration.HTTPAdditionalHeaders = [
"User-Agent": "Niantic App"
]
self.subrequests = subrequests
self.intent = intent
self.auth = auth
self.delegate = delegate
self.api = api
self.timeSinceStart = UInt64(NSDate().timeIntervalSince1970 * 1000.0)
self.locationHex = NSData()
self.encrypt = PGoEncrypt()
self.requestId = randomUInt64(UInt64(pow(Double(2),Double(62))), max: UInt64(pow(Double(2),Double(63))))
}
internal func request() {
let requestData = buildMainRequest().data()
Alamofire.request(.POST, auth.endpoint, parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = requestData
return (mutableRequest, nil)
})).responseData { response in
let statusCode = response.response?.statusCode
if statusCode != 200 {
print("Unexpected response code, should be 200, got \(statusCode)")
self.delegate?.didReceiveApiError(self.intent, statusCode: statusCode)
return
}
print("Got a response!")
self.delegate?.didReceiveApiResponse(self.intent, response: self.parseMainResponse(response.result.value!))
}
}
private func locationToHex(value:Double) -> NSData {
let f2d = String(unsafeBitCast(value, UInt64.self), radix: 16)
let s = f2d.uppercaseString.stringByReplacingOccurrencesOfString(" ", withString: "")
let data = NSMutableData(capacity: s.characters.count / 2)
for i in 0.stride(to:s.characters.count, by:2) {
var x = -(s.characters.count) + i + 2
if x > s.characters.count - 2 {
x = s.characters.count
}
if x > 0 {
continue
}
let r = s.startIndex.advancedBy(i)..<s.endIndex.advancedBy(x)
let substring = s[r]
let byte = UInt8(substring.withCString { strtoul($0, nil, 16) })
data?.appendBytes([byte] as [UInt8], length: 1)
}
return data!
}
private func hashAuthTicket() -> UInt32 {
let xxh32:xxhash = xxhash()
let firstHash = xxh32.xxh32(0x1B845238, input: auth.authToken!.data().getUInt8Array())
return xxh32.xxh32(firstHash, input: self.locationHex.getUInt8Array())
}
private func hashLocation() -> UInt32 {
let xxh32:xxhash = xxhash()
let LocationData = NSMutableData()
LocationData.appendData(locationToHex(self.api.Location.lat))
LocationData.appendData(locationToHex(self.api.Location.long))
if self.api.Location.alt == nil {
LocationData.appendData(locationToHex(0))
} else {
LocationData.appendData(locationToHex(self.api.Location.alt!))
}
self.locationHex = LocationData
return xxh32.xxh32(0x1B845238, input: LocationData.getUInt8Array())
}
private func randomUInt64(min: UInt64, max: UInt64) -> UInt64 {
return UInt64(Double(max - min) * drand48() + Double(min))
}
private func hashRequest(requestData:NSData) -> UInt64 {
let xxh64:xxhash = xxhash()
let firstHash = xxh64.xxh64(0x1B845238, input: auth.authToken!.data().getUInt8Array())
return xxh64.xxh64(firstHash, input: requestData.getUInt8Array())
}
private func buildMainRequest() -> Pogoprotos.Networking.Envelopes.RequestEnvelope {
print("Generating main request...")
let requestBuilder = Pogoprotos.Networking.Envelopes.RequestEnvelope.Builder()
requestBuilder.statusCode = 2
requestBuilder.requestId = self.requestId
requestBuilder.unknown12 = 989
requestBuilder.latitude = self.api.Location.lat
requestBuilder.longitude = self.api.Location.long
if self.api.Location.alt != nil {
requestBuilder.altitude = self.api.Location.alt!
}
print("Generating subrequests...")
let signatureBuilder = Pogoprotos.Networking.Envelopes.Signature.Builder()
for subrequest in subrequests {
print("Processing \(subrequest)...")
let subrequestBuilder = Pogoprotos.Networking.Requests.Request.Builder()
subrequestBuilder.requestType = subrequest.id
subrequestBuilder.requestMessage = subrequest.message.data()
let subData = try! subrequestBuilder.build()
requestBuilder.requests += [subData]
if auth.authToken != nil {
let h64 = hashRequest(subData.data())
signatureBuilder.requestHash.append(h64)
}
}
if (auth.authToken == nil) {
let authInfoBuilder = requestBuilder.getAuthInfoBuilder()
let authInfoTokenBuilder = authInfoBuilder.getTokenBuilder()
authInfoBuilder.provider = auth.authType.description
authInfoTokenBuilder.contents = auth.accessToken!
authInfoTokenBuilder.unknown2 = 59
} else {
requestBuilder.authTicket = auth.authToken!
signatureBuilder.locationHash2 = hashLocation()
signatureBuilder.locationHash1 = hashAuthTicket()
signatureBuilder.unknown22 = self.encrypt.randomBytes()
signatureBuilder.timestamp = UInt64(NSDate().timeIntervalSince1970 * 1000.0)
signatureBuilder.timestampSinceStart = UInt64(NSDate().timeIntervalSince1970 * 1000.0) - timeSinceStart
let signature = try! signatureBuilder.build()
let unknown6 = requestBuilder.getUnknown6Builder()
let unknown2 = unknown6.getUnknown2Builder()
unknown6.requestType = 6
let sigData = self.encrypt.encrypt(signature.data().getUInt8Array())
unknown2.encryptedSignature = NSData(bytes: sigData, length: sigData.count)
}
self.requestId += 1
print("Building request...")
return try! requestBuilder.build()
}
private func parseMainResponse(data: NSData) -> PGoApiResponse {
print("Parsing main response...")
let response = try! Pogoprotos.Networking.Envelopes.ResponseEnvelope.parseFromData(data)
let subresponses = parseSubResponses(response)
if auth.authToken == nil {
if response.hasAuthTicket {
auth.authToken = response.authTicket
}
if response.hasApiUrl {
auth.endpoint = "https://\(response.apiUrl)/rpc"
print("New endpoint: \(auth.endpoint)")
}
}
return PGoApiResponse(response: response, subresponses: subresponses)
}
private func parseSubResponses(response: Pogoprotos.Networking.Envelopes.ResponseEnvelope) -> [GeneratedMessage] {
print("Parsing subresponses...")
var subresponses: [GeneratedMessage] = []
for (idx, subresponseData) in response.returns.enumerate() {
let subrequest = subrequests[idx]
subresponses.append(subrequest.parser(subresponseData))
}
return subresponses
}
}
|
gpl-3.0
|
d8190b2675ead302a1dff13c65fe2aa4
| 38.369668 | 132 | 0.61719 | 4.622705 | false | false | false | false |
quire-io/SwiftyChrono
|
Sources/Parsers/DE/DETimeExpressionParser.swift
|
1
|
8451
|
//
// DETimeExpressionParser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 2/9/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
private let FIRST_REG_PATTERN = "(^|\\s|T)" +
"(?:(?:am|um|zu)\\s*)?" +
"(\\d{1,4}|mittag|mitternacht)" +
"(?:" +
"(?:\\.|\\:|\\:)(\\d{1,2})" +
"(?:" +
"(?:\\:|\\:)(\\d{2})" +
")?" +
")?" +
"(?:\\s*Uhr)?" +
"(?:\\s*(?:(A\\.M\\.|P\\.M\\.|AM?|PM?)|uhr))?" +
"(?=\\W|$)"
private let SECOND_REG_PATTERN = "^\\s*" +
"(bis|\\-|\\–|\\~|\\〜|to|\\?)\\s*" +
"(\\d{1,4})" +
"(?:" +
"(?:\\.|\\:|\\:)(\\d{1,2})" +
"(?:" +
"(?:\\.|\\:|\\:)(\\d{1,2})" +
")?" +
"(?:\\s*Uhr)?" +
")?" +
"(?:\\s*(?:(A\\.M\\.|P\\.M\\.|AM?|PM?)|uhr))?" +
"(?=\\W|$)"
private let hourGroup = 2
private let minuteGroup = 3
private let secondGroup = 4
private let amPmHourGroup = 5
public class DETimeExpressionParser: Parser {
override var pattern: String { return FIRST_REG_PATTERN }
override var language: Language { return .german }
override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
// This pattern can be overlaped Ex. [12] AM, 1[2] AM
let idx = match.range(at: 0).location
let str = text.substring(from: idx - 1, to: idx)
if idx > 0 && NSRegularExpression.isMatch(forPattern: "\\w", in: str) {
return nil
}
var (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match)
var result = ParsedResult(ref: ref, index: index, text: matchText)
result.tags[.deTimeExpressionParser] = true
result.start.imply(.day, to: ref.day)
result.start.imply(.month, to: ref.month)
result.start.imply(.year, to: ref.year)
var hour = 0
var minute = 0
var meridiem = -1
// ----- Second
if match.isNotEmpty(atRangeIndex: secondGroup) {
if let second = Int(match.string(from: text, atRangeIndex: secondGroup)) {
if second >= 60 {
return nil
}
result.start.assign(.second, value: second)
}
}
// ----- Hours
let hourText = match.isNotEmpty(atRangeIndex: hourGroup) ? match.string(from: text, atRangeIndex: hourGroup).lowercased() : ""
if hourText == "mittag" {
meridiem = 1
hour = 12
} else if hourText == "mitternacht" {
meridiem = 0
hour = 0
} else {
hour = Int(hourText)!
}
// ----- Minutes
if match.isNotEmpty(atRangeIndex: minuteGroup) {
minute = Int(match.string(from: text, atRangeIndex: minuteGroup))!
} else if hour > 100 {
minute = hour % 100
hour = hour/100
}
if minute >= 60 || hour > 24 {
return nil
}
if hour >= 12 {
meridiem = 1
}
// ----- AM & PM
if match.isNotEmpty(atRangeIndex: amPmHourGroup) {
if hour > 12 {
return nil
}
let ampm = match.string(from: text, atRangeIndex: amPmHourGroup).substring(from: 0, to: 1).lowercased()
if ampm == "a" {
meridiem = 0
if hour == 12 {
hour = 0
}
}
if ampm == "p" {
meridiem = 1
if hour != 12 {
hour += 12
}
}
}
result.start.assign(.hour, value: hour)
result.start.assign(.minute, value: minute)
if meridiem >= 0 {
result.start.assign(.meridiem, value: meridiem)
} else {
result.start.imply(.meridiem, to: hour < 12 ? 0 : 1)
}
// ==============================================================
// Extracting the 'to' chunk
// ==============================================================
let regex = try? NSRegularExpression(pattern: SECOND_REG_PATTERN, options: .caseInsensitive)
let secondText = text.substring(from: result.index + result.text.count)
guard let match = regex?.firstMatch(in: secondText, range: NSRange(location: 0, length: secondText.count)) else {
// Not accept number only result
if NSRegularExpression.isMatch(forPattern: "^\\d+$", in: result.text) {
return nil
}
return result
}
matchText = match.string(from: secondText, atRangeIndex: 0)
// Pattern "YY.YY -XXXX" is more like timezone offset
if NSRegularExpression.isMatch(forPattern: "^\\s*(\\+|\\-)\\s*\\d{3,4}$", in: matchText) {
return result
}
if result.end == nil {
result.end = ParsedComponents(components: nil, ref: result.start.date)
}
hour = 0
minute = 0
meridiem = -1
// ----- Second
if match.isNotEmpty(atRangeIndex: secondGroup) {
let second = Int(match.string(from: secondText, atRangeIndex: secondGroup))!
if second >= 60 {
return nil
}
result.end?.assign(.second, value: second)
}
hour = Int(match.string(from: secondText, atRangeIndex: hourGroup))!
// ----- Minute
if match.isNotEmpty(atRangeIndex: minuteGroup) {
minute = Int(match.string(from: secondText, atRangeIndex: minuteGroup))!
if minute >= 60 {
return result
}
} else if hour > 100 {
minute = hour % 100
hour = hour / 100
}
if minute >= 60 || hour > 24 {
return nil
}
if hour >= 12 {
meridiem = 1
}
// ----- AM & PM
if match.isNotEmpty(atRangeIndex: amPmHourGroup) {
if hour > 12 {
return nil
}
let ampm = match.string(from: secondText, atRangeIndex: amPmHourGroup).substring(from: 0, to: 1).lowercased()
if ampm == "a" {
meridiem = 0
if hour == 12 {
hour = 0
if !result.end!.isCertain(component: .day) {
result.end!.imply(.day, to: result.end![.day]! + 1)
}
}
}
if ampm == "p" {
meridiem = 1
if hour != 12 {
hour += 12
}
}
if !result.start.isCertain(component: .meridiem) {
if meridiem == 0 {
result.start.imply(.meridiem, to: 0)
if result.start[.hour] == 12 {
result.start.assign(.hour, value: 0)
}
} else {
result.start.imply(.meridiem, to: 1)
if let hour = result.start[.hour], hour != 12 {
result.start.assign(.hour, value: hour + 12)
}
}
}
}
result.text = result.text + matchText
result.end!.assign(.hour, value: hour)
result.end!.assign(.minute, value: minute)
if meridiem >= 0 {
result.end!.assign(.meridiem, value: meridiem)
} else {
let startAtPm = result.start.isCertain(component: .meridiem) && result.start[.meridiem]! == 1
if startAtPm && result.start[.hour]! > hour {
// 10pm - 1 (am)
result.end!.imply(.meridiem, to: 0)
} else if hour > 12 {
result.end!.imply(.meridiem, to: 1)
}
}
if result.end!.date.timeIntervalSince1970 < result.start.date.timeIntervalSince1970 {
let to = result.end![.day]! + 1
result.end?.imply(.day, to: to)
}
return result
}
}
|
mit
|
46a2483b3dcac6da6e3c97f2cace79a1
| 31.579151 | 134 | 0.444655 | 4.210579 | false | false | false | false |
daodaoliang/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Auth/AuthPhoneViewController.swift
|
5
|
11626
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class AuthPhoneViewController: AuthViewController, UITextFieldDelegate {
// MARK: -
// MARK: Private vars
private var grayBackground: UIView!
private var titleLabel: UILabel!
private var countryButton: UIButton!
private var phoneBackgroundView: UIImageView!
private var countryCodeLabel: UILabel!
private var phoneTextField: ABPhoneField!
private var hintLabel: UILabel!
private var navigationBarSeparator: UIView!
// MARK: -
// MARK: Public vars
var currentIso: String = "" {
didSet {
phoneTextField.currentIso = currentIso
let countryCode: String = ABPhoneField.callingCodeByCountryCode()[currentIso] as! String
countryCodeLabel.text = "+\(countryCode)"
countryButton.setTitle(ABPhoneField.countryNameByCountryCode()[currentIso] as? String, forState: UIControlState.Normal)
}
}
// MARK: -
// MARK: Constructors
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.whiteColor()
grayBackground = UIView()
grayBackground.backgroundColor = UIColor.RGB(0xf2f2f2)
view.addSubview(grayBackground)
titleLabel = UILabel()
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.textColor = UIColor.blackColor()
titleLabel.font = isIPad
? UIFont(name: "HelveticaNeue-Thin", size: 50.0)
: UIFont(name: "HelveticaNeue-Light", size: 30.0)
titleLabel.text = NSLocalizedString("AuthPhoneTitle", comment: "Title")
grayBackground.addSubview(titleLabel)
let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton")
let countryImageHighlighted: UIImage! = UIImage(named: "ModernAuthCountryButtonHighlighted")
countryButton = UIButton()
countryButton.setBackgroundImage(countryImage.stretchableImageWithLeftCapWidth(Int(countryImage.size.width / 2), topCapHeight: 0), forState: UIControlState.Normal)
countryButton.setBackgroundImage(countryImageHighlighted.stretchableImageWithLeftCapWidth(Int(countryImageHighlighted.size.width / 2), topCapHeight: 0), forState: UIControlState.Highlighted)
countryButton.titleLabel?.font = UIFont.systemFontOfSize(20.0)
countryButton.titleLabel?.textAlignment = NSTextAlignment.Left
countryButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
countryButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
countryButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 14, bottom: 9, right: 14)
countryButton.addTarget(self, action: Selector("showCountriesList"), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(countryButton)
let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground")
phoneBackgroundView = UIImageView(image: phoneImage.stretchableImageWithLeftCapWidth(Int(phoneImage.size.width / 2), topCapHeight: 0))
view.addSubview(phoneBackgroundView)
countryCodeLabel = UILabel()
countryCodeLabel.font = UIFont.systemFontOfSize(20.0)
countryCodeLabel.backgroundColor = UIColor.clearColor()
countryCodeLabel.textAlignment = NSTextAlignment.Center
phoneBackgroundView.addSubview(countryCodeLabel)
phoneTextField = ABPhoneField()
phoneTextField.font = UIFont.systemFontOfSize(20.0)
phoneTextField.backgroundColor = UIColor.whiteColor()
phoneTextField.placeholder = NSLocalizedString("AuthPhoneNumberHint", comment: "Hint")
phoneTextField.keyboardType = UIKeyboardType.NumberPad;
phoneTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
phoneTextField.delegate = self
view.addSubview(phoneTextField)
navigationBarSeparator = UIView()
navigationBarSeparator.backgroundColor = UIColor.RGB(0xc8c7cc)
view.addSubview(navigationBarSeparator)
hintLabel = UILabel()
hintLabel.font = UIFont.systemFontOfSize(17.0)
hintLabel.textColor = UIColor.RGB(0x999999)
hintLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
hintLabel.backgroundColor = UIColor.whiteColor()
hintLabel.textAlignment = NSTextAlignment.Center
hintLabel.contentMode = UIViewContentMode.Center
hintLabel.numberOfLines = 0
hintLabel.text = NSLocalizedString("AuthPhoneHint", comment: "Hint")
view.addSubview(hintLabel)
var nextBarButton = UIBarButtonItem(title: NSLocalizedString("NavigationNext", comment: "Next Title"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("nextButtonPressed")) // TODO: Localize
navigationItem.rightBarButtonItem = nextBarButton
currentIso = phoneTextField.currentIso
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let screenSize = UIScreen.mainScreen().bounds.size
let isWidescreen = screenSize.width > 320 || screenSize.height > 480
let isPortraint = screenSize.width < screenSize.height
let bgSize = isIPad
? (isPortraint ? 304.0: 140)
: (isWidescreen ? 131.0 : 90.0)
grayBackground.frame = CGRect(x: 0.0, y: 0.0, width: screenSize.width, height: CGFloat(bgSize))
let padding = isIPad
? (isPortraint ? 48 : 20)
: (20)
titleLabel.sizeToFit()
titleLabel.frame = CGRect(x: (screenSize.width - titleLabel.frame.size.width) / 2.0, y: grayBackground.frame.height - titleLabel.frame.size.height - CGFloat(padding), width: titleLabel.frame.size.width, height: titleLabel.frame.size.height)
navigationBarSeparator.frame = CGRect(x: 0, y: grayBackground.bounds.size.height, width: screenSize.width, height: 0.5)
let fieldWidth : CGFloat = isIPad
? (520)
: (screenSize.width)
let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton")
countryButton.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: grayBackground.frame.origin.y + grayBackground.bounds.size.height, width: fieldWidth, height: countryImage.size.height)
let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground")
phoneBackgroundView.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: countryButton.frame.origin.y + 57, width: fieldWidth, height: phoneImage.size.height)
let countryCodeLabelTopSpacing: CGFloat = 3.0
countryCodeLabel.frame = CGRect(x: 14, y: countryCodeLabelTopSpacing, width: 68, height: phoneBackgroundView.frame.size.height - countryCodeLabelTopSpacing)
phoneTextField.frame = CGRect(x: (screenSize.width - fieldWidth) / 2 + 96.0, y: phoneBackgroundView.frame.origin.y + 1, width: fieldWidth - 96.0 - 10.0, height: phoneBackgroundView.frame.size.height - 2)
let hintPadding : CGFloat = isIPad
? (isPortraint ? 460.0: 274.0)
: (isWidescreen ? 274.0 : 214.0)
let hintLabelSize = hintLabel.sizeThatFits(CGSize(width: 278.0, height: CGFloat.max))
hintLabel.frame = CGRect(x: (screenSize.width - hintLabelSize.width) / 2.0, y: hintPadding, width: hintLabelSize.width, height: hintLabelSize.height);
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
phoneTextField.becomeFirstResponder()
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
Actor.trackAuthPhoneTypeWithValue(textField.text)
return true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MainAppTheme.navigation.applyAuthStatusBar()
Actor.trackAuthPhoneOpen()
}
// MARK: -
// MARK: Methods
func nextButtonPressed() {
let action = "Request code"
Actor.trackCodeRequest()
let numberLength = count(phoneTextField.phoneNumber) as Int
let numberRequiredLength: Int = (ABPhoneField.phoneMinLengthByCountryCode()[currentIso] as! String).toInt()!
if (numberLength < numberRequiredLength) {
var msg = NSLocalizedString("AuthPhoneTooShort", comment: "Too short error");
var alertView = UIAlertView(title: nil, message: msg, delegate: self, cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok"))
alertView.show()
Actor.trackActionError(action, withTag: "LOCAL_EMPTY_PHONE", withMessage: msg)
} else {
execute(Actor.requestStartPhoneAuthCommandWithEmail(jlong((phoneTextField.phoneNumber as NSString).longLongValue)),
successBlock: { (val) -> () in
Actor.trackActionSuccess(action)
self.navigateToSms()
},
failureBlock: { (val) -> () in
var message = "Unknown error"
var tag = "UNKNOWN"
var canTryAgain = false
if let exception = val as? ACRpcException {
tag = exception.getTag()
if (tag == "PHONE_NUMBER_INVALID") {
message = NSLocalizedString("ErrorPhoneIncorrect", comment: "PHONE_NUMBER_INVALID error")
} else {
message = exception.getLocalizedMessage()
}
canTryAgain = exception.isCanTryAgain()
} else if let exception = val as? JavaLangException {
message = exception.getLocalizedMessage()
canTryAgain = true
}
Actor.trackActionError(action, withTag: tag, withMessage: message)
var alertView = UIAlertView(title: nil, message: message, delegate: self, cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok"))
alertView.show()
})
}
}
// MARK: -
// MARK: Navigation
func showCountriesList() {
var countriesController = AuthCountriesViewController()
countriesController.delegate = self
countriesController.currentIso = currentIso
var navigationController = AANavigationController(rootViewController: countriesController)
presentViewController(navigationController, animated: true, completion: nil)
}
func navigateToSms() {
var smsController = AuthSmsViewController()
smsController.phoneNumber = "+\(phoneTextField.formattedPhoneNumber)"
navigateNext(smsController, removeCurrent: false)
}
}
// MARK: -
// MARK: AAAuthCountriesController Delegate
extension AuthPhoneViewController: AuthCountriesViewControllerDelegate {
func countriesController(countriesController: AuthCountriesViewController, didChangeCurrentIso currentIso: String) {
self.currentIso = currentIso
}
}
|
mit
|
8bda55e3ad3a813ff458c550e7d417d7
| 45.138889 | 248 | 0.654997 | 5.306253 | false | false | false | false |
burczyk/SwiftTeamSelect
|
SwiftTeamSelect/GameViewController.swift
|
1
|
1977
|
//
// GameViewController.swift
// SwiftTeamSelect
//
// Created by Kamil Burczyk on 16.06.2014.
// Copyright (c) 2014 Sigmapoint. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData(contentsOfFile: path!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData!)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size:CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height))
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
|
mit
|
7c768667b8590e6f1900a4d8b62bd478
| 29.415385 | 120 | 0.665149 | 5.343243 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/StudyNote/StudyNote/MVVM/Demo/SNDemoNavViewController.swift
|
1
|
2325
|
//
// SNDemoNavViewController.swift
// StudyNote
//
// Created by wuyp on 2019/12/16.
// Copyright © 2019 Raymond. All rights reserved.
//
import UIKit
class SNDemoNavViewController: SHBaseViewController {
@objc private lazy dynamic var table: UITableView = {
let v = UITableView(frame: self.view.bounds, style: .grouped)
v.estimatedRowHeight = 0
v.estimatedSectionHeaderHeight = 0
v.estimatedSectionFooterHeight = 0
v.rowHeight = 50
v.separatorStyle = .none
v.delegate = self
v.dataSource = self
v.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return v
}()
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
}
@objc override dynamic func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
// MARK: - Public Method
}
// MARK: - Config UI
extension SNDemoNavViewController {
}
// MARK: - Bind Data
extension SNDemoNavViewController {
}
// MARK: - User Actions
extension SNDemoNavViewController {
}
// MARK: - UITableViewDelegate & UITableViewDataSource
extension SNDemoNavViewController: UITableViewDelegate, UITableViewDataSource {
@objc dynamic func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "一个页面只有一个VM"
break
case 1:
cell.textLabel?.text = "一个页面多个VM"
break
case 2:
cell.textLabel?.text = "一个页面对应不同的VM"
break
case 3:
cell.textLabel?.text = "深层VM事件传递"
break
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
// MARK: - Private Method
extension SNDemoNavViewController {
}
|
apache-2.0
|
ce76287b817cdc83a86b683e3e2e232a
| 22.604167 | 103 | 0.6015 | 4.969298 | false | false | false | false |
mozilla-mobile/focus-ios
|
Blockzilla/Utilities/SearchHistoryUtils.swift
|
5
|
2490
|
/* 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
struct textSearched {
var text: String
var isCurrentSearch: Bool
init(text: String, isCurrentSearch: Bool) {
self.text = text
self.isCurrentSearch = isCurrentSearch
}
init?(dictionary: [String: Any]) {
guard let text = dictionary["text"], let isCurrentSearch = dictionary["isCurrentSearch"] else { return nil }
self.init(text: text as! String, isCurrentSearch: isCurrentSearch as! Bool)
}
}
class SearchHistoryUtils {
static var isFromURLBar = false
static var isNavigating = false
static var isReload = false
private static var currentStack = [textSearched]()
static func pushSearchToStack(with searchedText: String) {
// Check whether the lastSearch is the current search. If not, remove subsequent searches
if let lastSearch = currentStack.last, !lastSearch.isCurrentSearch {
for index in 0..<currentStack.count {
if currentStack[index].isCurrentSearch {
currentStack.removeSubrange(index+1..<currentStack.count)
break
}
}
}
for index in 0..<currentStack.count {
currentStack[index].isCurrentSearch = false
}
currentStack.append(textSearched(text: searchedText, isCurrentSearch: true))
}
static func pullSearchFromStack() -> String? {
for search in currentStack {
if search.isCurrentSearch {
return search.text
}
}
return nil
}
static func goForward() {
isNavigating = true
for index in 0..<currentStack.count {
if currentStack[index].isCurrentSearch && index + 1 < currentStack.count {
currentStack[index + 1].isCurrentSearch = true
currentStack[index].isCurrentSearch = false
break
}
}
}
static func goBack() {
isNavigating = true
for index in 0..<currentStack.count {
if currentStack[index].isCurrentSearch && index - 1 >= 0 {
currentStack[index - 1].isCurrentSearch = true
currentStack[index].isCurrentSearch = false
break
}
}
}
}
|
mpl-2.0
|
56b8ba67348080ccb0fabaae83f220f0
| 30.923077 | 116 | 0.603614 | 4.872798 | false | false | false | false |
villematti/my-hood
|
My Hood/PostCell.swift
|
1
|
944
|
//
// PostCell.swift
// My Hood
//
// Created by Ville-Matti Hakanpää on 07/01/16.
// Copyright © 2016 Ville-Matti Hakanpää. All rights reserved.
//
import UIKit
// Custom cell class for our prototype cell
class PostCell: UITableViewCell {
// Cell outlets
@IBOutlet weak var postImg: UIImageView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var descLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// Make cell image round
postImg.layer.cornerRadius = postImg.frame.size.width / 2
postImg.clipsToBounds = true
}
// Configure the cell data for display
func configureCell (post: Post) {
self.titleLbl.text = post.title
self.descLbl.text = post.postDesc
// Get image path from DataService
postImg.image = DataService.instance.imageForPath(post.imagePath)
}
}
|
mit
|
64f214fb6d41b2c11378b02c77bc418e
| 25.828571 | 73 | 0.654952 | 4.154867 | false | true | false | false |
irisapp/das-quadrat
|
Source/OSX/AuthorizationWindowController.swift
|
1
|
3900
|
//
// AuthorizationWindowController.swift
// Quadrat
//
// Created by Constantine Fry on 09/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Cocoa
import WebKit
private enum AuthorizationWindowControllerStatus {
case None // View controller has been initialized.
case Loading // Web view loading page.
case Loaded // Page has been loaded successfully.
case Failed(NSError) // Web view failed to load page with error.
}
class AuthorizationWindowController: NSWindowController {
var authorizationURL: NSURL!
var redirectURL: NSURL!
weak var delegate: AuthorizationDelegate?
private var status: AuthorizationWindowControllerStatus = .None {
didSet {
self.updateUI()
}
}
@IBOutlet weak var webView: WebView!
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var refreshButton: NSButton!
@IBOutlet weak var loadIndicator: NSProgressIndicator!
// MARK: -
deinit {
self.webView.mainFrame.stopLoading()
}
override func windowDidLoad() {
super.windowDidLoad()
self.loadAuthorizationURL()
}
func loadAuthorizationURL() {
self.status = .Loading
let request = NSURLRequest(URL: self.authorizationURL)
self.webView.mainFrame.loadRequest(request)
}
// MARK: - Actions
@IBAction func doneButtonClicked(sender: AnyObject) {
self.delegate?.userDidCancel()
}
@IBAction func refreshButtonClicked(sender: AnyObject) {
self.loadAuthorizationURL()
}
// MARK: - Delegate methods
func webView(webView: WebView!, dragSourceActionMaskForPoint point: NSPoint) -> Int {
return Int(WebDragSourceAction.None.rawValue)
}
func webView(webView: WebView!,
dragDestinationActionMaskForDraggingInfo draggingInfo: NSDraggingInfo!) -> Int {
return Int(WebDragDestinationAction.None.rawValue)
}
func webView(webView: WebView!,
decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!,
request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
if let URLString = request.URL?.absoluteString {
if URLString.hasPrefix(self.redirectURL.absoluteString) {
self.delegate?.didReachRedirectURL(request.URL!)
listener.ignore()
}
}
listener.use()
}
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) {
self.status = .Loaded
}
func webView(sender: WebView!, didFailLoadWithError error: NSError!, forFrame frame: WebFrame!) {
self.status = .Failed(error)
}
func webView(sender: WebView!,
didFailProvisionalLoadWithError error: NSError!, forFrame frame: WebFrame!) {
self.status = .Failed(error)
}
// MARK: -
/** Updates UI to current status. */
func updateUI() {
switch self.status {
case .Loading:
self.loadIndicator.startAnimation(self)
self.statusLabel.stringValue = ""
self.refreshButton.hidden = true
case .Loaded:
self.loadIndicator.stopAnimation(self)
self.statusLabel.stringValue = ""
self.refreshButton.hidden = true
case .Failed(let error):
self.loadIndicator.stopAnimation(self)
self.statusLabel.stringValue = error.localizedDescription
self.refreshButton.hidden = false
case .None:
self.loadIndicator.stopAnimation(self)
self.statusLabel.stringValue = ""
self.refreshButton.hidden = true
}
}
}
|
bsd-2-clause
|
1015fd5843f1c13aacb88243875e0bf1
| 30.2 | 106 | 0.622564 | 5.18617 | false | false | false | false |
OliverCulleyDeLange/WeClimbRocks-IOS
|
wcr/AppDelegate.swift
|
1
|
6135
|
//
// AppDelegate.swift
// wcr
//
// Created by Oliver Culley De Lange on 08/09/2015.
// Copyright (c) 2015 Oliver Culley De Lange. 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 "uk.co.oliverdelange.wcr" 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("wcr", 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("wcr.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()
}
}
}
}
|
mit
|
f2cdf5da59eb92692e3ff5d6e5747941
| 54.27027 | 290 | 0.715077 | 5.68582 | false | false | false | false |
ccrama/Slide-iOS
|
Slide for Reddit/PostContentPresentationController.swift
|
1
|
3397
|
//
// PostContentPresentationController.swift
// Slide for Reddit
//
// Created by Jonathan Cole on 8/3/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import AVFoundation
import UIKit
class PostContentPresentationController: UIPresentationController {
private var sourceImageView: UIView
init(presentedViewController: UIViewController,
presenting presentingViewController: UIViewController?,
sourceImageView: UIView) {
self.sourceImageView = sourceImageView
super.init(presentedViewController: presentedViewController,
presenting: presentingViewController)
}
override func containerViewWillLayoutSubviews() {
presentedView?.frame = frameOfPresentedViewInContainerView
}
// func transformFromRect(from source: CGRect, toRect destination: CGRect) -> CGAffineTransform {
// return CGAffineTransform.identity
// .translatedBy(x: destination.midX - source.midX, y: destination.midY - source.midY)
// .scaledBy(x: destination.width / source.width, y: destination.height / source.height)
// }
// override func presentationTransitionWillBegin() {
// guard let coordinator = presentedViewController.transitionCoordinator else {
// return
// }
//
// if let vc = self.presentedViewController as? ModalMediaViewController {
//
// let image = (sourceImageView as! UIImageView).image!
// let fromRect = vc.view.convert(sourceImageView.bounds, from: sourceImageView)
//
// if let embeddedVC = vc.embeddedVC as? ImageMediaViewController {
//
// presentingViewController.view.layoutIfNeeded()
//
// let inner = AVMakeRect(aspectRatio: embeddedVC.imageView.bounds.size, insideRect: embeddedVC.view.bounds)
// let toRect = vc.view.convert(inner, from: embeddedVC.scrollView)
//
// let newTransform = transformFromRect(from: toRect, toRect: fromRect)
//
// embeddedVC.scrollView.transform = embeddedVC.scrollView.transform.concatenating(newTransform)
// let storedZ = embeddedVC.scrollView.layer.zPosition
// embeddedVC.scrollView.layer.zPosition = sourceImageView.layer.zPosition
// coordinator.animate(alongsideTransition: { _ in
// embeddedVC.scrollView.transform = CGAffineTransform.identity
// embeddedVC.scrollView.layer.zPosition = storedZ
// })
//
// } else if let embeddedVC = vc.embeddedVC as? VideoMediaViewController {
//
// if embeddedVC.isYoutubeView {
//
// } else {
// presentingViewController.view.layoutIfNeeded()
//
// let inner = AVMakeRect(aspectRatio: image.size, insideRect: embeddedVC.view.bounds)
// let toRect = vc.view.convert(inner, from: embeddedVC.view)
//
// let newTransform = transformFromRect(from: toRect, toRect: fromRect)
//
// embeddedVC.videoView.transform = embeddedVC.videoView.transform.concatenating(newTransform)
// coordinator.animate(alongsideTransition: { _ in
// embeddedVC.videoView.transform = CGAffineTransform.identity
// })
// }
// }
// }
// }
}
|
apache-2.0
|
a6cf457586b319b05a330fdc0c13b99c
| 39.915663 | 123 | 0.641048 | 5.192661 | false | false | false | false |
tardieu/swift
|
stdlib/public/core/LazySequence.swift
|
10
|
7786
|
//===--- LazySequence.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 on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Lazy sequences can be used to avoid needless storage allocation
/// and computation, because they use an underlying sequence for
/// storage and compute their elements on demand. For example,
///
/// [1, 2, 3].lazy.map { $0 * 2 }
///
/// is a sequence containing { `2`, `4`, `6` }. Each time an element
/// of the lazy sequence is accessed, an element of the underlying
/// array is accessed and transformed by the closure.
///
/// Sequence operations taking closure arguments, such as `map` and
/// `filter`, are normally eager: they use the closure immediately and
/// return a new array. Using the `lazy` property gives the standard
/// library explicit permission to store the closure and the sequence
/// in the result, and defer computation until it is needed.
///
/// To add new lazy sequence operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazySequenceProtocol`s. For example, given an eager `scan`
/// method defined as follows
///
/// extension Sequence {
/// /// Returns an array containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(n)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Iterator.Element) -> ResultElement
/// ) -> [ResultElement] {
/// var result = [initial]
/// for x in self {
/// result.append(nextPartialResult(result.last!, x))
/// }
/// return result
/// }
/// }
///
/// we can build a sequence that lazily computes the elements in the
/// result of `scan`:
///
/// struct LazyScanIterator<Base : IteratorProtocol, ResultElement>
/// : IteratorProtocol {
/// mutating func next() -> ResultElement? {
/// return nextElement.map { result in
/// nextElement = base.next().map { nextPartialResult(result, $0) }
/// return result
/// }
/// }
/// private var nextElement: ResultElement? // The next result of next().
/// private var base: Base // The underlying iterator.
/// private let nextPartialResult: (ResultElement, Base.Element) -> ResultElement
/// }
///
/// struct LazyScanSequence<Base: Sequence, ResultElement>
/// : LazySequenceProtocol // Chained operations on self are lazy, too
/// {
/// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> {
/// return LazyScanIterator(
/// nextElement: initial, base: base.makeIterator(), nextPartialResult)
/// }
/// private let initial: ResultElement
/// private let base: Base
/// private let nextPartialResult:
/// (ResultElement, Base.Iterator.Element) -> ResultElement
/// }
///
/// and finally, we can give all lazy sequences a lazy `scan` method:
///
/// extension LazySequenceProtocol {
/// /// Returns a sequence containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(1)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Iterator.Element) -> ResultElement
/// ) -> LazyScanSequence<Self, ResultElement> {
/// return LazyScanSequence(
/// initial: initial, base: self, nextPartialResult)
/// }
/// }
///
/// - See also: `LazySequence`, `LazyCollectionProtocol`, `LazyCollection`
///
/// - Note: The explicit permission to implement further operations
/// lazily applies only in contexts where the sequence is statically
/// known to conform to `LazySequenceProtocol`. Thus, side-effects such
/// as the accumulation of `result` below are never unexpectedly
/// dropped or deferred:
///
/// extension Sequence where Iterator.Element == Int {
/// func sum() -> Int {
/// var result = 0
/// _ = self.map { result += $0 }
/// return result
/// }
/// }
///
/// [We don't recommend that you use `map` this way, because it
/// creates and discards an array. `sum` would be better implemented
/// using `reduce`].
public protocol LazySequenceProtocol : Sequence {
/// A `Sequence` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements : Sequence = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing an extra
/// `LazySequence` layer. For example,
///
/// _prext_ example needed
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements { get }
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazySequenceProtocol where Elements == Self {
/// Identical to `self`.
public var elements: Self { return self }
}
/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`
public struct LazySequence<Base : Sequence>
: LazySequenceProtocol, _SequenceWrapper {
/// Creates a sequence that has the same elements as `base`, but on
/// which some operations such as `map` and `filter` are implemented
/// lazily.
internal init(_base: Base) {
self._base = _base
}
public var _base: Base
/// The `Base` (presumably non-lazy) sequence from which `self` was created.
public var elements: Base { return _base }
}
extension Sequence {
/// A sequence containing the same elements as this sequence,
/// but on which some operations, such as `map` and `filter`, are
/// implemented lazily.
///
/// - SeeAlso: `LazySequenceProtocol`, `LazySequence`
public var lazy: LazySequence<Self> {
return LazySequence(_base: self)
}
}
/// Avoid creating multiple layers of `LazySequence` wrapper.
/// Anything conforming to `LazySequenceProtocol` is already lazy.
extension LazySequenceProtocol {
/// Identical to `self`.
public var lazy: Self {
return self
}
}
@available(*, unavailable, renamed: "LazySequenceProtocol")
public typealias LazySequenceType = LazySequenceProtocol
extension LazySequenceProtocol {
@available(*, unavailable, message: "Please use Array initializer instead.")
public var array: [Iterator.Element] {
Builtin.unreachable()
}
}
|
apache-2.0
|
3d076ffdd14e009dcdfc02613d9c5509
| 36.432692 | 87 | 0.624968 | 4.359462 | false | false | false | false |
Solar1011/-
|
我的微博/我的微博/Classes/Model/Status.swift
|
1
|
5563
|
//
// Status.swift
// 我的微博
//
// Created by teacher on 15/8/1.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
import SDWebImage
/// 微博模型
class Status: NSObject {
/// 微博创建时间
var created_at: String?
/// 微博ID
var id: Int = 0
/// 微博信息内容
var text: String?
/// 微博来源
var source: String?
/// 配图数组
var pic_urls: [[String: AnyObject]]? {
didSet {
// 判断数组中是否有数据 nil
if pic_urls!.count == 0 {
return
}
// 实例化数组
storedPictureURLs = [NSURL]()
// 遍历字典生成 url 的数组
for dict in pic_urls! {
if let urlString = dict["thumbnail_pic"] as? String {
storedPictureURLs?.append(NSURL(string: urlString)!)
}
}
}
}
/// `保存`配图的 URL 的数组
private var storedPictureURLs: [NSURL]?
/// 配图的URL的`计算型`数组
/// 如果是原创微博,返回 storedPictureURLs
/// 如果是转发微博,返回 retweeted_status.storedPictureURLs
var pictureURLs: [NSURL]? {
return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
}
/// 用户
var user: User?
/// 转发微博
var retweeted_status: Status?
/// 显示微博所需的行高
var rowHeight: CGFloat?
/// 加载微博数据 - 返回`微博`数据的数组
class func loadStatus(since_id: Int, max_id: Int, finished: (dataList: [Status]?, error: NSError?) -> ()) {
NetworkTools.sharedTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
if error != nil {
finished(dataList: nil, error: error)
return
}
/// 判断能否获得字典数组
if let array = result?["statuses"] as? [[String: AnyObject]] {
// 遍历数组,字典转模型
var list = [Status]()
for dict in array {
list.append(Status(dict: dict))
}
// 缓存图片 self. 是本类只有一个
// 图片缓存结束之后,再进行回调
self.cacheWebImage(list, finished: finished)
} else {
finished(dataList: nil, error: nil)
}
}
}
/// 缓存微博的网络图片,缓存结束之后,才刷新数据
private class func cacheWebImage(list: [Status], finished: (dataList: [Status]?, error: NSError?) -> ()) {
// 创建调度组
let group = dispatch_group_create()
// 缓存图片的大小
var dataLength = 0
// 循环遍历数组
for status in list {
// 判断是否有图片
guard let urls = status.pictureURLs else {
// urls 为空
continue
}
// 遍历 urls 的数组,SDWebImage 缓存图片
for imageUrl in urls {
// 入组
dispatch_group_enter(group)
SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) in
// 将图像转换成二进制数据
let data = UIImagePNGRepresentation(image)!
dataLength += data.length
dispatch_group_leave(group)
})
}
}
// 监听所有缓存操作的通知
dispatch_group_notify(group, dispatch_get_main_queue()) {
// 因为新浪微博的服务器返回的图片都是缩略图,很小,不会占用用户太多时间,对用户体验影响不大!
print("缓存图片大小 \(dataLength / 1024) K")
// 获得完整的微博数组,可以回调
finished(dataList: list, error: nil)
}
}
// MARK: - 构造函数
init(dict: [String: AnyObject]) {
super.init()
// 会调用 setValue forKey 给每一个属性赋值
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forKey key: String) {
// 判断 key 是否是 user,如果是 user 单独处理
if key == "user" {
// 判断 value 是否是一个有效的字典
if let dict = value as? [String: AnyObject] {
// 创建用户数据
user = User(dict: dict)
}
return
}
// 判断 key 是否是 retweeted_status 是否为空
// 转发微博最多只会执行一次
if key == "retweeted_status" {
if let dict = value as? [String: AnyObject] {
retweeted_status = Status(dict: dict)
}
return
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let keys = ["created_at", "id", "text", "source", "pic_urls"]
return "\(dictionaryWithValuesForKeys(keys))"
}
}
|
mit
|
0f9a07184e38b1bfaaa6e15072d3cdf9
| 27.559524 | 172 | 0.481867 | 4.526415 | false | false | false | false |
normand1/SpriteKit-InventorySystem
|
InventoryTestApp/InventoryItemNode.swift
|
1
|
3256
|
//
// TouchableShapeNode.swift
// Inventory
//
// Created by David Norman on 8/16/15.
// Copyright (c) 2015 David Norman. All rights reserved.
//
import SpriteKit
protocol InventoryItemNodeProtocol {
func InventoryNodeTouched(item:InventoryItem?)
func resetAllNodesToDefault()
}
var INV_COLOR_SELECTED = UIColor.blueColor()
var INV_COLOR_DESELECTED = UIColor.blackColor()
class InventoryItemNode: SKShapeNode {
var delegate : InventoryItemNodeProtocol?
var itemName : InventoryItemName?
var selected = false
var imageNode : SKSpriteNode?
var backgroundImage: SKSpriteNode?
var number = 0
var item : InventoryItem?
override init() {
super.init()
self.userInteractionEnabled = true
}
func updateWithItem(item: InventoryItem?) {
self.removeAllChildren()
if let realItem = item {
self.item = item
self.itemName = InventoryItemName(rawValue: realItem.imageName!)
imageNode = SKSpriteNode(imageNamed: realItem.imageName!)
imageNode?.size = CGSizeMake(35, 35)
self.addChild(imageNode!)
let countLabel = SKLabelNode(text: realItem.numberInStack == 0 ? "" : String(realItem.numberInStack))
countLabel.fontSize = 20
countLabel.position = CGPointMake(-15, 5)
countLabel.fontColor = UIColor.whiteColor()
countLabel.fontName = "AmericanTypewriter-Bold"
countLabel.zPosition = 10
self.addChild(countLabel)
updateWithBackgroundImageNode()
} else {
self.imageNode = SKSpriteNode(imageNamed: "")
updateWithBackgroundImageNode()
}
}
func addImageOnly(item: InventoryItem?) {
if let realItem = item {
self.itemName = InventoryItemName(rawValue: realItem.imageName!)
imageNode = SKSpriteNode(imageNamed: realItem.imageName!)
self.addChild(imageNode!)
imageNode!.size = CGSizeMake(35, 35)
}
}
func updateWithBackgroundImageNode() {
if self.backgroundImage != nil {
self.addChild(backgroundImage!)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
delegate?.resetAllNodesToDefault()
self.selectItem()
delegate?.InventoryNodeTouched(self.item)
}
func selectItem() {
self.fillColor = INV_COLOR_SELECTED
self.selected = true
print("selected: \(self.itemName)")
}
func deselect() {
self.fillColor = INV_COLOR_DESELECTED
self.selected = false
}
override func copyWithZone(zone: NSZone) -> AnyObject {
let invItemNodeCopy = InventoryItemNode()
invItemNodeCopy.delegate = delegate
invItemNodeCopy.itemName = itemName
invItemNodeCopy.selected = selected
invItemNodeCopy.imageNode = imageNode
invItemNodeCopy.backgroundImage = backgroundImage
invItemNodeCopy.number = number
invItemNodeCopy.item = item
return invItemNodeCopy
}
}
|
mit
|
82ef5a34b716ffa3cafaddf215769d2d
| 28.87156 | 113 | 0.632985 | 4.92587 | false | false | false | false |
iZhang/travel-architect
|
main/Utilities/Utilities.swift
|
1
|
1438
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Utility functions and type extensions used throughout the projects.
*/
import Foundation
import ARKit
// MARK: - float4x4 extensions
extension float4x4 {
/**
Treats matrix as a (right-hand column-major convention) transform matrix
and factors out the translation component of the transform.
*/
var translation: float3 {
get {
let translation = columns.3
return float3(translation.x, translation.y, translation.z)
}
set(newValue) {
columns.3 = float4(newValue.x, newValue.y, newValue.z, columns.3.w)
}
}
/**
Factors out the orientation component of the transform.
*/
var orientation: simd_quatf {
return simd_quaternion(self)
}
/**
Creates a transform matrix with a uniform scale factor in all directions.
*/
init(uniformScale scale: Float) {
self = matrix_identity_float4x4
columns.0.x = scale
columns.1.y = scale
columns.2.z = scale
}
}
// MARK: - CGPoint extensions
extension CGPoint {
/// Extracts the screen space point from a vector returned by SCNView.projectPoint(_:).
init(_ vector: SCNVector3) {
self.init(x: CGFloat(vector.x), y: CGFloat(vector.y))
}
/// Returns the length of a point when considered as a vector. (Used with gesture recognizers.)
var length: CGFloat {
return sqrt(x * x + y * y)
}
}
|
mit
|
42134c014f282bfc36687e36a501aa2d
| 23.758621 | 99 | 0.668524 | 3.769029 | false | false | false | false |
ioscreator/ioscreator
|
SwiftUIObservableObjectTutorial/SwiftUIObservableObjectTutorial/Stopwatch.swift
|
1
|
616
|
//
// Stopwatch.swift
// SwiftUIObservableObjectTutorial
//
// Created by Arthur Knopper on 09/09/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
class Stopwatch: ObservableObject {
@Published var counter: Int = 0
var timer = Timer()
func start() {
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
self.counter += 1
}
}
func stop() {
timer.invalidate()
}
func reset() {
counter = 0
timer.invalidate()
}
}
|
mit
|
4fdb324bb5576e95b237b199375e8e33
| 18.21875 | 90 | 0.598374 | 4.241379 | false | false | false | false |
StachkaConf/ios-app
|
StachkaIOS/Pods/RectangleDissolve/RectangleDissolve/Classes/RandomArrayIndicesSequence.swift
|
2
|
1674
|
//
// RandomArrayIndicesSequence.swift
// GithubItunesViewer
//
// Created by MIKHAIL RAKHMANOV on 12.02.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import Foundation
class BatchRandomArrayIndicesIterator: IteratorProtocol {
let indicesIterator: RandomArrayIndicesIterator
let batchSize: Int
init(max: Int, batchSize: Int) {
indicesIterator = RandomArrayIndicesIterator(max: max)
self.batchSize = batchSize
}
func next() -> [Int]? {
var batch: [Int] = []
while batch.count < batchSize, let element = indicesIterator.next() {
batch.append(element)
}
return batch.count != 0 ? batch : nil
}
}
class RandomArrayIndicesIterator: IteratorProtocol {
var array: [Int] = []
var currentMax: Int = 0
init(max: Int) {
array = (1 ... max).enumerated().map { offset, element in
return offset
}
currentMax = array.count - 1
}
func next() -> Int? {
guard currentMax >= 0 else {
return nil
}
let randomElementIndex = Int(arc4random_uniform(UInt32(currentMax)))
let randomElement = array[randomElementIndex]
if randomElementIndex != currentMax {
swap(&array[randomElementIndex], &array[currentMax])
}
currentMax -= 1
return randomElement
}
}
class RandomArrayIndicesSequence: Sequence {
typealias Iterator = RandomArrayIndicesIterator
let max: Int
init(max: Int) {
self.max = max
}
func makeIterator() -> RandomArrayIndicesIterator {
return RandomArrayIndicesIterator(max: max)
}
}
|
mit
|
f4e193b1bd80904751a046f92e884702
| 22.9 | 77 | 0.622833 | 4.311856 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/SwiftyDemo/New Group/MGRequestModel.swift
|
1
|
21011
|
//
// MGRequestModel.swift
// SwiftyDemo
//
// Created by newunion on 2019/4/12.
// Copyright © 2019 firestonetmt. All rights reserved.
//
import Foundation
import UIKit
//import HandyJSON
//import SwiftyJSON
import SwiftyJSON
struct MGSong:Codable {
let content: [Song]?
let error_code:String?
enum CodingKeys: String, CodingKey {
case error_code
case content
}
}
struct Song:Codable {
let type: Int?
let count: Int?
let name:String?
let comment:String?
let web_url:String?
let pic_s192:String?
let pic_s444:String?
let pic_s260:String?
let pic_s210:String?
let color:String?
let bg_color:String?
let bg_pic:String?
let content:[Content] = [Content]()
enum CodingKeys: String, CodingKey {
case type
case count
case name
case comment
case web_url
case pic_s192
case pic_s444
case pic_s260
case pic_s210
case color
case bg_color
case bg_pic
case content
}
}
struct Content:Codable {
let title:String?
let author:String?
let song_id:String?
let album_id:String?
let album_title:String?
let rank_change:String?
let all_rate:String?
let biaoshi:String?
let pic_big:String?
let pic_small:String?
enum CodingKeys: String, CodingKey {
case title
case author
case song_id
case album_id
case album_title
case rank_change
case all_rate
case biaoshi
case pic_big
case pic_small
}
}
class LYMSong:NSObject,MGModelProtocol {
var content: [LSong]? = nil
var error_code:Int? = 0
required override init() {
super.init()
}
/**
* Instantiate the instance using the passed json values to set the properties values
*/
required convenience init(_ json: JSON!) {
self.init()
if json.isEmpty{
return
}
error_code = json["error_code"].intValue
content = [LSong]()
let contentArray = json["content"].arrayValue
for contentJson in contentArray{
let value = LSong(contentJson)
content!.append(value)
}
}
}
class LSong:NSObject,MGModelProtocol {
var type: Int? = nil
var count: Int? = nil
var name:String? = nil
var comment:String? = nil
var web_url:String? = nil
var pic_s192:String? = nil
var pic_s210:String? = nil
var pic_s260:String? = nil
var pic_s328:String? = nil
var pic_s444:String? = nil
var pic_s640:String? = nil
var color:String? = nil
var bg_color:String? = nil
var bg_pic:String? = nil
var content:[LYMContent]? = nil
required override init() {
super.init()
}
/**
* Instantiate the instance using the passed json values to set the properties values
*/
required convenience init(_ json: JSON!) {
self.init()
if json.isEmpty{
return
}
color = json["color"].stringValue
comment = json["comment"].stringValue
count = json["count"].intValue
name = json["name"].stringValue
pic_s192 = json["pic_s192"].stringValue
pic_s210 = json["pic_s210"].stringValue
pic_s260 = json["pic_s260"].stringValue
pic_s328 = json["pic_s328"].stringValue
pic_s444 = json["pic_s444"].stringValue
pic_s640 = json["pic_s640"].stringValue
type = json["type"].intValue
bg_color = json["bg_color"].stringValue
bg_pic = json["bg_pic"].stringValue
web_url = json["web_url"].stringValue
content = [LYMContent]()
let contentArray = json["content"].arrayValue
for contentJson in contentArray{
let value = LYMContent(contentJson)
content!.append(value)
}
}
}
class LYMContent:NSObject,MGModelProtocol {
var title:String? = nil
var author:String? = nil
var song_id:String? = nil
var album_id:String? = nil
var album_title:String? = nil
var rank_change:String? = nil
var all_rate:String? = nil
var biaoshi:String? = nil
var pic_big:String? = nil
var pic_small:String? = nil
required override init() {
super.init()
}
required convenience init(_ json: JSON!) {
self.init()
if json.isEmpty{
return
}
album_id = json["album_id"].stringValue
album_title = json["album_title"].stringValue
all_rate = json["all_rate"].stringValue
author = json["author"].stringValue
biaoshi = json["biaoshi"].stringValue
pic_big = json["pic_big"].stringValue
pic_small = json["pic_small"].stringValue
rank_change = json["rank_change"].stringValue
song_id = json["song_id"].stringValue
title = json["title"].stringValue
}
}
let json22222 =
"""
{
"content": [
{
"name": "热歌榜",
"type": 2,
"count": 4,
"comment": "该榜单是根据千千音乐平台歌曲每周播放量自动生成的数据榜单,统计范围为千千音乐平台上的全部歌曲,每日更新一次",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_1452f36a8dc430ccdb8f6e57be6df2ee.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/c83d70cf3bc79f3d98ca8e36b8a1cd11728b2988.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/838ba61ea8d3fd1f1326c83c324e251f95ca5f8c.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_734232335ef76f5a05179797875817f3.jpg",
"content": [
{
"title": "卡路里(电影《西虹市首富》插曲)",
"author": "火箭少女101",
"song_id": "601427388",
"album_id": "601427384",
"album_title": "卡路里(电影《西虹市首富》插曲)",
"rank_change": "0",
"all_rate": "96,224,128,320,flac",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/8d356491f24692ff802cc49c80f51fee/612356223/612356223.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/8d356491f24692ff802cc49c80f51fee/612356223/612356223.jpg@s_2,w_150,h_150"
}
],
"color": "0xDC5900",
"bg_color": "0xFBEFE6",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4e9aa7496_218.png"
},
{
"name": "新歌榜",
"type": 1,
"count": 4,
"comment": "该榜单是根据千千音乐平台歌曲每日播放量自动生成的数据榜单,统计范围为近期发行的歌曲,每日更新一次",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_9a4fbbbfa50203aaa9e69bf189c6a45b.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/78310a55b319ebc4845c84eb8026cffc1e17169f.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/e850352ac65c1038cb0f3cb0b0119313b07e894b.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_dea655f4be544132fb0b5899f063d82e.jpg",
"content": [
{
"title": "为悦己者容(弦乐版)(电视剧《面具背后》片尾曲)",
"author": "崔子格",
"song_id": "613440970",
"album_id": "613440967",
"album_title": "为悦己者容(弦乐版)(电视剧《面具背后》片尾曲)",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "first,lossless,vip,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/fe8308782dbb1c4daadd3e5716763ecf/613451063/613451063.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/fe8308782dbb1c4daadd3e5716763ecf/613451063/613451063.jpg@s_2,w_150,h_150"
},
{
"title": "少女年华(电影《过春天》粤语版青春共鸣曲)",
"author": "刘惜君",
"song_id": "613237527",
"album_id": "613237525",
"album_title": "少女年华",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "first,lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/f46eabeb389515a87f9dfbef46bfbe9c/613243638/613243638.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/f46eabeb389515a87f9dfbef46bfbe9c/613243638/613243638.jpg@s_2,w_150,h_150"
}
],
"color": "0x5B9400",
"bg_color": "0xEFF5E6",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5c3d586d234b4_292.png"
},
{
"name": "网络歌曲榜",
"type": 25,
"count": 4,
"comment": "实时展现千千音乐最热门网络歌曲排行",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_6b67628d46638bccdc6bd8c9854b759b.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/738b4710b912c8fca95d9ecbfe039245d688210d.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/6c224f4a20a44623d567cd649a22720e0cf3d703.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_e58a5196bcd49d77d4a099b60b0bc03b.jpg",
"content": [
{
"title": "为悦己者容(弦乐版)(电视剧《面具背后》片尾曲)",
"author": "崔子格",
"song_id": "613440970",
"album_id": "613440967",
"album_title": "为悦己者容(弦乐版)(电视剧《面具背后》片尾曲)",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "first,lossless,vip,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/fe8308782dbb1c4daadd3e5716763ecf/613451063/613451063.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/fe8308782dbb1c4daadd3e5716763ecf/613451063/613451063.jpg@s_2,w_150,h_150"
},
{
"title": "至少还有你爱我",
"author": "龙梅子,王娜",
"song_id": "602980311",
"album_id": "602980305",
"album_title": "至少还有你爱我",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/015c6c99e1ced5261f624ef20cd7912f/609142152/609142152.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/015c6c99e1ced5261f624ef20cd7912f/609142152/609142152.jpg@s_2,w_150,h_150"
},
{
"title": "缘为冰",
"author": "龙梅子",
"song_id": "611717057",
"album_id": "611717054",
"album_title": "缘为冰",
"rank_change": "0",
"all_rate": "96,224,128,320,flac",
"biaoshi": "lossless,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/3e6581f50cac570485718a4d7473fc13/611718813/611718813.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/3e6581f50cac570485718a4d7473fc13/611718813/611718813.jpg@s_2,w_150,h_150"
}
],
"color": "0x21BFA6",
"bg_color": "0xE9F9F6",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4eacbcea8_225.png"
},
{
"name": "原创音乐榜",
"type": 200,
"count": 3,
"comment": "",
"web_url": "",
"pic_s192": "http://y.baidu.com/cms/app/192-192.jpg",
"pic_s444": "http://business0.qianqian.com/qianqian/file/5b1616af74b79_903.jpg",
"pic_s260": "http://business0.qianqian.com/qianqian/file/5b1616af74b79_903.jpg",
"pic_s210": "http://business0.qianqian.com/qianqian/file/5b1616af74b79_903.jpg",
"pic_s328": "http://business0.qianqian.com/qianqian/file/5b1616c9bc63d_740.jpg",
"pic_s640": "http://business0.qianqian.com/qianqian/file/5b1616be0e3f9_347.jpg",
"content": [
{
"title": "半生无求--卿本佳人小说原创同人作品",
"author": "琴酒蜀黍",
"song_id": "74189487",
"album_id": "611659437",
"album_title": "半生无求--卿本佳人小说原创同人作品",
"rank_change": "0",
"all_rate": "96,128,224,320",
"biaoshi": "perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/e6b03749d2e19c357e13b4d5910b2a42/523150905/523150905.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/e6b03749d2e19c357e13b4d5910b2a42/523150905/523150905.jpg@s_2,w_150,h_150"
},
{
"title": "三体Opening Theme",
"author": "野萨满王利夫",
"song_id": "73830133",
"album_id": "611638041",
"album_title": "三体Opening Theme",
"rank_change": "0",
"all_rate": "96,128",
"biaoshi": "perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/default_album.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/default_album.jpg@s_2,w_150,h_150"
},
{
"title": "小提琴与钢琴--摇篮曲",
"author": "老友潸然",
"song_id": "74112702",
"album_id": "611639593",
"album_title": "小提琴与钢琴--摇篮曲",
"rank_change": "0",
"all_rate": "96,128,224,320",
"biaoshi": "perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/dc331745d6bf112e1f6a0a885de2b2f3/560292722/560292722.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/dc331745d6bf112e1f6a0a885de2b2f3/560292722/560292722.jpg@s_2,w_150,h_150"
}
],
"color": "0x7B6CBE",
"bg_color": "0xF2F1F9",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4ee203ee4_783.png"
},
{
"name": "影视金曲榜",
"type": 24,
"count": 4,
"comment": "实时展现千千音乐最热门影视歌曲排行",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_2347fb14878de20a3b972a8f44a5c3a8.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/f703738da97739121a5aed67fa198618367ae2bc.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/9f2f070828381f3052bae5afab014c086e06f011.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_4de71fefad5f1fdb0a90b3c51b5a6f97.jpg",
"content": [
{
"title": "大王叫我来巡山",
"author": "贾乃亮,贾云馨",
"song_id": "257535276",
"album_id": "260368616",
"album_title": "万万没想到 电影原声带",
"rank_change": "0",
"all_rate": "flac,320,128,224,96",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/260368391/260368391.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/260368391/260368391.jpg@s_2,w_150,h_150"
},
{
"title": "无敌",
"author": "邓超",
"song_id": "261498824",
"album_id": "261498722",
"album_title": "无敌",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/261498695/261498695.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/261498695/261498695.jpg@s_2,w_150,h_150"
},
{
"title": "不潮不用花钱",
"author": "林俊杰",
"song_id": "259242650",
"album_id": "258953281",
"album_title": "乌鸦嘴妙女郎 电视原声带",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/1ac5b0f1c95c78be5dd1f17343380a8c/613318868/613318868.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/1ac5b0f1c95c78be5dd1f17343380a8c/613318868/613318868.jpg@s_2,w_150,h_150"
},
{
"title": "被风吹过的夏天",
"author": "林俊杰,金莎",
"song_id": "246732955",
"album_id": "246732962",
"album_title": "最佳前男友 电视原声",
"rank_change": "3",
"all_rate": "flac,320,128,224,96",
"biaoshi": "lossless,vip,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/6e725d74079aa90476655effb1b7cbf3/611737404/611737404.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/6e725d74079aa90476655effb1b7cbf3/611737404/611737404.jpg@s_2,w_150,h_150"
}
],
"color": "0x967456",
"bg_color": "0xF5F1EE",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4ed160c12_921.png"
},
{
"name": "经典老歌榜",
"type": 22,
"count": 4,
"comment": "实时展现千千音乐最热门经典老歌排行",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_e6b795613995b69b73861ca7e7732015.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/6f061d950a7b0208b85e57e760d9f2d3572cc825.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/0bd162d9f2d3572cd909f4da8813632763d0c3c9.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_ecd2c13c57fb27574b9e758e4f707cef.jpg",
"content": [
{
"title": "后来",
"author": "刘若英",
"song_id": "790142",
"album_id": "190892",
"album_title": "我等你",
"rank_change": "0",
"all_rate": "flac,320,128,224,96",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/51677db1f7b51f1f1bacd1a2498665ff/190892/190892.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/51677db1f7b51f1f1bacd1a2498665ff/190892/190892.jpg@s_2,w_150,h_150"
},
{
"title": "伤心太平洋",
"author": "任贤齐",
"song_id": "704195",
"album_id": "173971",
"album_title": "情义",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-3",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/73a3804e1b971cbebc63d99260278136/173971/173971.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/73a3804e1b971cbebc63d99260278136/173971/173971.jpg@s_2,w_150,h_150"
}
],
"color": "0xD98E26",
"bg_color": "0xFBF4EA",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4e5a1364a_423.png"
},
{
"name": "欧美金曲榜",
"type": 21,
"count": 4,
"comment": "实时展现千千音乐最热门欧美歌曲排行",
"web_url": "",
"pic_s192": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_9362a5a55277e6fb271010a45bc99e17.jpg",
"pic_s444": "http://hiphotos.qianqian.com/ting/pic/item/8d5494eef01f3a291bf6bec89b25bc315c607cfd.jpg",
"pic_s260": "http://hiphotos.qianqian.com/ting/pic/item/8b13632762d0f7035cb3feda0afa513d2697c5b7.jpg",
"pic_s210": "http://business.cdn.qianqian.com/qianqian/pic/bos_client_ad19dd0cd653dbf9b2fca05b5ae6f87f.jpg",
"content": [
{
"title": "New Silk Road",
"author": "Maksim",
"song_id": "573313333",
"album_id": "573313330",
"album_title": "New Silk Road",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/d5dee954c872320a210a326180425cfc/591310208/591310208.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/d5dee954c872320a210a326180425cfc/591310208/591310208.jpg@s_2,w_150,h_150"
},
{
"title": "Симфония № 4(交响乐4号)",
"author": "Vitas",
"song_id": "590762992",
"album_id": "590762988",
"album_title": "20",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/4d475c81e4c562301e21c2d102165205/590761655/590761655.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/4d475c81e4c562301e21c2d102165205/590761655/590761655.jpg@s_2,w_150,h_150"
},
{
"title": "因为爱情 (法语版)",
"author": "弗雷德乐队",
"song_id": "65626244",
"album_id": "65626242",
"album_title": "致青春 (法语版)",
"rank_change": "0",
"all_rate": "96,128,224,320",
"biaoshi": "perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/88411609/88411609.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/88411609/88411609.jpg@s_2,w_150,h_150"
},
{
"title": "Dogs",
"author": "I WEAR* EXPERIMENT乐队",
"song_id": "588688244",
"album_id": "588688241",
"album_title": "Dogs",
"rank_change": "0",
"all_rate": "96,128,224,320,flac",
"biaoshi": "lossless,vip,perm-1",
"pic_small": "http://qukufile2.qianqian.com/data2/pic/3aa6422af908cf869262f9c75f3c3530/588688242/588688242.jpg@s_2,w_90,h_90",
"pic_big": "http://qukufile2.qianqian.com/data2/pic/3aa6422af908cf869262f9c75f3c3530/588688242/588688242.jpg@s_2,w_150,h_150"
}
],
"color": "0x4A90E2",
"bg_color": "0xEDF4FC",
"bg_pic": "http://business0.qianqian.com/qianqian/file/5bfe4e726acbc_309.png"
}
],
"error_code": 22000
}
"""
func MJJSON() {
let jsonData22222 = json22222.data(using: .utf8)!
let json222 = try? JSONSerialization.jsonObject(with: jsonData22222, options: JSONSerialization.ReadingOptions.allowFragments)
let song = LYMSong(try? JSON(data: jsonData22222))
// let song = LYMSong.mj_object(withKeyValues: json222)
print(song)
}
|
mit
|
8d2254e1a86d6fb5e99ca7202f4f42d0
| 34.379679 | 130 | 0.634573 | 2.368496 | false | false | false | false |
karstengresch/rw_studies
|
Apprentice/Checklists10/Checklists10/Checklists10/Checklist10ItemDetailViewController.swift
|
1
|
7636
|
//
// Checklist10ItemDetailViewController.swift
// Checklists10
//
// Created by Karsten Gresch on 20.11.16.
// Copyright © 2016 Closure One. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
protocol Checklist10ItemDetailViewControllerDelegate: class {
func checklist10ItemDetailViewControllerDidCancel(_ controller: Checklist10ItemDetailViewController)
func checklist10ItemDetailViewController(_ controller: Checklist10ItemDetailViewController, didFinishAdding checklist10Item: Checklist10Item)
func checklist10ItemDetailViewController(_ controller: Checklist10ItemDetailViewController, didFinishEditing checklist10Item: Checklist10Item)
}
class Checklist10ItemDetailViewController: UITableViewController, UITextFieldDelegate {
weak var delegate: Checklist10ItemDetailViewControllerDelegate?
var checklist10ItemToEdit: Checklist10Item?
var dueDate = Date()
var isDatePickerVisible = false
// MARK: IBOutlet/IBAction
@IBOutlet weak var addChecklist10ItemTextField: UITextField!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
@IBOutlet weak var shouldRemindSwitch: UISwitch!
@IBOutlet weak var dueDateLabel: UILabel!
@IBOutlet weak var datePickerCell: UITableViewCell!
@IBOutlet weak var datePicker: UIDatePicker!
@IBAction func dateChanged(_ datePicker: UIDatePicker) {
dueDate = datePicker.date
updateDueDateLabel()
}
@IBAction func shouldRemindToggled(_ switchControl: UISwitch) {
addChecklist10ItemTextField.resignFirstResponder()
if switchControl.isOn {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .sound]) {
granted, error in
}
// datePickerCell. = true
} else {
// datePickerCell.isEditing = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let checklist10Item = checklist10ItemToEdit {
title = "Edit Checklist10 Item"
addChecklist10ItemTextField.text = checklist10Item.text
doneBarButton.isEnabled = true
shouldRemindSwitch.isOn = checklist10Item.shouldRemind
dueDate = checklist10Item.dueDate
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addChecklist10ItemTextField.becomeFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addChecklist10ItemTextField.becomeFirstResponder()
}
@IBAction func cancel() {
// dismiss(animated: true, completion: nil)
print("CANCEL Contents of addChecklist10ItemTextField: \(addChecklist10ItemTextField.text ?? "N/V")")
delegate?.checklist10ItemDetailViewControllerDidCancel(self)
}
@IBAction func done() {
print("DONE Contents of addChecklist10ItemTextField: \(addChecklist10ItemTextField.text ?? "N/V")")
// dismiss(animated: true, completion: nil)
if let checklist10Item = checklist10ItemToEdit {
checklist10Item.text = addChecklist10ItemTextField.text!
checklist10Item.shouldRemind = shouldRemindSwitch.isOn
checklist10Item.dueDate = dueDate
updateDueDateLabel()
checklist10Item.scheduleNotification()
delegate?.checklist10ItemDetailViewController(self, didFinishEditing: checklist10Item)
}
else {
let checklist10Item = Checklist10Item()
checklist10Item.text = addChecklist10ItemTextField.text!
checklist10Item.checked = false
checklist10Item.shouldRemind = shouldRemindSwitch.isOn
checklist10Item.dueDate = dueDate
updateDueDateLabel()
checklist10Item.scheduleNotification()
delegate?.checklist10ItemDetailViewController(self, didFinishAdding: checklist10Item)
}
}
// MARK: TVC methods
// disallow row from selection
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 1 && indexPath.row == 1 {
return indexPath
} else {
return nil
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 && isDatePickerVisible {
return 3
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 1 && indexPath.row == 2 {
return 217
} else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
var newIndexPath = indexPath
if indexPath.section == 1 && indexPath.row == 2 {
newIndexPath = IndexPath(row: 0, section: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
addChecklist10ItemTextField.resignFirstResponder()
if indexPath.section == 1 && indexPath.row == 1 {
if !isDatePickerVisible {
showDatePicker()
} else {
hideDatePicker()
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 && indexPath.row == 2 {
return datePickerCell
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
let newText = oldText.replacingCharacters(in: range, with: string) as NSString
/*
if newText.characters.count > 0 {
doneBarButton.isEnabled = true
} else {
doneBarButton.isEnabled = false
}
*/
doneBarButton.isEnabled = (newText.length > 0)
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
hideDatePicker()
}
func updateDueDateLabel() {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
dueDateLabel.text = formatter.string(from: dueDate)
}
func showDatePicker() {
print("Calling: showDatePicker()")
isDatePickerVisible = true
let indexPathDateRow = IndexPath(row: 1, section: 1)
let indexPathDatePicker = IndexPath(row: 2, section: 1)
if let dateCell = tableView.cellForRow(at: indexPathDateRow) {
dateCell.detailTextLabel!.textColor = dateCell.detailTextLabel!.tintColor
}
tableView.beginUpdates()
tableView.insertRows(at: [indexPathDatePicker], with: .fade)
tableView.reloadRows(at: [indexPathDateRow], with: .none)
tableView.endUpdates()
datePicker.setDate(dueDate, animated: true)
}
func hideDatePicker() {
if isDatePickerVisible {
isDatePickerVisible = false
let indexPathDateRow = IndexPath(row: 1, section: 1)
let indexPathDatePicker = IndexPath(row: 2, section: 1)
if let datePickerCell = tableView.cellForRow(at: indexPathDateRow) {
datePickerCell.detailTextLabel!.textColor = UIColor(white: 0, alpha: 0.5)
}
tableView.beginUpdates()
tableView.reloadRows(at: [indexPathDateRow], with: .none)
tableView.deleteRows(at: [indexPathDatePicker], with: .fade)
tableView.endUpdates()
}
}
}
|
unlicense
|
71ed2ba74ad24a4090a136b8f516df38
| 30.680498 | 144 | 0.711722 | 5.006557 | false | false | false | false |
ckrey/mqttswift
|
Sources/MqttRetained.swift
|
1
|
1326
|
import Foundation
class MqttRetained {
private static var theInstance: MqttRetained?
public class func sharedInstance() -> MqttRetained {
if theInstance == nil {
theInstance = MqttRetained()
}
return theInstance!
}
var retained : [String: MqttMessage]
private var stateTimer: DispatchSourceTimer
private init() {
self.retained = [String: MqttMessage]()
let q = DispatchQueue.global()
self.stateTimer = DispatchSource.makeTimerSource(queue: q)
self.stateTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1), leeway: .seconds(1))
self.stateTimer.setEventHandler { [weak self] in
self!.expired()
}
self.stateTimer.resume()
}
func expired() {
let now = Date()
for (topic, message) in retained {
if message.publicationExpiryTime != nil {
if message.publicationExpiryTime! < now {
MqttCompliance.sharedInstance().log(target: "retained message expired")
retained[topic] = nil
}
}
}
}
func store(message: MqttMessage!) {
if message.data.count == 0 {
self.retained[message.topic] = nil
} else {
self.retained[message.topic] = message
}
}
}
|
gpl-3.0
|
3a826df388bb7f51bb1390782b331c03
| 27.212766 | 103 | 0.592006 | 4.494915 | false | false | false | false |
eeschimosu/LicensingVC
|
LicensingViewController/LicensingItemCell.swift
|
1
|
2080
|
//
// LicensingItemCell.swift
// LicensingViewController
//
// Created by Tiago Henriques on 15/07/15.
// Copyright (c) 2015 Tiago Henriques. All rights reserved.
//
import UIKit
class LicensingItemCell: UITableViewCell {
// MARK: - Constants
let spacing = 15
// MARK: - Properties
let titleLabel = UILabel()
let noticeLabel = UILabel()
// MARK: - Lifecycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = ""
noticeLabel.text = ""
}
// MARK: - Views
func setupSubviews() {
titleLabel.numberOfLines = 0
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(titleLabel)
noticeLabel.numberOfLines = 0
noticeLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(noticeLabel)
setupConstraints()
}
func setupConstraints() {
let views = [
"titleLabel": titleLabel,
"noticeLabel": noticeLabel
]
let metrics = [
"spacing": spacing
]
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-spacing-[titleLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-spacing-[titleLabel]-[noticeLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-spacing-[noticeLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
}
}
|
mit
|
d286833b7fd7c34162730a8a84979906
| 22.636364 | 133 | 0.6125 | 5.606469 | false | false | false | false |
tensorflow/swift-apis
|
Sources/x10/swift_bindings/optimizers/Optimizer.swift
|
1
|
11706
|
// Copyright 2020 TensorFlow Authors
//
// 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 _Differentiation
import TensorFlow
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
import Numerics
#endif
@_exported import x10_optimizers_tensor_visitor_plan
/// State for a single step of a single weight inside an optimizer.
public struct OptimizerWeightStepState {
/// Hyperparameters.
public let globals: [Tensor<Float>]
/// Temporary values (can only be assigned once).
public var locals: [Tensor<Float>] = []
/// The actual derivative of weight wrt to the loss function.
public var grad: Tensor<Float>
/// The weight being optimized.
public let weight: Tensor<Float>
/// Used for indexing into auxiliary arrays (like OptimizerState).
var weightId: Int
/// The final output of the optimizer. (should really only be set once).
/// nil means that the weight will not be touched.
/// This will be applied to the true weight at the end: `weight += step`.
public var step: Tensor<Float>? = nil
public subscript(_ local: LocalAccessor) -> Tensor<Float> {
get { return locals[local.index] }
set {
// Can only set to the next index.
precondition(locals.count == local.index)
locals.append(newValue)
}
}
public subscript(_ global: GlobalAccessor) -> Tensor<Float> {
get { return globals[global.index] }
}
}
/// Global state accessed through `StateAccessor`.
public struct OptimizerState {
public init(_ zeros: [Tensor<Float>], stateCount: Int) {
self.state = (0..<stateCount * zeros.count).map { zeros[$0 % zeros.count] }
self.stride = zeros.count
}
public init(copying other: OptimizerState, to device: Device) {
self.stride = other.stride
self.state = other.state.map { Tensor<Float>(copying: $0, to: device) }
}
public var state: [Tensor<Float>]
public var stride: Int
public subscript(_ stateId: Int, _ weightId: Int) -> Tensor<Float> {
get { state[stateId * stride + weightId] }
_modify { yield &state[stateId * stride + weightId] }
}
public subscript(_ state: OptimizerWeightStepState, _ index: StateAccessor) -> Tensor<Float> {
get { return self[index.index, state.weightId] }
_modify { yield &self[index.index, state.weightId] }
}
}
/// `[String: Float]` but elements can be accessed as though they were members.
@dynamicMemberLookup
public struct HyperparameterDictionary {
public init() {}
var values: [String: Float] = [String: Float]()
public subscript(dynamicMember name: String) -> Float? {
get { return values[name] }
_modify { yield &values[name] }
}
public subscript(name: String) -> Float? {
get { return values[name] }
_modify { yield &values[name] }
}
}
// TODO: Experiment with efficiently fusing these...
public typealias OptimizerCallback = (inout OptimizerWeightStepState, inout OptimizerState) -> Void
/// An optimizer that works on a single parameter group.
public struct ParameterGroupOptimizer {
public init() {}
public var hyperparameters = HyperparameterDictionary()
public var globals: [(HyperparameterDictionary, Device) -> Tensor<Float>] = []
public var localCount: Int = 0
public var callbacks: [OptimizerCallback] = []
public var stateCount: Int = 0
}
/// General optimizer that should be able to express multiple possible optimizations.
/// The optimizer is composed of a mapping from ParameterGroup to ParameterGroupOptimizer.
/// This optimizer also contains the number of elements working in a cross replica sum.
/// This is for efficiency to prevent multiple inefficient iterations over the gradient.
public class GeneralOptimizer<Model: EuclideanDifferentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & ElementaryFunctions & KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The set of steps taken.
public var step: Int = 0
/// Used to determine the scaling factor of the cross replica sum.
public var crossReplicaSumCount: Int? = nil
/// global optimizer state.
public var optimizerState: OptimizerState
/// Current device of the model. (Used for constructing hyperparameters)
public var device: Device
/// An array mapping nested weight indices to parameter group optimizers?
/// Weight i will be optimized by `parameterGroups[parameterGroupIndices[i]]`
public var parameterGroupIndices: [Int]
/// An array of parameter group optimizers.
public var parameterGroups: [ParameterGroupOptimizer]
/// The plan used to iterate over the Tensors of the model.
let kpPlan: TensorVisitorPlan<Model.TangentVector>
/// Overall learning rate of the optimizer.
public var learningRate: Float {
get { parameterGroups[0].hyperparameters.learningRate ?? 0.0 }
set {
for index in parameterGroups.indices {
parameterGroups[index].hyperparameters.learningRate = newValue
}
}
}
/// Per-parameter group optimizer learning rates.
public var learningRates: [Float] {
get { parameterGroups.map { $0.hyperparameters.learningRate ?? 0.0 } }
set {
for index in parameterGroups.indices {
parameterGroups[index].hyperparameters.learningRate = newValue[index]
}
}
}
/// Constructs an optimizer from a list of parameter group optimizers
/// and a selector that divides the weights into different parameter groups.
/// This is the most general constructor as there are many ways to construct
/// this selector vector.
public init(
for model: __shared Model,
_ kpPlan: TensorVisitorPlan<Model.TangentVector>,
parameterGroupIndices: [Int],
parameterGroups: [ParameterGroupOptimizer]
) {
self.kpPlan = kpPlan
let zerosPattern = model.differentiableVectorView
// TODO(parkers): Be more precise here...
let stateCount = parameterGroups.map { $0.stateCount }.max() ?? 0
self.optimizerState = OptimizerState(
kpPlan.allTensorKeyPaths.map { kp in
Tensor<Float>(zerosLike: zerosPattern[keyPath: kp])
}, stateCount: stateCount)
self.device = zerosPattern[keyPath: kpPlan.allTensorKeyPaths[0]].device
self.parameterGroupIndices = parameterGroupIndices
self.parameterGroups = parameterGroups
}
/// Constructs an optimizer from a sequence of per-parameter group optimizers
/// and then a final default parameter group optimizer. The `[Bool]` array
/// is per weight and is true for the weights in that param group. The
/// first parameterGroup will be used over subsequent ones.
public convenience init(
for model: __shared Model,
_ kpPlan: TensorVisitorPlan<Model.TangentVector>,
parameterGroups: ([Bool], ParameterGroupOptimizer)...,
defaultOptimizer: ParameterGroupOptimizer
) {
self.init(
for: model, kpPlan,
parameterGroupIndices: kpPlan.allTensorKeyPaths.indices.map { (index: Int) -> Int in
for (i, pg) in parameterGroups.enumerated() {
if pg.0[index] { return i }
}
return parameterGroups.count
}, parameterGroups: parameterGroups.map { $0.1 } + [defaultOptimizer])
}
/// The actual optimizer step. Maps over all the tensors of the gradient
/// and applies per-weight optimizers defined by ParameterGroupOptimizer.
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let globals = parameterGroups.map { pg in
pg.globals.map { globalInit in globalInit(pg.hyperparameters, device) }
}
var step = direction
let crsScale : Double? = crossReplicaSumCount.map { 1.0 / Double($0) }
// step plays dual-duties as an inout parameter for efficiency.
let _ = kpPlan.mapTensors(&step, model.differentiableVectorView) {
(step: inout Tensor<Float>, weight: Tensor<Float>, i: Int) in
let selector = parameterGroupIndices[i]
let paramGroup = parameterGroups[selector]
var state = OptimizerWeightStepState(
globals: globals[selector], grad: step, weight: weight, weightId: i)
if let crsScale = crsScale {
state.grad = _Raw.crossReplicaSum([state.grad], crsScale).first!
}
for cb in paramGroup.callbacks { cb(&state, &optimizerState) }
step = state.step ?? Tensor<Float>(zerosLike: step)
}
model.move(along: step)
}
/// Copies the optimizer to the specified device.
public required init(copying other: GeneralOptimizer, to device: Device) {
step = other.step
crossReplicaSumCount = other.crossReplicaSumCount
kpPlan = other.kpPlan
optimizerState = .init(copying: other.optimizerState, to: device)
parameterGroupIndices = other.parameterGroupIndices
parameterGroups = other.parameterGroups
self.device = device
}
}
/// A type-safe wrapper around an `Int` index value for optimizer local values.
public struct LocalAccessor {
init(_ index: Int) {
self.index = index
}
var index: Int
}
/// A type-safe wrapper around an `Int` index value for optimizer global values.
public struct GlobalAccessor {
init(_ index: Int) {
self.index = index
}
var index: Int
}
/// A type-safe wrapper around an `Int` index value for optimizer state values.
public struct StateAccessor {
init(_ index: Int) {
self.index = index
}
var index: Int
}
/// Builds a `ParameterGroupOptimizer`. This is used at essentially the level
/// of a single weight in the model. A mapping from parameter groups
/// selected by (`[Bool]` to ParameterGroupOptimizer) defines the final
/// optimizer.
public struct ParameterGroupOptimizerBuilder {
public init() {}
var result = ParameterGroupOptimizer()
var globalValues: [Float] = []
var globals: [String: GlobalAccessor] = [:]
var locals: [String: LocalAccessor] = [:]
var states: [String: StateAccessor] = [:]
public mutating func makeParameter(_ name: String, _ value: Float) -> GlobalAccessor {
precondition(globals[name] == nil, "Already a global parameter named \(name)")
let index = result.globals.count
result.hyperparameters[name] = value
result.globals.append({ Tensor<Float>($0[name]!, on: $1) })
globals[name] = GlobalAccessor(index)
globalValues.append(value)
return GlobalAccessor(index)
}
public subscript(_ global: GlobalAccessor) -> Float {
globalValues[global.index]
}
public subscript(state name: String) -> StateAccessor {
mutating get {
if let res = states[name] { return res }
let index = result.stateCount
result.stateCount += 1
states[name] = StateAccessor(index)
return StateAccessor(index)
}
}
public subscript(local name: String) -> LocalAccessor {
mutating get {
if let res = locals[name] { return res }
let index = result.localCount
result.localCount += 1
locals[name] = LocalAccessor(index)
return LocalAccessor(index)
}
}
/// Appends a callback to the list of callbacks.
public mutating func appendCallback(_ cb: @escaping OptimizerCallback) {
result.callbacks.append(cb)
}
/// Returns the optimizer and clears the builder.
public mutating func makeOptimizer() -> ParameterGroupOptimizer {
let tmp = result
self = ParameterGroupOptimizerBuilder()
return tmp
}
}
|
apache-2.0
|
0d34c801e3fafd6d7781c295eb1bc18d
| 34.689024 | 99 | 0.706561 | 4.180714 | false | false | false | false |
Salt7900/belly_codechallenge
|
belly_cc/LocationCell.swift
|
1
|
1301
|
//
// LocationCell.swift
// belly_cc
//
// Created by Ben Fallon on 12/15/15.
// Copyright © 2015 Ben Fallon. All rights reserved.
//
import UIKit
class LocationCell: UITableViewCell {
@IBOutlet weak var locationPicture: UIImageView!
@IBOutlet weak var locationName: UILabel!
@IBOutlet weak var locationDistance: UILabel!
@IBOutlet weak var locationCategory: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setCell(nameOfLocation: String, imageOfLocationPre: String, imageOfLocationSuf: String,categoryOfLocation: String, distanceTo: Double){
let totalImageUrl = "\(imageOfLocationPre)bg_88\(imageOfLocationSuf)"
if let url = NSURL(string: totalImageUrl) {
if let data = NSData(contentsOfURL: url) {
locationPicture.image = UIImage(data: data)
}
}
self.locationDistance.text = String("\(distanceTo) miles away")
self.locationName.text = nameOfLocation
self.locationCategory.text = categoryOfLocation
}
}
|
mit
|
68818f209840bc2bf2c726bc119a70b2
| 29.232558 | 144 | 0.663077 | 4.59364 | false | false | false | false |
wirecard/paymentSDK-iOS
|
Example-Swift/Embedded/ViewController.swift
|
1
|
3039
|
//
// ViewController.swift
// Embedded
//
// Created by Vrana, Jozef on 28/02/2019.
// Copyright © 2019 Vrana, Jozef. All rights reserved.
//
import WDeComCard
import WDeComCardScannerGallery
let PMTitleCard = "Card"
let PMTitleAnimatedCardfield = "Animated cardfield"
let PMTitleCardManualBrandSelection = "Card manual brand selection"
let PMTitleCardManualBrandSelectionAnimated = "Animated card manual brand selection"
class ViewController: PaymemtVC, UIActionSheetDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onPay(_ sender: UIButton) {
let actionSheetController = UIAlertController(title: "Payment", message: nil, preferredStyle: .actionSheet)
func handler(actionTarget: UIAlertAction){
if actionTarget.style == .cancel {
self.dismiss(animated: true, completion: nil)
return
}
let paymentTitle = actionTarget.title
if paymentTitle == PMTitleCard || paymentTitle == PMTitleCardManualBrandSelection {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "CardfieldVC")
self.navigationController?.pushViewController(vc, animated: true)
let manualCardbrandSelection = paymentTitle == PMTitleCardManualBrandSelection ? true : false
let cardLayout = WDECCardLayout.appearance()
cardLayout.manualCardBrandSelectionRequired = manualCardbrandSelection
}
if paymentTitle == PMTitleAnimatedCardfield || paymentTitle == PMTitleCardManualBrandSelectionAnimated {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "AnimatedCardfieldVC")
self.navigationController?.pushViewController(vc, animated: true)
let manualCardbrandSelection = paymentTitle == PMTitleCardManualBrandSelectionAnimated ? true : false
let cardLayout = WDECCardLayout.appearance()
cardLayout.manualCardBrandSelectionRequired = manualCardbrandSelection
}
}
actionSheetController.addAction(UIAlertAction(title: PMTitleCard, style: .default, handler: handler))
actionSheetController.addAction(UIAlertAction(title: PMTitleAnimatedCardfield, style: .default, handler: handler))
actionSheetController.addAction(UIAlertAction(title: PMTitleCardManualBrandSelection, style: .default, handler: handler))
actionSheetController.addAction(UIAlertAction(title: PMTitleCardManualBrandSelectionAnimated, style: .default, handler: handler))
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: handler))
self.present(actionSheetController, animated: true, completion: nil)
}
}
|
mit
|
6ca1499d3f6410eed89bce63e2d055e0
| 48.803279 | 137 | 0.684003 | 5.175468 | false | false | false | false |
ReactiveCocoa/ReactiveSwift
|
Tests/ReactiveSwiftTests/FlattenSpec.swift
|
1
|
37461
|
//
// FlattenSpec.swift
// ReactiveSwift
//
// Created by Oleg Shnitko on 1/22/16.
// Copyright © 2016 GitHub. All rights reserved.
//
import Nimble
import Quick
@testable import ReactiveSwift
import Dispatch
private extension Signal {
typealias Pipe = (output: Signal<Value, Error>, input: Signal<Value, Error>.Observer)
}
private typealias Pipe = Signal<SignalProducer<Int, TestError>, TestError>.Pipe
class FlattenSpec: QuickSpec {
override func spec() {
func describeSignalFlattenDisposal(_ flattenStrategy: FlattenStrategy, name: String) {
describe(name) {
var pipe: Pipe!
var disposable: Disposable?
beforeEach {
pipe = Signal.pipe()
disposable = pipe.output
.flatten(flattenStrategy)
.observe { _ in }
}
afterEach {
disposable?.dispose()
}
context("disposal") {
var disposed = false
beforeEach {
disposed = false
pipe.input.send(value: SignalProducer<Int, TestError> { _, lifetime in
lifetime.observeEnded { disposed = true }
})
}
it("should dispose inner signals when outer signal interrupted") {
pipe.input.sendInterrupted()
expect(disposed) == true
}
it("should dispose inner signals when outer signal failed") {
pipe.input.send(error: .default)
expect(disposed) == true
}
it("should not dispose inner signals when outer signal completed") {
pipe.input.sendCompleted()
expect(disposed) == false
}
}
}
}
context("Signal") {
describeSignalFlattenDisposal(.latest, name: "switchToLatest")
describeSignalFlattenDisposal(.merge, name: "merge")
describeSignalFlattenDisposal(.concat, name: "concat")
describeSignalFlattenDisposal(.concurrent(limit: 1024), name: "concurrent(limit: 1024)")
describeSignalFlattenDisposal(.race, name: "race")
}
func describeSignalProducerFlattenDisposal(_ flattenStrategy: FlattenStrategy, name: String) {
describe(name) {
it("disposes original signal when result signal interrupted") {
var disposed = false
let disposable = SignalProducer<SignalProducer<(), Never>, Never> { _, lifetime in
lifetime.observeEnded { disposed = true }
}
.flatten(flattenStrategy)
.start()
disposable.dispose()
expect(disposed) == true
}
}
}
context("SignalProducer") {
describeSignalProducerFlattenDisposal(.latest, name: "switchToLatest")
describeSignalProducerFlattenDisposal(.merge, name: "merge")
describeSignalProducerFlattenDisposal(.concat, name: "concat")
describeSignalProducerFlattenDisposal(.concurrent(limit: 1024), name: "concurrent(limit: 1024)")
describeSignalProducerFlattenDisposal(.race, name: "race")
}
describe("Signal.flatten()") {
it("works with TestError and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = Signal<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = Signal<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = Signal<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = Signal<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = Signal<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = Signal<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = Signal<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = Signal<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Sequence as a value") {
let (signal, innerObserver) = Signal<[Int], Never>.pipe()
let sequence = [1, 2, 3]
var observedValues = [Int]()
signal
.flatten()
.observeValues { value in
observedValues.append(value)
}
innerObserver.send(value: sequence)
expect(observedValues) == sequence
}
it("works with Sequence as a value and any arbitrary error") {
_ = Signal<[Int], TestError>.empty
.flatten()
}
it("works with Property and any arbitrary error") {
_ = Signal<Property<Int>, TestError>.empty
.flatten(.latest)
}
it("works with Property and Never") {
_ = Signal<Property<Int>, Never>.empty
.flatten(.latest)
}
}
describe("SignalProducer.flatten()") {
it("works with TestError and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = SignalProducer<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = SignalProducer<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = SignalProducer<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = SignalProducer<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = SignalProducer<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = SignalProducer<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = SignalProducer<Inner, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = SignalProducer<Inner, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatten(.latest)
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: inner)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Sequence as a value") {
let sequence = [1, 2, 3]
var observedValues = [Int]()
let producer = SignalProducer<[Int], Never>(value: sequence)
producer
.flatten()
.startWithValues { value in
observedValues.append(value)
}
expect(observedValues) == sequence
}
it("works with Sequence as a value and any arbitrary error") {
_ = SignalProducer<[Int], TestError>.empty
.flatten()
}
it("works with Property and any arbitrary error") {
_ = SignalProducer<Property<Int>, TestError>.empty
.flatten(.latest)
}
it("works with Property and Never") {
_ = SignalProducer<Property<Int>, Never>.empty
.flatten(.latest)
}
}
describe("Signal.flatMap()") {
it("works with TestError and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = Signal<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = Signal<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = Signal<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = Signal<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = Signal<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = Signal<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = Signal<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = Signal<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.observeValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Property and any arbitrary error") {
_ = Signal<Int, TestError>.empty
.flatMap(.latest) { _ in Property(value: 0) }
}
it("works with Property and Never") {
_ = Signal<Int, Never>.empty
.flatMap(.latest) { _ in Property(value: 0) }
}
it("should be able to fallback to SignalProducer for contextual lookups with explicit inner value and error type parameters, given an upstream of arbitrary error type") {
_ = Signal<Int, TestError>.empty
.flatMap(.latest) { _ in .init(result: Result<Int, TestError>(failure: .default)) }
}
it("should be able to fallback to SignalProducer for contextual lookups with implicit error type parameter") {
_ = Signal<Int, Never>.empty
.flatMap(.latest) { _ in .init(value: 0) }
}
it("should be able to fallback to SignalProducer for contextual lookups with implicit error type parameter") {
_ = Signal<Int, TestError>.empty
.flatMap(.latest) { _ in .init(value: 0) }
}
// NOTE: These test cases were disabled as the Swift 4.2 type checker apparently
// cannot infer the type paramaters when both are absent.
// it("should be able to fallback to SignalProducer for contextual lookups without explicit inner value and error type parameters") {
// _ = Signal<Int, Never>.empty
// .flatMap(.latest) { _ in .empty }
// }
//
// it("should be able to fallback to SignalProducer for contextual lookups without explicit inner value and error type parameters") {
// _ = Signal<Int, TestError>.empty
// .flatMap(.latest) { _ in .empty }
// }
it("should be able to fallback to SignalProducer for contextual lookups with explicit inner and error type parameters, given a Never upstream") {
_ = Signal<Int, Never>.empty
.flatMap(.latest) { _ in .init(result: Result<Int, TestError>.failure(.default)) }
}
}
describe("SignalProducer.flatMap()") {
it("works with TestError and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = SignalProducer<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError Signal") {
typealias Inner = Signal<Int, TestError>
typealias Outer = SignalProducer<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = SignalProducer<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never Signal") {
typealias Inner = Signal<Int, Never>
typealias Outer = SignalProducer<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = SignalProducer<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a TestError SignalProducer") {
typealias Inner = SignalProducer<Int, TestError>
typealias Outer = SignalProducer<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Never and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = SignalProducer<Int, Never>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with TestError and a Never SignalProducer") {
typealias Inner = SignalProducer<Int, Never>
typealias Outer = SignalProducer<Int, TestError>
let (inner, innerObserver) = Inner.pipe()
let (outer, outerObserver) = Outer.pipe()
var observed: Int? = nil
outer
.flatMap(.latest) { _ in inner }
.assumeNoErrors()
.startWithValues { value in
observed = value
}
outerObserver.send(value: 4)
innerObserver.send(value: 4)
expect(observed) == 4
}
it("works with Property and any arbitrary error") {
_ = SignalProducer<Int, TestError>.empty
.flatMap(.latest) { _ in Property(value: 0) }
}
it("works with Property and Never") {
_ = SignalProducer<Int, Never>.empty
.flatMap(.latest) { _ in Property(value: 0) }
}
it("should be able to fallback to SignalProducer for contextual lookups with explicit inner value and error type parameters, given an upstream of arbitrary error type") {
_ = SignalProducer<Int, TestError>.empty
.flatMap(.latest) { _ in .init(error: .default) } as SignalProducer<Int, TestError>
}
it("should be able to fallback to SignalProducer for contextual lookups with implicit inner error type parameter") {
_ = SignalProducer<Int, Never>.empty
.flatMap(.latest) { _ in .init(value: 0) }
}
it("should be able to fallback to SignalProducer for contextual lookups with implicit inner error type parameter") {
_ = SignalProducer<Int, TestError>.empty
.flatMap(.latest) { _ in .init(value: 0) }
}
// NOTE: These test cases were disabled as the Swift 4.2 type checker apparently
// cannot infer the type paramaters when both are absent.
// it("should be able to fallback to SignalProducer for contextual lookups without explicit inner value and error type parameters") {
// _ = SignalProducer<Int, Never>.empty
// .flatMap(.latest) { _ in .empty }
// }
//
// it("should be able to fallback to SignalProducer for contextual lookups without explicit inner value and error type parameters") {
// _ = SignalProducer<Int, TestError>.empty
// .flatMap(.latest) { _ in .empty }
// }
it("should be able to fallback to SignalProducer for contextual lookups with explicit inner and error type parameters, given a Never upstream.") {
_ = SignalProducer<Int, Never>.empty
.flatMap(.latest) { _ in .init(error: .default) } as SignalProducer<Int, TestError>
}
}
describe("Signal.merge()") {
it("should emit values from all signals") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let (signal3, observer3) = Signal<Int, Never>.pipe()
let mergedSignals = Signal.merge([signal1, signal2, signal3])
var lastValue: Int?
mergedSignals.observeValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer3.send(value: 3)
expect(lastValue) == 3
observer1.send(value: 4)
expect(lastValue) == 4
}
it("should not stop when one signal completes") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let (signal3, observer3) = Signal<Int, Never>.pipe()
let mergedSignals = Signal.merge([signal1, signal2, signal3])
var lastValue: Int?
mergedSignals.observeValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer1.sendCompleted()
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer3.send(value: 3)
expect(lastValue) == 3
}
it("should complete when all signals complete") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let (signal3, observer3) = Signal<Int, Never>.pipe()
let mergedSignals = Signal.merge([signal1, signal2, signal3])
var completed = false
mergedSignals.observeCompleted { completed = true }
expect(completed) == false
observer1.send(value: 1)
expect(completed) == false
observer1.sendCompleted()
expect(completed) == false
observer2.sendCompleted()
expect(completed) == false
observer3.sendCompleted()
expect(completed) == true
}
}
describe("Signal.merge(with:)") {
it("should emit values from both signals") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let mergedSignals = signal1.merge(with: signal2)
var lastValue: Int?
mergedSignals.observeValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer1.send(value: 3)
expect(lastValue) == 3
}
it("should not stop when one signal completes") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let mergedSignals = signal1.merge(with: signal2)
var lastValue: Int?
mergedSignals.observeValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer1.sendCompleted()
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
}
it("should complete when both signals complete") {
let (signal1, observer1) = Signal<Int, Never>.pipe()
let (signal2, observer2) = Signal<Int, Never>.pipe()
let mergedSignals = signal1.merge(with: signal2)
var completed = false
mergedSignals.observeCompleted { completed = true }
expect(completed) == false
observer1.send(value: 1)
expect(completed) == false
observer1.sendCompleted()
expect(completed) == false
observer2.sendCompleted()
expect(completed) == true
}
}
describe("SignalProducer.merge()") {
it("should emit values from all producers") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let (producer3, observer3) = SignalProducer<Int, Never>.pipe()
let mergedProducer = SignalProducer.merge([producer1, producer2, producer3])
var lastValue: Int?
mergedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer3.send(value: 3)
expect(lastValue) == 3
observer1.send(value: 4)
expect(lastValue) == 4
}
it("should not stop when one producer completes") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let (producer3, observer3) = SignalProducer<Int, Never>.pipe()
let mergedProducer = SignalProducer.merge([producer1, producer2, producer3])
var lastValue: Int?
mergedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer1.sendCompleted()
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer3.send(value: 3)
expect(lastValue) == 3
}
it("should complete when all producers complete") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let (producer3, observer3) = SignalProducer<Int, Never>.pipe()
let mergedProducer = SignalProducer.merge([producer1, producer2, producer3])
var completed = false
mergedProducer.startWithCompleted { completed = true }
expect(completed) == false
observer1.send(value: 1)
expect(completed) == false
observer1.sendCompleted()
expect(completed) == false
observer2.sendCompleted()
expect(completed) == false
observer3.sendCompleted()
expect(completed) == true
}
}
describe("SignalProducer.merge(with:)") {
it("should emit values from both producers") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let mergedProducer = producer1.merge(with: producer2)
var lastValue: Int?
mergedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
observer1.send(value: 3)
expect(lastValue) == 3
}
it("should not stop when one producer completes") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let mergedProducer = producer1.merge(with: producer2)
var lastValue: Int?
mergedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer1.send(value: 1)
expect(lastValue) == 1
observer1.sendCompleted()
expect(lastValue) == 1
observer2.send(value: 2)
expect(lastValue) == 2
}
it("should complete when both producers complete") {
let (producer1, observer1) = SignalProducer<Int, Never>.pipe()
let (producer2, observer2) = SignalProducer<Int, Never>.pipe()
let mergedProducer = producer1.merge(with: producer2)
var completed = false
mergedProducer.startWithCompleted { completed = true }
expect(completed) == false
observer1.send(value: 1)
expect(completed) == false
observer1.sendCompleted()
expect(completed) == false
observer2.sendCompleted()
expect(completed) == true
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.merge(with: .init(value: 0))
}
}
describe("SignalProducer.prefix()") {
it("should emit initial value") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.prefix(value: 0)
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
expect(lastValue) == 0
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
}
it("should emit initial value") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.prefix(SignalProducer(value: 0))
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
expect(lastValue) == 0
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
}
it("should accept SignalProducerConvertible conforming type") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.prefix(Property(value: 0))
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
expect(lastValue) == 0
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.prefix(.init(value: 0))
}
}
describe("SignalProducer.concat()") {
it("should emit final value") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.concat(value: 4)
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
observer.sendCompleted()
expect(lastValue) == 4
}
it("should emit final value") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.concat(SignalProducer(value: 4))
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
observer.sendCompleted()
expect(lastValue) == 4
}
it("should accept SignalProducerConvertible conforming type") {
let (signal, observer) = SignalProducer<Int, Never>.pipe()
let mergedSignals = signal.concat(Property(value: 4))
var lastValue: Int?
mergedSignals.startWithValues { lastValue = $0 }
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 3)
expect(lastValue) == 3
observer.sendCompleted()
expect(lastValue) == 4
}
it("should emit concatenated error") {
let (signal, observer) = SignalProducer<Int, TestError>.pipe()
let mergedSignals = signal.concat(error: TestError.default)
var results: [Result<Int, TestError>] = []
mergedSignals.startWithResult { results.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.sendCompleted()
expect(results).to(haveCount(4))
expect(results[0].value) == 1
expect(results[1].value) == 2
expect(results[2].value) == 3
expect(results[3].error) == .default
}
it("should not emit concatenated error for failed producer") {
let (signal, observer) = SignalProducer<Int, TestError>.pipe()
let mergedSignals = signal.concat(error: TestError.default)
var results: [Result<Int, TestError>] = []
mergedSignals.startWithResult { results.append($0) }
observer.send(error: TestError.error1)
expect(results).to(haveCount(1))
expect(results[0].error) == .error1
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.concat(.init(value: 0))
}
}
describe("FlattenStrategy.concurrent") {
func run(_ modifier: (SignalProducer<UInt, Never>) -> SignalProducer<UInt, Never>) {
let concurrentLimit: UInt = 4
let extra: UInt = 100
let (outer, outerObserver) = Signal<SignalProducer<UInt, Never>, Never>.pipe()
var values: [UInt] = []
outer.flatten(.concurrent(limit: concurrentLimit)).observeValues { values.append($0) }
var started: [UInt] = []
var observers: [Signal<UInt, Never>.Observer] = []
for i in 0 ..< (concurrentLimit + extra) {
let (signal, observer) = Signal<UInt, Never>.pipe()
observers.append(observer)
let producer = modifier(SignalProducer(signal).prefix(value: i).on(started: { started.append(i) }))
outerObserver.send(value: producer)
}
// The producers may be started asynchronously. So these
// expectations have to be asynchronous too.
expect(values).toEventually(equal(Array(0 ..< concurrentLimit)))
expect(started).toEventually(equal(Array(0 ..< concurrentLimit)))
for i in 0 ..< extra {
observers[Int(i)].sendCompleted()
expect(values).toEventually(equal(Array(0 ... (concurrentLimit + i))))
expect(started).toEventually(equal(Array(0 ... (concurrentLimit + i))))
}
}
it("should synchronously merge up to the stated limit, buffer any subsequent producers and dequeue them in the submission order") {
run { $0 }
}
it("should asynchronously merge up to the stated limit, buffer any subsequent producers and dequeue them in the submission order") {
let scheduler = QueueScheduler.makeForTesting()
run { $0.start(on: scheduler) }
}
}
}
}
|
mit
|
55e94ff82f198986008096ab24afc437
| 26.027417 | 173 | 0.649466 | 3.692095 | false | true | false | false |
mightydeveloper/swift
|
validation-test/compiler_crashers_fixed/0191-swift-astprinter-printtextimpl.swift
|
13
|
903
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
// Distributed under the terms of the MIT license
func v<dc {
enum v {
func r
var _ = r
}
}
class u {
}
struct r<ed> : r {
func r(r: r.w) {
}
}
enum dc<fe> { q v: fe
}
protocol n {
}
struct v : n {
func n<fe v r {
}
class n<v> {
func r<fe u: fe) {
}
func u(r: t = a) {
}
}
struct ed : u {
}
func b<fe : fe, ed : u cb ed.u == fe> (v: ed) {
}
func b<dc : u cb dc.u == v> (v: dc) {
}
class a<u : fe, fe : fe cb u.u == fe> {
}
protocol fe {
}
struct v<dc : fe> : fe {
}
class w {
func ed<r cb r: dc, r: w>(ed: r) {
}
func b(v: b) -> <r>(() -> r) -> b {
}
protocol u {
v fe w {
}
r r<ed : w> : w {
}
class u: u {
}
class x : ed {
}
class u<b : u
|
apache-2.0
|
f717f488041909e6cece0a466268d955
| 14.305085 | 87 | 0.524917 | 2.420912 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/SensorFilters/FrequencyBuffer.swift
|
1
|
3653
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// A filter that converts a series of values into a frequency based on a given window
/// and tolerance.
class FrequencyBuffer: ValueFilter {
private var readings = [DataPoint]()
private let window: Int64
private let denominatorInMillis: Double
private let filter: Double
private var averageValue: Double {
let total = readings.reduce(0, { total, value in total + value.y })
// Adding `filter` means that variations of less than `filter` won't register as cycles.
return total / Double(readings.count) + filter
}
private var latestFrequency: Double {
guard readings.count > 1 else {
return 0
}
let average = averageValue
var crossings = 0
var firstCrossingTime: Int64?
var lastCrossingTime: Int64?
var higherThanAverage = readings[0].y > average
for reading in readings[1..<readings.endIndex] {
let thisReadingHigher = reading.y > average
if higherThanAverage != thisReadingHigher {
higherThanAverage = thisReadingHigher
crossings += 1
if firstCrossingTime == nil {
firstCrossingTime = reading.x
} else {
lastCrossingTime = reading.x
}
}
}
// Drop the leading cross because that's where time starts.
crossings -= 1
guard let firstCrossing = firstCrossingTime, let lastCrossing = lastCrossingTime else {
return 0
}
let adjustedWindowMillis = Double(lastCrossing - firstCrossing)
if adjustedWindowMillis < Double(window / 4) {
// if the signal appears to have stopped 3/4 a window ago, then treat it as stopped.
// Without this, we can read very or infinitely short single spikes as representing a
// nonsensical, very high "frequency", leading to janky frequency "spikes" when
// signals stop and start.
return 0
}
let adjustedWindowUserUnits = adjustedWindowMillis / denominatorInMillis
let cycles = Double(crossings) / 2.0
let userUnitFrequency = cycles / adjustedWindowUserUnits
return userUnitFrequency
}
/// Designated Initializer
///
/// - Parameters:
/// - window: How many milliseconds of data to keep for frequency detection.
/// - denominatorInMillis: How many milliseconds are in the display unit (for Hz, this should
/// be 1000. For RPM, it should be 60,000)
/// - filter: Only consider signals with an amplitude at least twice this number.
init(window: Int64, denominatorInMillis: Double, filter: Double) {
self.window = window
self.denominatorInMillis = denominatorInMillis
self.filter = filter
}
func filterValue(timestamp: Int64, value: Double) -> Double {
readings.append(DataPoint(x: timestamp, y: value))
prune(fromTimestamp: timestamp)
return latestFrequency
}
// MARK: - Private
private func prune(fromTimestamp timestamp: Int64) {
let oldestRemaining = timestamp - window
while readings[0].x < oldestRemaining {
readings.remove(at: 0)
}
}
}
|
apache-2.0
|
a1ebcf16decc72ba61fed81278457533
| 32.824074 | 97 | 0.690118 | 4.395909 | false | false | false | false |
muukii/JAYSON
|
Sources/JAYSON/JSON+StrictGetter.swift
|
1
|
3884
|
// JSON+StrictGetter.swift
//
// Copyright (c) 2016 muukii
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// Get Swift Value
extension JSON {
public func getDictionary() throws -> [String : JSON] {
guard let value = dictionary else {
throw JSONError.failedToGetDictionary(source: source, json: self)
}
return value
}
public func getArray() throws -> [JSON] {
guard let value = array else {
throw JSONError.failedToGetArray(source: source, json: self)
}
return value
}
public func getNumber() throws -> NSNumber {
guard let value = number else {
throw JSONError.failedToGetNumber(source: source, json: self)
}
return value
}
public func getInt() throws -> Int {
return try getNumber().intValue
}
public func getInt8() throws -> Int8 {
return try getNumber().int8Value
}
public func getInt16() throws -> Int16 {
return try getNumber().int16Value
}
public func getInt32() throws -> Int32 {
return try getNumber().int32Value
}
public func getInt64() throws -> Int64 {
return try getNumber().int64Value
}
public func getUInt() throws -> UInt {
return try getNumber().uintValue
}
public func getUInt8() throws -> UInt8 {
return try getNumber().uint8Value
}
public func getUInt16() throws -> UInt16 {
return try getNumber().uint16Value
}
public func getUInt32() throws -> UInt32 {
return try getNumber().uint32Value
}
public func getUInt64() throws -> UInt64 {
return try getNumber().uint64Value
}
public func getString() throws -> String {
guard let value = string else {
throw JSONError.failedToGetString(source: source, json: self)
}
return value
}
public func getBool() throws -> Bool {
guard let value = source as? Bool else {
throw JSONError.failedToGetBool(source: source, json: self)
}
return value
}
public func getFloat() throws -> Float {
return try getNumber().floatValue
}
public func getDouble() throws -> Double {
return try getNumber().doubleValue
}
public func getURL() throws -> URL {
let string = try getString()
if let url = URL(string: string) {
return url
}
throw JSONError.failedToParseURL(source: source, json: self)
}
public func get<T>(_ s: (JSON) throws -> T) rethrows -> T {
do {
return try s(self)
} catch let jsonError as JSONError {
throw jsonError
} catch {
throw JSONError.decodeError(source: source, json: self, decodeError: error)
}
}
public func get<T>(with decoder: Decoder<T>) throws -> T {
do {
return try decoder.decode(self)
} catch let jsonError as JSONError {
throw jsonError
} catch {
throw JSONError.decodeError(source: source, json: self, decodeError: error)
}
}
}
|
mit
|
5cbd63147869c9739f00127aeed23d5f
| 26.742857 | 81 | 0.682029 | 4.320356 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
Revolution Tool CL/enums/PBRMoveEffectTypes.swift
|
1
|
1613
|
//
// XGMoveEffectTypes.swift
// GoDToolCL
//
// Created by The Steez on 06/05/2018.
//
import Foundation
enum XGMoveEffectTypes: Int, CaseIterable {
case none = 0
case regularAttack = 1
case buff = 2
case fixedDamage = 3
case leechSeed = 4
case poison = 5
case paralyse = 6
case fissure = 7
case nightShade = 8
case variableMove = 9
case hiddenPower = 10
case psyWaveMirrorCoat = 11
case burn = 12
case weatherBall = 13
case nerf = 14
case itemBasedType = 15
case unknown = 16
var string : String {
switch self {
case .none : return "None"
case .regularAttack : return "Regular Attack"
case .buff : return "Buff"
case .fixedDamage : return "Fixed Damage"
case .leechSeed : return "Leech Seed"
case .poison : return "Poison"
case .paralyse : return "Paralyse"
case .fissure : return "Fissure"
case .nightShade : return "Night Shade"
case .variableMove : return "Variable Move"
case .hiddenPower : return "Hidden Power"
case .psyWaveMirrorCoat : return "Psywave/Mirror Coat"
case .burn : return "Burn"
case .weatherBall : return "Weather Ball"
case .nerf : return "Nerf"
case .itemBasedType : return "Item Based Type"
case .unknown : return "Unknown"
}
}
}
extension XGMoveEffectTypes: XGEnumerable, Equatable {
var enumerableName: String {
return string.spaceToLength(20)
}
var enumerableValue: String? {
return rawValue.string
}
static var className: String {
return "Move Effect Types"
}
static var allValues: [XGMoveEffectTypes] {
return allCases
}
}
|
gpl-2.0
|
2405bd4af9f79a131a55d8cd8e4f2dc3
| 22.042857 | 56 | 0.67266 | 2.810105 | false | false | false | false |
jpush/jchat-swift
|
JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonInputViewLayout.swift
|
1
|
7005
|
//
// JCEmoticonInputViewLayout.swift
// JChat
//
// Created by JIGUANG on 2017/3/9.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
@objc internal protocol JCEmoticonInputViewDelegateLayout: UICollectionViewDelegate {
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, groupAt index: Int) -> JCEmoticonGroup?
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, insetForGroupAt index: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, numberOfRowsForGroupAt index: Int) -> Int
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, numberOfColumnsForGroupAt index: Int) -> Int
}
internal class JCEmoticonInputViewLayout: UICollectionViewLayout {
override var collectionViewContentSize: CGSize {
if let size = _cacheContentSize {
return size
}
guard let collectionView = collectionView else {
return .zero
}
let width = collectionView.frame.width
let count = (0 ..< collectionView.numberOfSections).reduce(0) {
return $0 + numberOfPages(in: $1)
}
let size = CGSize(width: CGFloat(count) * width, height: 0)
_cacheContentSize = size
return size
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if collectionView?.frame.width != newBounds.width {
return true
}
return false
}
override func prepare() {
super.prepare()
_cacheContentSize = nil
_cacheLayoutAttributes = nil
}
override func invalidateLayout() {
super.invalidateLayout()
_cacheContentSize = nil
_cacheLayoutAttributes = nil
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView else {
return nil
}
if let attributes = _cacheLayoutAttributes {
return attributes
}
var allAttributes = [UICollectionViewLayoutAttributes]()
var x = CGFloat(0)
let width = collectionView.frame.width
let height = collectionView.frame.height
(0 ..< collectionView.numberOfSections).forEach { section in
(0 ..< collectionView.numberOfItems(inSection: section)).forEach { item in
let idx = IndexPath(item: item, section: section)
let attributes = layoutAttributesForItem(at: idx) ?? UICollectionViewLayoutAttributes(forCellWith: idx)
attributes.frame = CGRect(x: x, y: 0, width: width, height: height)
x += width
allAttributes.append(attributes)
}
}
_cacheLayoutAttributes = allAttributes
return allAttributes
}
func page(at indexPath: IndexPath) -> JCEmoticonPage {
return _pages(at: indexPath.section, with: Int(collectionView?.frame.width ?? 0))[indexPath.item]
}
func pages(in section: Int) -> [JCEmoticonPage] {
return _pages(at: section, with: Int(collectionView?.frame.width ?? 0))
}
func numberOfPages(in section: Int) -> Int {
return _numberOfPages(in: section, with: Int(collectionView?.frame.width ?? 0))
}
func numberOfRows(in section: Int) -> Int {
guard let collectionView = collectionView else {
return 3
}
guard let delegate = collectionView.delegate as? JCEmoticonInputViewDelegateLayout else {
return 3
}
return delegate.collectionView?(collectionView, layout: self, numberOfRowsForGroupAt: section) ?? 3
}
func numberOfColumns(in section: Int) -> Int {
guard let collectionView = collectionView else {
return 7
}
guard let delegate = collectionView.delegate as? JCEmoticonInputViewDelegateLayout else {
return 7
}
return delegate.collectionView?(collectionView, layout: self, numberOfColumnsForGroupAt: section) ?? 7
}
func contentInset(in section: Int) -> UIEdgeInsets {
guard let collectionView = collectionView else {
return .zero
}
guard let delegate = collectionView.delegate as? JCEmoticonInputViewDelegateLayout else {
return .zero
}
return delegate.collectionView?(collectionView, layout: self, insetForGroupAt: section) ?? .zero
}
private func _group(at index: Int) -> JCEmoticonGroup? {
guard let collectionView = collectionView else {
return nil
}
guard let delegate = collectionView.delegate as? JCEmoticonInputViewDelegateLayout else {
return nil
}
return delegate.collectionView?(collectionView, layout: self, groupAt: index)
}
private func _pagesWithoutCache(at index: Int, with width: Int) -> [JCEmoticonPage] {
guard let group = _group(at: index) else {
return []
}
let inset = contentInset(in: index)
let rows = CGFloat(numberOfRows(in: index))
let columns = CGFloat(numberOfColumns(in: index))
let bounds = CGRect(origin: .zero, size: collectionView?.frame.size ?? .zero)
let rect = bounds.inset(by: inset)
let type = group.type
let size = CGSize(width: min(trunc((rect.width - 8 * columns) / columns), 80),
height: min(trunc((rect.height - 8 * rows) / rows), 80))
let nlsp = (rect.height / rows) - size.height
let nisp = (rect.width / columns) - size.width
return group.emoticons.reduce([]) {
if let page = $0.last, page.addEmoticon($1) {
return $0
}
return $0 + [JCEmoticonPage($1, size, rect, bounds, nlsp, nisp, type)]
}
}
private func _pages(at index: Int, with width: Int) -> [JCEmoticonPage] {
if let pages = _allPages[width]?[index] {
return pages
}
let pages = _pagesWithoutCache(at: index, with: width)
if _allPages[width] == nil {
_allPages[width] = [:]
}
_allPages[width]?[index] = pages
return pages
}
private func _numberOfPages(in index: Int, with width: Int) -> Int {
return _allPages[width]?[index]?.count ?? _pages(at: index, with: width).count
}
private var _cacheContentSize: CGSize?
private var _cacheLayoutAttributes: [UICollectionViewLayoutAttributes]?
// width + section + pages
private lazy var _allPages: [Int: [Int: [JCEmoticonPage]]] = [:]
}
|
mit
|
358929e28fe531a6d81dbc2c7576cb97
| 38.784091 | 175 | 0.625964 | 4.951909 | false | false | false | false |
khanirteza/fusion
|
Fusion/Fusion/UserDataProvider.swift
|
1
|
1457
|
//
// UserDataProvider.swift
// Fusion
//
// Created by Mohammad Irteza Khan on 7/31/17.
// Copyright © 2017 Mohammad Irteza Khan. All rights reserved.
//
import Foundation
import CoreData
import SwiftKeychainWrapper
class UserDataProvider{
static var user = [User]()
//static var loggedInUser = KeychainWrapper.standard.string(forKey: currentUser)
static let userFetchRequest = NSFetchRequest<User>(entityName: "User")
static func getLoggedInUser() -> String{
return KeychainWrapper.standard.string(forKey: currentUser)!
}
public static func getUserPhoto() -> UIImage{
userFetchRequest.predicate = NSPredicate(format: "userID == %@", getLoggedInUser())
do{
user = try CoreDataStack.sharedCoreDataStack.persistentContainer.viewContext.fetch(userFetchRequest)
return UIImage.init(data: (user.first?.userPhoto)!)!
} catch let error{
print(error)
}
return #imageLiteral(resourceName: "profile-photo-placeholder")
}
public static func getUserZipCode() -> String?{
userFetchRequest.predicate = NSPredicate(format: "userID == %@", getLoggedInUser())
do{
user = try CoreDataStack.sharedCoreDataStack.persistentContainer.viewContext.fetch(userFetchRequest)
return (user.first?.zipCode)!
} catch let error{
print(error)
}
return nil
}
}
|
apache-2.0
|
fcd9c6fb0bb8558a420e102e5bb88b7e
| 30.652174 | 112 | 0.659341 | 4.805281 | false | false | false | false |
jakecraige/SwiftLint
|
Source/SwiftLintFramework/Rules/ReturnArrowWhitespaceRule.swift
|
1
|
2034
|
//
// ReturningWhitespaceRule.swift
// SwiftLint
//
// Created by Akira Hirakawa on 2/6/15.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ReturnArrowWhitespaceRule: Rule {
public init() {}
public let identifier = "return_arrow_whitespace"
public func validateFile(file: File) -> [StyleViolation] {
// space doesn't include \n so that "func abc()->\n" can pass validation
let space = "[ \\f\\r\\t\\v]"
let spaceRegex = "(\(space){0}|\(space){2,})"
// ex: func abc()-> Int {
let pattern1 = file.matchPattern("\\)\(spaceRegex)\\->\\s*\\S+",
withSyntaxKinds: [.Typeidentifier])
// ex: func abc() ->Int {
let pattern2 = file.matchPattern("\\)\\s\\->\(spaceRegex)\\S+",
withSyntaxKinds: [.Typeidentifier])
return (pattern1 + pattern2).map { match in
return StyleViolation(type: .ReturnArrowWhitespace,
location: Location(file: file, offset: match.location),
severity: .Low,
reason: "File should have 1 space before return arrow and return type")
}
}
public let example = RuleExample(
ruleName: "Returning Whitespace Rule",
ruleDescription: "This rule checks whether you have 1 space before " +
"return arrow and return type",
nonTriggeringExamples: [
"func abc() -> Int {}\n",
"func abc() -> [Int] {}\n",
"func abc() -> (Int, Int) {}\n",
"var abc = {(param: Int) -> Void in }\n",
"func abc() ->\n"
],
triggeringExamples: [
"func abc()->Int {}\n",
"func abc()->[Int] {}\n",
"func abc()->(Int, Int) {}\n",
"func abc()-> Int {}\n",
"func abc() ->Int {}\n",
"func abc() -> Int {}\n",
"var abc = {(param: Int) ->Bool in }\n",
"var abc = {(param: Int)->Bool in }\n"
]
)
}
|
mit
|
b3a6326cd8b8a32f991f608305f53da9
| 32.9 | 87 | 0.523599 | 4.068 | false | false | false | false |
jevy-wangfei/FeedMeIOS
|
FeedMeIOS/Order.swift
|
1
|
3183
|
//
// Order.swift
// FeedMeIOS
//
// Created by Jun Chen on 25/03/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import Foundation
class Order {
// MARK: Properties
var userID: String?
var restaurantID: Int?
var orderTime: String?
var deliveryAddress: String?
var phoneNumber: String?
// information for all dishes in the shopping cart:
// list of all dishes:
var id2dish: [Int: Dish]
// count of every dish: Dish ID -> Dish Count:
var id2count: [Int: Int]
// total number of items:
var totalItems: Int = 0
// total number of prices:
var totalPrice: Double = 0
// MARK: Initialization
init(userID: String?, restaurantID: Int) {
self.userID = userID
self.restaurantID = restaurantID
self.id2dish = [Int: Dish]()
self.id2count = [Int: Int]()
}
// MARK: Methods
// Set the timestamp when order is conformed.
func setTime() {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
self.orderTime = dateFormatter.stringFromDate(NSDate())
}
// Set the delivery address.
func setDeliverAddress(deliveryAddress: String) {
self.deliveryAddress = deliveryAddress
}
// Set the contact phone number.
func setPhoneNumber(phoneNumber: String) {
self.phoneNumber = phoneNumber
}
// Change and set items count.
func changeItemsCount(increase: Bool, qty: Int) {
self.totalItems = increase ? self.totalItems + qty : self.totalItems - qty
}
// Change and set total price.
func changeTotalPrice(increase: Bool, amount: Double) {
self.totalPrice = increase ? self.totalPrice + amount : self.totalPrice - amount
}
// Add dish to the order.
func addDish(newDish: Dish, qty: Int = 1) {
let dishID = newDish.ID
if id2dish[dishID] != nil {
id2count[dishID] = id2count[dishID]! + qty
} else {
id2dish[dishID] = newDish
id2count[dishID] = qty
}
totalItems += qty
totalPrice += Double(newDish.price!) * Double(qty)
}
// Remove dish from the order.
func removeDish(dishID: Int, qty: Int = 1) {
totalItems -= qty
totalPrice -= Double(id2dish[dishID]!.price!) * Double(qty)
id2count[dishID] = id2count[dishID]! - qty
if id2count[dishID] == 0 {
id2dish.removeValueForKey(dishID)
id2count.removeValueForKey(dishID)
}
}
// Check if the order is empty.
func isEmptyOrder() -> Bool {
return self.totalPrice == 0
}
// Get the number of dishes group by dish.
func count() -> Int {
return self.id2count.count
}
// Get the list of all dishes.
func dishesList() -> [Dish] {
var dishesList = [Dish]()
for (_, dish) in id2dish {
dishesList += [dish]
}
return dishesList
}
// Get the Qty of a dish: Dish.
func dishQty(dish: Dish) -> Int {
return self.id2count[dish.ID]!
}
}
|
mit
|
7c6e44af11c269ae2b19bd065c80cc2f
| 25.747899 | 88 | 0.582024 | 3.89951 | false | false | false | false |
CoderFeiSu/FFCategoryHUD
|
FFCategoryHUD/FFConst.swift
|
1
|
441
|
//
// FFConst.swift
// FFCategoryHUDExample
//
// Created by 飞飞 on 2019/6/14.
// Copyright © 2019 Freedom. All rights reserved.
//
import UIKit
let kScreenW: CGFloat = UIScreen.main.bounds.width
let kScreenH: CGFloat = UIScreen.main.bounds.height
let kNavigationBarH: CGFloat = (kScreenH == 812.0 ? 88.0: 64.0)
let kStatusBarH: CGFloat = (kScreenH == 812.0 ? 44.0: 20.0)
let kTabBarH: CGFloat = (kScreenH == 812.0 ? 83.0: 49.0)
|
mit
|
24b75419923cef49111abdc31296b4d5
| 28.066667 | 63 | 0.690367 | 2.965986 | false | false | false | false |
angeldnd/dap.core.swift
|
DapCore/context/Handler.swift
|
1
|
8421
|
//
// Event.swift
// DapCore
//
// Created by YJ Park on 14/10/21.
// Copyright (c) 2014年 AngelDnD. All rights reserved.
//
import Foundation
public protocol RequestListener : class {
func onRequest(handlerPath: String, req: Data?) -> Void
}
public protocol ResponseListener : class {
func onResponse(handlerPath: String, req: Data?, res: Data?) -> Void
}
public protocol RequestHandler : class {
func doHandle(handlerPath: String, req: Data?) -> Data?
}
public final class Handler : BaseAspect {
private var _handler: RequestHandler?
public required init(entity: Entity, path: String) {
super.init(entity: entity, path: path)
}
public func setup(handler: RequestHandler) -> Bool {
if _handler == nil {
_handler = handler
return true
}
return false
}
private var _requestCheckers = [DataChecker]()
private var _requestListeners = [RequestListener]()
private var _responseListeners = [ResponseListener]()
//SILP: DECLARE_LIST(RequestChecker, checker, DataChecker, _requestCheckers)
private func getIndexOfRequestChecker(checker: DataChecker) -> Int? { //__SILP__
for (i, obj) in enumerate(_requestCheckers) { //__SILP__
if obj === checker { //__SILP__
return i //__SILP__
} //__SILP__
} //__SILP__
return nil //__SILP__
} //__SILP__
//__SILP__
public final func addRequestChecker(checker: DataChecker) -> Bool { //__SILP__
if getIndexOfRequestChecker(checker) == nil { //__SILP__
_requestCheckers.append(checker) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
//__SILP__
public final func removeRequestChecker(checker: DataChecker) -> Bool { //__SILP__
if let index = getIndexOfRequestChecker(checker) { //__SILP__
_requestCheckers.removeAtIndex(index) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
//SILP: DECLARE_LIST(RequestListener, listener, RequestListener, _requestListeners)
private func getIndexOfRequestListener(listener: RequestListener) -> Int? { //__SILP__
for (i, obj) in enumerate(_requestListeners) { //__SILP__
if obj === listener { //__SILP__
return i //__SILP__
} //__SILP__
} //__SILP__
return nil //__SILP__
} //__SILP__
//__SILP__
public final func addRequestListener(listener: RequestListener) -> Bool { //__SILP__
if getIndexOfRequestListener(listener) == nil { //__SILP__
_requestListeners.append(listener) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
//__SILP__
public final func removeRequestListener(listener: RequestListener) -> Bool { //__SILP__
if let index = getIndexOfRequestListener(listener) { //__SILP__
_requestListeners.removeAtIndex(index) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
//SILP: DECLARE_LIST(ResponseListener, listener, ResponseListener, _responseListeners)
private func getIndexOfResponseListener(listener: ResponseListener) -> Int? { //__SILP__
for (i, obj) in enumerate(_responseListeners) { //__SILP__
if obj === listener { //__SILP__
return i //__SILP__
} //__SILP__
} //__SILP__
return nil //__SILP__
} //__SILP__
//__SILP__
public final func addResponseListener(listener: ResponseListener) -> Bool { //__SILP__
if getIndexOfResponseListener(listener) == nil { //__SILP__
_responseListeners.append(listener) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
//__SILP__
public final func removeResponseListener(listener: ResponseListener) -> Bool { //__SILP__
if let index = getIndexOfResponseListener(listener) { //__SILP__
_responseListeners.removeAtIndex(index) //__SILP__
return true //__SILP__
} //__SILP__
return false //__SILP__
} //__SILP__
public final func handleRequest(req: Data?) -> Data? {
if _handler == nil {
return nil
}
for checker in _requestCheckers {
if !checker.isValid(req) {
return nil
}
}
for listener in _requestListeners {
listener.onRequest(path, req: req)
}
let res = _handler!.doHandle(path, req: req)
for listener in _responseListeners {
listener.onResponse(path, req: req, res: res)
}
return res
}
}
|
mit
|
26a202ceb32fd41e055cfdec17c393dd
| 57.881119 | 93 | 0.323435 | 7.146859 | false | false | false | false |
cwwise/CWWeChat
|
CWWeChat/ChatModule/CWChatClient/Bussiness/CWMessageDispatchManager.swift
|
2
|
3395
|
//
// CWMessageDispatchManager.swift
// CWWeChat
//
// Created by chenwei on 2017/3/26.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
/*
消息发送队列Manager
消息会生成对应的 Operation
1. 网络不通的情况,则等待
2. 如果网络通 但是xmpp链接 未链接则等待xmpp链接成功之后 重试
3. 发送消息 结果按照 XMPPStreamManagementDelegate来处理
根据xmpp返回的消息来判断 消息是否发送成功
*/
/// 消息发送管理队列
class CWMessageDispatchManager: NSObject {
/// 队列
var messageQueue: OperationQueue = OperationQueue()
// 消息队列状态
var messageQueueSuspended: Bool = false
override init() {
super.init()
messageQueue.name = "发送消息"
messageQueue.maxConcurrentOperationCount = 5
messageQueue.isSuspended = messageQueueSuspended
NotificationCenter.default.addObserver(self, selector: #selector(monitorNetworkStatus(_:)), name: kCWNetworkReachabilityNotification, object: nil)
/// 添加消息发送成功的通知
NotificationCenter.default.addObserver(forName: kCWMessageDispatchSuccessNotification, object: nil, queue: OperationQueue()) { (notication) in
if let messageIds = notication.object as? [String] {
self.sendMessageSuccess(messageIds: messageIds)
}
}
}
/// 监听网络状态和XMPP连接状态
@objc func monitorNetworkStatus(_ notification: Notification) {
guard let status = notification.object as? Bool else {
return
}
/// status = YES messageQueueSuspended = false 网络链接
// 网络连接不通的时候 将队列挂起
if status == messageQueueSuspended {
messageQueueSuspended = status
messageQueue.isSuspended = messageQueueSuspended
}
}
func sendMessage(_ message: CWMessage,
progress: CWMessageProgressBlock? = nil,
completion: CWMessageCompletionBlock? = nil) {
// 生成Operation
let operation = CWMessageDispatchOperation.operationWithMessage(message,
progress: progress,
completion: completion)
operation.local_ready = true
messageQueue.addOperation(operation)
}
// 收到消息id的通知,如果收到消息 本地没有,则不处理。
// 如果有正在发送的消息 发送成功。
func sendMessageSuccess(messageIds: [String]) {
for messageId in messageIds {
for messageOperation in messageQueue.operations {
let operation = messageOperation as! CWMessageDispatchOperation
if operation.message.messageId == messageId {
operation.messageSendCallback(true)
}
}
}
}
/**
取消所有线程
*/
func cancelAllOperation() {
messageQueue.cancelAllOperations()
}
deinit {
NotificationCenter.default.removeObserver(self)
log.debug("CWMessageDispatchManager销毁..")
}
}
|
mit
|
0c1826a47fd2d0563f6b61eea785c4b0
| 27.224299 | 154 | 0.589404 | 5.197935 | false | false | false | false |
lemberg/obd2-swift-lib
|
OBD2-Swift/Classes/Operations/CommandOperation.swift
|
1
|
2044
|
//
// CommandOperation.swift
// OBD2Swift
//
// Created by Sergiy Loza on 01.06.17.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
class CommandOperation: StreamHandleOperation {
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["readCompleted" as NSObject, "error" as NSObject]
}
private(set) var command:DataRequest
private(set) var reader: StreamReader
private var readCompleted = false {
didSet {
self.input.remove(from: .current, forMode: .defaultRunLoopMode)
self.output.remove(from: .current, forMode: .defaultRunLoopMode)
}
}
var onReceiveResponse:((_ response:Response) -> ())?
init(inputStream: InputStream, outputStream: OutputStream, command: DataRequest) {
self.command = command
self.reader = StreamReader(stream: inputStream)
super.init(inputStream: inputStream, outputStream: outputStream)
}
override var isFinished: Bool {
if error != nil {
return true
}
return readCompleted
}
override func execute() {
guard let data = command.data else { return }
let writer = StreamWriter(stream: output, data: data)
do {
try writer.write()
} catch let error {
print("Error \(error) on data writing")
self.error = InitializationError.DataWriteError
}
}
override func inputStremEvent(event: Stream.Event) {
if event == .hasBytesAvailable {
do {
if try reader.read() {
onReadEnd()
}
} catch let error {
self.error = error
}
}
}
private func onReadEnd() {
let package = Package(buffer: reader.readBuffer, length: reader.readBufferLenght)
let response = Parser.package.read(package: package)
onReceiveResponse?(response)
readCompleted = true
}
}
|
mit
|
238dcd42019f7e9ff33e3792e2f0c13c
| 28.185714 | 89 | 0.594224 | 4.795775 | false | false | false | false |
ndevenish/KerbalHUD
|
KerbalHUD/Framebuffers.swift
|
1
|
3636
|
//
// Framebuffers.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 26/08/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
import GLKit
struct Framebuffer : Equatable {
let name : GLuint
let texture : Texture
let stencil : GLuint
let size : Size2D<Int>
}
func ==(first: Framebuffer, second: Framebuffer) -> Bool {
return first.name == second.name
&& first.texture == second.texture
&& first.stencil == second.stencil
&& first.size == second.size
}
extension Framebuffer {
static var Default : Framebuffer {
return Framebuffer(name: 0, texture: Texture.None, stencil: 0, size: Size2D(w: 0,h: 0))
}
}
extension DrawingTools {
func createTextureFramebuffer(
size : Size2D<UInt>, depth: Bool, stencil : Bool) -> Framebuffer
{
return createTextureFramebuffer(size.map({Int($0)}), depth: depth, stencil: stencil)
}
func createTextureFramebuffer(
size : Size2D<Int>, depth: Bool, stencil : Bool) -> Framebuffer
{
// Generate a texture in the requested size
var texColorBuffer : GLuint = 0
glGenTextures(1, &texColorBuffer)
glBindTexture(GLenum(GL_TEXTURE_2D), texColorBuffer)
glTexImage2D(GLenum(GL_TEXTURE_2D),
0, GL_RGBA, GLint(size.w), GLint(size.h),
0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), nil)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
// Non power-of-two textures require non-wrapping settings
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_CLAMP_TO_EDGE)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_CLAMP_TO_EDGE)
let texture = Texture(glk: nil, name: texColorBuffer, target: GLenum(GL_TEXTURE_2D), size: size)
return createFramebufferForTexture(texture, addStencil: stencil)
}
func createFramebufferForTexture(texture : Texture, addStencil stencil : Bool = false) -> Framebuffer
{
guard let size = texture.size else {
fatalError("Need a size for texture to create framebuffer")
}
// Generate a framebuffer
var fb : GLuint = 0
glGenFramebuffers(1, &fb)
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), fb)
// Attach this texture to the framebuffer
glFramebufferTexture2D(GLenum(GL_FRAMEBUFFER),
GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_TEXTURE_2D),
texture.name, 0);
// Create a stencil buffer to attach, if we want it
var stencilBuffer : GLuint = 0
if stencil {
glGenRenderbuffers(1, &stencilBuffer)
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), stencilBuffer)
glRenderbufferStorage(GLenum(GL_RENDERBUFFER), GLenum(GL_STENCIL_INDEX8), GLint(size.w), GLint(size.h))
glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_STENCIL_ATTACHMENT), GLenum(GL_RENDERBUFFER), stencilBuffer)
}
if !(glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER)) == GLenum(GL_FRAMEBUFFER_COMPLETE)) {
fatalError("Framebuffer generation failed");
}
// Unbind the new framebuffer
forceBind(Framebuffer.Default)
return Framebuffer(name: fb,
texture: texture,
stencil: stencilBuffer,
size: size)
}
func deleteFramebuffer(buffer : Framebuffer, texture : Bool = true) {
var val : GLuint = 0
if buffer.stencil != 0 {
val = buffer.stencil
glDeleteFramebuffers(1, &val)
}
if texture {
deleteTexture(buffer.texture)
}
if buffer.name != 0 {
val = buffer.name
glDeleteFramebuffers(1, &val)
}
}
}
|
mit
|
13463e67e0f6f70222dabbb9f4219520
| 31.756757 | 126 | 0.686382 | 3.602577 | false | false | false | false |
hironytic/FormulaCalc
|
FormulaCalcTests/View/SheetListViewModelTests.swift
|
1
|
12031
|
//
// SheetListViewModelTests.swift
// FormulaCalcTests
//
// Copyright (c) 2017 Hironori Ichimiya <hiron@hironytic.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 XCTest
import RxSwift
@testable import FormulaCalc
class SheetListViewModelTests: XCTestCase {
class MockListStore: ISheetListStore {
let update: Observable<SheetListStoreUpdate>
let onCreateNewSheet: AnyObserver<String>
let onDeleteSheet: AnyObserver<String>
var _sheetList: [Sheet]
var _newIDCount = 0
var _update: Variable<SheetListStoreUpdate>
var _onCreateNewSheet = ActionObserver<String>()
var _onDeleteSheet = ActionObserver<String>()
init() {
let sheet0 = Sheet()
sheet0.id = "zero"
sheet0.name = "Sheet 0"
let sheet1 = Sheet()
sheet1.id = "one"
sheet1.name = "Sheet 1"
_sheetList = [sheet0, sheet1]
_update = Variable(SheetListStoreUpdate(sheetList: AnyRandomAccessCollection(_sheetList),
deletions: [],
insertions: [0, 1],
modifications: []))
update = _update.asObservable()
onCreateNewSheet = _onCreateNewSheet.asObserver()
onDeleteSheet = _onDeleteSheet.asObserver()
_onCreateNewSheet.handler = { [weak self] name in self?.handleCreateNewSheet(name: name) }
_onDeleteSheet.handler = { [weak self] id in self?.handleDeleteSheet(id: id) }
}
func handleCreateNewSheet(name: String) {
let newSheet = Sheet()
_newIDCount += 1
newSheet.id = "new_sheet_\(_newIDCount)"
newSheet.name = name
_sheetList.append(newSheet)
_update.value = SheetListStoreUpdate(sheetList: AnyRandomAccessCollection(_sheetList),
deletions: [],
insertions: [_sheetList.count - 1],
modifications: [])
}
func handleDeleteSheet(id: String) {
if let index = _sheetList.index(where: { $0.id == id }) {
_sheetList.remove(at: index)
_update.value = SheetListStoreUpdate(sheetList: AnyRandomAccessCollection(_sheetList),
deletions: [index],
insertions: [],
modifications: [])
}
}
}
class MockSheetViewModel: ISheetViewModel {
let id: String
let title = Observable<String?>.never()
let itemList = Observable<[ISheetElementViewModel]>.never()
var message = Observable<Message>.never()
let onTapDesignButton = ActionObserver<Void>().asObserver()
init(id: String) {
self.id = id
}
}
class MockLocator: SheetListViewModel.Locator {
func resolveSheetListStore() -> ISheetListStore {
return MockListStore()
}
func resolveSheetViewModel(id: String) -> ISheetViewModel {
return MockSheetViewModel(id: id)
}
}
var disposeBag: DisposeBag!
override func setUp() {
super.setUp()
disposeBag = DisposeBag()
}
override func tearDown() {
disposeBag = nil
super.tearDown()
}
func testSheetList() {
// SCENARIO:
// (1) A list of the sheets is shown and it contains two sheets.
// (2) The name of the first sheet is "Sheet 0".
let sheetListViewModel = SheetListViewModel(locator: MockLocator())
let sheetListObserver = FulfillObserver(expectation(description: "The sheet list contains two items.")) { (elementViewModels: [ISheetListElementViewModel]) in
// (1) A list of the sheets is shown and it contains two sheets.
guard elementViewModels.count == 2 else { return false }
let elementViewModel0 = elementViewModels[0]
guard elementViewModel0.id == "zero" else { return false }
let sheetTitleObserver = FulfillObserver(self.expectation(description: "Title of the sheet becomes 'Sheet 0'.")) { (title: String?) in
// (2) The name of the first sheet is "Sheet 0".
guard let title = title else { return false }
return title == "Sheet 0"
}
elementViewModel0.title
.bind(to: sheetTitleObserver)
.disposed(by: self.disposeBag)
return true
}
sheetListViewModel.sheetList
.bind(to: sheetListObserver)
.disposed(by: disposeBag)
waitForExpectations(timeout: 3.0)
}
func testOnNew() {
// SCENARIO:
// (1) New sheet button is tapped.
// (2) It asks user to input a name of new sheet.
// (3) User inputs "New Name".
// (4) New sheet is created with that name.
let sheetListViewModel = SheetListViewModel(locator: MockLocator())
sheetListViewModel.message
.subscribe(onNext: { message in
switch message {
case let transitionMessage as TransitionMessage:
guard let inputViewModel = transitionMessage.viewModel as? IInputOneTextViewModel else { break }
// (2) It asks user to input a name of new sheet.
// (3) User inputs "New Name".
inputViewModel.onDone.onNext("New Name")
inputViewModel.onDone.onCompleted()
inputViewModel.onCancel.onCompleted()
default:
break
}
}).disposed(by: disposeBag)
var sheetListDisposeBag: DisposeBag!
let expectNewSheet = expectation(description: "The new sheet name is 'New Name'")
sheetListViewModel.sheetList
.subscribe(onNext: { elementViewModels in
sheetListDisposeBag = DisposeBag()
for elementViewModel in elementViewModels {
elementViewModel.title
.subscribe(onNext: { title in
if let title = title {
if title == "New Name" {
// (4) New sheet is created with that name.
expectNewSheet.fulfill()
}
}
})
.disposed(by: sheetListDisposeBag)
}
}, onDisposed: {
sheetListDisposeBag = nil
})
.disposed(by: disposeBag)
// (1) New sheet button is tapped.
sheetListViewModel.onNew.onNext(())
waitForExpectations(timeout: 3.0)
}
func testOnDelete() {
// SCENARIO:
// (1) The list contains two sheets.
// (2) User deletes the first sheet.
// (3) The sheet is deleted and removed from the list.
let sheetListViewModel = SheetListViewModel(locator: MockLocator())
var sheetToBeRemoved: ISheetListElementViewModel?
let sheetListObserver = FulfillObserver(expectation(description: "The sheet list contains two items.")) { (elementViewModels: [ISheetListElementViewModel]) in
// (1) The list contains two sheets.
guard elementViewModels.count == 2 else { return false }
let elementViewModel0 = elementViewModels[0]
guard elementViewModel0.id == "zero" else { return false }
sheetToBeRemoved = elementViewModel0
return true
}
sheetListViewModel.sheetList
.bind(to: sheetListObserver)
.disposed(by: disposeBag)
waitForExpectations(timeout: 3.0)
sheetListObserver.reset(expectation(description: "The sheet doesn't contains Sheet 0")) { (elementViewModels: [ISheetListElementViewModel]) in
// (3) The sheet is deleted and removed from the list.
guard elementViewModels.count == 1 else { return false }
let elementViewModel0 = elementViewModels[0]
sheetToBeRemoved = elementViewModel0
guard elementViewModel0.id != "zero" else { return false }
return true
}
// (2) User deletes the first sheet.
guard let toBeRemoved = sheetToBeRemoved else { XCTFail(); return }
sheetListViewModel.onDelete.onNext(toBeRemoved)
waitForExpectations(timeout: 3.0)
}
func testOnSelect() {
// SCENARIO:
// (1) The list contains two sheets.
// (2) User selects the first sheet.
// (3) It transit to the scene whose view model is ISheetViewModel.
let sheetListViewModel = SheetListViewModel(locator: MockLocator())
var sheetToBeSelected: ISheetListElementViewModel?
let sheetListObserver = FulfillObserver(expectation(description: "The sheet list contains two items.")) { (elementViewModels: [ISheetListElementViewModel]) in
// (1) The list contains two sheets.
guard elementViewModels.count == 2 else { return false }
let elementViewModel0 = elementViewModels[0]
guard elementViewModel0.id == "zero" else { return false }
sheetToBeSelected = elementViewModel0
return true
}
sheetListViewModel.sheetList
.bind(to: sheetListObserver)
.disposed(by: disposeBag)
waitForExpectations(timeout: 3.0)
let messageObserver = FulfillObserver(expectation(description: "Scene transition")) { (message: Message) in
// (3) It transit to the scene whose view model is ISheetViewModel.
guard let transitionMessage = message as? TransitionMessage else { return false }
guard let viewModel = transitionMessage.viewModel as? MockSheetViewModel else { return false }
return viewModel.id == "zero"
}
sheetListViewModel.message
.bind(to: messageObserver)
.disposed(by: disposeBag)
// (2) User selects the first sheet.
guard let toBeSelected = sheetToBeSelected else { XCTFail(); return }
sheetListViewModel.onSelect.onNext(toBeSelected)
waitForExpectations(timeout: 3.0)
}
}
|
mit
|
c91be78e02684feed128bc82076a1afb
| 39.237458 | 166 | 0.569279 | 5.205971 | false | false | false | false |
hibu/apptentive-ios
|
Example/iOSExample/PictureManager.swift
|
1
|
3549
|
//
// PictureSource.swift
// ApptentiveExample
//
// Created by Frank Schmitt on 8/6/15.
// Copyright (c) 2015 Apptentive, Inc. All rights reserved.
//
import UIKit
import QuickLook
class PictureManager {
static let sharedManager = PictureManager()
var pictures = [Picture]()
var favoriteDataSource: PictureDataSource
var pictureDataSource: PictureDataSource
init() {
if let picturesFolderPath = NSBundle.mainBundle().pathForResource("Pictures", ofType: nil) {
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(picturesFolderPath)
while let element = enumerator?.nextObject() as? String {
let pictureURL = NSURL.fileURLWithPath(NSString(string: picturesFolderPath).stringByAppendingPathComponent(element as String))
let randomLikeCount = Int(arc4random_uniform(1000))
pictures.append(Picture(URL: pictureURL, likeCount: randomLikeCount))
}
}
self.pictureDataSource = PictureDataSource(pictures: self.pictures)
self.favoriteDataSource = PictureDataSource(pictures: [])
self.pictureDataSource.manager = self
self.favoriteDataSource.manager = self
}
func reset() {
self.favoriteDataSource.pictures = []
self.assignRandomLikes()
self.pictureDataSource.pictures = self.pictures.shuffled()
}
private func assignRandomLikes() {
self.pictures.forEach { (picture) in
picture.likeCount = Int(arc4random_uniform(1000))
}
}
private func indexOfFavorite(picture: Picture) -> Int? {
return self.favoriteDataSource.pictures.indexOf(picture)
}
func isFavorite(picture: Picture) -> Bool {
return self.indexOfFavorite(picture) != nil
}
func addFavorite(picture: Picture) {
if !self.isFavorite(picture) {
picture.likeCount += 1
self.favoriteDataSource.pictures.append(picture)
}
}
func removeFavorite(picture: Picture) {
if let index = self.indexOfFavorite(picture) {
picture.likeCount -= 1
self.favoriteDataSource.pictures.removeAtIndex(index)
}
}
}
class PictureDataSource {
var pictures: [Picture]
weak var manager: PictureManager?
init(pictures: [Picture]) {
self.pictures = pictures
}
func numberOfPictures() -> Int {
return self.pictures.count
}
func likeCountAtIndex(index: Int) -> Int {
return self.pictures[index].likeCount
}
func imageAtIndex(index: Int) -> UIImage? {
return self.pictures[index].image
}
func imageSizeAtIndex(index: Int) -> CGSize {
return self.imageAtIndex(index)?.size ?? CGSizeZero
}
func imageNameAtIndex(index: Int) -> String {
return self.pictures[index].URL.URLByDeletingPathExtension!.lastPathComponent!
}
func isLikedAtIndex(index: Int) -> Bool {
return self.manager!.isFavorite(pictures[index])
}
func setLiked(index: Int, liked: Bool) {
if liked && !self.isLikedAtIndex(index) {
self.manager!.addFavorite(self.pictures[index])
} else if !liked {
self.manager!.removeFavorite(self.pictures[index])
}
}
}
extension PictureDataSource: QLPreviewControllerDataSource {
@objc func numberOfPreviewItemsInPreviewController(controller: QLPreviewController) -> Int {
return self.numberOfPictures()
}
@objc func previewController(controller: QLPreviewController, previewItemAtIndex index: Int) -> QLPreviewItem {
return self.pictures[index]
}
}
extension Array {
func shuffled() -> [Element] {
if count < 2 {
return self
}
var list = self
for i in 0..<(list.count - 1) {
let j = Int(arc4random_uniform(UInt32(list.count - i))) + i
if i != j {
swap(&list[i], &list[j])
}
}
return list
}
}
|
bsd-3-clause
|
a7cbca369fccdccd5f169287d90f624a
| 24.170213 | 130 | 0.721893 | 3.67772 | false | false | false | false |
ztolley/VideoStationViewer
|
VideoStationViewerTests/MovieAPITest.swift
|
1
|
12401
|
import XCTest
import OHHTTPStubs
class MovieAPITest: XCTestCase {
var movieAPI = MovieAPI()
override func setUp() {
super.setUp()
let preferences: NSUserDefaults = NSUserDefaults.standardUserDefaults()
preferences.setObject("test.com", forKey: "HOSTNAME")
preferences.setObject("user", forKey: "USERID")
preferences.setObject("password", forKey: "PASSWORD")
preferences.synchronize()
}
override func tearDown() {
OHHTTPStubs.removeAllStubs()
super.tearDown()
}
func testGetMovieSummariesCallsCorrectUrl() {
let expectation = self.expectationWithDescription("testGetMovieSummariesCallsCorrectUrl")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
XCTAssertEqual(url.path!, "/webapi/VideoStation/movie.cgi")
XCTAssertEqual(url.host!, "test.com")
XCTAssertEqual(url.port!, 5000)
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movietitles.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovieTitles { (movies, total, offset,error) -> Void in
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetMovieSummariesAsksForLimitedFileds() {
let expectation = self.expectationWithDescription("testGetMovieSummariesAsksForLimitedFileds")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
if let query = url.query {
XCTAssert(query.containsString("api=SYNO.VideoStation.Movie"))
XCTAssert(query.containsString("version=2"))
XCTAssert(query.containsString("method=list"))
XCTAssert(query.containsString("offset=0"))
XCTAssert(query.containsString("limit=99999"))
XCTAssert(query.containsString("sort_by=added"))
XCTAssert(query.containsString("sort_direction=desc"))
XCTAssert(query.containsString("additional=%5B%22genre%22%2C%22summary%22%5D"))
XCTAssert(query.containsString("library_id=0"))
} else {
XCTFail()
}
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movietitles.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovieTitles { (movies, total, offset,error) -> Void in
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetMovieSummariesParsesMovies() {
let expectation = self.expectationWithDescription("testGetMovieSummariesParsesMovies")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
if url.path! == "/webapi/VideoStation/movie.cgi" {
return true
}
return false;
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movietitles.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovieTitles { (movies, total, offset,error) -> Void in
XCTAssertNotNil(movies)
XCTAssertTrue(movies!.count > 0)
let movie = movies![0]
XCTAssert(movie.title == "Get Santa")
XCTAssertEqual(1099, movie.id)
XCTAssert(movie.genre.contains("Comedy"))
XCTAssert(movie.genre.contains("Family"))
// todo check it indicates its a movie
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetMovieCallsCorrectUrl() {
let expectation = self.expectationWithDescription("testGetMovieCallsCorrectUrl")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
XCTAssertEqual(url.path!, "/webapi/VideoStation/movie.cgi")
XCTAssertEqual(url.host!, "test.com")
XCTAssertEqual(url.port!, 5000)
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movietitles.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovie(100) { (movie, error) -> Void in
NSLog(" ---------------------------------------")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetMovieAsksForAllFields() {
let expectation = self.expectationWithDescription("testGetMovieAsksForAllFields")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
if let query = url.query {
XCTAssert(query.containsString("api=SYNO.VideoStation.Movie"))
XCTAssert(query.containsString("version=2"))
XCTAssert(query.containsString("method=getinfo"))
XCTAssert(query.containsString("additional=%5B%22poster_mtime%22%2C%22summary%22%2C%22watched_ratio%22%2C%22collection%22%2C%22file%22%2C%22actor%22%2C%22write%22%2C%22director%22%2C%22genre%22%2C%22extra%22%5D"))
} else {
XCTFail()
}
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movietitles.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovie(100) { (movie, error) -> Void in
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetMovieParsesResult() {
let expectation = self.expectationWithDescription("testGetMovieParsesResult")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
if url.path! == "/webapi/VideoStation/movie.cgi" {
return true
}
return false;
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("movie.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getMovie(86) { (movie, error) -> Void in
if let movieValue = movie {
XCTAssertEqual("12 Years a Slave", movieValue.title!)
XCTAssert(movieValue.summary.characters.count > 0)
XCTAssertEqual(86, movieValue.id)
XCTAssertEqual("The extraordinary true story of Solomon Northup", movieValue.tagline)
XCTAssertEqual(42, movieValue.fileId)
XCTAssert(movieValue.genre.contains("Biography"))
XCTAssert(movieValue.genre.contains("Drama"))
XCTAssert(movieValue.genre.contains("History"))
XCTAssertEqual("Chiwetel Ejiofor", movieValue.actor[0])
XCTAssertEqual("Steve McQueen", movieValue.director[0])
} else {
XCTFail()
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetShowsAsksAPIForAllShows() {
let expectation = self.expectationWithDescription("testGetTVShows")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
XCTAssertEqual(url.path!, "/webapi/VideoStation/tvshow.cgi")
XCTAssertEqual(url.host!, "test.com")
XCTAssertEqual(url.port!, 5000)
if let query = url.query {
XCTAssert(query.containsString("api=SYNO.VideoStation.TVShow"))
XCTAssert(query.containsString("version=2"))
XCTAssert(query.containsString("method=list"))
XCTAssert(query.containsString("offset=0"))
XCTAssert(query.containsString("limit=99999"))
XCTAssert(query.containsString("sort_by=sort_title"))
XCTAssert(query.containsString("method=list"))
XCTAssert(query.containsString("additional=%5B%22summary%22%5D"))
} else {
XCTFail()
}
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("tvshows.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getTVShows { (shows, total, offset, error) -> Void in
if let showsValue = shows {
XCTAssertEqual(36, shows?.count)
let show = showsValue[35]
XCTAssertEqual("Stalker", show.title!)
XCTAssertEqual("Det", show.summary?.substringToIndex(show.summary.startIndex.advancedBy(3)))
XCTAssertEqual(275, show.id!)
XCTAssertEqual("Stalker", show.sortTitle!)
} else {
XCTFail()
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
func testGetShowEpisodeAsksAPIForEpisodesForAShow() {
let expectation = self.expectationWithDescription("testGetShowEpisodes")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
XCTAssertEqual(url.path!, "/webapi/VideoStation/tvshow_episode.cgi")
XCTAssertEqual(url.host!, "test.com")
XCTAssertEqual(url.port!, 5000)
if let query = url.query {
XCTAssert(query.containsString("tvshow_id=1"))
XCTAssert(query.containsString("api=SYNO.VideoStation.TVShow"))
XCTAssert(query.containsString("version=2"))
XCTAssert(query.containsString("method=list"))
XCTAssert(query.containsString("additional=%5B%22summary%22%2C%22file%22%2C%22actor%22%2C%22writer%22%2C%22director%22%2C%22extra%22%2C%22genre%22%2C%22collection%22%2C%22poster_mtime%22%2C%22watched_ratio%22%5D"))
} else {
XCTFail()
}
return true
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("episodes.json", self.dynamicType)!,
statusCode:200, headers:["Content-Type":"application/json"])
})
self.movieAPI.getTVShowEpisodes(118) { (episodes, error) -> Void in
if let episodesValue = episodes {
XCTAssertEqual(63, episodesValue.count)
let episode = episodesValue[0]
XCTAssertEqual("My Name Is Earl", episode.title!)
XCTAssertEqual("Very Bad Things", episode.tagline!)
XCTAssertEqual("When Joy", episode.summary?.substringToIndex(episode.summary.startIndex.advancedBy(8)))
XCTAssertEqual(118, episode.showId)
XCTAssertEqual(662, episode.id)
} else {
XCTFail()
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
}
|
gpl-3.0
|
1daba13477e3a4e1ded8f443f462a540
| 35.689349 | 229 | 0.621966 | 4.681389 | false | true | false | false |
ztolley/VideoStationViewer
|
VideoStationViewer/ImageAPI.swift
|
1
|
1671
|
import UIKit
import Alamofire
class ImageAPI {
static let sharedInstance = ImageAPI()
static var processedImageCache = NSCache()
private let preferences:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let httpManager:Alamofire.Manager = Alamofire.Manager()
func getImage(id: Int, type: String = "Movie", success: ((image: UIImage?, error: NSError?) -> Void)) {
var imageType = type.lowercaseString
if (imageType == "episode") {
imageType = "tvshow_episode"
}
func returnError() {
success(image: nil, error: NSError(domain:"com.scropt", code:1, userInfo:[NSLocalizedDescriptionKey : "Cannot Login."]))
}
let cachedImage = ImageAPI.processedImageCache.objectForKey(id) as? NSData
if let cachedImageValue = cachedImage {
guard let image = UIImage(data: cachedImageValue) else { return }
success(image: image, error: nil)
return
}
let preferences = NSUserDefaults.standardUserDefaults()
guard let hostname = preferences.stringForKey("HOSTNAME") else { return }
let parameters = [
"api" : "SYNO.VideoStation.Poster",
"version": "1",
"method": "getimage",
"id": "\(id)",
"type": imageType
]
httpManager.request(.GET, "http://\(hostname):5000/webapi/VideoStation/poster.cgi", parameters: parameters)
.response { request, response, data, error in
if error != nil {
returnError()
return
}
guard let imageData = data else {
returnError()
return
}
ImageAPI.processedImageCache.setObject(imageData, forKey: id)
guard let image = UIImage(data: imageData) else { return }
success(image: image, error: nil)
}
}
}
|
gpl-3.0
|
1410034ab687f298a48e5cd56024d24d
| 24.723077 | 124 | 0.676242 | 3.832569 | false | false | false | false |
hacktx/iOS-HackTX-2015
|
HackTX/AnnouncementsViewController.swift
|
1
|
3996
|
//
// AnnouncementsViewController.swift
// HackTX
//
// Created by Drew Romanyk on 8/15/15.
// Copyright (c) 2015 HackTX. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class AnnouncementsViewController: UITableViewController {
var announcementList = [Announcement]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTable:", name: "reloadTheTable", object: nil)
if Reachability.isConnectedToNetwork() {
print("Internet connection OK")
getAnnouncementData()
} else {
print("Internet connection FAILED")
let alert = UIAlertView(title: "No Internet Connection", message: "The HackTX app requires an internet connection to work. Talk to a volunteer about getting Internet access.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
func reloadTable(notification: NSNotification) {
if Reachability.isConnectedToNetwork() {
print("Internet connection OK")
getAnnouncementData()
} else {
print("Internet connection FAILED")
let alert = UIAlertView(title: "No Internet Connection", message: "The HackTX app requires an internet connection to work. Talk to a volunteer about getting Internet access.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
// Collect announcement data from the api
func getAnnouncementData() {
Alamofire.request(Router.Announcements())
.responseJSON{ (request, response, data) in
if data.isFailure {
let errorAlert = UIAlertView()
if errorAlert.title == "" {
errorAlert.title = "Error"
errorAlert.message = "Oops! Looks like there was a problem trying to get the announcements"
errorAlert.addButtonWithTitle("Ok")
errorAlert.show()
}
} else if let data: AnyObject = data.value {
let json = JSON(data)
self.announcementList.removeAll(keepCapacity: true)
for (_, subJson): (String, JSON) in json {
self.announcementList.insert(Announcement(text: subJson["text"].stringValue, ts: subJson["ts"].stringValue), atIndex: 0)
}
self.tableView.reloadData()
}
}
}
// Sort announcement messages by newest to oldest
func sortAnnouncements(this: Announcement, that: Announcement) -> Bool {
return this.getTsDate().compare(that.getTsDate()) == NSComparisonResult.OrderedDescending
}
// Setup Google Analytics for the controller
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: "Announcements")
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
* TABLE VIEW METHODS
*/
// Refresh the tableview data
@IBAction func refresh(sender: UIRefreshControl) {
getAnnouncementData()
sender.endRefreshing()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return announcementList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AnnouncementCell", forIndexPath: indexPath)
let announcement = announcementList[indexPath.row]
cell.textLabel!.text = announcement.text
cell.detailTextLabel!.text = announcement.getEnglishTs()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
|
mit
|
10c00d9a69ab04b16f0e77fceff6a83e
| 32.3 | 218 | 0.692943 | 4.814458 | false | false | false | false |
nalexn/ViewInspector
|
Sources/ViewInspector/SwiftUI/Alert.swift
|
1
|
11483
|
import SwiftUI
// MARK: - Alert
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct Alert: KnownViewType {
public static var typePrefix: String = ViewType.PopupContainer<Alert>.typePrefix
static var typePrefixIOS15: String = "AlertModifier"
public static var namespacedPrefixes: [String] {
[typePrefix, "SwiftUI." + typePrefixIOS15]
}
public static func inspectionCall(typeName: String) -> String {
return "alert(\(ViewType.indexPlaceholder))"
}
}
}
// MARK: - Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func alert(_ index: Int? = nil) throws -> InspectableView<ViewType.Alert> {
return try contentForModifierLookup.alert(parent: self, index: index)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension Content {
func alert(parent: UnwrappedView, index: Int?) throws -> InspectableView<ViewType.Alert> {
do {
return try popup(parent: parent, index: index,
modifierPredicate: isDeprecatedAlertPresenter(modifier:),
standardPredicate: deprecatedStandardAlertModifier)
} catch {
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *),
let alert = try? alertIOS15(parent: parent, index: index) {
return alert
} else {
throw error
}
}
}
private func deprecatedStandardAlertModifier(_ name: String = "Alert") throws -> Any {
return try self.modifier({
$0.modifierType == "IdentifiedPreferenceTransformModifier<Key>"
|| $0.modifierType.contains("AlertTransformModifier")
}, call: name.firstLetterLowercased)
}
func alertsForSearch() -> [ViewSearch.ModifierIdentity] {
let count = medium.viewModifiers
.filter { modifier in
isDeprecatedAlertPresenter(modifier: modifier)
|| isAlertIOS15(modifier: modifier)
}
.count
return Array(0..<count).map { _ in
.init(name: "", builder: { parent, index in
try parent.content.alert(parent: parent, index: index)
})
}
}
private func isDeprecatedAlertPresenter(modifier: Any) -> Bool {
let modifier = try? Inspector.attribute(
label: "modifier", value: modifier, type: BasePopupPresenter.self)
return modifier?.isAlertPresenter == true
}
// MARK: - iOS 15
var isIOS15Modifier: Bool {
let type = ViewType.PopupContainer<ViewType.Alert>.self
return (try? Inspector.cast(value: view, type: type)) == nil
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
func alertIOS15(parent: UnwrappedView, index: Int?) throws -> InspectableView<ViewType.Alert> {
let modifier = try self.modifierAttribute(
modifierLookup: isAlertIOS15(modifier:), path: "modifier",
type: Any.self, call: "alert", index: index ?? 0)
let medium = self.medium.resettingViewModifiers()
let content = Content(modifier, medium: medium)
let call = ViewType.inspectionCall(
base: ViewType.Alert.inspectionCall(typeName: ""), index: index)
let view = try InspectableView<ViewType.Alert>(
content, parent: parent, call: call, index: index)
guard try view.isPresentedBinding().wrappedValue else {
throw InspectionError.viewNotFound(parent: "Alert")
}
return view
}
private func isAlertIOS15(modifier: Any) -> Bool {
guard let modifier = modifier as? ModifierNameProvider
else { return false }
return modifier.modifierType.contains(ViewType.Alert.typePrefixIOS15)
}
}
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.Alert {
func title() throws -> InspectableView<ViewType.Text> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.Text.self)
}
func message() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 1)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func primaryButton() throws -> InspectableView<ViewType.AlertButton> {
return try View.supplementaryChildren(self).element(at: 2)
.asInspectableView(ofType: ViewType.AlertButton.self)
}
func secondaryButton() throws -> InspectableView<ViewType.AlertButton> {
return try View.supplementaryChildren(self).element(at: 3)
.asInspectableView(ofType: ViewType.AlertButton.self)
}
func dismiss() throws {
do {
let container = try Inspector.cast(
value: content.view, type: ViewType.PopupContainer<ViewType.Alert>.self)
container.presenter.dismissPopup()
} catch {
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *),
let binding = try? isPresentedBinding() {
binding.wrappedValue = false
} else {
throw error
}
}
}
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public extension InspectableView where View == ViewType.Alert {
func actions() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 2)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.Alert: SupplementaryChildren {
static func supplementaryChildren(_ parent: UnwrappedView) throws -> LazyGroup<SupplementaryView> {
let iOS15Modifier = parent.content.isIOS15Modifier
return .init(count: iOS15Modifier ? 3 : 4) { index in
let medium = parent.content.medium.resettingViewModifiers()
switch index {
case 0:
let path = iOS15Modifier ? "title" : "popup|title"
let view = try Inspector.attribute(path: path, value: parent.content.view)
let content = try Inspector.unwrap(content: Content(view, medium: medium))
return try InspectableView<ViewType.Text>(content, parent: parent, call: "title()")
case 1:
let path = iOS15Modifier ? "message" : "popup|message"
do {
let view = try Inspector.attribute(path: path, value: parent.content.view)
let content = try Inspector.unwrap(content: Content(view, medium: medium))
return try InspectableView<ViewType.ClassifiedView>(
content, parent: parent, call: "message()")
} catch {
if let inspError = error as? InspectionError,
case .viewNotFound = inspError {
throw InspectionError.viewNotFound(parent: "message")
}
throw error
}
case 2:
if iOS15Modifier {
let view = try Inspector.attribute(path: "actions", value: parent.content.view)
let content = try Inspector.unwrap(content: Content(view, medium: medium))
return try InspectableView<ViewType.ClassifiedView>(
content, parent: parent, call: "actions()")
}
let view = try Inspector.attribute(path: "popup|primaryButton", value: parent.content.view)
let content = try Inspector.unwrap(content: Content(view, medium: medium))
return try InspectableView<ViewType.AlertButton>(
content, parent: parent, call: "primaryButton()")
default:
let maybeView = try Inspector.attribute(
path: "popup|secondaryButton", value: parent.content.view, type: Alert.Button?.self)
guard let view = maybeView else {
throw InspectionError.viewNotFound(parent: "secondaryButton")
}
let content = try Inspector.unwrap(content: Content(view, medium: medium))
return try InspectableView<ViewType.AlertButton>(
content, parent: parent, call: "secondaryButton()")
}
}
}
}
// MARK: - AlertButton
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct AlertButton: KnownViewType {
public static var typePrefix: String = "Alert.Button"
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension SwiftUI.Alert.Button: CustomViewIdentityMapping {
var viewTypeForSearch: KnownViewType.Type { ViewType.AlertButton.self }
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.AlertButton: SupplementaryChildren {
static func supplementaryChildren(_ parent: UnwrappedView) throws -> LazyGroup<SupplementaryView> {
return .init(count: 1) { _ in
let child = try Inspector.attribute(path: "label", value: parent.content.view)
let medium = parent.content.medium.resettingViewModifiers()
let content = try Inspector.unwrap(content: Content(child, medium: medium))
return try InspectableView<ViewType.Text>(content, parent: parent, call: "labelView()")
}
}
}
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension Alert.Button {
enum Style: String {
case `default`, cancel, destructive
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.AlertButton {
func labelView() throws -> InspectableView<ViewType.Text> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.Text.self)
}
func style() throws -> Alert.Button.Style {
let value = try Inspector.attribute(label: "style", value: content.view)
let stringValue = String(describing: value)
guard let style = Alert.Button.Style(rawValue: stringValue) else {
throw InspectionError.notSupported("Unknown Alert.Button.Style: \(stringValue)")
}
return style
}
func tap() throws {
guard let container = self.parentView?.content.view,
let presenter = try? Inspector.attribute(
label: "presenter", value: container,
type: BasePopupPresenter.self)
else { throw InspectionError.parentViewNotFound(view: "Alert.Button") }
presenter.dismissPopup()
typealias Callback = () -> Void
let callback = try Inspector
.attribute(label: "action", value: content.view, type: Callback.self)
callback()
}
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
private extension InspectableView where View == ViewType.Alert {
func isPresentedBinding() throws -> Binding<Bool> {
return try Inspector.attribute(
label: "isPresented", value: content.view, type: Binding<Bool>.self)
}
}
|
mit
|
97cd9b081a728c37ebb053699c86abd2
| 39.433099 | 107 | 0.616477 | 4.591363 | false | false | false | false |
Doracool/UITableView1204
|
MyPlayground.playground/Contents.swift
|
1
|
664
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let myValue:Float = 4
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
let apples = 2
let aranges = 4
let appleSummary = "I have \(apples) apples"
let fruitSummary = "I have \(apples + aranges) pieces of fruit"
let name = "Lihua"
let number:Float = 3
let hello = "My name is \(name) I have \(number) apple"
var shoopingList = ["cat","water","tulips","blue"]
shoopingList[1] = "bottle of water"
var occcupations = [
"Malcolm":"Captain",
"Kaylee":"Mechanic",
]
occcupations["Jayne"] = "Public Relations"
occcupations["Kaylee"]
|
mit
|
620f3c292f0e037408d48e92fec0b90a
| 19.121212 | 63 | 0.688253 | 2.990991 | false | false | false | false |
zehrer/SOGraphDB
|
Sources/SOGraphDB_old/Stores_OLD/ValueStore.swift
|
1
|
10583
|
//
// ValueStore.swift
// SOGraphDB
//
// Created by Stephan Zehrer on 23.06.15.
// Copyright © 2015 Stephan Zehrer. All rights reserved.
//
import Foundation
public typealias UID = Int // UInt32 don't save to much memory at the moment
public protocol Identiy {
var uid: UID? {set get} //identity
init (uid aID : UID)
}
/**
extension Identiy {
// MARK: Hashable
public var hashValue: Int {
get {
if uid != nil {
return uid!.hashValue
}
return 0
}
}
}
extension Identiy {
public init (uid aID : UID) {
uid = aID
}
}
*/
// TODO: test without codeing
public protocol SizeTest : Coding {
static func generateSizeTestInstance() -> Self
}
extension SizeTest {
static func calculateDataSize(_ encoder : SOEncoder) -> Int {
let value = generateSizeTestInstance()
encoder.reset()
encoder.encode(value)
return encoder.length
}
}
public protocol ValueStoreElement : Identiy, SizeTest {
//var dirty: Bool {get set}
}
open class ValueStore<V: ValueStoreElement> {
var url: URL
var fileHandle: FileHandle
var newFile = false
let fileOffset = 1 // see createNewFile
var endOfFile : CUnsignedLongLong = 0
var encoder : SOEncoder
var decoder = SODecoder()
// UInt8 = size of type of boolean (used flag)
let blockSize : Int
// this set contails a collection of block POS in the file which are not used
var unusedDataSegments = Set<CUnsignedLongLong>()
// Throws
public init(url aURL: URL) throws {
self.url = aURL;
let encoder = SOEncoder()
self.encoder = encoder
let dataSize = V.calculateDataSize(encoder)
self.blockSize = MemoryLayout<UInt8>.size + dataSize
if !url.isFileExisting() {
// file does NOT exist
do {
let data = ValueStore.createFileHeader()
try data.write(to: self.url, options: NSData.WritingOptions.atomic)
self.newFile = true
} catch {
fileHandle = FileHandle.nullDevice
throw error
}
}
do {
self.fileHandle = try FileHandle(forUpdating: url)
} catch {
fileHandle = FileHandle.nullDevice
throw error
}
self.endOfFile = self.fileHandle.seekToEndOfFile()
// central check of there store need an init
// or a existing store need to read configuration
if newFile {
initStore()
} else {
readStoreConfiguration()
}
}
// possible to override in subclasses
// - create a new file
// - update fileOffset the default value is wrong
class func createFileHeader() -> Data {
let firstChar = "X"
// tested code
return firstChar.data(using: String.Encoding.utf8)!
}
// subclasses should overide this method
// Create a block with the ID:0
// ID 0 is not allowd to use in the store because
open func initStore() {
//registerBlock()
// store SampleData as ID:0 in the file
// ID:0 is a reserved ID and should not be availabled for public access
//let block = Block(used: false)
//self.writeBlock(block)
//var sampleData = O()
//sampleData.uid = 0
//let emptyData = NSMutableData(length: V.dataSize())
//self.write(emptyData!)
}
// precondition: self.endOfFile is correct
func readStoreConfiguration() {
var pos = calculatePos(1)
self.fileHandle.seek(toFileOffset: pos)
while (pos < self.endOfFile) {
// reade the complete file
//var header = readHeader()
let data = readBlockData()
decoder.resetData(data)
let used : Bool = decoder.decode()
//let index = calculateID(pos)
if used {
//analyseUsedBlock(block!, forUID: index)
} else {
// add pos into the special dictionary
unusedDataSegments.insert(pos)
}
/**
let data = self.fileHandle.readDataOfLength(dataSize)
if block.used {
analyseUsedData(data, forUID: index)
}
*/
pos = self.fileHandle.offsetInFile
}
}
//---------------------------------------------------------------------------------------------------------
//MARK: Value
//---------------------------------------------------------------------------------------------------------
/**
subscript(index: UID) -> O! {
get {
return self.readObject(index)
}
set {
let pos = calculatePos(index)
if (newValue != nil) {
// TODO: Check index and object UID
updateObject(newValue)
} else {
// newValue = nil -> delete
deleteObject(index)
}
}
}
*/
open func registerValue() -> UID {
let pos = self.registerBlock()
return self.calculateID(pos)
}
open func createValue() -> V {
let uid = registerValue()
let result = V(uid: uid)
return result
}
/**
public func addValue(value: V) -> UID {
let pos = registerBlock()
let uid = calculateID(pos)
self.writeBlock(aObj, atPos: pos)
value.uid = uid
value.dirty = false
//cache.setObject(aObj, forKey: uid)
return uid
}*/
open func readValue(_ index : UID) -> V? {
self.seekToFileID(index)
let data = readBlockData()
if data.count > 0 {
decoder.resetData(data)
let used : Bool = decoder.decode()
if used {
let result : V? = decoder.decode()
if var result = result {
result.uid = index
}
return result
}
}
return nil
}
open func updateValue(_ value: V) {
if value.uid != nil {
let pos = calculatePos(value.uid!)
writeBlock(value, atPos: pos)
} else {
assertionFailure("ID is missing")
}
}
open func delete(_ value : V) {
if value.uid != nil {
deleteBlock(value.uid!)
//aObj.uid = nil;
} else {
assertionFailure("ID is missing")
}
}
//---------------------------------------------------------------------------------------------------------
//MARK: BLOCK
//---------------------------------------------------------------------------------------------------------
func readBlockData() -> Data {
return self.fileHandle.readData(ofLength: blockSize);
}
func registerBlock() -> CUnsignedLongLong {
var pos: CUnsignedLongLong? = nil
if !unusedDataSegments.isEmpty {
pos = unusedDataSegments.first
}
if pos != nil {
unusedDataSegments.remove(pos!)
} else {
pos = self.extendFile()
}
return pos!;
}
func writeBlock(_ value: V, atPos pos: CUnsignedLongLong) {
fileHandle.seek(toFileOffset: pos)
encodeHeader(true)
encoder.encode(value)
if encoder.length > blockSize {
assertionFailure("ERROR: blocksize is to small")
}
write(encoder.output as Data)
}
func deleteBlock(_ aID: UID) -> CUnsignedLongLong {
let pos = self.seekToFileID(aID)
encodeHeader(false)
write(encoder.output as Data)
self.unusedDataSegments.remove(pos)
return pos
}
func encodeHeader(_ used : Bool) {
encoder.reset()
encoder.encode(used)
}
/**
public func createBlock(data: O) -> UID {
let pos = registerBlock()
writeBlock(data, atPos: pos)
return calculateID(pos)
}
func writeBlock(aObj: O, atPos pos: CUnsignedLongLong) {
fileHandle.seekToFileOffset(pos)
let block = Block(obj: aObj)
writeBlock(block)
}
func writeBlock(block: Block) {
let data = FastCoder.dataWithRootObject(block)
if data != nil {
if data!.length > blockSize {
assertionFailure("ERROR: blocksize is to small")
}
write(data!)
} else {
assertionFailure("NSData is nil")
}
}
*/
//---------------------------------------------------------------------------------------------------------
//MARK: File Methode
//---------------------------------------------------------------------------------------------------------
// #pragma mark - register and endofFile
// used to write header and data
func write(_ data: Data) {
self.fileHandle.write(data);
}
func seekEndOfFile() -> CUnsignedLongLong {
return self.fileHandle.seekToEndOfFile()
}
// increase the virtual EndOfFile pointer by on dataSize
func extendFile() -> CUnsignedLongLong {
let pos = self.endOfFile
self.endOfFile += CUnsignedLongLong(blockSize)
return pos;
}
func calculatePos(_ aID: UID) -> CUnsignedLongLong {
return CUnsignedLongLong((aID * self.blockSize) + self.fileOffset)
}
func calculateID(_ pos: CUnsignedLongLong) -> UID {
let result = (Int(pos) - self.fileOffset) / self.blockSize;
return result
}
func seekToFileID(_ aID: UID) -> CUnsignedLongLong {
let pos = self.calculatePos(aID)
self.fileHandle.seek(toFileOffset: pos)
return pos
}
}
|
mit
|
ae4987b91ddc605f96a6e41047b4d5df
| 22.887133 | 111 | 0.478265 | 5.2231 | false | false | false | false |
wenbobao/SwiftStudy
|
Day0517.playground/Contents.swift
|
1
|
9622
|
//: Playground - noun: a place where people can play
// From 108 页
import UIKit
//switch 每一个 case 分支都必须包含至少一条语句
//一个 case 也可以包含多个模式,用逗号把它们分开
//case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用 了——这种行为被称为值绑定(value binding)。
//在值绑定中,如果匹配了所有情况,不用再写默认分支
//---------------------------控制转移语句------------------------
// continue
//continue 语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已 经执行完了”,但是并不会离开整个循环体。
// swift 的switch case 不需要break,如果你需要case 完成后继续执行,可以用 fallthrough
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
case 4:
description += " A"
fallthrough
default:
description += " an integer."
}
print(description)
//注意: fallthrough 关键字不会检查它下一个将会落入执行的 case 中的匹配条件。 fallthrough 简单地使代 码执行继续连接到下一个 case 中的执行代码,这和 C 语言标准中的 switch 语句特性是一样的。
//---------------------------guard------------------------
//使用 guard 语句来要求条件必须为真 时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 分句,如果条件不为真则执 行 else 分句中的代码。
//guard let location = person["location"] else {
// print("I hope the weather is nice near you.")
// return
//}
//---------------------------检测 API 可用性------------------------
if #available(iOS 9 ,OSX 10.10,*){
// 在 iOS 使用 iOS 9 的 API, 在 OS X 使用 OS X v10.10 的 API
}else{
// 使用先前版本的 iOS 和 OS X 的 API
}
//---------------------------函数------------------------
func sayHello(personName: String) -> String {
return "hello " + personName
}
sayHello("bob")
func sayHelloWorld() -> String{
return "hello world !"
}
sayHelloWorld()
func sayHello(personName: String,age: Int) -> String {
return "hello " + personName + " age :" + String(age)
}
//当调用超过一个参数的函数时,第一个参数后的参数根据其对应的参数名称标记
sayHello("bob", age: 13)
func sayHelloVoid(name:String){
print("hello + \(name)")
}
sayHelloVoid("bob")
//多重返回值函数
//返回元组
func minMax(array:[Int]) ->(min:Int,max:Int){
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count]{
if value < currentMin{
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return (currentMin,currentMax)
}
minMax([5,9,7,8,4]).0
minMax([5,9,7,8,4]).max
//minMax([]) 会报错
//可选元组返回类型
// 如果函数返回的元组类型有可能整个元组都“没有值”,你可以使用可选的(Optional) 元组返回类型反映整个 元组可以是 nil 的事实。你可以通过在元组类型的右括号后放置一个问号来定义一个可选元组,例如 (Int, Int)? 或 (String, Int, Bool)?
//注意 可选元组类型如 (Int, Int)? 与元组包含可选类型如 (Int?, Int?) 是不同的.可选的元组类型,整个元组是可选 的,而不只是元组中的每个元素值。
func minMax2(array:[Int]) ->(min:Int,max:Int)?{
if array.isEmpty{
return nil
}
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count]{
if value < currentMin{
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return (currentMin,currentMax)
}
if let bounds = minMax2([4,5]){
print(bounds.max)
}
//函数参数名称
//func sayHello(personName: String,age: Int) -> String {
// return "hello " + personName + " age :" + String(age)
//}
// personName 省略外部参数名 age 用局部参数名 作为外部参数名
// 指定外部参数名
//注 : 如果你提供了外部参数名,那么函数在被调用时,必须使用外部参数名。
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
//如果你不想为第二个及后续的参数设置外部参数名,用一个下划线( _ )代替一个明确的参数名。
func sayHello( person: String, _ anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello("bob", "hello"))
//注 : 因为第一个参数默认忽略其外部参数名称,显式地写下划线是多余的。
//默认参数值
func someFoundation (paragrams : Int = 8){
print(paragrams)
}
someFoundation(10)
someFoundation()
//可变参数
// 一个 可变参数(variadic parameter) 可以接受零个或多个值
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers{
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(4,5,6)
//一个函数最多只能有一个可变参数
//如果函数有一个或多个带默认值的参数,而且还有一个可变参数,那么把可变参数放在参数表的最后
//常量参数和变量参数
//函数参数默认是常量 , 试图在函数体中更改参数值将会导致编译错误。这意味着你不能错误地更改参数值
func alignLeft(aa: String, totalLength: Int, pad: Character) -> String
{
var string = aa
let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + string
}
return string
}
func alignRight(var string: String, totalLength: Int, pad: Character) -> String {
let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, totalLength: 10, pad: "-")
let paddedString2 = alignLeft(originalString, totalLength: 10, pad: "-")
//对变量参数所进行的修改在函数调用结束后便消失了,并且对于函数体外是不可见的。变量参数仅仅存在于函数调用的生命周期中。
//输入输出参数
//变量参数,正如上面所述,仅仅能在函数体内被更改。如果你想要一个函数可以修改参数的值,并且想要在这些 修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数(In-Out Parameters)
//定义一个输入输出参数时,在参数定义前加 inout 关键字。
//函数类型
func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
return a * b
}
func printHelloWorld() {
print("hello, world")
}
var mathFunction :(Int,Int)->Int = addTwoInts
mathFunction(2,3)
//---------------------------闭包------------------------ 133 页
//闭包表达式
//---------------------------类和结构体------------------------ 151 页
//定义语法
// 首字母大写
class SomeClass{
}
struct SomeStructure {
}
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
//类和结构体的实例
let someVideoMode = VideoMode()
//结构体类型的成员逐一构造器
let vga = Resolution(width: 5, height: 5)
var cinema = vga //vga 和cinema 是两个完全不同的实例 但是值相同
//结构体和枚举是值类型
//值类型被赋予给一个变量、常量或者被传递给一个函数的时候,其值会被拷贝。
//在 Swift 中,所有的基本类型:整数(Integer)、浮 点数(floating-point)、布尔值(Boolean)、字符串(string)、数组(array)和字典(dictionary),都是 值类型,并且在底层都是以结构体的形式所实现。
//类是引用类型
//与值类型不同,引用类型在被赋予到一个变量、常量或者被传递到一个函数时,其值不会被拷贝。因此,引用的是已存在的实例本身而不是其拷贝。
let tenEighty = VideoMode()
tenEighty.resolution = vga
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same Resolution instance.")
}
//tenEighty & alsoTenEighty 是 同一个实例的两种叫法
//需要注意的是 tenEighty 和 alsoTenEighty 被声明为常量而不是变量。然而你依然可以改变 tenEighty.frameRate 和 alsoTenEighty.frameRate ,因为 tenEighty 和 alsoTenEighty 这两个常量的值并未改变。它们并不“存储”这 个 VideoMode 实例,而仅仅是对 VideoMode 实例的引用。所以,改变的是被引用的 VideoMode 的 frameRate 属 性,而不是引用 VideoMode 的常量的值。
//“等价于”(用三个等号表示, === )与“等于”(用两个等号表示, == )的不同:
// End 159 页
|
mit
|
50b64381289d49c1a02bcf35aa9e4794
| 20.845912 | 252 | 0.653038 | 3.010837 | false | false | false | false |
roambotics/swift
|
stdlib/public/core/CTypes.swift
|
1
|
9710
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
#if os(Windows) && (arch(x86_64) || arch(arm64))
public typealias CUnsignedLong = UInt32
#else
public typealias CUnsignedLong = UInt
#endif
/// The C 'unsigned long long' type.
public typealias CUnsignedLongLong = UInt64
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && (arch(x86_64) || arch(arm64))
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
public typealias CLongLong = Int64
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
/// The C '_Float16' type.
@available(SwiftStdlib 5.3, *)
public typealias CFloat16 = Float16
#endif
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
/// The C 'long double' type.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// On Darwin, long double is Float80 on x86, and Double otherwise.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#else
public typealias CLongDouble = Double
#endif
#elseif os(Windows)
// On Windows, long double is always Double.
public typealias CLongDouble = Double
#elseif os(Linux)
// On Linux/x86, long double is Float80.
// TODO: Fill in definitions for additional architectures as needed. IIRC
// armv7 should map to Double, but arm64 and ppc64le should map to Float128,
// which we don't yet have in Swift.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#endif
// TODO: Fill in definitions for other OSes.
#if arch(s390x)
// On s390x '-mlong-double-64' option with size of 64-bits makes the
// Long Double type equivalent to Double type.
public typealias CLongDouble = Double
#endif
#elseif os(Android)
// On Android, long double is Float128 for AAPCS64, which we don't have yet in
// Swift (https://github.com/apple/swift/issues/51573); and Double for ARMv7.
#if arch(arm)
public typealias CLongDouble = Double
#endif
#elseif os(OpenBSD)
public typealias CLongDouble = Float80
#endif
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = Unicode.Scalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = Unicode.Scalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@frozen
public struct OpaquePointer {
@usableFromInline
internal var _rawValue: Builtin.RawPointer
@usableFromInline @_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension OpaquePointer: Equatable {
@inlinable // unsafe-performance
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension OpaquePointer: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue)))
}
}
extension OpaquePointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
/// A wrapper around a C `va_list` pointer.
#if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: (__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32)
@inlinable // unsafe-performance
public // @testable
init(__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32) {
_value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off)
}
}
extension CVaListPointer: CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_value.__stack.debugDescription), " +
"\(_value.__gr_top.debugDescription), " +
"\(_value.__vr_top.debugDescription), " +
"\(_value.__gr_off), " +
"\(_value.__vr_off))"
}
}
#else
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: UnsafeMutableRawPointer
@inlinable // unsafe-performance
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
_value = from
}
}
extension CVaListPointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _value.debugDescription
}
}
#endif
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` should not overlap.
@inlinable
internal func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` may overlap.
@inlinable
internal func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
|
apache-2.0
|
4403bc1721fff65dd6bcda03acb5f592
| 28.969136 | 84 | 0.671164 | 3.995885 | false | false | false | false |
zhangjk4859/animal-plant_pool
|
animal-plant_pool/animal-plant_pool/消息/Controller/subController/LikeTableVC.swift
|
1
|
3166
|
//
// LikeTableVC.swift
// animal-plant_pool
//
// Created by 张俊凯 on 2017/2/16.
// Copyright © 2017年 张俊凯. All rights reserved.
//
import UIKit
class LikeTableVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
tableView.backgroundColor = UIColor.green
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
04b52074361d9b6b7941483da8512761
| 31.822917 | 136 | 0.668359 | 5.269231 | false | false | false | false |
sora0077/DribbbleKit
|
DribbbleKit/Sources/Users/Followers/ListUserFollowing.swift
|
1
|
1877
|
//
// ListUserFollowing.swift
// DribbbleKit
//
// Created by 林 達也 on 2017/04/26.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
import Alter
// MARK: - ListUserFollowings
public struct ListUserFollowing<Data: FollowerData, User: UserData>: PaginatorRequest {
public typealias Element = (data: Data, followee: User)
public let path: String
public let parameters: Any?
public init(id: User.Identifier, page: Int? = nil, perPage: Int? = configuration?.perPage) {
path = "/users/\(id.value)/following"
parameters = [
"page": page,
"per_page": perPage].cleaned
}
public init(path: String, parameters: [String : Any]) throws {
self.path = path
self.parameters = parameters
}
public func responseElements(from objects: [Any], meta: Meta) throws -> [(data: Data, followee: User)] {
return try objects.map {
try (decode($0), decode($0, rootKeyPath: "followee"))
}
}
}
// MARK: - ListAuthenticatedUserFollowing
public struct ListAuthenticatedUserFollowing<Data: FollowerData, User: UserData>: PaginatorRequest {
public typealias Element = (data: Data, followee: User)
public let path: String
public let parameters: Any?
public init(page: Int? = nil, perPage: Int? = configuration?.perPage) {
path = "/users/following"
parameters = [
"page": page,
"per_page": perPage].cleaned
}
public init(path: String, parameters: [String : Any]) throws {
self.path = path
self.parameters = parameters
}
public func responseElements(from objects: [Any], meta: Meta) throws -> [(data: Data, followee: User)] {
return try objects.map {
try (decode($0), decode($0, rootKeyPath: "followee"))
}
}
}
|
mit
|
ed07db8712e78b22e910061c8791a7a9
| 28.650794 | 108 | 0.627944 | 4.04329 | false | false | false | false |
FabrizioBrancati/BFKit-Swift
|
Sources/BFKit/Apple/UIKit/UIView+Extensions.swift
|
1
|
23217
|
//
// UIView+Extensions.swift
// BFKit-Swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2019 Fabrizio Brancati.
//
// 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
import Foundation
import QuartzCore
import UIKit
// MARK: - UIView extension
/// This extesion adds some useful functions to UIView.
public extension UIView {
// MARK: - Variables
/// Direction of flip animation.
enum UIViewAnimationFlipDirection: String {
/// Flip animation from top.
case top = "fromTop"
/// Flip animation from left.
case left = "fromLeft"
/// Flip animation from right.
case right = "fromRight"
/// Flip animation from bottom.
case bottom = "fromBottom"
}
/// Direction of the translation.
enum UIViewAnimationTranslationDirection: Int {
/// Translation from left to right.
case leftToRight
/// Translation from right to left.
case rightToLeft
}
/// Direction of the linear gradient.
enum UIViewGradientDirection {
/// Linear gradient vertical.
case vertical
/// Linear gradient horizontal.
case horizontal
/// Linear gradient from left top to right down.
case diagonalLeftTopToRightDown
/// Linear gradient from left down to right top.
case diagonalLeftDownToRightTop
/// Linear gradient from right top to left down.
case diagonalRightTopToLeftDown
/// Linear gradient from right down to left top.
case diagonalRightDownToLeftTop
/// Custom gradient direction.
case custom(startPoint: CGPoint, endPoint: CGPoint)
}
/// Type of gradient.
enum UIViewGradientType {
/// Linear gradient.
case linear
/// Radial gradient.
case radial
}
// MARK: - Functions
/// Create an UIView with the given frame and background color.
///
/// - Parameters:
/// - frame: UIView frame.
/// - backgroundColor: UIView background color.
convenience init(frame: CGRect, backgroundColor: UIColor) {
self.init(frame: frame)
self.backgroundColor = backgroundColor
}
/// Creates a border around the UIView.
///
/// - Parameters:
/// - color: Border color.
/// - radius: Border radius.
/// - width: Border width.
func border(color: UIColor, radius: CGFloat, width: CGFloat) {
layer.borderWidth = width
layer.cornerRadius = radius
layer.shouldRasterize = false
layer.rasterizationScale = 2
clipsToBounds = true
layer.masksToBounds = true
let cgColor: CGColor = color.cgColor
layer.borderColor = cgColor
}
/// Removes border around the UIView.
func removeBorder(maskToBounds: Bool = true) {
layer.borderWidth = 0
layer.cornerRadius = 0
layer.borderColor = nil
layer.masksToBounds = maskToBounds
}
/// Set the corner radius of UIView only at the given corner.
/// Currently doesn't support `frame` property changes.
/// If you change the frame, you have to call this function again.
///
/// - Parameters:
/// - corners: Corners to apply radius.
/// - radius: Radius value.
func cornerRadius(corners: UIRectCorner, radius: CGFloat) {
if #available(iOS 11, *) {
var cornerMask: CACornerMask = []
if corners.contains(.allCorners) {
cornerMask = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
} else {
if corners.contains(.bottomLeft) {
cornerMask.update(with: .layerMinXMaxYCorner)
}
if corners.contains(.bottomRight) {
cornerMask.update(with: .layerMaxXMaxYCorner)
}
if corners.contains(.topLeft) {
cornerMask.update(with: .layerMinXMinYCorner)
}
if corners.contains(.topRight) {
cornerMask.update(with: .layerMaxXMinYCorner)
}
}
layer.cornerRadius = radius
layer.masksToBounds = true
layer.maskedCorners = cornerMask
} else {
let rectShape = CAShapeLayer()
rectShape.bounds = frame
rectShape.position = center
rectShape.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
layer.mask = rectShape
}
}
/// Set the corner radius of UIView for all corners.
/// This function supports `frame` property changes,
/// it's different from `cornerRadius(corners: UIRectCorner, radius: CGFloat)`
/// that doesn't support it.
///
/// - Parameter radius: Radius value.
func cornerRadius(_ radius: CGFloat) {
layer.cornerRadius = radius
layer.masksToBounds = true
}
/// Create a shadow on the UIView.
///
/// - Parameters:
/// - offset: Shadow offset.
/// - opacity: Shadow opacity.
/// - radius: Shadow radius.
/// - color: Shadow color. Default is black.
func shadow(offset: CGSize, opacity: Float, radius: CGFloat, cornerRadius: CGFloat = 0, color: UIColor = UIColor.black) {
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offset
layer.shadowRadius = radius
if cornerRadius != 0 {
layer.cornerRadius = cornerRadius
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
}
layer.masksToBounds = false
}
/// Removes shadow around the UIView.
func removeShadow(maskToBounds: Bool = true) {
layer.shadowColor = nil
layer.shadowOpacity = 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 0
layer.cornerRadius = 0
layer.shadowPath = nil
layer.masksToBounds = maskToBounds
}
/// Create a linear gradient.
///
/// - Parameters:
/// - colors: Array of UIColor instances.
/// - direction: Direction of the gradient.
/// - Returns: Returns the created CAGradientLayer.
@discardableResult
func gradient(colors: [UIColor], direction: UIViewGradientDirection) -> CAGradientLayer {
let gradient = CAGradientLayer()
gradient.frame = bounds
var mutableColors: [Any] = colors
for index in 0 ..< colors.count {
let currentColor: UIColor = colors[index]
mutableColors[index] = currentColor.cgColor
}
gradient.colors = mutableColors
switch direction {
case .vertical:
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
case .horizontal:
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
case .diagonalLeftTopToRightDown:
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
case .diagonalLeftDownToRightTop:
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 0.0)
case .diagonalRightTopToLeftDown:
gradient.startPoint = CGPoint(x: 1.0, y: 0.0)
gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
case .diagonalRightDownToLeftTop:
gradient.startPoint = CGPoint(x: 1.0, y: 1.0)
gradient.endPoint = CGPoint(x: 0.0, y: 0.0)
case let .custom(startPoint, endPoint):
gradient.startPoint = startPoint
gradient.endPoint = endPoint
}
layer.insertSublayer(gradient, at: 0)
return gradient
}
/// Create a smooth linear gradient, requires more computational time than
///
/// gradient(colors:,direction:)
///
/// - Parameters:
/// - colors: Array of UIColor instances.
/// - direction: Direction of the gradient.
func smoothGradient(colors: [UIColor], direction: UIViewGradientDirection, type: UIViewGradientType = .linear) {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIImage.screenScale())
guard let context = UIGraphicsGetCurrentContext() else {
return
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
var locations: [CGFloat] = [0.0, 1.0]
var components: [CGFloat] = []
for (index, color) in colors.enumerated() {
if index != 0 && index != 1 {
locations.insert(CGFloat(Float(1) / Float(colors.count - 1)), at: 1)
}
components.append(color.redComponent)
components.append(color.greenComponent)
components.append(color.blueComponent)
components.append(color.alpha)
}
var startPoint: CGPoint
var endPoint: CGPoint
switch direction {
case .vertical:
startPoint = CGPoint(x: bounds.midX, y: 0.0)
endPoint = CGPoint(x: bounds.midX, y: bounds.height)
case .horizontal:
startPoint = CGPoint(x: 0.0, y: bounds.midY)
endPoint = CGPoint(x: bounds.width, y: bounds.midY)
case .diagonalLeftTopToRightDown:
startPoint = CGPoint(x: 0.0, y: 0.0)
endPoint = CGPoint(x: bounds.width, y: bounds.height)
case .diagonalLeftDownToRightTop:
startPoint = CGPoint(x: 0.0, y: bounds.height)
endPoint = CGPoint(x: bounds.width, y: 0.0)
case .diagonalRightTopToLeftDown:
startPoint = CGPoint(x: bounds.width, y: 0.0)
endPoint = CGPoint(x: 0.0, y: bounds.height)
case .diagonalRightDownToLeftTop:
startPoint = CGPoint(x: bounds.width, y: bounds.height)
endPoint = CGPoint(x: 0.0, y: 0.0)
case let .custom(customStartPoint, customEndPoint):
startPoint = customStartPoint
endPoint = customEndPoint
}
guard let gradient = CGGradient(colorSpace: colorSpace, colorComponents: components, locations: locations, count: locations.count) else {
return
}
switch type {
case .linear:
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation)
case .radial:
context.drawRadialGradient(gradient, startCenter: startPoint, startRadius: 0.0, endCenter: endPoint, endRadius: 1.0, options: .drawsBeforeStartLocation)
}
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
UIGraphicsEndImageContext()
return
}
UIGraphicsEndImageContext()
let imageView = UIImageView(image: image)
insertSubview(imageView, at: 0)
}
/// Adds a motion effect to the view.
func applyMotionEffects() {
let horizontalEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
let verticalEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
let motionEffectGroup = UIMotionEffectGroup()
horizontalEffect.minimumRelativeValue = -10.0
horizontalEffect.maximumRelativeValue = 10.0
verticalEffect.minimumRelativeValue = -10.0
verticalEffect.maximumRelativeValue = 10.0
motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect]
addMotionEffect(motionEffectGroup)
}
/// Take a screenshot of the current view
///
/// - Parameter save: Save the screenshot in user pictures. Default is false.
/// - Returns: Returns screenshot as UIImage
func screenshot(save: Bool = false) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
if save {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
return image
}
/// Removes all subviews from current view
func removeAllSubviews() {
subviews.forEach { subview in
subview.removeFromSuperview()
}
}
}
// MARK: - UIView animatable extension
/// Extends UIView with animatable functions.
public extension UIView {
/// Create a shake effect.
///
/// - Parameters:
/// - count: Shakes count. Default is 2.
/// - duration: Shake duration. Default is 0.15.
/// - translation: Shake translation. Default is 5.
func shake(count: Float = 2, duration: TimeInterval = 0.15, translation: Float = 5) {
let animation = CABasicAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.repeatCount = count
animation.duration = (duration) / TimeInterval(animation.repeatCount)
animation.autoreverses = true
animation.byValue = translation
layer.add(animation, forKey: "shake")
}
/// Create a pulse effect.
///
/// - Parameters:
/// - count: Pulse count. Default is 1.
/// - duration: Pulse duration. Default is 1.
func pulse(count: Float = 1, duration: TimeInterval = 1) {
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = duration
animation.fromValue = 0
animation.toValue = 1
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.autoreverses = true
animation.repeatCount = count
layer.add(animation, forKey: "pulse")
}
/// Create a heartbeat effect.
///
/// - Parameters:
/// - count: Seconds of animation. Default is 1.
/// - maxSize: Maximum size of the object to animate. Default is 1.4.
/// - durationPerBeat: Duration per beat. Default is 0.5.
func heartbeat(count: Float = 1, maxSize: CGFloat = 1.4, durationPerBeat: TimeInterval = 0.5) {
let animation = CAKeyframeAnimation(keyPath: "transform")
let scale1 = CATransform3DMakeScale(0.8, 0.8, 1)
let scale2 = CATransform3DMakeScale(maxSize, maxSize, 1)
let scale3 = CATransform3DMakeScale(maxSize - 0.3, maxSize - 0.3, 1)
let scale4 = CATransform3DMakeScale(1.0, 1.0, 1)
let frameValues = [NSValue(caTransform3D: scale1), NSValue(caTransform3D: scale2), NSValue(caTransform3D: scale3), NSValue(caTransform3D: scale4)]
animation.values = frameValues
let frameTimes = [NSNumber(value: 0.05), NSNumber(value: 0.2), NSNumber(value: 0.6), NSNumber(value: 1.0)]
animation.keyTimes = frameTimes
animation.fillMode = CAMediaTimingFillMode.forwards
animation.duration = durationPerBeat
animation.repeatCount = count / Float(durationPerBeat)
layer.add(animation, forKey: "heartbeat")
}
/// Create a flip effect.
///
/// - Parameters:
/// - duration: Seconds of animation.
/// - direction: Direction of the flip animation.
func flip(duration: TimeInterval, direction: UIViewAnimationFlipDirection) {
let transition = CATransition()
transition.subtype = CATransitionSubtype(rawValue: direction.rawValue)
transition.startProgress = 0
transition.endProgress = 1.0
transition.type = CATransitionType(rawValue: "flip")
transition.duration = duration
transition.repeatCount = 1
transition.autoreverses = true
layer.add(transition, forKey: "flip")
}
/// Translate the UIView around the topView.
///
/// - Parameters:
/// - topView: Top view to translate to.
/// - duration: Duration of the translation.
/// - direction: Direction of the translation.
/// - repeatAnimation: If the animation must be repeat or no.
/// - startFromEdge: If the animation must start from the edge.
func translateAround(topView: UIView, duration: CGFloat, direction: UIViewAnimationTranslationDirection, repeatAnimation: Bool = true, startFromEdge: Bool = true) {
var startPosition: CGFloat = center.x, endPosition: CGFloat
switch direction {
case .leftToRight:
startPosition = frame.size.width / 2
endPosition = -(frame.size.width / 2) + topView.frame.size.width
case .rightToLeft:
startPosition = -(frame.size.width / 2) + topView.frame.size.width
endPosition = frame.size.width / 2
}
if startFromEdge {
center = CGPoint(x: startPosition, y: center.y)
}
UIView.animate(
withDuration: TimeInterval(duration / 2),
delay: 1,
options: UIView.AnimationOptions(),
animations: {
self.center = CGPoint(x: endPosition, y: self.center.y)
}, completion: { finished in
if finished {
UIView.animate(
withDuration: TimeInterval(duration / 2),
delay: 1,
options: UIView.AnimationOptions(),
animations: {
self.center = CGPoint(x: startPosition, y: self.center.y)
}, completion: { finished in
if finished {
if repeatAnimation {
self.translateAround(topView: topView, duration: duration, direction: direction, repeatAnimation: repeatAnimation, startFromEdge: startFromEdge)
}
}
}
)
}
}
)
}
/// Animate along path.
///
/// - Parameters:
/// - path: Path to follow.
/// - count: Animation repeat count. Default is 1.
/// - duration: Animation duration.
func animate(path: UIBezierPath, count: Float = 1, duration: TimeInterval, autoreverses: Bool = false) {
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path.cgPath
animation.repeatCount = count
animation.duration = duration
animation.autoreverses = autoreverses
layer.add(animation, forKey: "animateAlongPath")
}
}
// MARK: - UIView inspectable extension
/// Extends UIView with inspectable variables.
@IBDesignable
extension UIView {
// MARK: - Variables
/// Inspectable border size.
@IBInspectable public var borderWidth: CGFloat {
get {
layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
/// Inspectable border color.
@IBInspectable public var borderColor: UIColor {
get {
guard let borderColor = layer.borderColor else {
return UIColor.clear
}
return UIColor(cgColor: borderColor)
}
set {
layer.borderColor = newValue.cgColor
}
}
/// Inspectable mask to bounds.
///
/// Set it to true if you want to enable corner radius.
///
/// Set it to false if you want to enable shadow.
@IBInspectable public var maskToBounds: Bool {
get {
layer.masksToBounds
}
set {
layer.masksToBounds = newValue
}
}
/// Inspectable corners size.
///
/// Remeber to set maskToBounds to true.
@IBInspectable public var cornerRadius: CGFloat {
get {
layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
/// Inspectable shadow color.
///
/// Remeber to set maskToBounds to false.
@IBInspectable public var shadowColor: UIColor {
get {
guard let shadowColor = layer.shadowColor else {
return UIColor.clear
}
return UIColor(cgColor: shadowColor)
}
set {
layer.shadowColor = newValue.cgColor
}
}
/// Inspectable shadow opacity.
///
/// Remeber to set maskToBounds to false.
@IBInspectable public var shadowOpacity: Float {
get {
layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
/// Inspectable shadow offset X.
///
/// Remeber to set maskToBounds to false.
@IBInspectable public var shadowOffsetX: CGFloat {
get {
layer.shadowOffset.width
}
set {
layer.shadowOffset = CGSize(width: newValue, height: layer.shadowOffset.height)
}
}
/// Inspectable shadow offset Y.
///
/// Remeber to set maskToBounds to false.
@IBInspectable public var shadowOffsetY: CGFloat {
get {
layer.shadowOffset.height
}
set {
layer.shadowOffset = CGSize(width: layer.shadowOffset.width, height: newValue)
}
}
/// Inspectable shadow radius.
///
/// Remeber to set maskToBounds to false.
@IBInspectable public var shadowRadius: CGFloat {
get {
layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
}
|
mit
|
97c80afb15215fe8b64ed495eeb6422e
| 34.124054 | 180 | 0.597192 | 4.956661 | false | false | false | false |
NobodyNada/SwiftChatSE
|
Sources/SwiftChatSE/CommandDeleteMessage.swift
|
1
|
2269
|
//
// CommandDeleteMessage.swift
// SwiftChatSE
//
// Created by NobodyNada on 5/24/17.
//
//
import Foundation
open class CommandDeleteMessage: Command {
override open class func usage() -> [String] {
return ["del ...", "delete ...", "poof ...", "remove ...", "ninja'd ..."]
}
enum TranscriptURLParsingError: Error {
case wrongHost
case notChatMessage
}
private func parseTranscriptURL(_ url: URL) throws -> Int {
guard url.host == message.room.host.chatDomain else {
throw TranscriptURLParsingError.wrongHost
}
guard url.pathComponents.count > 2, url.pathComponents[1] == "transcript" else {
throw TranscriptURLParsingError.notChatMessage
}
if let id = url.fragment.flatMap({Int($0)}) { return id }
else if let id =
URLComponents(url: url, resolvingAgainstBaseURL: true)?
.queryItems?.first(where: {$0.name == "m"})?.value
.flatMap({Int($0)}) { return id }
else if let id = Int(url.pathComponents.last!) { return id }
else { throw TranscriptURLParsingError.notChatMessage }
}
override open func run() throws {
var ids = [Int]()
do {
//Get the message ID canidates.
([
//the raw message ID as arguments
arguments.compactMap { Int($0) },
//the transcript URL as arguments
try arguments.compactMap {
if let url = URL(string: $0), url.host != nil {
return try parseTranscriptURL(url)
} else { return nil }
},
//the reply ID
[arguments.isEmpty ? message.replyID : nil].compactMap { $0 }
] as [[Int]])
.reduce([], +)
.forEach {
//remove duplicates
if !ids.contains($0) { ids.append($0) }
}
} catch TranscriptURLParsingError.wrongHost {
reply("I cannot delete messages on a different chat host.")
return
} catch TranscriptURLParsingError.notChatMessage {
reply("That URL does not look like a link to a chat message.")
return
}
if ids.isEmpty {
reply("Which messages should be deleted?")
return
}
do {
for id in ids {
try message.room.delete(id)
}
} catch ChatRoom.DeletionError.notAllowed {
reply("I am not allowed to delete that message.")
} catch ChatRoom.DeletionError.tooLate {
reply("It is too late to delete that message.")
}
}
}
|
mit
|
7ae5e317b69c0919660b72ced567a1a9
| 24.494382 | 82 | 0.643015 | 3.562009 | false | false | false | false |
SwiftAndroid/swift
|
stdlib/public/core/AssertCommon.swift
|
1
|
7710
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Implementation Note: this file intentionally uses very LOW-LEVEL
// CONSTRUCTS, so that assert and fatal may be used liberally in
// building library abstractions without fear of infinite recursion.
//
// FIXME: We could go farther with this simplification, e.g. avoiding
// UnsafeMutablePointer
@_transparent
@warn_unused_result
public // @testable
func _isDebugAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 0
}
@_versioned
@_transparent
@warn_unused_result
internal func _isReleaseAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 1
}
@_transparent
@warn_unused_result
public // @testable
func _isFastAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 2
}
@_transparent
@warn_unused_result
public // @testable
func _isStdlibInternalChecksEnabled() -> Bool {
#if INTERNAL_CHECKS_ENABLED
return true
#else
return false
#endif
}
@_versioned
@_transparent
@warn_unused_result
internal
func _fatalErrorFlags() -> UInt32 {
// The current flags are:
// (1 << 0): Report backtrace on fatal error
#if os(iOS) || os(tvOS) || os(watchOS)
return 0
#else
return _isDebugAssertConfiguration() ? 1 : 0
#endif
}
@_silgen_name("_swift_stdlib_reportFatalErrorInFile")
func _reportFatalErrorInFile(
_ prefix: UnsafePointer<UInt8>, _ prefixLength: UInt,
_ message: UnsafePointer<UInt8>, _ messageLength: UInt,
_ file: UnsafePointer<UInt8>, _ fileLength: UInt,
_ line: UInt, flags: UInt32)
@_silgen_name("_swift_stdlib_reportFatalError")
func _reportFatalError(
_ prefix: UnsafePointer<UInt8>, _ prefixLength: UInt,
_ message: UnsafePointer<UInt8>, _ messageLength: UInt,
flags: UInt32)
@_versioned
@_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile")
func _reportUnimplementedInitializerInFile(
_ className: UnsafePointer<UInt8>, _ classNameLength: UInt,
_ initName: UnsafePointer<UInt8>, _ initNameLength: UInt,
_ file: UnsafePointer<UInt8>, _ fileLength: UInt,
_ line: UInt, _ column: UInt,
flags: UInt32)
@_versioned
@_silgen_name("_swift_stdlib_reportUnimplementedInitializer")
func _reportUnimplementedInitializer(
_ className: UnsafePointer<UInt8>, _ classNameLength: UInt,
_ initName: UnsafePointer<UInt8>, _ initNameLength: UInt,
flags: UInt32)
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@_versioned
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
func _assertionFailed(
_ prefix: StaticString, _ message: StaticString,
_ file: StaticString, _ line: UInt,
flags: UInt32
) {
prefix.withUTF8Buffer {
(prefix) -> Void in
message.withUTF8Buffer {
(message) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_reportFatalErrorInFile(
prefix.baseAddress!, UInt(prefix.count),
message.baseAddress!, UInt(message.count),
file.baseAddress!, UInt(file.count), line,
flags: flags)
Builtin.int_trap()
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@_versioned
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
func _assertionFailed(
_ prefix: StaticString, _ message: String,
_ file: StaticString, _ line: UInt,
flags: UInt32
) {
prefix.withUTF8Buffer {
(prefix) -> Void in
let messageUTF8 = message.nulTerminatedUTF8
messageUTF8.withUnsafeBufferPointer {
(messageUTF8) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_reportFatalErrorInFile(
prefix.baseAddress!, UInt(prefix.count),
messageUTF8.baseAddress!, UInt(messageUTF8.count),
file.baseAddress!, UInt(file.count), line,
flags: flags)
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of stdlib
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@_versioned
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
@_semantics("arc.programtermination_point")
func _fatalErrorMessage(
_ prefix: StaticString, _ message: StaticString,
_ file: StaticString, _ line: UInt,
flags: UInt32
) {
#if INTERNAL_CHECKS_ENABLED
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
file.withUTF8Buffer {
(file) in
_reportFatalErrorInFile(
prefix.baseAddress!, UInt(prefix.count),
message.baseAddress!, UInt(message.count),
file.baseAddress!, UInt(file.count), line,
flags: flags)
}
}
}
#else
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
_reportFatalError(
prefix.baseAddress!, UInt(prefix.count),
message.baseAddress!, UInt(message.count),
flags: flags)
}
}
#endif
Builtin.int_trap()
}
/// Prints a fatal error message when an unimplemented initializer gets
/// called by the Objective-C runtime.
@_transparent @noreturn
public // COMPILER_INTRINSIC
func _unimplemented_initializer(className: StaticString,
initName: StaticString = #function,
file: StaticString = #file,
line: UInt = #line,
column: UInt = #column) {
// This function is marked @_transparent so that it is inlined into the caller
// (the initializer stub), and, depending on the build configuration,
// redundant parameter values (#file etc.) are eliminated, and don't leak
// information about the user's source.
if _isDebugAssertConfiguration() {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
file.withUTF8Buffer {
(file) in
_reportUnimplementedInitializerInFile(
className.baseAddress!, UInt(className.count),
initName.baseAddress!, UInt(initName.count),
file.baseAddress!, UInt(file.count), line, column,
flags: 0)
}
}
}
} else {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
_reportUnimplementedInitializer(
className.baseAddress!, UInt(className.count),
initName.baseAddress!, UInt(initName.count),
flags: 0)
}
}
}
Builtin.int_trap()
}
@noreturn
public // COMPILER_INTRINSIC
func _undefined<T>(
@autoclosure _ message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) -> T {
_assertionFailed("fatal error", message(), file, line, flags: 0)
}
|
apache-2.0
|
863850236207c279064bb0590a033c5b
| 27.876404 | 80 | 0.65655 | 4.240924 | false | false | false | false |
achimk/Cars
|
CarsApp/Features/Cars/List/CarsListViewModel.swift
|
1
|
2104
|
//
// CarsListViewModel.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Result
typealias CarsListResult = Result<Array<CarsListItemPresentable>, CarsServiceError>
protocol CarsListViewModelInputs {
func fetch()
}
protocol CarsListViewModelOutputs {
var onPresentResult: Driver<CarsListResult> { get }
var onLoading: Driver<Bool> { get }
}
protocol CarsListViewModelType {
var inputs: CarsListViewModelInputs { get }
var outputs: CarsListViewModelOutputs { get }
}
final class CarsListViewModel: CarsListViewModelType {
fileprivate let signalFetch: PublishSubject<Void>
fileprivate let signalRequest: ObservableProbe
fileprivate let driverPresentResult: Driver<CarsListResult>
var inputs: CarsListViewModelInputs { return self }
var outputs: CarsListViewModelOutputs { return self }
init(service: CarsListServiceType) {
let trigger = PublishSubject<Void>()
let probe = ObservableProbe()
signalFetch = trigger
signalRequest = probe
driverPresentResult = trigger
.withLatestFrom(probe)
.filter { !$0 }
.flatMapLatest { _ in
return service
.requestCarsList()
.take(1)
.map {
$0.map { CarsListPresentationItem($0) as CarsListItemPresentable }
}
.trackActivity(probe)
.mapCarsServiceResult()
}
.asDriver(onErrorDriveWith: Driver.never())
}
deinit {
print("[*] \(type(of: self)): \(#function)")
}
}
extension CarsListViewModel: CarsListViewModelInputs {
func fetch() {
signalFetch.onNext()
}
}
extension CarsListViewModel: CarsListViewModelOutputs {
var onPresentResult: Driver<CarsListResult> {
return driverPresentResult
}
var onLoading: Driver<Bool> {
return signalRequest.asDriver()
}
}
|
mit
|
8d714af6e7744e2e1e846b99a409d049
| 24.646341 | 90 | 0.642416 | 4.834483 | false | false | false | false |
Rizbi/RZKit
|
RZKit Example/ScaleDemoViewController.swift
|
1
|
5650
|
//
// ScaleDemoViewController.swift
// RZKit Example
//
// Created by Rizbi on 8/18/16.
// Copyright © 2016 rzkit. All rights reserved.
//
import UIKit
class ScaleDemoViewController: UIViewController, UITextFieldDelegate
{
@IBOutlet var rzView: RZView?
@IBOutlet var durationField: RZTextField?
@IBOutlet var rzButtonScaleUp: RZButton?
@IBOutlet var rzButtonScaleDown: RZButton?
@IBOutlet var rzButtonSequence: RZButton?
var anchor: RZAnimationScaleAnchor = RZAnimationScaleAnchor.Default
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Anchor (Center)"
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction
private func startScaleUpAnimation(sender: RZButton)
{
if let _view = self.rzView
{
self.enableAllButtons(false)
let scaleUp = RZAnimationScale(view: _view, duration: self.getAnimationDuration(), percent: 400.0, anchor: self.anchor)
scaleUp.completionHandler = self.animationFinished(_:)
scaleUp.start()
}
}
@IBAction
private func startScaleDownAnimation(sender: RZButton)
{
if let _view = self.rzView
{
self.enableAllButtons(false)
let scaleDown = RZAnimationScale(view: _view, duration: self.getAnimationDuration(), percent: 25.0, anchor: self.anchor)
scaleDown.completionHandler = self.animationFinished(_:)
scaleDown.start()
}
}
@IBAction
private func startSequenceAnimation(sender: RZButton)
{
if let _view = self.rzView
{
// keep buttons disbled while an animation is in effect
// Not mandatory!
self.enableAllButtons(false)
let scaleDown = RZAnimationScale(view: _view, duration: self.getAnimationDuration(), percent: 25.0, anchor: self.anchor)
let scaleUp = RZAnimationScale(view: _view, duration: self.getAnimationDuration(), percent: 400.0, anchor: self.anchor)
let seq = RZAnimationSequence(sequence: [scaleDown, scaleUp])
seq.shouldRepeat = true
seq.repeatOption = RZAnimationSequenceRepeatOption.Cycle
seq.completionHandler = self.animationFinished(_:)
seq.start()
}
}
private func animationFinished(anim: RZAnimation)
{
self.enableAllButtons(true)
}
private func enableAllButtons(enabled: Bool)
{
self.rzButtonScaleUp?.enabled = enabled
self.rzButtonScaleDown?.enabled = enabled
self.rzButtonSequence?.enabled = enabled
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
self.durationField?.text = "\(self.getAnimationDuration())"
textField.resignFirstResponder()
return true
}
private func getAnimationDuration() -> NSTimeInterval
{
var duration: NSTimeInterval = 0.5
if let _textField = self.durationField, let _text = _textField.text
{
duration = NSTimeInterval((_text as NSString).doubleValue)
}
if duration < 0.1
{
duration = 0.1
}
return duration
}
@IBAction
private func setAnchor(sender: UIBarButtonItem)
{
let alertController = UIAlertController(title: "Choose Anchor Point", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let x = UIAlertAction(title: "Default/Center", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.anchor = RZAnimationScaleAnchor.Center
self.title = "Anchor (Center)"
}
alertController.addAction(x)
let a = UIAlertAction(title: "Left Top", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.anchor = RZAnimationScaleAnchor.LeftTop
self.title = "Anchor (Left Top)"
}
alertController.addAction(a)
let b = UIAlertAction(title: "Left Bottom", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.anchor = RZAnimationScaleAnchor.LeftBottom
self.title = "Anchor (Left Bottom)"
}
alertController.addAction(b)
let c = UIAlertAction(title: "Right Top", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.anchor = RZAnimationScaleAnchor.RightTop
self.title = "Anchor (Right Top)"
}
alertController.addAction(c)
let d = UIAlertAction(title: "Right Bottom", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.anchor = RZAnimationScaleAnchor.RightBottom
self.title = "Anchor (Right Bottom)"
}
alertController.addAction(d)
let z = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(z)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad)
{
if let popover = alertController.popoverPresentationController
{
popover.barButtonItem = sender
popover.sourceView = self.view
popover.permittedArrowDirections = UIPopoverArrowDirection.Up
}
}
self.presentViewController(alertController, animated: true, completion: nil)
}
}
|
gpl-3.0
|
631418aed53e60b1c1f93c5b134deeaf
| 32.625 | 143 | 0.616746 | 4.95092 | false | false | false | false |
JakeLin/IBAnimatable
|
Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationSemiCircleSpin.swift
|
2
|
1205
|
//
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationSemiCircleSpin: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.6
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circle = ActivityIndicatorShape.circleSemi.makeLayer(size: size, color: color)
let frame = CGRect(
x: (layer.bounds.width - size.width) / 2,
y: (layer.bounds.height - size.height) / 2,
width: size.width,
height: size.height
)
circle.frame = frame
circle.add(defaultAnimation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationSemiCircleSpin {
var defaultAnimation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: .rotationZ)
animation.keyTimes = [0, 0.5, 1]
animation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
|
mit
|
f504ce2a6d7da0290b911a2ad0750cf1
| 26.386364 | 86 | 0.712863 | 4.242958 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/Login/AKFLogin.swift
|
1
|
3386
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import WebKit
import SnapKit
class AKFLoginViewController: ViewController {
// window.webkit.messageHandlers.LoginCompleted message
private static let LoginCompletedHandlerKey: String = "LoginCompleted"
var webview: WKWebView = WKWebView()
deinit {
// explicitly remove the message handler to avoid a circular reference
webview.configuration.userContentController.removeScriptMessageHandler(
forName: AKFLoginViewController.LoginCompletedHandlerKey)
}
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
private func configure() {
view.backgroundColor = Style.Colors.Background
view.addSubview(webview) { (make) in
make.centerX.centerY.equalToSuperview()
make.width.height.equalToSuperview()
}
webview.configuration.userContentController.add(self, name: AKFLoginViewController.LoginCompletedHandlerKey)
webview.load(URLRequest(url: URL(string: "https://www.akfusa.org/steps4impact/?fbid=\(User.id)")!)) // swiftlint:disable:this force_unwrapping line_length
webview.navigationDelegate = self
}
}
extension AKFLoginViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
// TODO(compnerd) handle the message, save the AKFID
}
}
extension AKFLoginViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView,
decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if !(webView.url?.absoluteString.starts(with: "https://www.akfusa.org/thank-you-steps4impact/") ?? false) {
return decisionHandler(.allow)
}
UserInfo.AKFProfileCreated = true
AppController.shared.onAKFLoginCompleted()
return decisionHandler(.allow)
}
}
|
bsd-3-clause
|
585d2000c8d7ca762fe2f2125149d647
| 39.783133 | 158 | 0.751551 | 4.870504 | false | false | false | false |
Wei-Xia/TVMLKitchen
|
Sources/KitchenTabBar.swift
|
1
|
1836
|
//
// KitchenTabBar.swift
// TVMLKitchen
//
// Created by Stephen Radford on 15/03/2016.
// Copyright © 2016 toshi0383. All rights reserved.
//
public protocol TabItem {
/// The title that will be displayed on the tab bar.
var title: String { get }
/**
This handler will be called whenever the focus changes to it.
*/
func handler()
}
public struct KitchenTabBar: TemplateRecipeType {
public let theme = EmptyTheme()
/// The items that are displayed in the tab bar.
/// The `displayTabBar` method will automatically be called.
public var items: [TabItem]! {
didSet {
displayTabBar()
}
}
/// for UnitTesting use.
/// - parameter items:
public init(items: [TabItem]? = nil) {
self.items = items
}
/// Constructed string from the `items` array.
public var template: String {
let url = KitchenTabBar.bundle.URLForResource(templateFileName, withExtension: "xml")!
// swiftlint:disable:next force_try
let xml = try! String(contentsOfURL: url)
var string = ""
for (index, item) in items.enumerate() {
string += "<menuItem menuIndex=\"\(index)\">\n"
string += "<title>\(item.title)</title>\n"
string += "</menuItem>\n"
}
return xml.stringByReplacingOccurrencesOfString("{{menuItems}}", withString: string)
}
/**
Display the tab bar using the generated `xmlString`.
*/
func displayTabBar() {
openTVMLTemplateFromXMLString(xmlString)
}
/**
Called whenever the tab view changes.
The handler defined by the relevant `TabItem` will automatically be called.
- parameter index: The new selected index
*/
func tabChanged(index: Int) {
items[index].handler()
}
}
|
mit
|
9aac999864ef7441ada161bfab256718
| 25.214286 | 94 | 0.611989 | 4.389952 | false | false | false | false |
AttilaTheFun/SwaggerParser
|
Sources/ObjectMetadata.swift
|
1
|
2187
|
public struct ObjectMetadata {
/// The minimum number of properties. If set it must be a non-negative integer.
public let minProperties: Int?
/// The maximum number of properties. If set it must be a non-negative integer.
public let maxProperties: Int?
/// Adds support for polymorphism.
/// The discriminator is the schema property name that is used to differentiate between other schema
/// that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the
/// required property list. When used, the value MUST be the name of this schema or any schema that
/// inherits it.
public let discriminator: String?
/// Determines whether or not the schema should be considered abstract. This
/// can be used to indicate that a schema is an interface rather than a
/// concrete model object.
///
/// Corresponds to the boolean value for `x-abstract`. The default value is
/// false.
public let abstract: Bool
}
struct ObjectMetadataBuilder: Codable {
let minProperties: Int?
let maxProperties: Int?
let discriminator: String?
let abstract: Bool
enum CodingKeys: String, CodingKey {
case minProperties
case maxProperties
case discriminator
case abstract = "x-abstract"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.minProperties = try values.decodeIfPresent(Int.self, forKey: .minProperties)
self.maxProperties = try values.decodeIfPresent(Int.self, forKey: .maxProperties)
self.discriminator = try values.decodeIfPresent(String.self, forKey: .discriminator)
self.abstract = (try values.decodeIfPresent(Bool.self, forKey: .abstract)) ?? false
}
}
extension ObjectMetadataBuilder: Builder {
typealias Building = ObjectMetadata
func build(_ swagger: SwaggerBuilder) throws -> ObjectMetadata {
return ObjectMetadata(
minProperties: self.minProperties,
maxProperties: self.maxProperties,
discriminator: self.discriminator,
abstract: self.abstract)
}
}
|
mit
|
15713cb6d3279ad190ad189004842e61
| 36.067797 | 109 | 0.694102 | 4.775109 | false | false | false | false |
ilyahal/VKMusic
|
VkPlaylist/PlaylistMusicTableViewController.swift
|
1
|
14981
|
//
// PlaylistMusicTableViewController.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/// Контроллер содержащий таблицу со списком аудиозаписей содержащихся в выбранном плейлисте
class PlaylistMusicTableViewController: UITableViewController {
/// Родительский контроллер
weak var playlistMusicViewController: PlaylistMusicViewController!
/// Идентификатор текущего списка аудиозаписей
var playlistIdentifier: String!
/// Выбранный плейлист
var playlist: Playlist!
/// Массив аудиозаписей содержащихся в плейлисте
var tracks = [TrackInPlaylist]()
/// Массив найденных аудиозаписей
var filteredMusic: [TrackInPlaylist]!
/// Массив аудиозаписей, отображаемый на экране
var activeArray: [TrackInPlaylist] {
if isSearched {
return filteredMusic
} else {
return tracks
}
}
/// Поисковый контроллер
let searchController = UISearchController(searchResultsController: nil)
/// Выполняется ли сейчас поиск
var isSearched: Bool {
return searchController.active && !searchController.searchBar.text!.isEmpty
}
override func viewDidLoad() {
super.viewDidLoad()
// Настройка поисковой панели
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.searchBarStyle = .Prominent
searchController.searchBar.placeholder = "Поиск"
definesPresentationContext = true
// Кастомизация tableView
tableView.tableFooterView = UIView() // Чистим пустое пространство под таблицей
// Регистрация ячеек
var cellNib = UINib(nibName: TableViewCellIdentifiers.nothingFoundCell, bundle: nil) // Ячейка "Ничего не найдено"
tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.nothingFoundCell)
cellNib = UINib(nibName: TableViewCellIdentifiers.offlineAudioCell, bundle: nil) // Ячейка с аудиозаписью
tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.offlineAudioCell)
cellNib = UINib(nibName: TableViewCellIdentifiers.numberOfRowsCell, bundle: nil) // Ячейка с количеством строк
tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.numberOfRowsCell)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tracks = DataManager.sharedInstance.getTracksForPlaylist(playlist)
playlistIdentifier = NSUUID().UUIDString
searchEnable(tracks.count != 0)
reloadTableView()
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
if let _ = tableView.tableHeaderView {
if tableView.contentOffset.y == 0 {
tableView.hideSearchBar()
}
}
}
deinit {
if let superView = searchController.view.superview {
superView.removeFromSuperview()
}
}
/// Заново отрисовать таблицу
func reloadTableView() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
// MARK: Работа с клавиатурой
/// Распознаватель тапов по экрану
lazy var tapRecognizer: UITapGestureRecognizer = {
var recognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
return recognizer
}()
/// Спрятать клавиатуру у поисковой строки
func dismissKeyboard() {
searchController.searchBar.resignFirstResponder()
if searchController.active && searchController.searchBar.text!.isEmpty {
searchController.active = false
}
}
// MARK: Поиск
/// Управление доступностью поиска
func searchEnable(enable: Bool) {
if enable {
if tableView.tableHeaderView == nil {
searchController.searchBar.alpha = 1
tableView.tableHeaderView = searchController.searchBar
tableView.hideSearchBar()
}
} else {
if let _ = tableView.tableHeaderView {
searchController.searchBar.alpha = 0
searchController.active = false
tableView.tableHeaderView = nil
tableView.contentOffset = CGPointZero
}
}
}
/// Выполнение поиска
func filterContentForSearchText(searchText: String) {
filteredMusic = tracks.filter { trackInPlaylist in
let track = trackInPlaylist.track
return track.title.lowercaseString.containsString(searchText.lowercaseString) || track.artist.lowercaseString.containsString(searchText.lowercaseString)
}
}
// MARK: Получение ячеек для строк таблицы helpers
// Текст для ячейки с сообщением о том, что плейлист не содержит аудиозаписи
var noResultsLabelText: String {
return "Плейлист пустой"
}
// Текст для ячейки с сообщением о том, что при поиске ничего не найдено
var nothingFoundLabelText: String {
return "Измените поисковый запрос"
}
// Получение количества треков в списке для ячейки с количеством аудиозаписей
func numberOfAudioRowForIndexPath(indexPath: NSIndexPath) -> Int? {
if activeArray.count == indexPath.row {
return activeArray.count
} else {
return nil
}
}
// MARK: Получение ячеек для строк таблицы
// Ячейка для строки с сообщением что плейлист пустой
func getCellForNoResultsRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell
cell.messageLabel.text = noResultsLabelText
return cell
}
// Ячейка для строки с сообщением, что при поиске ничего не было найдено
func getCellForNothingFoundRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell {
let nothingFoundCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell
nothingFoundCell.messageLabel.text = nothingFoundLabelText
return nothingFoundCell
}
// Пытаемся получить ячейку для строки с количеством аудиозаписей
func getCellForNumberOfAudioRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell? {
let count = numberOfAudioRowForIndexPath(indexPath)
if let count = count {
let numberOfRowsCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.numberOfRowsCell) as! NumberOfRowsCell
numberOfRowsCell.configureForType(.Audio, withCount: count)
return numberOfRowsCell
}
return nil
}
// Ячейка для строки с треком
func getCellForOfflineAudioForIndexPath(indexPath: NSIndexPath) -> UITableViewCell {
let track = activeArray[indexPath.row].track
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.offlineAudioCell, forIndexPath: indexPath) as! OfflineAudioCell
cell.configureForTrack(track)
return cell
}
}
// MARK: UITableViewDataSource
private typealias _PlaylistMusicTableViewControllerDataSource = PlaylistMusicTableViewController
extension _PlaylistMusicTableViewControllerDataSource {
// Получение количества строк таблицы
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activeArray.count + 1
}
// Получение ячейки для строки таблицы
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tracks.count == 0 {
return getCellForNoResultsRowForIndexPath(indexPath)
} else {
if isSearched && filteredMusic.count == 0 {
return getCellForNothingFoundRowForIndexPath(indexPath)
}
if let numberOfRowsCell = getCellForNumberOfAudioRowForIndexPath(indexPath) {
return numberOfRowsCell
}
return getCellForOfflineAudioForIndexPath(indexPath)
}
}
// Возможно ли редактировать ячейку
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return activeArray.count != indexPath.row
}
// Обработка удаления ячейки
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let trackInPlaylist = activeArray[indexPath.row]
if DataManager.sharedInstance.deleteTrackFromPlaylist(trackInPlaylist) {
tracks.removeAtIndex(tracks.indexOf(trackInPlaylist)!)
if let index = filteredMusic?.indexOf(trackInPlaylist) {
filteredMusic.removeAtIndex(index)
}
reloadTableView()
} else {
let alertController = UIAlertController(title: "Ошибка", message: "При удалении аудиозаписи из плейлиста произошла ошибка, попробуйте еще раз..", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
}
}
// MARK: UITableViewDelegate
private typealias _PlaylistMusicTableViewControllerDelegate = PlaylistMusicTableViewController
extension _PlaylistMusicTableViewControllerDelegate {
// Высота каждой строки
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if activeArray.count != 0 {
if activeArray.count == indexPath.row {
return 44
}
}
return 62
}
// Вызывается при тапе по строке таблицы
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if tableView.cellForRowAtIndexPath(indexPath) is OfflineAudioCell {
let track = activeArray[indexPath.row]
let index = tracks.indexOf({ $0 === track })!
PlayerManager.sharedInstance.playItemWithIndex(index, inPlaylist: tracks, withPlaylistIdentifier: playlistIdentifier)
}
}
}
// MARK: UISearchBarDelegate
extension PlaylistMusicTableViewController: UISearchBarDelegate {
// Пользователь хочет начать поиск
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
return tracks.count != 0
}
// Пользователь начал редактирование поискового текста
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
view.addGestureRecognizer(tapRecognizer)
}
// Пользователь закончил редактирование поискового текста
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
view.removeGestureRecognizer(tapRecognizer)
}
// В поисковой панели была нажата кнопка "Отмена"
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
filteredMusic.removeAll()
}
}
// MARK: UISearchResultsUpdating
extension PlaylistMusicTableViewController: UISearchResultsUpdating {
// Поле поиска получило фокус или значение поискового запроса изменилось
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
reloadTableView()
}
}
|
mit
|
2413ae580ead2176747bf26aa1d638ff
| 36.179558 | 185 | 0.681453 | 5.317266 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/core/StringGutsSlice.swift
|
8
|
2950
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
// TODO(String performance): Unfortunately, this slice struct seems to add
// overhead. We may want to wean ourselves off of this and have all users just
// also store a range.
// A sliced _StringGuts, convenient for unifying String/Substring comparison,
// hashing, and RRC.
internal struct _StringGutsSlice {
internal var _guts: _StringGuts
internal var _offsetRange: Range<Int>
@inline(__always)
internal init(_ guts: _StringGuts) {
self._guts = guts
self._offsetRange = Range(_uncheckedBounds: (0, guts.count))
}
@inline(__always)
internal init(_ guts: _StringGuts, _ offsetRange: Range<Int>) {
_internalInvariant(
offsetRange.lowerBound >= 0 && offsetRange.upperBound <= guts.count)
self._guts = guts
self._offsetRange = offsetRange
}
internal var start: Int {
@inline(__always) get { return _offsetRange.lowerBound }
}
internal var end: Int {
@inline(__always) get { return _offsetRange.upperBound }
}
internal var count: Int {
@inline(__always) get { return _offsetRange.count }
}
internal var isNFCFastUTF8: Bool {
@inline(__always) get { return _guts.isNFCFastUTF8 }
}
internal var isASCII: Bool {
@inline(__always) get { return _guts.isASCII }
}
internal var isFastUTF8: Bool {
@inline(__always) get { return _guts.isFastUTF8 }
}
internal var utf8Count: Int {
@inline(__always) get {
if _fastPath(self.isFastUTF8) {
return _offsetRange.count
}
return Substring(self).utf8.count
}
}
internal var range: Range<String.Index> {
@inline(__always) get {
let lower = String.Index(_encodedOffset: _offsetRange.lowerBound)
._scalarAligned
let higher = String.Index(_encodedOffset: _offsetRange.upperBound)
._scalarAligned
return Range(_uncheckedBounds: (lower, higher))
}
}
@inline(__always)
internal func withFastUTF8<R>(
_ f: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R {
return try _guts.withFastUTF8(range: _offsetRange, f)
}
@_effects(releasenone)
internal func foreignErrorCorrectedScalar(
startingAt idx: String.Index
) -> (Unicode.Scalar, scalarLength: Int) {
let (scalar, len) = _guts.foreignErrorCorrectedScalar(startingAt: idx)
if _slowPath(idx.encoded(offsetBy: len) > range.upperBound) {
return (Unicode.Scalar._replacementCharacter, 1)
}
return (scalar, len)
}
}
|
apache-2.0
|
3ea649056d396d1b33f6a8493f874c4f
| 29.102041 | 80 | 0.640678 | 4.256854 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
MonTransit/Source/UI/ViewController/MenuController.swift
|
1
|
4947
|
//
// MenuController.swift
// SidebarMenu
//
import UIKit
class MenuController: UITableViewController {
@IBOutlet weak var resizeView: UIView!
private let updateDialogView:UpdateDialogView = UpdateDialogView()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = true
resizeView.frame.size = CGSize(width: resizeView.frame.width, height: UIScreen.mainScreen().bounds.height - 44*8 - 20)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "BusSegue") {
AgencyManager.setCurrentAgency(0)
}
else if (segue.identifier == "MetroSegue"){
AgencyManager.setCurrentAgency(1)
}
else if (segue.identifier == "TrainSegue"){
AgencyManager.setCurrentAgency(2)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
if selectedCell.reuseIdentifier == "UpdateId" {
updateDialogView.show(NSLocalizedString("Update", comment: "Title"),
doneButtonTitle: NSLocalizedString("UpdateKey", comment: "Update"),
cancelButtonTitle: NSLocalizedString("CancelKey", comment: "Cancel")) {
(date) -> Void in
}
}
}
}
extension UIViewController: SWRevealViewControllerDelegate
{
public func revealController(revealController: SWRevealViewController!, willMoveToPosition position: FrontViewPosition) {
self.clearAllNotice()
let tagId = 42078
if revealController.frontViewPosition == FrontViewPosition.Right {
let lock = self.view.viewWithTag(tagId)
UIView.animateWithDuration(0.3, animations: {
lock?.alpha = 0.0
}, completion: {(finished: Bool) in
lock?.removeFromSuperview()
})
} else if revealController.frontViewPosition == FrontViewPosition.Left {
let lock = UIView(frame: self.view.bounds)
lock.autoresizingMask = UIViewAutoresizing.FlexibleWidth
lock.tag = tagId
lock.alpha = 0
lock.backgroundColor = UIColor.blackColor()
lock.addGestureRecognizer(UITapGestureRecognizer(target: self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:))))
self.view.addSubview(lock)
UIView.animateWithDuration(0.3, animations: {
lock.alpha = 0.5
}
)
}
}
func checkDateLimits(providerId:Int) -> Bool{
let wServiceDateProvider = ServiceDateDataProvider()
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day ]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: NSDate())
let wYear = dateTimeComponents.year
let wMonth = dateTimeComponents.month
let wDay = dateTimeComponents.day
//Verify if the current date is in DB
let wDate = wServiceDateProvider.getDatesLimit(providerId)
let wTimeString = String(format: "%04d", wYear) + String(format: "%02d", wMonth) + String(format: "%02d", wDay)
let wTimeInt = Int(wTimeString)!
if wDate.max.getNSDate().getDateToInt() < wTimeInt{
return true
}
else{
return false
}
}
func displayDataOutdatedPopup(dataKeyString:String){
let alert = UIAlertController(title: "Alert", message: NSLocalizedString(dataKeyString, comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OkKey", comment: ""), style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
|
apache-2.0
|
67d3a3d394dc1d9775d388776d66d719
| 36.484848 | 158 | 0.617142 | 5.564679 | false | false | false | false |
gregomni/swift
|
test/Generics/generic_types.swift
|
2
|
6795
|
// RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<T : IteratorProtocol, U : IteratorProtocol>
where T.Element == U.Element {
}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: Range<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : Sequence>
where R.Iterator.Element : MyFormattedPrintable {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ExpressibleByArrayLiteral {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> { // expected-note{{'XParam' declared here}}
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of generic struct 'generic_types.XParam<Swift.Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {}
// expected-error@-1 {{'Bottom' requires that 'Top' inherit from 'Bottom<Top>'}}
// expected-note@-2 {{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}}
// expected-error@-3 *{{generic class 'Bottom' has self-referential generic requirements}}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'T'}}
// expected-error@-2 {{type 'T' constrained to non-protocol, non-class type 'T.A'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'U'}}
// expected-error@-2 {{'A' is not a member type of type 'T'}}
// expected-error@-3 {{type 'T' constrained to non-protocol, non-class type 'U.A'}}
// expected-error@-4 {{type 'U' constrained to non-protocol, non-class type 'T.A'}}
enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}}
// expected-error@-1{{cannot find type 'G' in scope}}
// Test that contextual type resolution for generic metatypes is consistent
// under a same-type constraint.
protocol MetatypeTypeResolutionProto {}
struct X8<T> {
static var property1: T.Type { T.self }
static func method1() -> T.Type { T.self }
}
extension X8 where T == MetatypeTypeResolutionProto {
static var property2: T.Type { property1 } // ok, still .Protocol
static func method2() -> T.Type { method1() } // ok, still .Protocol
}
|
apache-2.0
|
93f7a873ad800cc46f6e535d6780fa09
| 25.134615 | 148 | 0.643414 | 3.097083 | false | false | false | false |
cacawai/Tap2Read
|
tap2read/Pods/Cartography/Cartography/Property.swift
|
21
|
7740
|
//
// Property.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol Property {
var attribute: NSLayoutAttribute { get }
var context: Context { get }
var view: View { get }
}
// MARK: Equality
/// Properties conforming to this protocol can use the `==` operator with
/// numerical constants.
public protocol NumericalEquality : Property { }
/// Declares a property equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func == (lhs: NumericalEquality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs))
}
/// Properties conforming to this protocol can use the `==` operator with other
/// properties of the same type.
public protocol RelativeEquality : Property { }
/// Declares a property equal to a the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The expression.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func == <P: RelativeEquality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs.value, coefficients: rhs.coefficients[0])
}
/// Declares a property equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
@discardableResult public func == <P: RelativeEquality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs)
}
// MARK: Inequality
/// Properties conforming to this protocol can use the `<=` and `>=` operators
/// with numerical constants.
public protocol NumericalInequality : Property { }
/// Declares a property less than or equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.lessThanOrEqual)
}
/// Declares a property greater than or equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.greaterThanOrEqual)
}
/// Properties conforming to this protocol can use the `<=` and `>=` operators
/// with other properties of the same type.
public protocol RelativeInequality : Property { }
/// Declares a property less than or equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.lessThanOrEqual)
}
/// Declares a property greater than or equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.greaterThanOrEqual)
}
/// Declares a property less than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs.value, coefficients: rhs.coefficients[0], relation: NSLayoutRelation.lessThanOrEqual)
}
/// Declares a property greater than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs.value, coefficients: rhs.coefficients[0], relation: NSLayoutRelation.greaterThanOrEqual)
}
// MARK: Addition
public protocol Addition : Property { }
public func + <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(1, c) ])
}
public func + <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs + lhs
}
public func + <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 + c })
}
public func + <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs + lhs
}
public func - <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(1, -c) ])
}
public func - <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs - lhs
}
public func - <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 - c})
}
public func - <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs - lhs
}
#if os(iOS) || os(tvOS)
public func + (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> {
return Expression<LayoutSupport>(lhs, [Coefficients(1, c)])
}
public func - (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> {
return lhs + (-c)
}
#endif
// MARK: Multiplication
public protocol Multiplication : Property { }
public func * <P: Multiplication>(m: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 * m })
}
public func * <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs * lhs
}
public func * <P: Multiplication>(m: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(m, 0) ])
}
public func * <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs * lhs
}
public func / <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return lhs * (1 / rhs)
}
public func / <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> {
return lhs * (1 / rhs)
}
|
mit
|
b0010ad008cbd7ca79b3324e3cab0875
| 34.172727 | 138 | 0.695399 | 4.098517 | false | false | false | false |
whiteath/ReadFoundationSource
|
Foundation/NSUUID.swift
|
6
|
4258
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin.uuid
#elseif os(Linux) || CYGWIN
import Glibc
#endif
open class NSUUID : NSObject, NSCopying, NSSecureCoding, NSCoding {
internal var buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
deinit {
buffer.deinitialize()
buffer.deallocate(capacity: 16)
}
public override init() {
_cf_uuid_generate_random(buffer)
}
public convenience init?(uuidString string: String) {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
defer {
buffer.deinitialize()
buffer.deallocate(capacity: 16)
}
if _cf_uuid_parse(string, buffer) != 0 {
return nil
}
self.init(uuidBytes: buffer)
}
public init(uuidBytes bytes: UnsafePointer<UInt8>) {
memcpy(UnsafeMutableRawPointer(buffer), UnsafeRawPointer(bytes), 16)
}
open func getBytes(_ uuid: UnsafeMutablePointer<UInt8>) {
_cf_uuid_copy(uuid, buffer)
}
open var uuidString: String {
let strPtr = UnsafeMutablePointer<Int8>.allocate(capacity: 37)
defer {
strPtr.deinitialize()
strPtr.deallocate(capacity: 37)
}
_cf_uuid_unparse_upper(buffer, strPtr)
return String(cString: strPtr)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
public convenience required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let decodedData : Data? = coder.withDecodedUnsafeBufferPointer(forKey: "NS.uuidbytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
guard data.count == 16 else { return nil }
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
defer {
buffer.deinitialize()
buffer.deallocate(capacity: 16)
}
data.copyBytes(to: buffer, count: 16)
self.init(uuidBytes: buffer)
}
open func encode(with aCoder: NSCoder) {
aCoder.encodeBytes(buffer, length: 16, forKey: "NS.uuidbytes")
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as UUID:
return other.uuid.0 == buffer[0] &&
other.uuid.1 == buffer[1] &&
other.uuid.2 == buffer[2] &&
other.uuid.3 == buffer[3] &&
other.uuid.4 == buffer[4] &&
other.uuid.5 == buffer[5] &&
other.uuid.6 == buffer[6] &&
other.uuid.7 == buffer[7] &&
other.uuid.8 == buffer[8] &&
other.uuid.9 == buffer[9] &&
other.uuid.10 == buffer[10] &&
other.uuid.11 == buffer[11] &&
other.uuid.12 == buffer[12] &&
other.uuid.13 == buffer[13] &&
other.uuid.14 == buffer[14] &&
other.uuid.15 == buffer[15]
case let other as NSUUID:
return other === self || _cf_uuid_compare(buffer, other.buffer) == 0
default:
return false
}
}
open override var hash: Int {
return Int(bitPattern: CFHashBytes(buffer, 16))
}
open override var description: String {
return uuidString
}
}
extension NSUUID : _StructTypeBridgeable {
public typealias _StructType = UUID
public func _bridgeToSwift() -> UUID {
return UUID._unconditionallyBridgeFromObjectiveC(self)
}
}
|
apache-2.0
|
585080016e704ae89b375051981f2a3e
| 29.855072 | 96 | 0.575388 | 4.417012 | false | false | false | false |
sgr-ksmt/Alertift
|
Sources/Alert.swift
|
1
|
7123
|
//
// Alert.swift
// Alertift
//
// Created by Suguru Kishimoto on 4/26/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import Foundation
import UIKit
extension Alertift {
public enum AlertImagePosition {
case top // Above title and message
case center // Between title and message
case bottom // Below title and message
}
/// Alert
final public class Alert: AlertType, _AlertType {
public typealias Handler = (UIAlertAction, Int, [UITextField]?) -> Void
/// TextFieldHandler
public typealias TextFieldHandler = ((UITextField, Int) -> Void)
/// ActionWithTextFieldsHandler
public typealias ActionWithTextFieldsHandler = ([UITextField]?) -> Void
var _alertController: InnerAlertController!
public var alertController: UIAlertController {
return _alertController as UIAlertController
}
public static var backgroundColor: UIColor?
public static var buttonTextColor: UIColor?
public static var titleTextColor: UIColor?
public static var messageTextColor: UIColor?
/// Make alert
///
/// - Parameters:
/// - title: The title of the alert. Use this string to get the user’s attention and communicate the reason for the alert.
/// - message: Descriptive text that provides additional details about the reason for the alert.
/// - Returns: Instance of **Alert**
public init(title: String? = nil, message: String? = nil) {
buildAlertControlelr(title: title, message: message, style: .alert)
}
public func action(_ action: Alertift.Action, handler: Handler?) -> Self {
return self.action(action, isPreferred: false, handler: handler)
}
public func action(_ action: Alertift.Action, handler: ShortHandler? = nil) -> Self {
return self.action(action) { _, _, _ in handler?() }
}
/// Add action to Alert
///
/// - Parameters:
/// - action: Alert action.
/// - isPreferred: If you want to change this action to preferredAction, set true. Default is false.
/// - handler: The block to execute after this action performed.
/// - Returns: Myself
public func action(_ action: Alertift.Action, isPreferred: Bool, handler: Handler?) -> Self {
return self.action(action, image: nil, isPreferred: isPreferred, handler: handler)
}
public func action(_ action: Alertift.Action, isPreferred: Bool, handler: ShortHandler? = nil) -> Self {
return self.action(action, image: nil, isPreferred: isPreferred) { _, _, _ in handler?() }
}
/// Add action to Alert
///
/// - Parameters:
/// - action: Alert action.
/// - image: Image of action.
/// - renderMode: Render mode for alert action image. Default is `.automatic`
/// - handler: The block to execute after this action performed.
/// - Returns: Myself
public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, handler: Handler?) -> Self {
return self.action(action, image: image, renderingMode: renderingMode, isPreferred: false, handler: handler)
}
public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, handler: ShortHandler? = nil) -> Self {
return self.action(action, image: image, renderingMode: renderingMode, isPreferred: false) { _, _, _ in handler?() }
}
/// Add action to Alert
///
/// - Parameters:
/// - action: Alert action.
/// - image: Image of action
/// - renderMode: Render mode for alert action image. Default is `.automatic`
/// - isPreferred: If you want to change this action to preferredAction, set true. Default is false.
/// - handler: The block to execute after this action performed.
/// - Returns: Myself
public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, isPreferred: Bool, handler: Handler?) -> Self {
let alertAction = buildAlertAction(
action,
handler: merge(_alertController.actionWithTextFieldsHandler, handler ?? { (_, _, _)in })
)
if let image = image {
alertAction.setValue(image.withRenderingMode(renderingMode), forKey: "image")
}
addActionToAlertController(alertAction, isPreferred: isPreferred)
return self
}
public func action(_ action: Alertift.Action, image: UIImage?, renderingMode: UIImage.RenderingMode = .automatic, isPreferred: Bool, handler: ShortHandler? = nil) -> Self {
return self.action(action, image: image, renderingMode: renderingMode, isPreferred: isPreferred) { _, _, _ in handler?() }
}
/// Add text field to alertController
///
/// - Parameter handler: Define handler if you want to customize UITextField. Default is nil.
/// - Returns: Myself
public func textField(configurationHandler handler: ((UITextField) -> Void)? = nil) -> Self {
_alertController.addTextField { [weak self] textField in
handler?(textField)
self?._alertController.registerTextFieldObserver(textField)
}
return self
}
/// Add textFieldHandler to alertController.
///
/// If text field's text is changed, execute textFieldHandler with text field and index.
///
/// - Parameter textFieldTextDidChangeHandler: TextFieldHandler (UITextField, Int) -> Void
/// - Returns: Myself
public func handleTextFieldTextDidChange(textFieldTextDidChangeHandler: TextFieldHandler?) -> Self {
_alertController.textFieldTextDidChangeHandler = textFieldTextDidChangeHandler
return self
}
/// Add alertAction to alertController
///
/// - Parameters:
/// - alertAction: UIAlertAction
/// - isPreferred: If isPreferred is true, alertAction becomes preferredAction.
private func addActionToAlertController(_ alertAction: UIAlertAction, isPreferred: Bool) {
_alertController.addAction(alertAction)
if isPreferred {
_alertController.preferredAction = alertAction
}
}
func convertFinallyHandler(_ handler: Any) -> InnerAlertController.FinallyHandler {
return { (handler as? Handler)?($0, $1, $2) }
}
public func image(_ image: UIImage?, imageTopMargin: Alertift.ImageTopMargin = .none) -> Self {
_alertController.setImage(image, imageTopMargin: imageTopMargin)
return self
}
deinit {
Debug.log()
}
}
}
|
mit
|
6cc556648baacada8cf02d69b201bc06
| 42.680982 | 180 | 0.610674 | 5.056818 | false | false | false | false |
grimbolt/BaseSwiftProject
|
BaseSwiftProject/Sources/Types/FetchViewController.swift
|
1
|
6030
|
//
// FetchViewController.swift
// BaseSwiftProject
//
// Created by Grimbolt on 10.01.2017.
//
//
import UIKit
import CoreData
protocol FakeFetchProtocol {}
private var xoAssociationKey: UInt8 = 0
extension UIViewController: FakeFetchProtocol {
private struct FetchData {
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>
var tableView: UITableView?
}
private var fetchData: [FetchData]? {
get {
return objc_getAssociatedObject(self, &xoAssociationKey) as? [FetchData]
}
set {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
open func addFetchedResultsController(_ clazz: AnyClass, sortDescription: [NSSortDescriptor]? = nil, predicate: NSPredicate? = nil, tableView: UITableView? = nil) -> NSFetchedResultsController<NSFetchRequestResult>? {
let entityName = NSStringFromClass(clazz)
guard let fetchedResultsController = DatabaseHelper.sharedInstance.createFetchedResultController(entityName, sortDescriptor: sortDescription, predicate: predicate) else {
return nil
}
if let delegate = self as? NSFetchedResultsControllerDelegate {
fetchedResultsController.delegate = delegate
}
do {
try fetchedResultsController.performFetch()
} catch { }
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
if fetchData == nil {
fetchData = [FetchData]()
}
fetchData?.append(FetchData(fetchedResultsController: fetchedResultsController, tableView: tableView))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if let tableView = tableView {
tableView.reloadData()
}
}
return fetchedResultsController
}
@objc open func appDidBecomeActive(_ notification: Notification) { }
@objc open func appWillEnterForeground(_ notification: Notification) { }
open func setPredicate(predicate: NSPredicate?, for controller: NSFetchedResultsController<NSFetchRequestResult>) {
controller.fetchRequest.predicate = predicate
do {
try controller.performFetch()
tableView(forController: controller)?.reloadData()
} catch {}
}
open func setSort(descriptors: [NSSortDescriptor]?, for controller: NSFetchedResultsController<NSFetchRequestResult>) {
controller.fetchRequest.sortDescriptors = descriptors
do {
try controller.performFetch()
tableView(forController: controller)?.reloadData()
} catch {}
}
private func tableView(forController controller: NSFetchedResultsController<NSFetchRequestResult>) -> UITableView? {
if let data = fetchData?.first(where: { $0.fetchedResultsController == controller }), let tableView = data.tableView {
return tableView
}
return nil
}
// MARK: - NSFetchedResultControllerDelegate
@objc(controllerWillChangeContent:) open func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if let tableView = tableView(forController: controller) {
tableView.beginUpdates()
}
}
@objc(controller:didChangeSection:atIndex:forChangeType:) open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
if let tableView = tableView(forController: controller) {
switch type {
case .insert:
tableView.insertSections([sectionIndex], with: .fade)
case .delete:
tableView.deleteSections([sectionIndex], with: .fade)
default: break
}
}
}
@objc(controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:) open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if let tableView = tableView(forController: controller) {
switch type {
case .insert:
if let newIndexPath = newIndexPath {
tableView.insertRows(at: [newIndexPath], with: .fade)
}
case .delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
case .update:
if let indexPath = indexPath {
tableView.reloadRows(at: [indexPath], with: .fade)
}
case .move:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
if let newIndexPath = newIndexPath {
tableView.insertRows(at: [newIndexPath], with: .fade)
}
}
}
}
@objc(controllerDidChangeContent:) open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if let tableView = tableView(forController: controller) {
tableView.endUpdates()
}
}
}
|
mit
|
15814eda0804bb22ce0ceae189a69921
| 40.30137 | 279 | 0.654561 | 5.940887 | false | false | false | false |
williamFalcon/WFLocationService
|
WFLocationService/Extensions/AddressConvertions/LocationService+AddressConvertions.swift
|
1
|
3247
|
//
// LocationService+AddressConvertions.swift
//
//
// Created by William Falcon on 6/17/15.
// Copyright (c) 2015 William Falcon. All rights reserved.
//
import Foundation
import CoreLocation
extension LocationService {
///Returns an address from a location using Apple geocoder
func addressFromLocation(location:CLLocation!, completionClosure:((NSDictionary?)->())){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placeMarks, error) -> Void in
if let places = placeMarks {
let marks = places[0]
completionClosure(marks.addressDictionary)
}else {
completionClosure(nil)
}
})
})
}
///Returns a location from a given address using google API
func locationFromAddress(address: String, successClosure success:((latitude:Double, longitude:Double)->()), failureClosure failure:(()->())){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// assemble request
//let addressNS:NSString = address as NSString
//let range = NSRange(location: 0, length: addressNS.length)
// Replace white spaces with plus signs
//let escapedAddress = addressNS.stringByReplacingOccurrencesOfString(" ", withString: "+")
//TODO: move API keys out of class
//let requestURL = "https://maps.googleapis.com/maps/api/geocode/json?address=\(escapedAddress)&key=\(self.GOOGLE_PLACES_API_KEY)"
/*
// Place request
WFHttp.GET(requestURL, optionalParameters: nil, optionalHTTPHeaders: nil, completion: { (result, statusCode, response) -> Void in
if statusCode == 200 { // success
if result.count > 0 {
let (lat, lon) = googlePlacesLocationJSONToCoordinates(result as! NSDictionary)
success(latitude: lat as! Double, longitude: long as! Double)
}
else {
failure()
}
}else {
failure()
}
})*/
})
}
///Extracts the coordinates from google places API
private func googlePlacesLocationJSONToCoordinates(json:NSDictionary) -> (lat:Double?, lon:Double?) {
// get result
let results = json.objectForKey("results") as! NSArray
let geomResult = results.objectAtIndex(0) as! NSDictionary
let geometry = geomResult.valueForKey("geometry") as! NSDictionary
let location = geometry.valueForKey("location") as! NSDictionary
let lat = location.valueForKey("lat") as? NSNumber
let lon = location.valueForKey("lng") as? NSNumber
return (lat:lat?.doubleValue, lon:lon?.doubleValue)
}
}
|
mit
|
cf69a95ad091d74680adbf5ca0a4f1df
| 38.609756 | 145 | 0.563289 | 5.358086 | false | false | false | false |
SwampThingTom/Pokebase
|
Pokebase/ViewController.swift
|
1
|
16436
|
//
// ViewController.swift
// Pokebase
//
// Created by Thomas Aylesworth on 12/10/16.
// Copyright © 2016 Thomas H Aylesworth. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSControlTextEditingDelegate, NSComboBoxDataSource, NSComboBoxDelegate, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var trainerLevelField: NSTextField!
@IBOutlet weak var pokémonField: NSComboBox!
@IBOutlet weak var cpField: NSTextField!
@IBOutlet weak var hpField: NSTextField!
@IBOutlet weak var dustField: NSPopUpButton!
@IBOutlet weak var isPoweredUpField: NSPopUpButton!
@IBOutlet weak var appraisalField: NSPopUpButton!
@IBOutlet weak var isAttBestField: NSButton!
@IBOutlet weak var isDefBestField: NSButton!
@IBOutlet weak var isHpBestField: NSButton!
@IBOutlet weak var bestStatField: NSPopUpButton!
@IBOutlet weak var resultLabel: NSTextField!
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var tableView: NSTableView!
private var savedPokémon = PokémonBox()
private var selectedAppraisal: StatsAppraisal.Appraisal {
get {
guard let appraisal = StatsAppraisal.Appraisal(rawValue: appraisalField.indexOfSelectedItem) else {
return StatsAppraisal.Appraisal.Unknown
}
return appraisal
}
}
private var selectedBestStat: StatsAppraisal.BestStat {
get {
guard let bestStat = StatsAppraisal.BestStat(rawValue: bestStatField.indexOfSelectedItem) else {
return StatsAppraisal.BestStat.Best
}
return bestStat
}
}
private var isAtkBest: Bool {
get {
return isAttBestField.state == NSOnState
}
}
private var isDefBest: Bool {
get {
return isDefBestField.state == NSOnState
}
}
private var isStaBest: Bool {
get {
return isHpBestField.state == NSOnState
}
}
private var appraisal: StatsAppraisal {
get {
if selectedAppraisal == .Unknown {
return StatsAppraisal.None
}
return StatsAppraisal(appraisal: selectedAppraisal,
bestStat: selectedBestStat,
atk: isAtkBest,
def: isDefBest,
sta: isStaBest)
}
}
override func viewDidLoad() {
super.viewDidLoad()
trainerLevelField.stringValue = "\(savedPokémon.trainerLevel)"
pokémonField.selectItem(at: 0)
statusLabel.stringValue = statusString()
tableView.sortDescriptors = [NSSortDescriptor(key: "pokédex", ascending: true)]
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func importFromCsv() {
let fileSelectionPanel = NSOpenPanel.init()
fileSelectionPanel.begin { (result) in
if result != NSFileHandlingPanelOKButton {
return
}
guard let fileUrl = fileSelectionPanel.urls.first else {
return
}
self.savedPokémon.importFromCsv(file: fileUrl)
self.refresh()
}
}
@IBAction func calculateIVs(sender: NSButton) {
guard let ivCalculator = ivCalculator() else {
return
}
let possibleIVs = ivCalculator.derivePossibleIVs()
resultLabel.stringValue = ivResultString(forIVs: possibleIVs)
}
@IBAction func savePokémon(sender: NSButton) {
guard let ivCalculator = ivCalculator() else {
return
}
let pokémon = Pokémon(ivCalculator)
savedPokémon.add(pokémon)
savedPokémon.sort(using: tableView.sortDescriptors)
refresh()
}
@IBAction func removePokémon(_ sender: NSButton) {
let remove = confirm(question: "Are you sure you want to remove this Pokémon?",
text: "This can not be undone")
if remove {
let index = tableView.row(for: sender)
savedPokémon.remove(at: index)
refresh()
}
}
private func confirm(question: String, text: String) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "Yes")
alert.addButton(withTitle: "No")
return alert.runModal() == NSAlertFirstButtonReturn
}
private func ivCalculator() -> IVCalculator? {
guard let dustString = dustField.titleOfSelectedItem,
let dust = Int(dustString) else {
return nil
}
let pokémonIndex = pokémonField.indexOfSelectedItem
if pokémonIndex < 0 {
return nil
}
let species = Species.names[pokémonIndex]
let cp = cpField.integerValue
let hp = hpField.integerValue
let poweredUp = isPoweredUpField.titleOfSelectedItem == "Yes"
let calculator = IVCalculator(species: species,
cp: cp,
hp: hp,
dustPrice: dust,
poweredUp: poweredUp,
appraisal: appraisal)
return calculator
}
private func ivResultString(forIVs ivs: [IndividualValues]) -> String {
let combinations = ivs.count
if combinations == 0 {
return "No combinations found"
}
if combinations > 1 {
let range = ivs.reduce((min: 100, max: 0), { (range, ivs) -> MinMaxRange in
let perfection = Pokémon.percentOfMax(ivs: ivs)
return (min: min(range.min, perfection), max: max(range.max, perfection))
})
return "There are \(combinations) possible combinations with an IV range of \(range.min) - \(range.max)"
}
let iv = ivs.first!
let perfection = Pokémon.percentOfMax(ivs: iv)
return "Level: \(iv.level) ATK: \(iv.atk) DEF: \(iv.def) STA: \(iv.sta) Perfection: \(perfection)"
}
private func refresh() {
tableView.reloadData()
statusLabel.stringValue = statusString()
}
private func statusString() -> String {
let numberOfPokémon = savedPokémon.count
let numberOfSpecies = savedPokémon.uniqueSpeciesCount
return "Total Pokémon: \(numberOfPokémon) Unique Species: \(numberOfSpecies)"
}
// MARK: - Appraisal
@IBAction func appraisalChanged(_ sender: NSPopUpButton) {
let enableAppraisal = sender.indexOfSelectedItem != StatsAppraisal.Appraisal.Unknown.rawValue
isAttBestField.isEnabled = enableAppraisal
isDefBestField.isEnabled = enableAppraisal
isHpBestField.isEnabled = enableAppraisal
bestStatField.isEnabled = enableAppraisal
}
// MARK: - NSControlTextEditingDelegate
func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
guard let identifier = control.identifier else {
return true
}
switch(identifier) {
case "trainerLevelField":
return trainerLevelFieldShouldEndEditing()
case "ivCalcSpeciesField":
return ivCalcSpeciesFieldShouldEndEditing()
default:
return true
}
}
func trainerLevelFieldShouldEndEditing() -> Bool {
let level = trainerLevelField.integerValue
if level < 1 || level > 40 {
return false
}
savedPokémon.trainerLevel = level
refresh()
return true
}
func ivCalcSpeciesFieldShouldEndEditing() -> Bool {
guard let speciesIndex = Species.names.index(of: pokémonField.stringValue) else {
return false
}
pokémonField.selectItem(at: speciesIndex)
return true
}
// MARK: - ComboBox Data Source
func numberOfItems(in comboBox: NSComboBox) -> Int {
return Species.names.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return Species.names[index]
}
func comboBoxSelectionDidChange(_ notification: Notification) {
let pokémonIndex = pokémonField.indexOfSelectedItem
if pokémonIndex < 0 {
return
}
let species = Species.names[pokémonIndex]
scroll(toSpecies: species)
}
// MARK: - Name DidEndEditing
@IBAction func nameDidEndEditing(_ sender: NSTextField) {
let index = tableView.row(for: sender)
if index < 0 {
return
}
savedPokémon.updatePokémon(at: index, name: sender.stringValue)
}
// MARK: - TableView Delegate
func numberOfRows(in tableView: NSTableView) -> Int {
return savedPokémon.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let columnIdentifier = tableColumn?.identifier else {
return nil
}
guard let cellView = tableView.make(withIdentifier: columnIdentifier, owner: self) as? NSTableCellView else {
return nil
}
let cell = cellTextForColumn(columnIdentifier, row: row)
cellView.textField?.stringValue = cell.text
cellView.textField?.alignment = cellAlignmentForColumn(columnIdentifier)
cellView.wantsLayer = cell.color != nil
cellView.layer?.backgroundColor = cell.color
return cellView
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
savedPokémon.sort(using: tableView.sortDescriptors)
tableView.reloadData()
}
func scroll(toSpecies species: String) {
guard let speciesRow = savedPokémon.indexOfFirst(species: species) else {
return
}
guard let visibleRows = visibleRows() else {
return
}
if visibleRows.contains(speciesRow) {
return
}
let headerHeight = tableView.headerView?.headerRect(ofColumn: 0).height ?? 0
let rowRect = tableView.rect(ofRow: speciesRow)
let rowOrigin = CGPoint(x: rowRect.origin.x,
y: rowRect.origin.y - headerHeight)
tableView.scroll(rowOrigin)
}
func visibleRows() -> Range<Int>? {
let visibleRect = tableView.visibleRect
let visibleRows = tableView.rows(in: visibleRect)
return visibleRows.toRange()
}
/// MARK: - TableView Cell Configuration
private func cellAlignmentForColumn(_ columnIdentifier: String) -> NSTextAlignment {
switch columnIdentifier {
case "NameColumn", "SpeciesColumn":
return .left
default:
return .center
}
}
private let editableCellBackgroundColor = CGColor(red: 255.0 / 255.0, green: 250.0 / 255.0, blue: 205.0 / 255.0, alpha: 1.0)
private let attributeCellBackgroundColor = CGColor(red: 190.0 / 255.0, green: 227.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
private let maxCpCellBackgroundColor = CGColor(red: 240.0 / 255.0, green: 240.0 / 255.0, blue: 240.0 / 255.0, alpha: 1.0)
private func cellTextForColumn(_ columnIdentifier: String, row: Int) -> (text: String, color: CGColor?) {
let thisPokémon = savedPokémon[row]
switch columnIdentifier {
case "NameColumn":
guard let name = thisPokémon.name else {
return ("", editableCellBackgroundColor)
}
return (name, editableCellBackgroundColor)
case "SpeciesColumn":
return (thisPokémon.species, editableCellBackgroundColor)
case "CPColumn":
return ("\(thisPokémon.cp)", editableCellBackgroundColor)
case "HPColumn":
return ("\(thisPokémon.hp)", editableCellBackgroundColor)
case "DustColumn":
return ("\(thisPokémon.dustPrice)", editableCellBackgroundColor)
case "PoweredColumn":
return (thisPokémon.poweredUp ? "yes" : "no", editableCellBackgroundColor)
case "LevelColumn":
guard let level = thisPokémon.level else {
return ("", attributeCellBackgroundColor)
}
return ("\(level)", attributeCellBackgroundColor)
case "ATKColumn":
guard let atk = thisPokémon.atk else {
return ("", attributeCellBackgroundColor)
}
return ("\(atk)", attributeCellBackgroundColor)
case "DEFColumn":
guard let def = thisPokémon.def else {
return ("", attributeCellBackgroundColor)
}
return ("\(def)", attributeCellBackgroundColor)
case "STAColumn":
guard let sta = thisPokémon.sta else {
return ("", attributeCellBackgroundColor)
}
return ("\(sta)", attributeCellBackgroundColor)
case "PercentColumn":
if let ivPercent = thisPokémon.ivPercent {
return ("\(ivPercent)", backgroundColor(forIvPercent: CGFloat(ivPercent) / CGFloat(100.0)))
}
let range = thisPokémon.ivPercentRange
if range.max < range.min {
return ("unknown", nil)
}
let color = backgroundColor(forIvPercent: CGFloat(range.max) / CGFloat(100.0))
return ("\(range.min) - \(range.max)", color)
case "PerfectCPColumn":
guard let perfectCP = thisPokémon.perfectCP else {
return ("", maxCpCellBackgroundColor)
}
return ("\(perfectCP)", maxCpCellBackgroundColor)
case "PoweredUpCPColumn":
guard let poweredUpCP = thisPokémon.poweredUpCP else {
return ("", maxCpCellBackgroundColor)
}
return ("\(poweredUpCP)", maxCpCellBackgroundColor)
case "MaxedCPColumn":
guard let maxCP = thisPokémon.maxCP else {
return ("", maxCpCellBackgroundColor)
}
return ("\(maxCP)", maxCpCellBackgroundColor)
case "RemoveColumn":
return ("", nil)
default:
return ("WHOA", nil)
}
}
private func backgroundColor(forIvPercent percent: CGFloat) -> CGColor {
let bad = rgbFloat(red: 230, green: 124, blue: 115)
let good = rgbFloat(red: 87, green: 187, blue: 138)
let white = rgbFloat(red: 255, green: 255, blue: 255)
let rgb = percent <= 0.5 ? gradient(percent: percent, a: bad, b: white) : gradient(percent: percent - 0.5, a: white, b: good)
return CGColor(red: rgb.red, green: rgb.green, blue: rgb.blue, alpha: 1.0)
}
private typealias rgb = (red: CGFloat, green: CGFloat, blue: CGFloat)
private func rgbFloat(red: Int, green: Int, blue: Int) -> rgb {
let maxScalar = CGFloat(255)
return (red: CGFloat(red) / maxScalar,
green: CGFloat(green) / maxScalar,
blue: CGFloat(blue) / maxScalar)
}
private func gradient(percent: CGFloat, a: rgb, b: rgb) -> rgb {
return (red: gradient(percent: percent, a: a.red, b: b.red),
green: gradient(percent: percent, a: a.green, b: b.green),
blue: gradient(percent: percent, a: a.blue, b: b.blue))
}
private func gradient(percent: CGFloat, a: CGFloat, b: CGFloat) -> CGFloat {
let a1 = a * (0.5 - percent)
let b1 = b * (percent)
return (a1 + b1) * 2.0
}
}
|
mit
|
c6be9a645b608a2837b3c2dbfdf0b777
| 34.148069 | 156 | 0.58056 | 4.665053 | false | false | false | false |
Knoxantropicen/Focus-iOS
|
Focus/PopUpViewController.swift
|
1
|
4070
|
//
// PopUpViewController.swift
// Focus
//
// Created by TianKnox on 2017/5/27.
// Copyright © 2017年 TianKnox. All rights reserved.
//
import UIKit
class PopUpViewController: UIViewController {
static var popingUp = false
var rowNum: Int = 0
@IBOutlet weak var viewFrame: UIView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var editButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
viewFrame.backgroundColor = Style.popBackgroundColor
descriptionText.backgroundColor = Style.cellBackgroundColor
let textColor = Style.mainTextColor
descriptionLabel.textColor = textColor
descriptionText.textColor = textColor
closeButton.setTitleColor(textColor, for: .normal)
editButton.setTitleColor(textColor, for: .normal)
descriptionLabel.text = Language.description
closeButton.setTitle(Language.close, for: .normal)
editButton.setTitle(Language.edit, for: .normal)
let tapGesture = UITapGestureRecognizer(target: self, action:#selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
self.showAnimate()
}
func showAnimate() {
PopUpViewController.popingUp = true
descriptionText.text = DoneTableViewController.descriptions[rowNum]
if descriptionText.text == Language.englishEditModel && !Language.EnglishLanguage {
descriptionText.text = Language.chineseEditModel
} else if descriptionText.text == Language.chineseEditModel && Language.EnglishLanguage {
descriptionText.text = Language.englishEditModel
}
if descriptionText.text == Language.editModel {
descriptionText.alpha = 0.3
}
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: {
self.view.alpha = 1.0
self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "disableSwipe"), object: nil)
}
func hideKeyboard() {
if descriptionText.text == "" {
descriptionText.text = Language.editModel
descriptionText.alpha = 0.3
}
view.endEditing(true)
}
@IBAction func EnableEdit(_ sender: UIButton) {
descriptionText.backgroundColor = Style.editTextColor
descriptionText.isEditable = true
descriptionText.becomeFirstResponder()
descriptionText.alpha = 1
if descriptionText.text == Language.editModel {
descriptionText.selectedTextRange = descriptionText.textRange(from: descriptionText.beginningOfDocument, to: descriptionText.endOfDocument)
} else {
descriptionText.selectedRange = NSRange(location: descriptionText.text.lengthOfBytes(using: .utf8), length: 0)
}
}
@IBAction func closePopUp(_ sender: UIButton) {
descriptionText.isEditable = false
DoneTableViewController.descriptions[rowNum] = descriptionText.text
removeAnimate()
}
func removeAnimate() {
UIView.animate(withDuration: 0.25, animations: {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
}, completion:{(finished : Bool) in
if (finished)
{
self.view.removeFromSuperview()
}
self.descriptionText.backgroundColor = UIColor(colorLiteralRed: 245/255, green: 245/255, blue: 245/255, alpha: 1)
})
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "enableSwipe"), object: nil)
PopUpViewController.popingUp = false
}
}
|
mit
|
5aa8236917c86313a002db74388aad7d
| 35.972727 | 151 | 0.652324 | 5.039653 | false | false | false | false |
Imgur/Hermes
|
Hermes/Hermes.swift
|
1
|
4919
|
import UIKit
import AVFoundation
@objc public protocol HermesDelegate {
/**
:param: hermes the Hermes instance
:param: notification the notification being made
:returns: the notification view, or nil to use HermesDefaultNotificationView
*/
optional func hermesNotificationViewForNotification(hermes hermes: Hermes, notification: HermesNotification) -> HermesNotificationView?
/**
:param: hermes the Hermes instance
:param: explicit is true if the user closed the bulletin with their finger, instead of relying on autoclose
:param: notification the notification that was showing when Hermes was closed
*/
optional func hermesDidClose(hermes: Hermes, explicit: Bool, notification: HermesNotification)
}
/**
Hermes is an in-app notification system that has a simple interface and can work with just about any sort of notification you can think of.
Examples include, but are not limited to:
- Success alerts
- Failure alerts
- Push Notifications
- Social Notifications (someone just commented on your post!)
Notes:
- Currently, this library only works well when you keep your app in one orientation. Switching between portrait and landscape causes some gnarly
bugs and still needs to be handled.
*/
@objc public enum HermesStyle : Int {
case Dark, Light
}
public class Hermes: NSObject, HermesBulletinViewDelegate {
// MARK: - Public variables
// MARK: - Singleton
/**
You typically will never need to use more than one instance of Hermes
*/
public static let sharedInstance = Hermes()
public var style: HermesStyle = .Dark
// MARK: -
weak public var delegate: HermesDelegate?
// MARK: - private variables
private var bulletinView: HermesBulletinView?
private var notifications = [HermesNotification]()
var audioPlayer: AVAudioPlayer?
/**
When Hermes is waiting, he will collect all of your notifications. Use wait() and go() to tell Hermes when to collect and when to deliver notifications
*/
private var waiting = false {
didSet {
if !waiting {
showNotifications()
}
}
}
// MARK: - Public methods
/**
Give Hermes one notification to post. If waiting == false, you'll see this notification right away
:param: notification The notification you want Hermes to post
*/
public func postNotification(notification: HermesNotification) {
postNotifications([notification])
}
/**
Give Hermes an array of notifications to post. If waiting == false, you'll see these notifications right away
:param: notifications The notifications you want Hermes to post
*/
public func postNotifications(notifications: [HermesNotification]) {
self.notifications += notifications
if let firstNotification = self.notifications.first {
if firstNotification.soundPath != nil {
prepareSound(path: firstNotification.soundPath!)
}
}
showNotifications()
}
/**
Tell Hermes to wait and you can queue up multiple notifications
*/
public func wait() {
waiting = true
}
/**
Done queuing up those notifications? Tell Hermes to go!
*/
public func go() {
waiting = false
showNotifications()
}
public func close() {
bulletinView?.close(explicit: false)
}
public func containsNotification(notification: HermesNotification) -> Bool{
if let bulletinView = self.bulletinView {
return bulletinView.notifications.contains(notification)
}
return false
}
// MARK: - private methods
/**
This method will attempt to show all currently queued up notifications. If Hermes has waiting set to true,
or if there are not notifications, this method will do nothing
*/
private func showNotifications() {
if waiting || notifications.count == 0 || bulletinView != nil {
return
}
bulletinView = HermesBulletinView()
switch style {
case .Dark:
bulletinView!.style = .Dark
case .Light:
bulletinView!.style = .Light
}
bulletinView!.delegate = self
bulletinView!.notifications = notifications
bulletinView!.show()
audioPlayer?.play()
notifications.removeAll(keepCapacity: true)
}
// Initial setup
func prepareSound(path path: String) {
let sound = NSURL(fileURLWithPath: path)
audioPlayer = try! AVAudioPlayer(contentsOfURL: sound)
audioPlayer!.prepareToPlay()
}
// MARK: - HermesBulletinViewDelegate
func bulletinViewDidClose(bulletinView: HermesBulletinView, explicit: Bool) {
delegate?.hermesDidClose?(self, explicit: explicit, notification: bulletinView.currentNotification)
self.bulletinView = nil
showNotifications()
}
func bulletinViewNotificationViewForNotification(notification: HermesNotification) -> HermesNotificationView? {
return delegate?.hermesNotificationViewForNotification?(hermes: self, notification: notification)
}
}
|
mit
|
79065555e4eaf705a3919416bb934e42
| 28.45509 | 153 | 0.715593 | 4.775728 | false | false | false | false |
JohnEstropia/CoreStore
|
Demo/Sources/Demos/Advanced/EvolutionDemo/Advanced.EvolutionDemo.GeologicalPeriod.swift
|
1
|
2466
|
//
// Demo
// Copyright © 2020 John Rommel Estropia, Inc. All rights reserved.
import CoreStore
// MARK: - AdvancedEvolutionDemo
extension Advanced.EvolutionDemo {
// MARK: - GeologicalPeriod
enum GeologicalPeriod: RawRepresentable, CaseIterable, Hashable, CustomStringConvertible {
// MARK: Internal
case ageOfInvertebrates
case ageOfFishes
case ageOfReptiles
case ageOfMammals
var version: ModelVersion {
return self.rawValue
}
var creatureType: Advanced.EvolutionDemo.CreatureType.Type {
switch self {
case .ageOfInvertebrates:
return Advanced.EvolutionDemo.V1.Creature.self
case .ageOfFishes:
return Advanced.EvolutionDemo.V2.Creature.self
case .ageOfReptiles:
return Advanced.EvolutionDemo.V3.Creature.self
case .ageOfMammals:
return Advanced.EvolutionDemo.V4.Creature.self
}
}
// MARK: CustomStringConvertible
var description: String {
switch self {
case .ageOfInvertebrates:
return "Invertebrates"
case .ageOfFishes:
return "Fishes"
case .ageOfReptiles:
return "Reptiles"
case .ageOfMammals:
return "Mammals"
}
}
// MARK: RawRepresentable
typealias RawValue = ModelVersion
var rawValue: ModelVersion {
switch self {
case .ageOfInvertebrates:
return Advanced.EvolutionDemo.V1.name
case .ageOfFishes:
return Advanced.EvolutionDemo.V2.name
case .ageOfReptiles:
return Advanced.EvolutionDemo.V3.name
case .ageOfMammals:
return Advanced.EvolutionDemo.V4.name
}
}
init?(rawValue: ModelVersion) {
switch rawValue {
case Advanced.EvolutionDemo.V1.name:
self = .ageOfInvertebrates
case Advanced.EvolutionDemo.V2.name:
self = .ageOfFishes
case Advanced.EvolutionDemo.V3.name:
self = .ageOfReptiles
case Advanced.EvolutionDemo.V4.name:
self = .ageOfMammals
default:
return nil
}
}
}
}
|
mit
|
ba7da3691707bfd797a2d1a78cb0a7a8
| 23.89899 | 94 | 0.551318 | 4.758687 | false | false | false | false |
ryanorendorff/tablescope
|
tablescope/timer.swift
|
1
|
4120
|
//
// timer.swift
//
// Simple scheduling of closures, based off NSTimer.
//
// Created by Ryan Orendorff on 7/2/15.
import Foundation
/**
A class that calls some function at some specified interval.
This class allows you to easily call some closure at a regular
frequency, potentially starting at some date. This makes it very simple
to schedule functions to run at a certain time.
The design of this class is designed to match NSTimer.
:param: fireDate The date to start firing. If not given, this defaults
to now.
:param: interval The amount of time, in seconds, between triggering.
:param: repeats Whether to keep repeating the firing or not.
:param: f The function to call when triggering.
:returns: Timer object
*/
class Timer {
private var timer : NSTimer? = nil
private let fireDate : NSDate
private let timeInvterval : NSTimeInterval
private let f : () -> ()
var valid = true
convenience init(interval : NSTimeInterval,
repeats : Bool,
f : () -> ())
{
self.init(fireDate: NSDate(), interval: interval,
repeats: repeats, f: f)
}
init(fireDate : NSDate,
interval : NSTimeInterval,
repeats : Bool,
f : () -> ())
{
self.f = f
self.fireDate = fireDate
self.timeInvterval = interval
self.timer = NSTimer(fireDate: fireDate, interval: interval,
target: self, selector: "fire",
userInfo: nil, repeats: repeats)
}
/**
Creates and returns a new Timer object and schedules it on the current
run loop in the default mode.
:param: interval The number of seconds between firings of the timer. If
seconds is less than or equal to 0.0, this method
chooses the nonnegative value of 0.1 milliseconds
instead.
:param: repeats If true, the timer will repeatedly reschedule itself
until invalidated. If false, the timer will be
invalidated after it fires.
:param: f The function to call each time the timer triggers.
:returns: A new Timer object.
*/
class func scheduledTimerWithTimeInterval(interval : NSTimeInterval,
repeats : Bool,
f : () -> ())
{
let t = Timer(interval: interval, repeats: repeats, f: f)
NSRunLoop.mainRunLoop().addTimer(t.timer!,
forMode: NSRunLoopCommonModes)
}
/**
Creates and returns a new Timer object and schedules it on the current
run loop in the default mode.
:param: fireDate The time at which the timer should first fire.
:param: interval The number of seconds between firings of the timer. If
seconds is less than or equal to 0.0, this method
chooses the nonnegative value of 0.1 milliseconds
instead.
:param: repeats If true, the timer will repeatedly reschedule itself
until invalidated. If false, the timer will be
invalidated after it fires.
:param: f The function to call each time the timer triggers.
:returns: A new Timer object.
*/
class func scheduledTimerWithTimeInterval(fireDate : NSDate,
interval : NSTimeInterval,
repeats : Bool,
f : () -> ())
{
let t = Timer(fireDate: fireDate, interval: interval,
repeats: repeats, f: f)
NSRunLoop.mainRunLoop().addTimer(t.timer!,
forMode: NSRunLoopCommonModes)
}
/**
Creates and returns a new Timer object and schedules it on the current
run loop in the default mode.
*/
@objc func fire() {
f()
}
/**
Stop the triggered function from firing again.
*/
func invalidate(){
timer!.invalidate()
valid = false
}
deinit {
self.invalidate()
}
}
|
gpl-3.0
|
043a4713739ea6dae23b899c0a4368f8
| 30.937984 | 75 | 0.586408 | 4.975845 | false | false | false | false |
evermeer/PassportScanner
|
Pods/EVGPUImage2/framework/Source/FramebufferCache.swift
|
1
|
2444
|
#if os(Linux)
#if GLES
import COpenGLES.gles2
#else
import COpenGL
#endif
#else
#if GLES
import OpenGLES
#else
import OpenGL.GL3
#endif
#endif
// TODO: Add mechanism to purge framebuffers on low memory
public class FramebufferCache {
var framebufferCache = [Int64:[Framebuffer]]()
let context:OpenGLContext
init(context:OpenGLContext) {
self.context = context
}
public func requestFramebufferWithProperties(orientation:ImageOrientation, size:GLSize, textureOnly:Bool = false, minFilter:Int32 = GL_LINEAR, magFilter:Int32 = GL_LINEAR, wrapS:Int32 = GL_CLAMP_TO_EDGE, wrapT:Int32 = GL_CLAMP_TO_EDGE, internalFormat:Int32 = GL_RGBA, format:Int32 = GL_BGRA, type:Int32 = GL_UNSIGNED_BYTE, stencil:Bool = false) -> Framebuffer {
let hash = hashForFramebufferWithProperties(orientation:orientation, size:size, textureOnly:textureOnly, minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
let framebuffer:Framebuffer
if ((framebufferCache[hash]?.count ?? -1) > 0) {
// print("Restoring previous framebuffer")
framebuffer = framebufferCache[hash]!.removeLast()
framebuffer.orientation = orientation
} else {
do {
//debugPrint("Generating new framebuffer at size: \(size)")
framebuffer = try Framebuffer(context:context, orientation:orientation, size:size, textureOnly:textureOnly, minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
framebuffer.cache = self
} catch {
fatalError("Could not create a framebuffer of the size (\(size.width), \(size.height)), error: \(error)")
}
}
return framebuffer
}
public func purgeAllUnassignedFramebuffers() {
framebufferCache.removeAll()
}
func returnToCache(_ framebuffer:Framebuffer) {
// print("Returning to cache: \(framebuffer)")
context.runOperationSynchronously{
if (self.framebufferCache[framebuffer.hash] != nil) {
self.framebufferCache[framebuffer.hash]!.append(framebuffer)
} else {
self.framebufferCache[framebuffer.hash] = [framebuffer]
}
}
}
}
|
bsd-3-clause
|
403dfde2b3f8f975e1db46ced9d2eb8a
| 39.733333 | 365 | 0.662439 | 4.484404 | false | false | false | false |
clappr/clappr-ios
|
Tests/Clappr_Tests/Classes/Plugin/Core/Drawer/DrawerPluginTests.swift
|
1
|
6694
|
import Quick
import Nimble
@testable import Clappr
class DrawerPluginTests: QuickSpec {
override func spec() {
describe(".DrawerPluginTests") {
var plugin: DrawerPlugin!
var core: CoreStub!
beforeEach {
core = CoreStub()
plugin = DrawerPlugin(context: core)
}
describe("#init") {
it("has a position") {
expect(plugin.position).to(equal(.undefined))
}
it("has a size") {
expect(plugin.size).to(equal(.zero))
}
it("starts closed") {
expect(plugin.isClosed).to(beTrue())
}
it("has a placeholder") {
expect(plugin.placeholder).to(equal(.zero))
}
it("starts with alpha zero") {
expect(plugin.view.alpha).to(equal(.zero))
}
}
describe("event listening") {
var triggeredEvents: [Event] = []
beforeEach {
triggeredEvents.removeAll()
core.on(Event.willHideDrawerPlugin.rawValue) {_ in
triggeredEvents.append(.willHideDrawerPlugin)
}
core.on(Event.didHideDrawerPlugin.rawValue) {_ in
triggeredEvents.append(.didHideDrawerPlugin)
}
core.on(Event.willShowDrawerPlugin.rawValue) {_ in
triggeredEvents.append(.willShowDrawerPlugin)
}
core.on(Event.didShowDrawerPlugin.rawValue) {_ in
triggeredEvents.append(.didShowDrawerPlugin)
}
}
context("when showDrawerPlugin is triggered") {
it("opens the drawer") {
core.trigger(.showDrawerPlugin)
expect(plugin.isClosed).to(beFalse())
expect(triggeredEvents).to(equal([.willShowDrawerPlugin, .didShowDrawerPlugin]))
}
}
context("when hideDrawerPlugin is triggered") {
it("closes the drawer") {
core.trigger(.hideDrawerPlugin)
expect(plugin.isClosed).to(beTrue())
expect(triggeredEvents).to(equal([.willHideDrawerPlugin, .didHideDrawerPlugin]))
}
}
context("when open and closes drawer") {
it("triggers the will show and will hide drawer events") {
core.trigger(.showDrawerPlugin)
core.trigger(.hideDrawerPlugin)
expect(plugin.isClosed).to(beTrue())
expect(triggeredEvents).to(equal([.willShowDrawerPlugin, .didShowDrawerPlugin, .willHideDrawerPlugin, .didHideDrawerPlugin]))
}
}
context("when media control is going to be presented") {
it("sets drawer plugin alpha to 1") {
plugin.view.alpha = 0
core.trigger(.willShowMediaControl)
expect(plugin.view.alpha).toEventually(equal(1))
}
}
context("when media control is going to be dismissed") {
it("sets drawer plugin alpha to 1") {
plugin.view.alpha = 1
core.trigger(.willHideMediaControl)
expect(plugin.view.alpha).toEventually(equal(0))
}
}
context("when drawer is opened") {
context("and media control will be dismissed") {
it("keeps the drawer with alpha 1") {
core.trigger(.showDrawerPlugin)
core.trigger(.willShowMediaControl)
core.trigger(.willHideMediaControl)
expect(plugin.view.alpha).toEventually(equal(1))
}
}
}
context("when the didTappedCore event is triggered") {
it("calls hideDrawer event") {
var didCallHideDrawer = false
core.on(Event.hideDrawerPlugin.rawValue) { _ in didCallHideDrawer.toggle() }
core.trigger(.showDrawerPlugin)
core.trigger(InternalEvent.didTappedCore.rawValue)
expect(didCallHideDrawer).to(beTrue())
}
}
}
describe("rendering") {
context("when placeholder is greater than zero") {
it("triggers requestPadding event") {
let core = CoreStub()
let plugin = MockDrawerPlugin(context: core)
plugin._placeholder = 32.0
var paddingRequested: CGFloat = .zero
core.on(Event.requestPadding.rawValue) { info in
paddingRequested = info?["padding"] as? CGFloat ?? .zero
}
plugin.render()
expect(plugin.placeholder).to(equal(32))
expect(paddingRequested).to(equal(32))
}
}
context("when placeholder less than or equal zero") {
it("doesn't trigger requestPadding event") {
let core = CoreStub()
let plugin = MockDrawerPlugin(context: core)
plugin._placeholder = .zero
var didCallRequestPadding = false
core.on(Event.requestPadding.rawValue) { info in
didCallRequestPadding.toggle()
}
plugin.render()
expect(plugin.placeholder).to(equal(.zero))
expect(didCallRequestPadding).to(beFalse())
}
}
}
}
}
}
class MockDrawerPlugin: DrawerPlugin {
var _placeholder: CGFloat = .zero
var didCallRender = false
override var placeholder: CGFloat {
return _placeholder
}
override func render() {
super.render()
didCallRender = true
}
}
|
bsd-3-clause
|
c402653bd86f3241c15fdcb7d49d1d5d
| 34.796791 | 149 | 0.460114 | 5.929141 | false | false | false | false |
mahmudahsan/AppsPortfolio
|
AppsPortfolio/Sources/AppsPortfolioViewController.swift
|
1
|
6826
|
/**
* Apps Portfolio
*
* Copyright (c) 2017 Mahmud Ahsan. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import UIKit
public class AppsPortfolioViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var segmentControl:UISegmentedControl!
@IBOutlet weak var tableView:UITableView!
@IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
var animDuration:Double = 0.3
var animDelay:Double = 0.1
var appList:AppList = AppList()
var segmentIndex = 0 //default tab
var analytics:Analytics? // defined in AppList
override public func viewDidLoad() {
super.viewDidLoad()
// In UI design it has 2 segment so removed those at initialization
segmentControl.removeAllSegments()
segmentControl.isHidden = true
segmentIndex = 0
if let category = appList.portfolioCategory{
// We don't show portfolio category at the top, if there is only one category in .plist
if category.count > 1 {
for (index, title) in category.enumerated(){
segmentControl.insertSegment(withTitle: title, at: index, animated: false)
}
segmentControl.isHidden = false
segmentControl.selectedSegmentIndex = 0
}
else {
//if provideo one category then adjust the constrain to place within segmented area
tableViewTopConstraint.constant = -28.0
}
}
}
// MARK:-- Load the portfolio from plist file
/**
* Protocol to detect whether user tap an app in the portfolio
*/
public func loadAppList(name:String){
appList.loadAppList(listName: name)
appList.processAppList()
}
public func setAnalyticsDelegate(any: Any){
analytics = any as? Analytics
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rootArrList = appList.portfolioListDetails as NSArray?
if rootArrList != nil{
let categoryWiseItemList = rootArrList?.object(at: segmentIndex) as! NSArray
return categoryWiseItemList.count
}
return 0
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70.0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:AppsPortfolioTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell") as? AppsPortfolioTableViewCell
if (cell == nil){
let bundle = Bundle(for: AppsPortfolioViewController.self)
cell = bundle.loadNibNamed("AppsPortfolioTableViewCell", owner: self, options: nil)?[0] as? AppsPortfolioTableViewCell
}
let rootArrList = appList.portfolioListDetails as NSArray?
if rootArrList != nil{
let categoryWiseItemList = rootArrList?.object(at: segmentIndex) as! NSArray
let appDetail = categoryWiseItemList.object(at: indexPath.row) as! NSDictionary
cell?.title!.text = appDetail.value(forKey: "name") as? String
cell?.imgIcon.image = UIImage(named: appDetail.value(forKey: "image") as! String)
}
/**
* Animation to show the table items in style
*/
// if (!cell!.isAnimationDone){
// cell!.alpha = 0.0
//
// ModelEffect.sharedInstance.bouneEffectAnimation(duration: animDuration, delay: animDelay, view: cell!, vOrH: false, animVal: 30.0, pOn: false)
// cell!.isAnimationDone = true
// animDuration += 0.1
// animDelay += 0.01
// }
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: self.tableView.indexPathForSelectedRow!, animated: true)
var appUrl:String = ""
var appTitle:String = ""
let rootArrList = appList.portfolioListDetails as NSArray?
if rootArrList != nil{
let categoryWiseItemList = rootArrList?.object(at: segmentIndex) as! NSArray
let appDetail = categoryWiseItemList.object(at: indexPath.row) as! NSDictionary
appUrl = (appDetail.value(forKey: "url") as? String)!
appTitle = (appDetail.value(forKey: "name") as? String)!
}
//analytics call delegate
analytics?.appClicked(appNamed: appTitle)
UIApplication.shared.open(NSURL(string : appUrl)! as URL,
options:convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
/**
* When segmented tab changed, the table view reload
*/
@IBAction func reloadList(sender: AnyObject) {
segmentIndex = segmentControl.selectedSegmentIndex
tableView.reloadData()
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
|
mit
|
00882624206e2659156181484e13d66a
| 40.621951 | 156 | 0.655289 | 4.960756 | false | false | false | false |
strivingboy/CocoaChinaPlus
|
Code/CocoaChinaPlus/Application/Business/Util/Helper/HTMLModel/Parser/CCHTMLParser+OptionPage.swift
|
1
|
3241
|
//
// CCHTMLParser+OptionPage.swift
// CocoaChinaPlus
//
// Created by user on 15/10/31.
// Copyright © 2015年 zixun. All rights reserved.
//
import Foundation
import Ji
extension CCHTMLParser {
func parsePage(urlString:String,result:(model:[CCArticleModel],nextURL:String?)->Void) {
weak var weakSelf = self
CCRequest(.GET, urlString).responseJi { (ji, error) -> Void in
let nextPageURL = weakSelf!.parseNextPageURL(ji!, currentURL: urlString)
let article = weakSelf!.parseArticle(ji!)
result(model: article, nextURL: nextPageURL)
}
}
private func parseNextPageURL(ji:Ji,currentURL:String) -> String? {
guard let nodes = ji.xPath("//div[@id='page']/a") else {
return nil
}
var find = false
var urlString:String?
for node in nodes {
//如果上一次循环已经发现当前页面,说明这一次循环就是下一页
if find {
//如果是末页,说明这是最后一页,没有下一页
if node.content != "末页" {
urlString = node["href"]
}
break
}
//判断是否当前页
if node["class"] == "thisclass" {
find = true
}
}
guard urlString != nil else {
return nil
}
return self.optionPathOfURL(currentURL) + urlString!
}
private func optionPathOfURL(urlString:String) -> String {
let str = urlString as NSString
var count = 0
for var i = 0; i < str.length; i++ {
let temp = str.substringWithRange(NSMakeRange(i, 1))
if temp == "/" {
count++
if count >= 4 {
return str.substringWithRange(NSMakeRange(0,i+1))
}
}
}
return urlString
}
private func parseArticle(ji: Ji) -> [CCArticleModel] {
guard let nodes = ji.xPath("//div[@class='clearfix']") else {
return [CCArticleModel]()
}
var models = [CCArticleModel]()
for node in nodes {
let model = CCArticleModel()
var inner = node.xPath(".//a[@class='pic float-l']").first!
let href = "http://www.cocoachina.com" + inner["href"]!
let title = inner["title"]!
inner = inner.xPath(".//img").first!
let imageURL = inner["src"]!
let addtion = node.xPath("//div[@class='clearfix zx_manage']/div[@class='float-l']/span")
let postTime = addtion[0].content!
let viewed = addtion[1].content!
model.linkURL = href
model.title = title
model.postTime = postTime
model.viewed = viewed
model.imageURL = imageURL
models.append(model)
}
return models
}
}
|
mit
|
fe05c1f183d7e18dbcd9d367ecc1c54b
| 26.412281 | 101 | 0.473431 | 4.74772 | false | false | false | false |
BalestraPatrick/Tweetometer
|
TweetometerKit/TimelineDownloaderOperation.swift
|
2
|
1958
|
//
// TimelineDownloaderOperation.swift
// TweetometerKit
//
// Created by Patrick Balestra on 8/17/18.
// Copyright © 2018 Patrick Balestra. All rights reserved.
//
import Foundation
import TwitterKit
class TimelineDownloaderOperation: Operation {
let client: TWTRAPIClient
let maxId: String?
let semaphore = DispatchSemaphore(value: 0)
var result: Result<[Tweet]>?
init(client: TWTRAPIClient, maxId: String? = nil) {
self.client = client
self.maxId = maxId
}
override func main() {
let url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
var parameters = ["count": "200", "exclude_replies": "false"]
if let maxId = maxId {
parameters["max_id"] = maxId
}
let request = client.urlRequest(withMethod: "GET", urlString: url, parameters: parameters, error: nil)
client.sendTwitterRequest(request) { [unowned self] response, data, error in
// Closure is called on main thread for whatever Twitter engineers reason had, go back to background thread to do JSON decoding.
DispatchQueue.global(qos: .userInitiated).async {
if let error = error {
self.result = .error(TweetometerError.from(error))
self.semaphore.signal()
return
}
guard let data = data else {
self.result = .error(TweetometerError.invalidResponse)
self.semaphore.signal()
return
}
do {
let tweets = try JSONDecoder.twitter.decode([Tweet].self, from: data)
self.result = .success(tweets)
} catch {
self.result = .error(TweetometerError.invalidResponse)
}
self.semaphore.signal()
}
}
self.semaphore.wait()
}
}
|
mit
|
ef6bee2ef2c61c0316a03c52daf96d7d
| 33.333333 | 140 | 0.568728 | 4.670644 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
SwiftCallOC/SwiftCallOC/MainViewController.swift
|
1
|
730
|
//
// ViewController.swift
// SwiftCallOC
//
// Created by bingoogol on 14/9/21.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let img = UIImage(named: "hehe.jpg")
var iv = QFImageView(frame: CGRectMake(100, 100, 200, 200))
iv.image = img
iv.addTarget(self, withSelector: Selector("imageClick:"))
self.view.addSubview(iv)
}
func imageClick(iv:QFImageView) {
println("点击了图片")
iv.test()
var name:String = "你好"
var c = iv.getLetter(name)
println("首字母是:\(c)")
}
}
|
apache-2.0
|
9a15766b43e0f68b09c61505e1634fe2
| 22.5 | 67 | 0.59517 | 3.724868 | false | false | false | false |
e78l/swift-corelibs-foundation
|
Foundation/NSNumber.swift
|
1
|
40531
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(macOS) || os(iOS)
internal let kCFNumberSInt8Type = CFNumberType.sInt8Type
internal let kCFNumberSInt16Type = CFNumberType.sInt16Type
internal let kCFNumberSInt32Type = CFNumberType.sInt32Type
internal let kCFNumberSInt64Type = CFNumberType.sInt64Type
internal let kCFNumberFloat32Type = CFNumberType.float32Type
internal let kCFNumberFloat64Type = CFNumberType.float64Type
internal let kCFNumberCharType = CFNumberType.charType
internal let kCFNumberShortType = CFNumberType.shortType
internal let kCFNumberIntType = CFNumberType.intType
internal let kCFNumberLongType = CFNumberType.longType
internal let kCFNumberLongLongType = CFNumberType.longLongType
internal let kCFNumberFloatType = CFNumberType.floatType
internal let kCFNumberDoubleType = CFNumberType.doubleType
internal let kCFNumberCFIndexType = CFNumberType.cfIndexType
internal let kCFNumberNSIntegerType = CFNumberType.nsIntegerType
internal let kCFNumberCGFloatType = CFNumberType.cgFloatType
internal let kCFNumberSInt128Type = CFNumberType(rawValue: 17)!
#else
internal let kCFNumberSInt128Type: CFNumberType = 17
#endif
extension Int8 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.int8Value
}
public init(truncating number: NSNumber) {
self = number.int8Value
}
public init?(exactly number: NSNumber) {
let value = number.int8Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int8?) -> Bool {
guard let value = Int8(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int8 {
var result: Int8?
guard let src = source else { return Int8(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int8(0) }
return result!
}
}
extension UInt8 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.uint8Value
}
public init(truncating number: NSNumber) {
self = number.uint8Value
}
public init?(exactly number: NSNumber) {
let value = number.uint8Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt8?) -> Bool {
guard let value = UInt8(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt8 {
var result: UInt8?
guard let src = source else { return UInt8(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt8(0) }
return result!
}
}
extension Int16 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.int16Value
}
public init(truncating number: NSNumber) {
self = number.int16Value
}
public init?(exactly number: NSNumber) {
let value = number.int16Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int16?) -> Bool {
guard let value = Int16(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int16 {
var result: Int16?
guard let src = source else { return Int16(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int16(0) }
return result!
}
}
extension UInt16 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.uint16Value
}
public init(truncating number: NSNumber) {
self = number.uint16Value
}
public init?(exactly number: NSNumber) {
let value = number.uint16Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt16?) -> Bool {
guard let value = UInt16(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt16 {
var result: UInt16?
guard let src = source else { return UInt16(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt16(0) }
return result!
}
}
extension Int32 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.int32Value
}
public init(truncating number: NSNumber) {
self = number.int32Value
}
public init?(exactly number: NSNumber) {
let value = number.int32Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int32?) -> Bool {
guard let value = Int32(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int32 {
var result: Int32?
guard let src = source else { return Int32(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int32(0) }
return result!
}
}
extension UInt32 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.uint32Value
}
public init(truncating number: NSNumber) {
self = number.uint32Value
}
public init?(exactly number: NSNumber) {
let value = number.uint32Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt32?) -> Bool {
guard let value = UInt32(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt32 {
var result: UInt32?
guard let src = source else { return UInt32(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt32(0) }
return result!
}
}
extension Int64 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.int64Value
}
public init(truncating number: NSNumber) {
self = number.int64Value
}
public init?(exactly number: NSNumber) {
let value = number.int64Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int64?) -> Bool {
guard let value = Int64(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int64 {
var result: Int64?
guard let src = source else { return Int64(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int64(0) }
return result!
}
}
extension UInt64 : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.uint64Value
}
public init(truncating number: NSNumber) {
self = number.uint64Value
}
public init?(exactly number: NSNumber) {
let value = number.uint64Value
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt64?) -> Bool {
guard let value = UInt64(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt64 {
var result: UInt64?
guard let src = source else { return UInt64(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt64(0) }
return result!
}
}
extension Int : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.intValue
}
public init(truncating number: NSNumber) {
self = number.intValue
}
public init?(exactly number: NSNumber) {
let value = number.intValue
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Int?) -> Bool {
guard let value = Int(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Int {
var result: Int?
guard let src = source else { return Int(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Int(0) }
return result!
}
}
extension UInt : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.uintValue
}
public init(truncating number: NSNumber) {
self = number.uintValue
}
public init?(exactly number: NSNumber) {
let value = number.uintValue
guard NSNumber(value: value) == number else { return nil }
self = value
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout UInt?) -> Bool {
guard let value = UInt(exactly: x) else { return false }
result = value
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> UInt {
var result: UInt?
guard let src = source else { return UInt(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return UInt(0) }
return result!
}
}
extension Float : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.floatValue
}
public init(truncating number: NSNumber) {
self = number.floatValue
}
public init?(exactly number: NSNumber) {
let type = number.objCType.pointee
if type == 0x49 || type == 0x4c || type == 0x51 {
guard let result = Float(exactly: number.uint64Value) else { return nil }
self = result
} else if type == 0x69 || type == 0x6c || type == 0x71 {
guard let result = Float(exactly: number.int64Value) else { return nil }
self = result
} else {
guard let result = Float(exactly: number.doubleValue) else { return nil }
self = result
}
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Float?) -> Bool {
if x.floatValue.isNaN {
result = x.floatValue
return true
}
result = Float(exactly: x)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Float {
var result: Float?
guard let src = source else { return Float(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Float(0) }
return result!
}
}
extension Double : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.doubleValue
}
public init(truncating number: NSNumber) {
self = number.doubleValue
}
public init?(exactly number: NSNumber) {
let type = number.objCType.pointee
if type == 0x51 {
guard let result = Double(exactly: number.uint64Value) else { return nil }
self = result
} else if type == 0x71 {
guard let result = Double(exactly: number.int64Value) else { return nil }
self = result
} else {
// All other integer types and single-precision floating points will
// fit in a `Double` without truncation.
guard let result = Double(exactly: number.doubleValue) else { return nil }
self = result
}
}
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(value: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Double?) -> Bool {
if x.doubleValue.isNaN {
result = x.doubleValue
return true
}
result = Double(exactly: x)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Double {
var result: Double?
guard let src = source else { return Double(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Double(0) }
return result!
}
}
extension Bool : _ObjectiveCBridgeable {
@available(swift, deprecated: 4, renamed: "init(truncating:)")
public init(_ number: NSNumber) {
self = number.boolValue
}
public init(truncating number: NSNumber) {
self = number.boolValue
}
public init?(exactly number: NSNumber) {
if number === kCFBooleanTrue || NSNumber(value: 1) == number {
self = true
} else if number === kCFBooleanFalse || NSNumber(value: 0) == number {
self = false
} else {
return nil
}
}
public func _bridgeToObjectiveC() -> NSNumber {
return unsafeBitCast(self ? kCFBooleanTrue : kCFBooleanFalse, to: NSNumber.self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNumber, result: inout Bool?) -> Bool {
if x === kCFBooleanTrue || NSNumber(value: 1) == x {
result = true
return true
} else if x === kCFBooleanFalse || NSNumber(value: 0) == x {
result = false
return true
}
result = nil
return false
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNumber?) -> Bool {
var result: Bool?
guard let src = source else { return false }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return false }
return result!
}
}
extension Bool : _CFBridgeable {
typealias CFType = CFBoolean
var _cfObject: CFType {
return self ? kCFBooleanTrue : kCFBooleanFalse
}
}
extension NSNumber : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral {
}
private struct CFSInt128Struct {
var high: Int64
var low: UInt64
}
fileprivate func cast<T, U>(_ t: T) -> U {
return t as! U
}
open class NSNumber : NSValue {
typealias CFType = CFNumber
// This layout MUST be the same as CFNumber so that they are bridgeable
private var _base = _CFInfo(typeID: CFNumberGetTypeID())
private var _pad: UInt64 = 0
internal var _cfObject: CFType {
return unsafeBitCast(self, to: CFType.self)
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
// IMPORTANT:
// .isEqual() is invoked by the bridging machinery that gets triggered whenever you use '(-a NSNumber value-) as{,?,!} Int', so using a refutable pattern ('case let other as NSNumber') below will cause an infinite loop if value is an Int, and similarly for other types we can bridge to.
// To prevent this, _this check must come first._ If you change it, _do not use the 'as' operator_ or any of its variants _unless_ you know that value _is_ actually a NSNumber to avoid infinite loops. ('is' is fine.)
if let value = value, value is NSNumber {
return compare(value as! NSNumber) == .orderedSame
}
switch value {
case let other as Int:
return intValue == other
case let other as Double:
return doubleValue == other
case let other as Bool:
return boolValue == other
default:
return false
}
}
open override var objCType: UnsafePointer<Int8> {
func _objCType(_ staticString: StaticString) -> UnsafePointer<Int8> {
return UnsafeRawPointer(staticString.utf8Start).assumingMemoryBound(to: Int8.self)
}
let numberType = _CFNumberGetType2(_cfObject)
switch numberType {
case kCFNumberSInt8Type:
return _objCType("c")
case kCFNumberSInt16Type:
return _objCType("s")
case kCFNumberSInt32Type:
return _objCType("i")
case kCFNumberSInt64Type:
return _objCType("q")
case kCFNumberFloat32Type:
return _objCType("f")
case kCFNumberFloat64Type:
return _objCType("d")
case kCFNumberSInt128Type:
return _objCType("Q")
default:
fatalError("unsupported CFNumberType: '\(numberType)'")
}
}
internal var _swiftValueOfOptimalType: Any {
if self === kCFBooleanTrue {
return true
} else if self === kCFBooleanFalse {
return false
}
let numberType = _CFNumberGetType2(_cfObject)
switch numberType {
case kCFNumberSInt8Type:
return Int(int8Value)
case kCFNumberSInt16Type:
return Int(int16Value)
case kCFNumberSInt32Type:
return Int(int32Value)
case kCFNumberSInt64Type:
return int64Value < Int.max ? Int(int64Value) : int64Value
case kCFNumberFloat32Type:
return floatValue
case kCFNumberFloat64Type:
return doubleValue
case kCFNumberSInt128Type:
// If the high portion is 0, return just the low portion as a UInt64, which reasonably fixes trying to roundtrip UInt.max and UInt64.max.
if int128Value.high == 0 {
return int128Value.low
} else {
return int128Value
}
default:
fatalError("unsupported CFNumberType: '\(numberType)'")
}
}
deinit {
_CFDeinit(self)
}
private convenience init(bytes: UnsafeRawPointer, numberType: CFNumberType) {
let cfnumber = CFNumberCreate(nil, numberType, bytes)
self.init(factory: { cast(unsafeBitCast(cfnumber, to: NSNumber.self)) })
}
public convenience init(value: Int8) {
var value = value
self.init(bytes: &value, numberType: kCFNumberSInt8Type)
}
public convenience init(value: UInt8) {
var value = Int16(value)
self.init(bytes: &value, numberType: kCFNumberSInt16Type)
}
public convenience init(value: Int16) {
var value = value
self.init(bytes: &value, numberType: kCFNumberSInt16Type)
}
public convenience init(value: UInt16) {
var value = Int32(value)
self.init(bytes: &value, numberType: kCFNumberSInt32Type)
}
public convenience init(value: Int32) {
var value = value
self.init(bytes: &value, numberType: kCFNumberSInt32Type)
}
public convenience init(value: UInt32) {
var value = Int64(value)
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
}
public convenience init(value: Int) {
var value = value
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
#elseif arch(i386) || arch(arm)
self.init(bytes: &value, numberType: kCFNumberSInt32Type)
#endif
}
public convenience init(value: UInt) {
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
if value > UInt64(Int64.max) {
var value = CFSInt128Struct(high: 0, low: UInt64(value))
self.init(bytes: &value, numberType: kCFNumberSInt128Type)
} else {
var value = Int64(value)
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
}
#elseif arch(i386) || arch(arm)
var value = Int64(value)
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
#endif
}
public convenience init(value: Int64) {
var value = value
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
}
public convenience init(value: UInt64) {
if value > UInt64(Int64.max) {
var value = CFSInt128Struct(high: 0, low: UInt64(value))
self.init(bytes: &value, numberType: kCFNumberSInt128Type)
} else {
var value = Int64(value)
self.init(bytes: &value, numberType: kCFNumberSInt64Type)
}
}
public convenience init(value: Float) {
var value = value
self.init(bytes: &value, numberType: kCFNumberFloatType)
}
public convenience init(value: Double) {
var value = value
self.init(bytes: &value, numberType: kCFNumberDoubleType)
}
public convenience init(value: Bool) {
self.init(factory: cast(value._bridgeToObjectiveC))
}
override internal init() {
super.init()
}
public required convenience init(bytes buffer: UnsafeRawPointer, objCType: UnsafePointer<Int8>) {
guard let type = _NSSimpleObjCType(UInt8(objCType.pointee)) else {
fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'")
}
switch type {
case .Bool:
self.init(value:buffer.load(as: Bool.self))
case .Char:
self.init(value:buffer.load(as: Int8.self))
case .UChar:
self.init(value:buffer.load(as: UInt8.self))
case .Short:
self.init(value:buffer.load(as: Int16.self))
case .UShort:
self.init(value:buffer.load(as: UInt16.self))
case .Int, .Long:
self.init(value:buffer.load(as: Int32.self))
case .UInt, .ULong:
self.init(value:buffer.load(as: UInt32.self))
case .LongLong:
self.init(value:buffer.load(as: Int64.self))
case .ULongLong:
self.init(value:buffer.load(as: UInt64.self))
case .Float:
self.init(value:buffer.load(as: Float.self))
case .Double:
self.init(value:buffer.load(as: Double.self))
default:
fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'")
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.number") {
let number = aDecoder._decodePropertyListForKey("NS.number")
if let val = number as? Double {
self.init(value:val)
} else if let val = number as? Int {
self.init(value:val)
} else if let val = number as? Bool {
self.init(value:val)
} else {
return nil
}
} else {
if aDecoder.containsValue(forKey: "NS.boolval") {
self.init(value: aDecoder.decodeBool(forKey: "NS.boolval"))
} else if aDecoder.containsValue(forKey: "NS.intval") {
self.init(value: aDecoder.decodeInt64(forKey: "NS.intval"))
} else if aDecoder.containsValue(forKey: "NS.dblval") {
self.init(value: aDecoder.decodeDouble(forKey: "NS.dblval"))
} else {
return nil
}
}
}
open var int8Value: Int8 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var uint8Value: UInt8 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var int16Value: Int16 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var uint16Value: UInt16 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var int32Value: Int32 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var uint32Value: UInt32 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var int64Value: Int64 {
var value: Int64 = 0
CFNumberGetValue(_cfObject, kCFNumberSInt64Type, &value)
return .init(truncatingIfNeeded: value)
}
open var uint64Value: UInt64 {
var value = CFSInt128Struct(high: 0, low: 0)
CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value)
return .init(truncatingIfNeeded: value.low)
}
private var int128Value: CFSInt128Struct {
var value = CFSInt128Struct(high: 0, low: 0)
CFNumberGetValue(_cfObject, kCFNumberSInt128Type, &value)
return value
}
open var floatValue: Float {
var value: Float = 0
CFNumberGetValue(_cfObject, kCFNumberFloatType, &value)
return value
}
open var doubleValue: Double {
var value: Double = 0
CFNumberGetValue(_cfObject, kCFNumberDoubleType, &value)
return value
}
open var boolValue: Bool {
// Darwin Foundation NSNumber appears to have a bug and return false for NSNumber(value: Int64.min).boolValue,
// even though the documentation says:
// "A 0 value always means false, and any nonzero value is interpreted as true."
return (int64Value != 0) && (int64Value != Int64.min)
}
open var intValue: Int {
var val: Int = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongType, value)
}
return val
}
open var uintValue: UInt {
var val: UInt = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongType, value)
}
return val
}
open var stringValue: String {
return self.description
}
/// Create an instance initialized to `value`.
public required convenience init(integerLiteral value: Int) {
self.init(value: value)
}
/// Create an instance initialized to `value`.
public required convenience init(floatLiteral value: Double) {
self.init(value: value)
}
/// Create an instance initialized to `value`.
public required convenience init(booleanLiteral value: Bool) {
self.init(value: value)
}
open func compare(_ otherNumber: NSNumber) -> ComparisonResult {
switch (_cfNumberType(), otherNumber._cfNumberType()) {
case (kCFNumberFloatType, _), (_, kCFNumberFloatType): fallthrough
case (kCFNumberDoubleType, _), (_, kCFNumberDoubleType):
let (lhs, rhs) = (doubleValue, otherNumber.doubleValue)
// Apply special handling for NaN as <, >, == always return false
// when comparing with NaN
if lhs.isNaN && rhs.isNaN { return .orderedSame }
if lhs.isNaN { return rhs < 0 ? .orderedDescending : .orderedAscending }
if rhs.isNaN { return lhs < 0 ? .orderedAscending : .orderedDescending }
if lhs < rhs { return .orderedAscending }
if lhs > rhs { return .orderedDescending }
return .orderedSame
default: // For signed and unsigned integers expand upto S128Int
let (lhs, rhs) = (int128Value, otherNumber.int128Value)
if lhs.high < rhs.high { return .orderedAscending }
if lhs.high > rhs.high { return .orderedDescending }
if lhs.low < rhs.low { return .orderedAscending }
if lhs.low > rhs.low { return .orderedDescending }
return .orderedSame
}
}
open func description(withLocale locale: Locale?) -> String {
guard let locale = locale else { return self.description }
switch _CFNumberGetType2(_cfObject) {
case kCFNumberSInt8Type, kCFNumberCharType:
return String(format: "%d", locale: locale, self.int8Value)
case kCFNumberSInt16Type, kCFNumberShortType:
return String(format: "%hi", locale: locale, self.int16Value)
case kCFNumberSInt32Type:
return String(format: "%d", locale: locale, self.int32Value)
case kCFNumberIntType, kCFNumberLongType, kCFNumberNSIntegerType, kCFNumberCFIndexType:
return String(format: "%ld", locale: locale, self.intValue)
case kCFNumberSInt64Type, kCFNumberLongLongType:
return String(format: "%lld", locale: locale, self.int64Value)
case kCFNumberSInt128Type:
let value = self.int128Value
if value.high == 0 {
return value.low.description // BUG: "%llu" doesnt work correctly and treats number as signed
} else {
// BUG: Note the locale is actually ignored here as this is converted using CFNumber.c:emit128()
return String(format: "%@", locale: locale, unsafeBitCast(_cfObject, to: UnsafePointer<CFNumber>.self))
}
case kCFNumberFloatType, kCFNumberFloat32Type:
return String(format: "%0.7g", locale: locale, self.floatValue)
case kCFNumberFloat64Type, kCFNumberDoubleType:
return String(format: "%0.16g", locale: locale, self.doubleValue)
case kCFNumberCGFloatType:
if Int.max == Int32.max {
return String(format: "%0.7g", locale: locale, self.floatValue)
} else {
return String(format: "%0.16g", locale: locale, self.doubleValue)
}
default: fatalError("Unknown NSNumber Type")
}
}
override open var _cfTypeID: CFTypeID {
return CFNumberGetTypeID()
}
open override var description: String {
switch _CFNumberGetType2(_cfObject) {
case kCFNumberSInt8Type, kCFNumberCharType, kCFNumberSInt16Type, kCFNumberShortType,
kCFNumberSInt32Type, kCFNumberIntType, kCFNumberLongType, kCFNumberNSIntegerType, kCFNumberCFIndexType:
return self.intValue.description
case kCFNumberSInt64Type, kCFNumberLongLongType:
return self.int64Value.description
case kCFNumberSInt128Type:
let value = self.int128Value
if value.high == 0 {
return value.low.description
} else {
return String(format: "%@", locale: nil, unsafeBitCast(_cfObject, to: UnsafePointer<CFNumber>.self))
}
case kCFNumberFloatType, kCFNumberFloat32Type:
return self.floatValue.description
case kCFNumberFloat64Type, kCFNumberDoubleType:
return self.doubleValue.description
case kCFNumberCGFloatType:
if Int.max == Int32.max {
return self.floatValue.description
} else {
return self.doubleValue.description
}
default: fatalError("Unknown NSNumber Type")
}
}
internal func _cfNumberType() -> CFNumberType {
switch objCType.pointee {
case 0x42: return kCFNumberCharType
case 0x63: return kCFNumberCharType
case 0x43: return kCFNumberShortType
case 0x73: return kCFNumberShortType
case 0x53: return kCFNumberIntType
case 0x69: return kCFNumberIntType
case 0x49: return Int(uint32Value) < Int(Int32.max) ? kCFNumberIntType : kCFNumberLongLongType
case 0x6C: return kCFNumberLongType
case 0x4C: return uintValue < UInt(Int.max) ? kCFNumberLongType : kCFNumberLongLongType
case 0x66: return kCFNumberFloatType
case 0x64: return kCFNumberDoubleType
case 0x71: return kCFNumberLongLongType
case 0x51: return kCFNumberLongLongType
default: fatalError()
}
}
internal func _getValue(_ valuePtr: UnsafeMutableRawPointer, forType type: CFNumberType) -> Bool {
switch type {
case kCFNumberSInt8Type:
valuePtr.assumingMemoryBound(to: Int8.self).pointee = int8Value
case kCFNumberSInt16Type:
valuePtr.assumingMemoryBound(to: Int16.self).pointee = int16Value
case kCFNumberSInt32Type:
valuePtr.assumingMemoryBound(to: Int32.self).pointee = int32Value
case kCFNumberSInt64Type:
valuePtr.assumingMemoryBound(to: Int64.self).pointee = int64Value
case kCFNumberSInt128Type:
struct CFSInt128Struct {
var high: Int64
var low: UInt64
}
let val = int64Value
valuePtr.assumingMemoryBound(to: CFSInt128Struct.self).pointee = CFSInt128Struct.init(high: (val < 0) ? -1 : 0, low: UInt64(bitPattern: val))
case kCFNumberFloat32Type:
valuePtr.assumingMemoryBound(to: Float.self).pointee = floatValue
case kCFNumberFloat64Type:
valuePtr.assumingMemoryBound(to: Double.self).pointee = doubleValue
default: fatalError()
}
return true
}
open override func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if let keyedCoder = aCoder as? NSKeyedArchiver {
keyedCoder._encodePropertyList(self)
} else {
if CFGetTypeID(self) == CFBooleanGetTypeID() {
aCoder.encode(boolValue, forKey: "NS.boolval")
} else {
switch objCType.pointee {
case 0x42:
aCoder.encode(boolValue, forKey: "NS.boolval")
case 0x63: fallthrough
case 0x43: fallthrough
case 0x73: fallthrough
case 0x53: fallthrough
case 0x69: fallthrough
case 0x49: fallthrough
case 0x6C: fallthrough
case 0x4C: fallthrough
case 0x71: fallthrough
case 0x51:
aCoder.encode(int64Value, forKey: "NS.intval")
case 0x66: fallthrough
case 0x64:
aCoder.encode(doubleValue, forKey: "NS.dblval")
default: break
}
}
}
}
open override var classForCoder: AnyClass { return NSNumber.self }
}
extension CFNumber : _NSBridgeable {
typealias NSType = NSNumber
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
}
internal func _CFSwiftNumberGetType(_ obj: CFTypeRef) -> CFNumberType {
return unsafeBitCast(obj, to: NSNumber.self)._cfNumberType()
}
internal func _CFSwiftNumberGetValue(_ obj: CFTypeRef, _ valuePtr: UnsafeMutableRawPointer, _ type: CFNumberType) -> Bool {
return unsafeBitCast(obj, to: NSNumber.self)._getValue(valuePtr, forType: type)
}
internal func _CFSwiftNumberGetBoolValue(_ obj: CFTypeRef) -> Bool {
return unsafeBitCast(obj, to: NSNumber.self).boolValue
}
protocol _NSNumberCastingWithoutBridging {
var _swiftValueOfOptimalType: Any { get }
}
extension NSNumber: _NSNumberCastingWithoutBridging {}
|
apache-2.0
|
a8694cce32af1d83dc7e666755944d1f
| 34.33653 | 294 | 0.629197 | 4.542816 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Requests/User/SearchInFollowersResponseHandler.swift
|
1
|
2316
|
//
// SearchInFollowersResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ObjectMapper
class SearchInFollowersResponseHandler: ResponseHandler {
fileprivate let completion: UsersClosure?
init(completion: UsersClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let usersMapper = Mapper<UserMapper>().mapArray(JSONObject: response["data"]) {
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let users = usersMapper.map({ User(mapper: $0, dataMapper: dataMapper, metadata: metadata) })
executeOnMainQueue { self.completion?(users, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
|
mit
|
78502f6b1baa00381efdbb780f07b5f8
| 46.265306 | 128 | 0.721503 | 4.775258 | false | false | false | false |
Fri3ndlyGerman/OpenWeatherSwift
|
Sources/HPOpenWeather/Requests/TimeMachineRequest.swift
|
1
|
2346
|
import Foundation
import CoreLocation
import HPNetwork
public struct TimeMachineRequest: OpenWeatherRequest {
public typealias Output = TimeMachineResponse
public let coordinate: CLLocationCoordinate2D
public let date: Date
private let urlSession: URLSession
private let finishingQueue: DispatchQueue
public init(coordinate: CLLocationCoordinate2D, date: Date, urlSession: URLSession = .shared, finishingQueue: DispatchQueue = .main) {
self.coordinate = coordinate
self.date = date
self.urlSession = urlSession
self.finishingQueue = finishingQueue
}
public func makeNetworkRequest(settings: HPOpenWeather.Settings) throws -> DecodableRequest<TimeMachineResponse> {
guard date.timeIntervalSinceNow < -6 * .hour else {
throw NSError.timeMachineDate
}
return TimeMachineNetworkRequest(request: self, settings: settings, urlSession: urlSession, finishingQueue: finishingQueue)
}
}
class TimeMachineNetworkRequest: DecodableRequest<TimeMachineResponse> {
public typealias Output = TimeMachineResponse
public override var url: URL? {
URLQueryItemsBuilder.weatherBase
.addingPathComponent("timemachine")
.addingQueryItem(coordinate.latitude, digits: 5, name: "lat")
.addingQueryItem(coordinate.longitude, digits: 5, name: "lon")
.addingQueryItem("\(Int(date.timeIntervalSince1970))", name: "dt")
.addingQueryItem(settings.apiKey, name: "appid")
.addingQueryItem(settings.units.rawValue, name: "units")
.addingQueryItem(settings.language.rawValue, name: "lang")
.build()
}
public override var decoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
private let coordinate: CLLocationCoordinate2D
private let settings: HPOpenWeather.Settings
private let date: Date
init(request: TimeMachineRequest, settings: HPOpenWeather.Settings, urlSession: URLSession, finishingQueue: DispatchQueue) {
self.coordinate = request.coordinate
self.settings = settings
self.date = request.date
super.init(urlString: "www.google.com", urlSession: urlSession, finishingQueue: finishingQueue)
}
}
|
mit
|
3c498e34dae7381f39d6d056aaea29e9
| 36.238095 | 138 | 0.70844 | 5.088937 | false | false | false | false |
MaxHasADHD/TraktKit
|
Common/Wrapper/Comments.swift
|
1
|
10805
|
//
// Comments.swift
// TraktKit
//
// Created by Maximilian Litteral on 11/15/15.
// Copyright © 2015 Maximilian Litteral. All rights reserved.
//
import Foundation
extension TraktManager {
// MARK: - Comments
/**
Add a new comment to a movie, show, season, episode, or list. Make sure to allow and encourage spoilers to be indicated in your app and follow the rules listed above.
🔒 OAuth: Required
*/
@discardableResult
public func postComment(movie: SyncId? = nil, show: SyncId? = nil, season: SyncId? = nil, episode: SyncId? = nil, list: SyncId? = nil, comment: String, isSpoiler spoiler: Bool? = nil, completion: @escaping SuccessCompletionHandler) throws -> URLSessionDataTaskProtocol? {
let body = TraktCommentBody(movie: movie, show: show, season: season, episode: episode, list: list, comment: comment, spoiler: spoiler)
guard let request = post("comments", body: body) else { return nil }
return performRequest(request: request, completion: completion)
}
/**
Returns a single comment and indicates how many replies it has. Use **GET** `/comments/:id/replies` to get the actual replies.
*/
@discardableResult
public func getComment<T: CustomStringConvertible>(commentID id: T, completion: @escaping ObjectCompletionHandler<Comment>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)",
withQuery: [:],
isAuthorized: false,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
/**
Update a single comment created within the last hour. The OAuth user must match the author of the comment in order to update it.
🔒 OAuth: Required
*/
@discardableResult
public func updateComment<T: CustomStringConvertible>(commentID id: T, newComment comment: String, isSpoiler spoiler: Bool? = nil, completion: @escaping ObjectCompletionHandler<Comment>) throws -> URLSessionDataTaskProtocol? {
let body = TraktCommentBody(comment: comment, spoiler: spoiler)
guard var request = mutableRequest(forPath: "comments/\(id)",
withQuery: [:],
isAuthorized: true,
withHTTPMethod: .PUT) else { return nil }
request.httpBody = try jsonEncoder.encode(body)
return performRequest(request: request,
completion: completion)
}
/**
Delete a single comment created within the last hour. This also effectively removes any replies this comment has. The OAuth user must match the author of the comment in order to delete it.
🔒 OAuth: Required
*/
@discardableResult
public func deleteComment<T: CustomStringConvertible>(commentID id: T, completion: @escaping SuccessCompletionHandler) -> URLSessionDataTaskProtocol? {
guard
let request = mutableRequest(forPath: "comments/\(id)",
withQuery: [:],
isAuthorized: true,
withHTTPMethod: .DELETE) else { return nil }
return performRequest(request: request, completion: completion)
}
// MARK: - Replies
/**
Returns all replies for a comment. It is possible these replies could have replies themselves, so in that case you would just call **GET** `/comments/:id/replies` again with the new comment `id`.
📄 Pagination
*/
@discardableResult
public func getReplies<T: CustomStringConvertible>(commentID id: T, completion: @escaping ObjectsCompletionHandler<Comment>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)/replies",
withQuery: [:],
isAuthorized: false,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
/**
Add a new reply to an existing comment. Make sure to allow and encourage spoilers to be indicated in your app and follow the rules listed above.
🔒 OAuth: Required
*/
@discardableResult
public func postReply<T: CustomStringConvertible>(commentID id: T, comment: String, isSpoiler spoiler: Bool? = nil, completion: @escaping ObjectCompletionHandler<Comment>) throws -> URLSessionDataTaskProtocol? {
let body = TraktCommentBody(comment: comment, spoiler: spoiler)
guard let request = post("comments/\(id)/replies", body: body) else { return nil }
return performRequest(request: request, completion: completion)
}
// MARK: - Item
/**
Returns all users who liked a comment. If you only need the `replies` count, the main `comment` object already has that, so no need to use this method.
📄 Pagination
*/
@discardableResult
public func getAttachedMediaItem<T: CustomStringConvertible>(commentID id: T, completion: @escaping ObjectCompletionHandler<TraktAttachedMediaItem>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)/item",
withQuery: [:],
isAuthorized: true,
withHTTPMethod: .POST) else { return nil }
return performRequest(request: request,
completion: completion)
}
// MARK: - Likes
/**
Returns the media item this comment is attached to. The media type can be `movie`, `show`, `season`, `episode`, or `list` and it also returns the standard media object for that media type.
✨ Extended Info
*/
@discardableResult
public func getUsersWhoLikedComment<T: CustomStringConvertible>(commentID id: T, completion: @escaping ObjectsCompletionHandler<TraktCommentLikedUser>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)/likes",
withQuery: [:],
isAuthorized: true,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
// MARK: - Like
/**
Votes help determine popular comments. Only one like is allowed per comment per user.
🔒 OAuth: Required
*/
@discardableResult
public func likeComment<T: CustomStringConvertible>(commentID id: T, completion: @escaping SuccessCompletionHandler) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)/like",
withQuery: [:],
isAuthorized: false,
withHTTPMethod: .POST) else { return nil }
return performRequest(request: request,
completion: completion)
}
/**
Remove a like on a comment.
🔒 OAuth: Required
*/
@discardableResult
public func removeLikeOnComment<T: CustomStringConvertible>(commentID id: T, completion: @escaping SuccessCompletionHandler) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/\(id)/like",
withQuery: [:],
isAuthorized: false,
withHTTPMethod: .DELETE) else { return nil }
return performRequest(request: request,
completion: completion)
}
// MARK: - Trending
/**
Returns all comments with the most likes and replies over the last 7 days. You can optionally filter by the `comment_type` and media `type` to limit what gets returned. If you want to `include_replies` that will return replies in place alongside top level comments.
📄 Pagination
✨ Extended
*/
@discardableResult
public func getTrendingComments(commentType: CommentType, mediaType: Type2, includeReplies: Bool, completion: @escaping ObjectsCompletionHandler<TraktTrendingComment>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/trending/\(commentType.rawValue)/\(mediaType.rawValue)",
withQuery: ["include_replies": "\(includeReplies)"],
isAuthorized: false,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
// MARK: - Recent
/**
Returns the most recently written comments across all of Trakt. You can optionally filter by the `comment_type` and media `type` to limit what gets returned. If you want to `include_replies` that will return replies in place alongside top level comments.
📄 Pagination
✨ Extended
*/
@discardableResult
public func getRecentComments(commentType: CommentType, mediaType: Type2, includeReplies: Bool, completion: @escaping ObjectsCompletionHandler<TraktTrendingComment>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/recent/\(commentType.rawValue)/\(mediaType.rawValue)",
withQuery: ["include_replies": "\(includeReplies)"],
isAuthorized: false,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
// MARK: - Updates
/**
Returns the most recently updated comments across all of Trakt. You can optionally filter by the `comment_type` and media `type` to limit what gets returned. If you want to `include_replies` that will return replies in place alongside top level comments.
📄 Pagination
✨ Extended
*/
@discardableResult
public func getRecentlyUpdatedComments(commentType: CommentType, mediaType: Type2, includeReplies: Bool, completion: @escaping ObjectsCompletionHandler<TraktTrendingComment>) -> URLSessionDataTaskProtocol? {
guard let request = mutableRequest(forPath: "comments/updates/\(commentType.rawValue)/\(mediaType.rawValue)",
withQuery: ["include_replies": "\(includeReplies)"],
isAuthorized: false,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request,
completion: completion)
}
}
|
mit
|
6caf3ea9e2f6a33b17e5cf8a73bcf629
| 47.922727 | 275 | 0.628542 | 5.46068 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Views/UIImageView+Avatar.swift
|
1
|
596
|
//
// UIImageView+Avatar.swift
// Freetime
//
// Created by Ryan Nystrom on 11/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
extension UIImageView {
func configureForAvatar(border: Bool = true) {
contentMode = .scaleAspectFill
backgroundColor = Styles.Colors.Gray.lighter.color
layer.cornerRadius = Styles.Sizes.avatarCornerRadius
if border {
layer.borderColor = Styles.Colors.Gray.light.color.cgColor
layer.borderWidth = 1.0 / UIScreen.main.scale
}
clipsToBounds = true
}
}
|
mit
|
341e4a380e94c901794f307c98285cd5
| 23.791667 | 70 | 0.655462 | 4.280576 | false | false | false | false |
frootloops/swift
|
test/PlaygroundTransform/nested_function.swift
|
4
|
1815
|
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
func returnSum() -> Int {
var y = 10
func add() {
y += 5
}
add()
let addAgain = {
y += 5
}
addAgain()
let addMulti = {
y += 5
_ = 0 // force a multi-statement closure
}
addMulti()
return y
}
returnSum()
// CHECK-NOT: $builtin
// CHECK: [9:{{.*}}] $builtin_log_scope_entry
// CHECK-NEXT: [10:{{.*}}] $builtin_log[y='10']
// CHECK-NEXT: [11:{{.*}}] $builtin_log_scope_entry
// CHECK-NEXT: [12:{{.*}}] $builtin_log[y='15']
// CHECK-NEXT: [11:{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [15:{{.*}}] $builtin_log[addAgain='{{.*}}']
// CHECK-NEXT: [15:{{.*}}] $builtin_log_scope_entry
// FIXME: We drop the log for the addition here.
// CHECK-NEXT: [16:{{.*}}] $builtin_log[='()']
// CHECK-NEXT: [15:{{.*}}] $builtin_log_scope_exit
// FIXME: There's an extra, unbalanced scope exit here.
// CHECK-NEXT: [9:{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [19:{{.*}}] $builtin_log[addMulti='{{.*}}']
// CHECK-NEXT: [19:{{.*}}] $builtin_log_scope_entry
// CHECK-NEXT: [20:{{.*}}] $builtin_log[y='25']
// CHECK-NEXT: [21:{{.*}}] $builtin_log[='0']
// CHECK-NEXT: [19:{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [24:{{.*}}] $builtin_log[='25']
// CHECK-NEXT: [9:{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [27:{{.*}}] $builtin_log[='25']
// CHECK-NOT: $builtin
|
apache-2.0
|
c406da5657c22d4932b1f46a17bfde55
| 32.611111 | 197 | 0.598347 | 2.960848 | false | false | false | false |
github641/testRepo
|
SwiftProgrammingLanguage/SwiftProgrammingLanguage/Deinitialization.swift
|
1
|
6737
|
//
// ViewController.swift
// SwiftProgrammingLanguage
//
// Created by admin on 2017/9/30.
// Copyright © 2017年 alldk. All rights reserved.
//
/*lzy170930注:
这个类,对应的是 The Swift Programming Language第二章(Language Guide)的内容:
析构过程(Deinitialization)
本页包含内容:
• 析构过程原理 (页 0)
• 析构器实践 (页 0)
*/
import UIKit
class Deinitialization: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*
析构器只适用于类类型,当一个类的实例被释放之前,析构器会被立即调用。析构器用关键字 deinit 来标示,类
似于构造器要用 init 来标示。
*/
// MARK: - 析构过程原理
/*
Swift 会自动释放不再需要的实例以释放资源。如自动引用计数章节中所讲述,Swift 通过 自动引用计数(AR C) 处理实例的内存管理。通常当你的实例被释放时不需要手动地去清理。但是,当使用自己的资源时,你可能 需要进行一些额外的清理。例如,如果创建了一个自定义的类来打开一个文件,并写入一些数据,你可能需要在 类实例被释放之前手动去关闭该文件。
在类的定义中,每个类最多只能有一个析构器,而且析构器不带任何参数,如下所示:
deinit {
// 执行析构过程
}
析构器是在实例释放发生前被自动调用。你不能主动调用析构器。子类继承了父类的析构器,并且在子类析构器
实现的最后,父类的析构器会被自动调用。即使子类没有提供自己的析构器,父类的析构器也同样会被调用。
因为直到实例的析构器被调用后,实例才会被释放,所以析构器可以访问实例的所有属性,并且可以根据那些属
性可以修改它的行为(比如查找一个需要被关闭的文件)。
*/
// MARK: - 析构器实践
/*这是一个析构器实践的例子。这个例子描述了一个简单的游戏,这里定义了两种新类型,分别是 Bank 和 Player 。 Bank 类管理一种虚拟硬币,确保流通的硬币数量永远不可能超过 10,000。在游戏中有且只能有一个 Bank 存 在,因此 Bank 用类来实现,并使用类型属性和类型方法来存储和管理其当前状态。
*/
class Bank {
static var coinsInBank = 10000
static func distribute(coins numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVent = min(numberOfCoinsRequested, coinsInBank)
coinsInBank -= numberOfCoinsToVent
return numberOfCoinsToVent
}
static func receive(coins: Int) {
coinsInBank += coins
}
}
/*
Bank 使用 coinsInBank 属性来跟踪它当前拥有的硬币数量。 Bank 还提供了两个方法, distribute(coins:) 和 receive(coins:) ,分别用来处理硬币的分发和收 。
distribute(coins:) 方法在 Bank 对象分发硬币之前检查是否有足够的硬币。如果硬币不足, Bank 对象会返回一 个比请求时小的数字(如果 Bank 对象中没有硬币了就返回 0 )。此方法返回一个整型值,表示提供的硬币的实 际数量。
receive(coins:) 方法只是将 Bank 实例接收到的硬币数目加回硬币存储中。
Player 类描述了游戏中的一个玩家。每一个玩家在任意时间都有一定数量的硬币存储在他们的钱包中。这通过玩 家的 coinsInPurse 属性来表示:*/
class Player {
var coinsInPurse: Int
init(coins: Int){
coinsInPurse = Bank.distribute(coins: coins)
}
func win(coins: Int){
coinsInPurse += Bank.distribute(coins: coins)
}
deinit{
Bank.receive(coins: coinsInPurse)
}
}
/*
每个 Player 实例在初始化的过程中,都从 Bank 对象获取指定数量的硬币。如果没有足够的硬币可用, Player 实例可能会收到比指定数量少的硬币.
Player 类定义了一个 win(coins:) 方法,该方法从 Bank 对象获取一定数量的硬币,并把它们添加到玩家的钱 包。 Player 类还实现了一个析构器,这个析构器在 Player 实例释放前被调用。在这里,析构器的作用只是将玩 家的所有硬币都返还给 Bank 对象:
*/
var playerOne: Player? = Player(coins:100)
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
// 打印 "A new player has joined the game with 100 coins"
print("There are now \(Bank.coinsInBank) coins left in the bank")
// 打印 "There are now 9900 coins left in the bank"
/*
创建一个 Player 实例的时候,会向 Bank 对象请求 100 个硬币,如果有足够的硬币可用的话。这个 Player 实例 存储在一个名为 playerOne 的可选类型的变量中。这里使用了一个可选类型的变量,因为玩家可以随时离开游 戏,设置为可选使你可以追踪玩家当前是否在游戏中。
因为 playerOne 是可选的,所以访问其 coinsInPurse 属性来打印钱包中的硬币数量时,使用感叹号( ! )来解 包:
*/
playerOne!.win(coins: 2000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") // 输出 "PlayerOne won 2000 coins & now has 2100 coins"
print("The bank now only has \(Bank.coinsInBank) coins left")
// 输出 "The bank now only has 7900 coins left"
/*
这里,玩家已经赢得了 2,000 枚硬币,所以玩家的钱包中现在有 2,100 枚硬币,而 Bank 对象只剩余 7,900 枚 硬币。
玩家现在已经离开了游戏。这通过将可选类型的 playerOne 变量设置为 nil 来表示,意味着“没有 Player 实 例”。当这一切发生时, playerOne 变量对 Player 实例的引用被破坏了。没有其它属性或者变量引用 Player 实 例,因此该实例会被释放,以便回收内存。在这之前,该实例的析构器被自动调用,玩家的硬币被返还给银行。
*/
playerOne = nil
print("PlayerOne has left the game")
// 打印 "PlayerOne has left the game"
print("The bank now has \(Bank.coinsInBank) coins")
// 打印 "The bank now has 10000 coins"
}
}
|
mit
|
9eac5a44a89dcc0e6d20f26f910407d2
| 38.886792 | 185 | 0.63245 | 2.828094 | false | false | false | false |
fizx/jane
|
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Core/ChannelArgument.swift
|
4
|
8041
|
/*
* Copyright 2018, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if SWIFT_PACKAGE
import CgRPC
#endif
import Foundation // for String.Encoding
extension Channel {
public enum Argument {
case stringValued(key: String, value: String)
case integerValued(key: String, value: Int32)
public static func timeIntervalValued(key: String, value: TimeInterval) -> Channel.Argument { return .integerValued(key: key, value: Int32(value * 1_000)) }
public static func boolValued(key: String, value: Bool) -> Channel.Argument { return .integerValued(key: key, value: Int32(value ? 1 : 0)) }
/// Default authority to pass if none specified on call construction.
public static func defaultAuthority(_ value: String) -> Channel.Argument { return .stringValued(key: "grpc.default_authority", value: value) }
/// Primary user agent. Goes at the start of the user-agent metadata sent
/// on each request.
public static func primaryUserAgent(_ value: String) -> Channel.Argument { return .stringValued(key: "grpc.primary_user_agent", value: value) }
/// Secondary user agent. Goes at the end of the user-agent metadata sent
/// on each request.
public static func secondaryUserAgent(_ value: String) -> Channel.Argument { return .stringValued(key: "grpc.secondary_user_agent", value: value) }
/// After a duration of this time, the client/server pings its peer to see
/// if the transport is still alive.
public static func keepAliveTime(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.keepalive_time_ms", value: value) }
/// After waiting for a duration of this time, if the keepalive ping sender does
/// not receive the ping ack, it will close the transport.
public static func keepAliveTimeout(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.keepalive_timeout_ms", value: value) }
/// Is it permissible to send keepalive pings without any outstanding streams?
public static func keepAlivePermitWithoutCalls(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.keepalive_permit_without_calls", value: value) }
/// The time between the first and second connection attempts.
public static func reconnectBackoffInitial(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.initial_reconnect_backoff_ms", value: value) }
/// The minimum time between subsequent connection attempts.
public static func reconnectBackoffMin(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.min_reconnect_backoff_ms", value: value) }
/// The maximum time between subsequent connection attempts.
public static func reconnectBackoffMax(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.max_reconnect_backoff_ms", value: value) }
/// Should we allow receipt of true-binary data on http2 connections?
/// Defaults to on (true)
public static func http2EnableTrueBinary(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.http2.true_binary", value: value) }
/// Minimum time between sending successive ping frames without receiving
/// any data frame.
public static func http2MinSentPingInterval(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.http2.min_time_between_pings_ms", value: value) }
/// Number of pings before needing to send a data frame or header frame.
/// `0` indicates that an infinite number of pings can be sent without
/// sending a data frame or header frame.
public static func http2MaxPingsWithoutData(_ value: UInt32) -> Channel.Argument { return .integerValued(key: "grpc.http2.max_pings_without_data", value: Int32(value)) }
/// This *should* be used for testing only.
/// Override the target name used for SSL host name checking using this
/// channel argument. If this argument is not specified, the name used
/// for SSL host name checking will be the target parameter (assuming that the
/// secure channel is an SSL channel). If this parameter is specified and the
/// underlying is not an SSL channel, it will just be ignored.
public static func sslTargetNameOverride(_ value: String) -> Channel.Argument { return .stringValued(key: "grpc.ssl_target_name_override", value: value) }
/// Enable census for tracing and stats collection.
public static func enableCensus(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.census", value: value) }
/// Enable load reporting.
public static func enableLoadReporting(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.loadreporting", value: value) }
/// Request that optional features default to off (regarless of what they usually
/// default to) - to enable tight control over what gets enabled.
public static func enableMinimalStack(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.minimal_stack", value: value) }
/// Maximum number of concurrent incoming streams to allow on a http2 connection.
public static func maxConcurrentStreams(_ value: UInt32) -> Channel.Argument { return .integerValued(key: "grpc.max_concurrent_streams", value: Int32(value)) }
/// Maximum message length that the channel can receive (in byts).
/// -1 means unlimited.
public static func maxReceiveMessageLength(_ value: Int32) -> Channel.Argument { return .integerValued(key: "grpc.max_receive_message_length", value: value) }
/// Maximum message length that the channel can send (in bytes).
/// -1 means unlimited.
public static func maxSendMessageLength(_ value: Int32) -> Channel.Argument { return .integerValued(key: "grpc.max_send_message_length", value: value) }
/// Maximum time that a channel may have no outstanding rpcs.
public static func maxConnectionIdle(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.max_connection_idle_ms", value: value) }
/// Maximum time that a channel may exist.
public static func maxConnectionAge(_ value: TimeInterval) -> Channel.Argument { return .timeIntervalValued(key: "grpc.max_connection_age_ms", value: value) }
/// Enable/disable support for deadline checking.
/// Defaults to true, unless `enableMinimalStack` is enabled, in which case it
/// defaults to false.
public static func enableDeadlineChecks(_ value: Bool) -> Channel.Argument { return .boolValued(key: "grpc.enable_deadline_checking", value: value) }
}
}
extension Channel.Argument {
class Wrapper {
// Creating a `grpc_arg` allocates memory. This wrapper ensures that the memory is freed after use.
let wrapped: grpc_arg
init(_ wrapped: grpc_arg) {
self.wrapped = wrapped
}
deinit {
gpr_free(wrapped.key)
if wrapped.type == GRPC_ARG_STRING {
gpr_free(wrapped.value.string)
}
}
}
func toCArg() -> Wrapper {
var arg = grpc_arg()
switch self {
case let .stringValued(key, value):
arg.key = gpr_strdup(key)
arg.type = GRPC_ARG_STRING
arg.value.string = gpr_strdup(value)
case let .integerValued(key, value):
arg.key = gpr_strdup(key)
arg.type = GRPC_ARG_INTEGER
arg.value.integer = value
}
return Channel.Argument.Wrapper(arg)
}
}
|
mit
|
4bcd920d43a9e813410188671eb597db
| 53.70068 | 180 | 0.70725 | 4.225434 | false | false | false | false |
aijaz/icw1502
|
playgrounds/Week06.playground/Pages/Methods.xcplaygroundpage/Contents.swift
|
1
|
874
|
//: [Previous](@previous) [Next](@next)
import Foundation
struct Vertex {
var x: Double
let y: Double
func mag() -> Double {
return sqrt(x*x + y*y)
}
mutating func moveByX(deltaX: Double) {
x += deltaX
}
func movedByX(deltaX: Double) -> Vertex {
return Vertex(x: x+deltaX, y: y)
}
}
extension Vertex : CustomStringConvertible {
var description: String {
return "(\(x), \(y))"
}
}
extension Vertex : Equatable {}
func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return (lhs.x == rhs.x && lhs.y == rhs.y)
}
var point = Vertex(x: 3, y: 4)
point
print("On this line, my point is \(point)")
var point2 = Vertex(x: 3, y: 4)
point2
point == point2
point != point2
point.moveByX(50)
let point3 = point.movedByX(50)
point
//: [Previous](@previous) [Next](@next)
|
mit
|
5660a47c134a282ccefe081b41496072
| 10.972603 | 45 | 0.564073 | 3.348659 | false | false | false | false |
gyro-n/PaymentsIos
|
Example/Tests/MockApiServer.swift
|
1
|
63298
|
//
// MockApiServer.swift
// GyronPayments
//
// Created by Ye David on 11/24/16.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
import Embassy
import EnvoyAmbassador
class MockApiServer {
let loop: SelectorEventLoop?
let router: MockRouter = MockRouter()
var defaultPort: Int = 9000
var server: DefaultHTTPServer?
init(port: Int = 9000) {
self.loop = try! SelectorEventLoop(selector: try! KqueueSelector())
print("started loop")
defaultPort = port
server = DefaultHTTPServer(eventLoop: self.loop!, port: self.defaultPort, app: self.router.app)
}
func run() -> MockRouter {
// Start HTTP server to listen on the port
try! server?.start()
print("started server")
DispatchQueue.global(qos: .background).async {
print("This is run on the background queue")
func getEnvironValue(key: String = "REQUEST_METHOD", environ: [String:Any], defaultValue: String = "GET") -> String {
return environ[key] as? String ?? defaultValue
}
func setRefundRoutes() {
// Refunds
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges/11e78878-b63c-d890-b803-a779b0d6dd10/refunds/11e78878-b63c-d890-b803-a779b0d6dd10"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"ledger_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"reason": "null",
"message": "null",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"ledger_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"amount": 300,
"currency": "JPY",
"amount_formatted": 300,
"reason": "null",
"message": "null",
"status": "successful",
"error": "null",
"metadata": [
"id": "testid"
],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges/11e78878-b63c-d890-b803-a779b0d6dd10/refunds"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"ledger_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"reason": "null",
"message": "null",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"ledger_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"reason": "null",
"message": "null",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"]
} else {
return [:]
}
}))
}
func setTransactionTokenRoutes() {
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/tokens/11e78878-b636-a2d6-bdc6-db9e892a1e19"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"email": "root_admin@univapay.com",
"payment_type": "card",
"active": true,
"mode": "test",
"type": "recurring",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"last_used_on": "2017-08-24T12:02:49.301+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"email": "root_admin@univapay.com",
"payment_type": "card",
"active": true,
"mode": "test",
"type": "one_time",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"last_used_on": "2017-08-24T12:02:49.301+09:00"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/tokens"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return [
"items": [
[
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"email": "root_admin@univapay.com",
"payment_type": "card",
"active": true,
"mode": "test",
"type": "recurring",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"last_used_on": "2017-08-24T12:02:49.301+09:00"
]
],
"has_more": false
]
}))
self.router["/tokens"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"email": "root_admin@univapay.com",
"payment_type": "card",
"active": true,
"mode": "test",
"type": "recurring",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"last_used_on": "2017-08-24T12:02:49.301+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"email": "root_admin@univapay.com",
"payment_type": "card",
"active": true,
"mode": "test",
"type": "recurring",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"last_used_on": "2017-08-24T12:02:49.301+09:00"]
} else {
return [:]
}
}))
}
func setChargeRoutes() {
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges/11e78878-b63c-d890-b803-a779b0d6dd10"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [:],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [
"id": "testid"
],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-09-01T13:29:19.144459+09:00"
]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [:],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
} else {
return [:]
}
}))
self.router["/charges"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [:],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [:],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"]
} else {
return [:]
}
}))
}
func setStoreRoutes() {
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"name": "Store",
"active": true,
"created_on": "2017-08-17T16:44:19.37961+09:00",
"updated_on": "2017-08-17T16:44:19.37961+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"name": "Store Updated",
"active": true,
"created_on": "2017-08-17T16:44:19.37961+09:00",
"updated_on": "2017-08-17T16:44:19.37961+09:00"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
self.router["/stores"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"name": "Store",
"active": true,
"created_on": "2017-08-17T16:44:19.37961+09:00",
"updated_on": "2017-08-17T16:44:19.37961+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"name": "Store",
"active": true,
"created_on": "2017-08-17T16:44:19.37961+09:00",
"updated_on": "2017-08-17T16:44:19.37961+09:00"]
} else {
return [:]
}
}))
}
func setMerchantRoutes() {
self.router["/me"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod: String = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return
[
"id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"name": "Root Admin",
"email": "root_admin@univapay.com",
"active": true,
"roles": [
"admin"
],
"verified": false,
"created_on": "2017-08-17T16:44:19.348722+09:00",
"updated_on": "2017-08-17T16:44:19.348722+09:00",
"configuration": [
"id": "11e7831f-e099-dc9a-ab2c-d3fac39b8bf4",
"percent_fee": "null",
"flat_fees": "null",
"wait_period": "null",
"logo_url": "null",
"transfer_schedule": "null",
"card_configuration": [
"enabled": "null",
"debit_enabled": "null",
"prepaid_enabled": "null",
"forbidden_card_brands": "null",
"allowed_countries_by_ip": "null",
"foreign_cards_allowed": "null",
"fail_on_new_email": "null",
"monthly_limit": "null"
],
"qr_scan_configuration": [
"enabled": "null",
"forbidden_qr_scan_gateways": "null"
],
"recurring_token_configuration": [
"recurring_type": "null",
"charge_wait_period": "null"
],
"security_configuration": [
"inspect_suspicious_login_after": "null"
],
"card_brand_percent_fees": [
"visa": "null",
"american_express": "null",
"mastercard": "null",
"maestro": "null",
"discover": "null",
"jcb": "null",
"diners_club": "null",
"union_pay": "null"
]
],
"all_roles": [
"admin"
]
]
} else {
return [:]
}
}))
}
func setCancelRoutes() {
// Cancel
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges/11e78878-b63c-d890-b803-a779b0d6dd10/cancels"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00"]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/charges/11e78878-b63c-d890-b803-a779b0d6dd10/cancels/11e78878-b63c-d890-b803-a779b0d6dd10"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"status": "pending",
"error": "null",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"charge_id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"status": "successful",
"error": "null",
"metadata": ["test":"test"],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00"
]
} else {
return [:]
}
}))
}
func setBankAccountRoutes() {
self.router["/bank_accounts"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "POST") {
return [
"id": "11e78ebd-25f9-f1b4-9da4-db50f9df95e9",
"holder_name": "test user",
"bank_name": "test bank",
"branch_name": "test branch",
"country": "JP",
"bank_address": "test address",
"currency": "JPY",
"account_number": "1234567890",
"swift_code": "DEUTDEFF",
"last_four": "7890",
"active": true,
"status": "new",
"account_type": "savings",
"created_on": "2017-09-01T11:27:49.511556+09:00",
"updated_on": "2017-09-01T11:27:49.511556+09:00",
"primary": false
]
} else {
return [
"items": [
[
"id": "11e7831f-e0f2-c6ac-8cde-1b74c58a0e61",
"holder_name": "Name",
"bank_name": "Name",
"branch_name": "null",
"country": "JP",
"bank_address": "null",
"currency": "JPY",
"account_number": "1234",
"last_four": "1234",
"active": true,
"status": "verified",
"account_type": "savings",
"created_on": "2017-08-17T16:44:19.925758+09:00",
"updated_on": "2017-08-17T16:44:19.925758+09:00",
"primary": true
]
],
"has_more": false
]
}
}))
self.router["/bank_accounts/11e7831f-e0f2-c6ac-8cde-1b74c58a0e61"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e7831f-e0f2-c6ac-8cde-1b74c58a0e61",
"holder_name": "Name",
"bank_name": "Name",
"branch_name": "null",
"country": "JP",
"bank_address": "null",
"currency": "JPY",
"account_number": "1234",
"last_four": "1234",
"active": true,
"status": "verified",
"account_type": "savings",
"created_on": "2017-08-17T16:44:19.925758+09:00",
"updated_on": "2017-08-17T16:44:19.925758+09:00",
"primary": true
]
} else {
return [:]
}
}))
self.router["/bank_accounts/primary"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return [
"id": "11e7831f-e0f2-c6ac-8cde-1b74c58a0e61",
"holder_name": "Name",
"bank_name": "Name",
"branch_name": "null",
"country": "JP",
"bank_address": "null",
"currency": "JPY",
"account_number": "1234",
"last_four": "1234",
"active": true,
"status": "verified",
"account_type": "savings",
"created_on": "2017-08-17T16:44:19.925758+09:00",
"updated_on": "2017-08-17T16:44:19.925758+09:00",
"primary": true
]
}))
self.router["/bank_accounts/11e7831f-e0f2-c6ac-8cde-1b74c58a0e61"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "PATCH") {
return [
"id": "11e78ebd-25f9-f1b4-9da4-db50f9df95e9",
"holder_name": "test updated user",
"bank_name": "test bank",
"branch_name": "test branch",
"country": "JP",
"bank_address": "test address",
"currency": "USD",
"account_number": "1234567890",
"swift_code": "DEUTDEFF",
"last_four": "7890",
"active": true,
"status": "new",
"account_type": "savings",
"created_on": "2017-09-01T11:27:49.511556+09:00",
"updated_on": "2017-09-01T11:37:06.416081+09:00",
"primary": false
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
}
func setLedgerRoutes() {
// Ledgers
self.router["/transfers/11e78878-b636-a2d6-bdc6-db9e892a1e19/ledgers"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return ["items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transfer_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"percent_fee": 10,
"flat_fee": 10,
"flat_fee_currency": "JPY",
"flat_fee_formatted": 10,
"exchangeRate": 1,
"origin": "",
"note": "",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
}))
}
func setSubscriptionRoutes() {
// Subscriptions
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/subscriptions/11e78878-b63c-d890-b803-a779b0d6dd10"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"transactionTokenId": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"period": "weekly",
"active": true,
"status": "unverified",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"transactionTokenId": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"amount": 2000,
"currency": "JPY",
"amount_formatted": 2000,
"period": "weekly",
"active": true,
"status": "unverified",
"metadata": ["test": "test"],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/subscriptions"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"transactionTokenId": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"period": "weekly",
"active": true,
"status": "unverified",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/subscriptions/11e78878-b63c-d890-b803-a779b0d6dd10/charges"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"platform_id": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"transaction_token_id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"transaction_token_type": "recurring",
"requested_amount": 1000,
"requested_currency": "JPY",
"requested_amount_formatted": 1000,
"charged_amount": 1000,
"charged_currency": "JPY",
"charged_amount_formatted": 1000,
"status": "successful",
"error": "null",
"metadata": [:],
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
}))
self.router["/subscriptions"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"transactionTokenId": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"period": "weekly",
"active": true,
"status": "unverified",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78878-b63c-d890-b803-a779b0d6dd10",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"transactionTokenId": "11e7831f-dd87-82e6-8cde-ff0073b9c1fa",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"period": "weekly",
"active": true,
"status": "unverified",
"metadata": "null",
"mode": "test",
"created_on": "2017-08-24T12:02:49.297608+09:00",
"updated_on": "2017-08-24T12:02:49.413191+09:00"]
} else {
return [:]
}
}))
}
func setTransferRoutes() {
// Transfers
self.router["/transfers/11e78878-b636-a2d6-bdc6-db9e892a1e19/status_changes"] = DelayResponse(JSONResponse(handler: { environ -> Any in
return [
"items": [
[
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"bankAccount_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"status": "created",
"error_code": "null",
"error_text": "null",
"metadata": "null",
"started_by": "test",
"from": "test",
"to": "test",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"updated_on": "2017-08-24T12:02:49.301+09:00"
]
],
"has_more": false
]
}))
self.router["/transfers/11e78878-b636-a2d6-bdc6-db9e892a1e19"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"bankAccount_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"status": "created",
"error_code": "null",
"error_text": "null",
"metadata": "null",
"started_by": "test",
"from": "test",
"to": "test",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"updated_on": "2017-08-24T12:02:49.301+09:00"
]
} else {
return [:]
}
}))
self.router["/transfers"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78878-b636-a2d6-bdc6-db9e892a1e19",
"bankAccount_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"amount": 1000,
"currency": "JPY",
"amount_formatted": 1000,
"status": "created",
"error_code": "null",
"error_text": "null",
"metadata": "null",
"started_by": "test",
"from": "test",
"to": "test",
"created_on": "2017-08-24T12:02:49.249856+09:00",
"updated_on": "2017-08-24T12:02:49.301+09:00"
]
],
"has_more": false
]
} else {
return [:]
}
}))
}
func setWebhookRoutes() {
// Webhooks
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/webhooks/11e78edf-ac3a-51c0-8571-a7a6ccf207bc"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished_updated",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/webhooks"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"]
} else {
return [:]
}
}))
self.router["/webhooks/11e78edf-ac3a-51c0-8571-a7a6ccf207bc"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished_updated",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
self.router["/webhooks"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"items": [
[
"id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"
]
],
"has_more": false
]
} else if (requestMethod == "POST") {
return ["id": "11e78edf-ac3a-51c0-8571-a7a6ccf207bc",
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"triggers": [
"charge_finished"
],
"url": "http://localhost/charge_finished",
"active": true,
"created_on": "2017-09-01T15:34:57.644122+09:00",
"updated_on": "2017-09-01T15:34:57.644122+09:00"]
} else {
return [:]
}
}))
}
func setAuthenticationRoutes() {
// Authentication
self.router["/authenticate"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "POST") {
return [
"merchant_id": "11e7831f-e09b-0444-ab2c-878ea010551f",
"token": "2Mz7qabSj7QHgYRceJRR"
]
} else {
return [:]
}
}))
self.router["/logout"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "POST") {
return [:]
} else {
return [:]
}
}))
}
// Application tokens
func setApplicationTokenRoutes() {
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/app_tokens"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"has_more": false,
"items": [
[
"id": "11e7929a-59b0-aa62-b373-5bc836713861",
"platform_id": "11e73ea1-d72c-8ce2-996d-4bb6671eb667",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"token": "xqK4P9HVGre3yuZmC9Vb",
"domains": [],
"active": true,
"mode": "test",
"created_on": "2017-09-06T00:28:48.545708Z",
"updated_on": "2017-09-06T00:28:48.545708Z"
]
]
]
} else if (requestMethod == "POST") {
return [
"id": "11e7929a-59b0-aa62-b373-5bc836713861",
"platform_id": "11e73ea1-d72c-8ce2-996d-4bb6671eb667",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"token": "xqK4P9HVGre3yuZmC9Vb",
"domains": [],
"active": true,
"mode": "test",
"created_on": "2017-09-06T00:28:48.545708Z",
"updated_on": "2017-09-06T00:28:48.545708Z"
]
} else {
return [:]
}
}))
self.router["/stores/11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3/app_tokens/11e7929a-59b0-aa62-b373-5bc836713861"] = DelayResponse(JSONResponse(handler: { environ -> Any in
let requestMethod = getEnvironValue(environ: environ)
if (requestMethod == "GET") {
return [
"id": "11e7929a-59b0-aa62-b373-5bc836713861",
"platform_id": "11e73ea1-d72c-8ce2-996d-4bb6671eb667",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"token": "xqK4P9HVGre3yuZmC9Vb",
"domains": [],
"active": true,
"mode": "test",
"created_on": "2017-09-06T00:28:48.545708Z",
"updated_on": "2017-09-06T00:28:48.545708Z"
]
} else if (requestMethod == "PATCH") {
return [
"id": "11e7929a-59b0-aa62-b373-5bc836713861",
"platform_id": "11e73ea1-d72c-8ce2-996d-4bb6671eb667",
"store_id": "11e7831f-e0a9-0b7a-ab2c-1f739e21b8a3",
"token": "xqK4P9HVGre3yuZmC9Vb",
"domains": ["testdomain.com"],
"active": true,
"mode": "test",
"created_on": "2017-09-06T00:28:48.545708Z",
"updated_on": "2017-09-06T00:28:48.545708Z"
]
} else if (requestMethod == "DELETE") {
return [:]
} else {
return [:]
}
}))
}
setApplicationTokenRoutes()
setTransactionTokenRoutes()
setRefundRoutes()
setChargeRoutes()
setStoreRoutes()
setMerchantRoutes()
setCancelRoutes()
setLedgerRoutes()
setWebhookRoutes()
setTransferRoutes()
setBankAccountRoutes()
setSubscriptionRoutes()
setAuthenticationRoutes()
// Start HTTP server to listen on the port
// try! server.start()
// Run event loop
self.loop?.runForever()
/*DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}*/
}
return router
}
func stop() {
self.server?.stop()
self.loop?.stop()
}
func defineRoute(name: String, returnValue: Any) -> MockRouter {
router[name] = DelayResponse(JSONResponse(handler: { _ -> Any in
return returnValue
}))
return router
}
}
|
mit
|
6d0c8d50cf58b207b5cdc81cd255f685
| 51.441591 | 223 | 0.356715 | 4.432563 | false | false | false | false |
mapzen/ios
|
MapzenSDK/SearchResponse.swift
|
1
|
2155
|
//
// SearchResponse.swift
// ios-sdk
//
// Created by Sarah Lensing on 3/21/17.
// Copyright © 2017 Mapzen. All rights reserved.
//
import Foundation
import Pelias
/// Represents a response for a request executed by 'MapzenSearch'
@objc(MZSearchResponse)
public class SearchResponse : NSObject {
public let peliasResponse: PeliasResponse
private lazy var internalParsedResponse: ParsedSearchResponse? = { [unowned self] in
guard let peliasParsedResponse = self.peliasResponse.parsedResponse else { return nil }
return ParsedSearchResponse.init(peliasParsedResponse)
}()
/// The raw response data
public var data: Data? {
get {
return peliasResponse.data
}
}
/// The url response if the request completed successfully.
public var response: URLResponse? {
get {
return peliasResponse.response
}
}
/// The error if an error occured executing the operation.
public var error: NSError? {
get {
return peliasResponse.error
}
}
public var parsedResponse: ParsedSearchResponse? {
get {
return internalParsedResponse
}
}
init(_ response: PeliasResponse) {
peliasResponse = response
}
public override func isEqual(_ object: Any?) -> Bool {
guard let response = object as? SearchResponse else { return false }
return response.peliasResponse.data == peliasResponse.data &&
response.peliasResponse.response == peliasResponse.response &&
response.peliasResponse.error == peliasResponse.error
}
}
@objc(MZParsedSearchResponse)
public class ParsedSearchResponse: NSObject {
let peliasResponse: PeliasSearchResponse
public var parsedResponse: Dictionary<String, Any> {
get {
return peliasResponse.parsedResponse
}
}
init(_ response: PeliasSearchResponse) {
peliasResponse = response
}
public static func encode(_ response: ParsedSearchResponse) {
PeliasSearchResponse.encode(response.peliasResponse)
}
public func decode() -> ParsedSearchResponse? {
guard let decoded = PeliasSearchResponse.decode() else { return nil }
return ParsedSearchResponse.init(decoded)
}
}
|
apache-2.0
|
b48d2643cdb46d0ce87015a1e2dd22af
| 24.642857 | 91 | 0.712163 | 4.142308 | false | false | false | false |
Kunstmaan/i18n-swift
|
KunstmaanI18nSwift/Extensions/UIViewI18nExtension.swift
|
1
|
2886
|
//
// UIViewExtension.swift
// KunstmaanI18nSwift
//
// Created by Daan Poron on 19/04/16.
// Copyright © 2016 Kunstmaan. All rights reserved.
//
import Foundation
@IBDesignable
extension UIView {
fileprivate struct AssociatedKeys {
static var i18nKeys = "i18nKeys"
static var i18nShouldUppercase = "i18nShouldUppercase"
}
@IBInspectable
open var i18nShouldUppercase : Bool
{
get {
return objc_getAssociatedObject(self, &AssociatedKeys.i18nShouldUppercase) as? Bool ?? false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.i18nShouldUppercase, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
internal class func swizzle() {
for method in ["willMoveToWindow"] {
let originalSelector = Selector("\(method):")
let swizzledSelector = Selector("i18n_\(method):")
Utils.swizzle(self, originalSelector, swizzledSelector)
}
}
fileprivate func getI18nKeys() -> [String: String]? {
return objc_getAssociatedObject(self, &AssociatedKeys.i18nKeys) as? [String: String]
}
public func i18n_willMoveToWindow(_ newWindow: UIWindow?) {
self.i18n_willMoveToWindow(newWindow)
if newWindow == nil {
NotificationCenter.default.removeObserver(self, name: I18n.Events.onChange, object: nil)
} else {
NotificationCenter.default.addObserver(self, selector: #selector(UIView.updateTranslations), name: I18n.Events.onChange, object: nil)
self.updateTranslations()
}
}
public func localizedString(forKey key: String, withFallback fallback: String? = nil) -> String {
let translated = I18n.localizedString(forKey: key, withFallback: fallback)
return self.i18nShouldUppercase
? translated.uppercased()
: translated
}
@objc public func updateTranslations() {
if let i18nKeys = self.getI18nKeys() {
for (type, key) in i18nKeys {
self.update(i18nKey: key, forType: type)
}
}
}
public func retrieveI18nKey(forType type: String) -> String? {
return self.getI18nKeys()?[type]
}
public func register(i18nKey key: String, forType type: String) {
var keys = getI18nKeys()
if keys == nil {
keys = [String: String]()
}
keys![type] = key
objc_setAssociatedObject(self, &AssociatedKeys.i18nKeys, keys!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.update(i18nKey: key, forType: type)
}
@objc open func update(i18nKey key: String, forType type: String) { /* Should be overriden */ }
}
|
mit
|
f454e5a81eaf6185f3d1a98d3bcf5566
| 30.358696 | 147 | 0.610745 | 4.371212 | false | false | false | false |
HotWordland/HotWordLandIOSNetWork
|
Wp8IndicatorClasses/DTIAnimSpotify.swift
|
1
|
4119
|
//
// DTIAnimSpotify.swift
// SampleObjc
//
// Created by dtissera on 16/08/2014.
// Copyright (c) 2014 o--O--o. All rights reserved.
//
import UIKit
import QuartzCore
class DTIAnimSpotify: DTIAnimProtocol {
/** private properties */
private let owner: DTIActivityIndicatorView
private let spinnerView = UIView()
private let circleView = UIView()
private let animationDuration = CFTimeInterval(1.2)
private let circleCount = 3
/** ctor */
init(indicatorView: DTIActivityIndicatorView) {
self.owner = indicatorView
for var index = 0; index < circleCount; ++index {
let layer = CALayer()
self.circleView.layer.addSublayer(layer)
}
}
// -------------------------------------------------------------------------
// DTIAnimProtocol
// -------------------------------------------------------------------------
func needLayoutSubviews() {
self.spinnerView.frame = self.owner.bounds
let contentSize = self.owner.bounds.size
let circleWidth: CGFloat = contentSize.width / CGFloat(circleCount*2+1)
let posY: CGFloat = (contentSize.height-circleWidth)/2
self.circleView.frame = self.owner.bounds
// self.spinnerView.layer.cornerRadius = circleWidth/2
for var index = 0; index < circleCount; ++index {
let circleLayer = self.circleView.layer.sublayers[index] as CALayer
circleLayer.frame = CGRect(x: circleWidth+CGFloat(index)*(circleWidth*2), y: posY, width: circleWidth, height: circleWidth)
circleLayer.cornerRadius = circleWidth/2
//circleLayer.transform = CATransform3DMakeScale(2.0, 2.0, 0.0);
}
}
func needUpdateColor() {
// Debug stuff
// self.spinnerView.backgroundColor = UIColor.grayColor()
for var index = 0; index < circleCount; ++index {
let circleLayer = self.circleView.layer.sublayers[index] as CALayer
circleLayer.backgroundColor = self.owner.indicatorColor.CGColor
}
}
func setUp() {
self.spinnerView.addSubview(self.circleView)
//self.spinnerView.layer.shouldRasterize = true
}
func startActivity() {
self.owner.addSubview(self.spinnerView)
let beginTime = CACurrentMediaTime() + self.animationDuration;
for var index = 0; index < circleCount; ++index {
let circleLayer = self.circleView.layer.sublayers[index] as CALayer
let aniScale = CAKeyframeAnimation()
aniScale.keyPath = "transform.scale"
aniScale.values = [1.0, 1.7, 1.0, 1.0]
aniScale.removedOnCompletion = false
aniScale.repeatCount = HUGE
aniScale.beginTime = beginTime - self.animationDuration + CFTimeInterval(index) * 0.2;
aniScale.keyTimes = [0.0, 0.2, 0.4, 1.0];
aniScale.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
]
aniScale.duration = self.animationDuration
circleLayer.addAnimation(aniScale, forKey: "DTIAnimSpotify~scale")
}
}
func stopActivity(animated: Bool) {
func removeAnimations() {
self.spinnerView.layer.removeAllAnimations()
for var index = 0; index < circleCount; ++index {
let circleLayer = self.circleView.layer.sublayers[index] as CALayer
circleLayer.removeAllAnimations()
}
self.spinnerView.removeFromSuperview()
}
if (animated) {
self.spinnerView.layer.dismissAnimated(removeAnimations)
}
else {
removeAnimations()
}
}
}
|
mit
|
3e488aa816b8e2d626f2640fb02e34f3
| 35.140351 | 135 | 0.589706 | 5.321705 | false | false | false | false |
sugar2010/arcgis-runtime-samples-ios
|
DynamicSubLayerReorderSample/swift/DynamicSubLayerReorder/Controllers/LayersListViewController.swift
|
4
|
7562
|
/*
Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import ArcGIS
let POPOVER_WIDTH:CGFloat = 200
let POPOVER_HEIGHT:CGFloat = 200
protocol LayersListDelegate:class {
func layersListViewController(layersListViewController:LayersListViewController, didUpdateLayerInfos dynamicLayerInfos:[AGSDynamicLayerInfo])
}
class LayersListViewController: UIViewController, OptionsDelegate, UITableViewDataSource, UITableViewDelegate {
var layerInfos:[AGSLayerInfo]! {
didSet {
//initialize the deleted infos array if done already
if self.deletedLayerInfos == nil {
self.deletedLayerInfos = [AGSDynamicLayerInfo]()
}
//relaod the table view to reflect the layer info changes
self.tableView.reloadData()
}
}
weak var delegate:LayersListDelegate?
@IBOutlet weak var addButton:UIBarButtonItem!
@IBOutlet weak var editButton:UIBarButtonItem!
@IBOutlet weak var tableView:UITableView!
var deletedLayerInfos:[AGSLayerInfo]!
var optionsViewController:OptionsViewController!
var popover:UIPopoverController!
override func viewDidLoad() {
super.viewDidLoad()
//initialize the optionsViewController
self.optionsViewController = OptionsViewController()
self.optionsViewController.delegate = self
//initialize the popover controller
self.popover = UIPopoverController(contentViewController: self.optionsViewController)
self.popover.popoverContentSize = CGSizeMake(POPOVER_WIDTH, POPOVER_HEIGHT)
//enable editing on tableview
self.tableView.editing = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - table view datasource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.layerInfos != nil {
return self.layerInfos.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reusableIdentifier = "LayersListCell"
let cell = tableView.dequeueReusableCellWithIdentifier(reusableIdentifier) as! UITableViewCell
let layerInfo = self.layerInfos[indexPath.row]
cell.textLabel?.text = layerInfo.name
//enable reordering on each cell
cell.showsReorderControl = true
return cell
}
//enable re ordering on each row
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
//MARK: - table view delegates
//update the order of layer infos in the array
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
//get the layer info being moved
let layerInfo = self.layerInfos[sourceIndexPath.row]
//remove the layerInfo from the previous index
self.layerInfos.removeAtIndex(sourceIndexPath.row)
//add the layer info at the new index
self.layerInfos.insert(layerInfo, atIndex:destinationIndexPath.row)
//notify the delegate to update the dynamic service layer
self.updateDynamicServiceLayer()
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
//check if the editing style is Delete
if editingStyle == .Delete {
//save the object in the deleted layer infos array
let layerInfo = self.layerInfos[indexPath.row]
self.deletedLayerInfos.append(layerInfo)
tableView.beginUpdates()
//remove the layer info from the data source array
self.layerInfos.removeAtIndex(indexPath.row)
//delete the row
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic)
tableView.endUpdates()
//update dynamic service
self.updateDynamicServiceLayer()
//update the add button status
self.updateAddButtonStatus()
}
else {
println("Editing style other than delete")
}
}
//MARK: -
//the method creates an array of AGSDynamicLayerInfo from the array of AGSLayerInfo
//the AGSDynamicLayerInfo array can be assigned to the AGSDynamicMapService to update
//the ordering or add or delete a layer
func createDynamicLayerInfos(layerInfos:[AGSLayerInfo]) -> [AGSDynamicLayerInfo] {
//instantiate a new mutable array
var dynamicLayerInfos = [AGSDynamicLayerInfo]()
//loop through the layer infos array and create a corresponding
//dynamic layer info
for layerInfo in layerInfos {
let dynamicLayerInfo = AGSDynamicLayerInfo(layerID: layerInfo.layerId)
dynamicLayerInfos.append(dynamicLayerInfo)
}
return dynamicLayerInfos
}
//the method notifies the delegate about the changes in the layerInfos
func updateDynamicServiceLayer() {
//create dynamic layer infos from the layer infos
let dynamicLayerInfos = self.createDynamicLayerInfos(self.layerInfos)
//notify the delegate
self.delegate?.layersListViewController(self, didUpdateLayerInfos: dynamicLayerInfos)
}
//this method enables/disables the Add bar button item based on the
//count of values in the deletedLayerInfos array
func updateAddButtonStatus() {
self.addButton.enabled = self.deletedLayerInfos.count > 0
}
//MARK: - Actions
@IBAction func addAction(sender:UIBarButtonItem) {
//update the options array with the current layerInfos array
self.optionsViewController.options = self.deletedLayerInfos
//present the popover controller
self.popover.presentPopoverFromBarButtonItem(sender, permittedArrowDirections:.Down, animated:true)
}
//MARK: - OptionsDelegate
func optionsViewController(optionsViewController: OptionsViewController, didSelectOption option: AGSLayerInfo) {
//hide the popover controller
self.popover.dismissPopoverAnimated(true)
//remove the layer info from deleted layer Infos
if let index = find(self.deletedLayerInfos, option) {
self.deletedLayerInfos.removeAtIndex(index)
}
//and add it to the layer infos
self.layerInfos.insert(option, atIndex:0)
//reload tableview
self.tableView.reloadData()
//notify the delegate to update the dynamic service
self.updateDynamicServiceLayer()
//update the status of the add button
self.updateAddButtonStatus()
}
}
|
apache-2.0
|
55dc6f0ca3a1cc5406b89139771b0241
| 38.385417 | 148 | 0.693335 | 5.393723 | false | false | false | false |
imxieyi/waifu2x-ios
|
waifu2x/UIImage+Expand.swift
|
1
|
6967
|
//
// UIImage+MultiArray.swift
// waifu2x-ios
//
// Created by xieyi on 2017/9/14.
// Copyright © 2017年 xieyi. All rights reserved.
//
import UIKit
import CoreML
extension UIImage {
/// Expand the original image by shrink_size and store rgb in float array.
/// The model will shrink the input image by 7 px.
///
/// - Returns: Float array of rgb values
public func expand(withAlpha: Bool) -> [Float] {
let width = Int(self.cgImage!.width)
let height = Int(self.cgImage!.height)
let exwidth = width + 2 * Waifu2x.shrink_size
let exheight = height + 2 * Waifu2x.shrink_size
var u8Array = [UInt8](repeating: 0, count: width * height * 4)
u8Array.withUnsafeMutableBytes { u8Pointer in
let context = CGContext(data: u8Pointer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
context!.draw(cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))
}
var arr = [Float](repeating: 0, count: 3 * exwidth * exheight)
var xx, yy, pixel: Int
var r, g, b, a: UInt8
var fr, fg, fb: Float
// http://www.jianshu.com/p/516f01fed6e4
for y in 0..<height {
for x in 0..<width {
xx = x + Waifu2x.shrink_size
yy = y + Waifu2x.shrink_size
pixel = (width * y + x) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
// !!! rgb values are from 0 to 1
// https://github.com/chungexcy/waifu2x-new/blob/master/image_test.py
fr = Float(r) / 255 + Waifu2x.clip_eta8
fg = Float(g) / 255 + Waifu2x.clip_eta8
fb = Float(b) / 255 + Waifu2x.clip_eta8
if withAlpha {
a = u8Array[pixel + 3]
if a > 0 {
fr *= 255 / Float(a)
fg *= 255 / Float(a)
fb *= 255 / Float(a)
}
}
arr[yy * exwidth + xx] = fr
arr[yy * exwidth + xx + exwidth * exheight] = fg
arr[yy * exwidth + xx + exwidth * exheight * 2] = fb
}
}
// Top-left corner
pixel = 0
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in 0..<Waifu2x.shrink_size {
for x in 0..<Waifu2x.shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Top-right corner
pixel = (width - 1) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in 0..<Waifu2x.shrink_size {
for x in width+Waifu2x.shrink_size..<width+2*Waifu2x.shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Bottom-left corner
pixel = (width * (height - 1)) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in height+Waifu2x.shrink_size..<height+2*Waifu2x.shrink_size {
for x in 0..<Waifu2x.shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Bottom-right corner
pixel = (width * (height - 1) + (width - 1)) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in height+Waifu2x.shrink_size..<height+2*Waifu2x.shrink_size {
for x in width+Waifu2x.shrink_size..<width+2*Waifu2x.shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Top & bottom bar
for x in 0..<width {
pixel = x * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
xx = x + Waifu2x.shrink_size
for y in 0..<Waifu2x.shrink_size {
arr[y * exwidth + xx] = fr
arr[y * exwidth + xx + exwidth * exheight] = fg
arr[y * exwidth + xx + exwidth * exheight * 2] = fb
}
pixel = (width * (height - 1) + x) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
xx = x + Waifu2x.shrink_size
for y in height+Waifu2x.shrink_size..<height+2*Waifu2x.shrink_size {
arr[y * exwidth + xx] = fr
arr[y * exwidth + xx + exwidth * exheight] = fg
arr[y * exwidth + xx + exwidth * exheight * 2] = fb
}
}
// Left & right bar
for y in 0..<height {
pixel = (width * y) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
yy = y + Waifu2x.shrink_size
for x in 0..<Waifu2x.shrink_size {
arr[yy * exwidth + x] = fr
arr[yy * exwidth + x + exwidth * exheight] = fg
arr[yy * exwidth + x + exwidth * exheight * 2] = fb
}
pixel = (width * y + (width - 1)) * 4
r = u8Array[pixel]
g = u8Array[pixel + 1]
b = u8Array[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
yy = y + Waifu2x.shrink_size
for x in width+Waifu2x.shrink_size..<width+2*Waifu2x.shrink_size {
arr[yy * exwidth + x] = fr
arr[yy * exwidth + x + exwidth * exheight] = fg
arr[yy * exwidth + x + exwidth * exheight * 2] = fb
}
}
return arr
}
}
|
mit
|
c85aa4b514a3b1b89155a26f88208524
| 36.847826 | 234 | 0.460655 | 3.440711 | false | false | false | false |
kickstarter/ios-oss
|
Library/OptimizelyExperiment.swift
|
1
|
949
|
import Foundation
import KsApi
public enum OptimizelyExperiment {
public enum Key: String, CaseIterable {
case nativeOnboarding = "native_onboarding_series_new_backers"
case onboardingCategoryPersonalizationFlow = "onboarding_category_personalization_flow"
case nativeProjectCards = "native_project_cards"
case nativeRiskMessaging = "native_risk_messaging"
}
public enum Variant: String, Equatable {
case control
case variant1 = "variant-1"
case variant2 = "variant-2"
}
}
extension OptimizelyExperiment {
// Returns variation via getVariation for native_project_cards experiment
static func nativeProjectCardsExperimentVariant() -> OptimizelyExperiment.Variant {
guard let optimizelyClient = AppEnvironment.current.optimizelyClient else {
return .control
}
let variant = optimizelyClient.getVariation(for: OptimizelyExperiment.Key.nativeProjectCards.rawValue)
return variant
}
}
|
apache-2.0
|
fc8130424a8cbe6363117c50da08d68f
| 30.633333 | 106 | 0.76607 | 4.629268 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.