repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yzhou65/DSWeibo | DSWeibo/Classes/Home/QRCode/QRCodeViewController.swift | 1 | 8053 | //
// QRCodeViewController.swift
// DSWeibo
//
// Created by Yue on 9/7/16.
// Copyright © 2016 fda. All rights reserved.
//
import UIKit
import AVFoundation
class QRCodeViewController: UIViewController, UITabBarDelegate {
///扫描容器高度约束
@IBOutlet weak var containerHeightCons: NSLayoutConstraint!
///扫描线视图
@IBOutlet weak var scanLineView: UIImageView!
///扫描线视图的顶部约束
@IBOutlet weak var scanLineCons: NSLayoutConstraint!
///底部试图
@IBOutlet weak var customTabBar: UITabBar!
///保存扫描到的结果
@IBOutlet weak var resultLabel: UILabel!
///监听名片按钮点击
@IBAction func myCardBtnClick(sender: AnyObject) {
let vc = QRCodeCardViewController()
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func closeBtnClick(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//设置底部视图默认选中“二维码”
customTabBar.selectedItem = customTabBar.items![0]
customTabBar.delegate = self;
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//开时“冲击波”动画
startAnimation()
//开时扫描
startScan()
}
/**
扫描二维码
*/
private func startScan(){
//判断是否能将输入添加到会话
if !session.canAddInput(deviceInput) {
return
}
//判断是否能将输出添加到会话
if !session.canAddOutput(output) {
return
}
//将输入和输出都添加到会话
session.addInput(deviceInput)
session.addOutput(output)
//设置输出能够解析的数据类型
//注意:设置能够解析的数据类型,一定要在输出对象添加到会话之后设置,否则会报错
output.metadataObjectTypes = output.availableMetadataObjectTypes
//设置输出对象的代理,只要解析成功就会通知代理
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
//系统自带的二维码扫描不支持只扫描一张图片(加入屏幕上某区域有多个二维码)。只能设置让二维码只有出现在某一块区域才去扫描
output.rectOfInterest = CGRectMake(0.0, 0.0, 1.0, 1.0)
//添加预览图层。要避免盖住“扫描线冲击波”
view.layer.insertSublayer(previewLayer, atIndex: 0)
//添加绘制图层到预览图层上
previewLayer.addSublayer(drawLayer)
//告诉session开始扫描
session.startRunning()
}
/**
执行动画
*/
private func startAnimation() {
//让约束从顶部开始
self.scanLineCons.constant = -self.containerHeightCons.constant
//强制更新界面
self.scanLineView.layoutIfNeeded()
//执行“冲击波”动画
UIView.animateWithDuration(5.0, animations: {
//修改约束
self.scanLineCons.constant = self.containerHeightCons.constant
//设置动画的次数
UIView.setAnimationRepeatCount(MAXFLOAT)
//强制更新界面
self.scanLineView.layoutIfNeeded()
})
}
//MARK: -UITabBarDelegate
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
//修改容器高度
if item.tag == 1 {
// print("qrcode")
self.containerHeightCons.constant = 300
} else {
// print("barcode")
self.containerHeightCons.constant *= 0.5
}
//停止动画再开时
scanLineView.layer.removeAllAnimations()
startAnimation()
}
//MARK: -懒加载
//会话. 以下是懒加载的一种简单写法, 前提是不需要传入参数
private lazy var session: AVCaptureSession = AVCaptureSession()
//拿到输入设备
private lazy var deviceInput: AVCaptureDeviceInput? = {
//获取摄像头
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
//创建输入对象
do{
let input = try AVCaptureDeviceInput(device: device)
return input
}catch{
print(error)
return nil
}
}()
//拿到输出对象
private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
//创建预览图层
private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session) //闭包中访问成员属性要加上self
layer.frame = UIScreen.mainScreen().bounds
return layer
}()
//创建用于绘制边线的图层
private lazy var drawLayer: CALayer = {
let layer = CALayer()
layer.frame = UIScreen.mainScreen().bounds
return layer
}()
}
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate
{
/**
只要解析到数据就会调用
*/
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
//清空图层
clearCorners()
//获取扫描到的数据
//注意:要使用stringValue将metadataObjects中的对象转为string
resultLabel.text = metadataObjects.last?.stringValue
resultLabel.sizeToFit()
//获取扫描到的二维码位置
//转换坐标
for obj in metadataObjects
{
//判断当前获取到的数据,机器是否可以识别
if obj is AVMetadataMachineReadableCodeObject {
//将坐标转换成界面可识别的坐标
let codeObj = previewLayer.transformedMetadataObjectForMetadataObject(obj as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
//绘制图形
drawCorners(codeObj)
}
}
}
/**
扫描到二维码后,绘制一个边框来指示扫描到了
*/
private func drawCorners(codeObj: AVMetadataMachineReadableCodeObject){
if codeObj.corners.isEmpty {
return
}
//创建一个图层
let layer = CAShapeLayer()
layer.lineWidth = 4
layer.strokeColor = UIColor.greenColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
//创建路径
// layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).CGPath
let path = UIBezierPath()
var point = CGPointZero
var index: Int = 0
//从corners数组中取出第0个,将这个字典中的x/y赋值给point
CGPointMakeWithDictionaryRepresentation((codeObj.corners[index++] as! CFDictionaryRef), &point)
path.moveToPoint(point)
//移动到其他点
while index < codeObj.corners.count
{
CGPointMakeWithDictionaryRepresentation((codeObj.corners[index++] as! CFDictionaryRef), &point)
path.addLineToPoint(point)
}
//关闭路径
path.closePath()
layer.path = path.CGPath
//将绘制好的图层添加到drawLayer上
drawLayer.addSublayer(layer)
}
/**
清空边线
*/
private func clearCorners(){
if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0 {
return
}
for sublayer in drawLayer.sublayers!
{
sublayer.removeFromSuperlayer()
}
}
}
| apache-2.0 | 3450037e7f7ca858df7a5f0bf65cec8f | 26.31746 | 162 | 0.591226 | 4.807263 | false | false | false | false |
fhchina/ReactiveCocoa | ReactiveCocoaTests/Swift/SignalProducerSpec.swift | 134 | 42757 | //
// SignalProducerSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import Box
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++
return
}
signalProducer.start()
signalProducer.start()
expect(handlerCalledTimes).to(equal(2))
}
it("should release signal observers when given disposable is disposed") {
var disposable: Disposable!
let producer = SignalProducer<Int, NoError> { observer, innerDisposable in
disposable = innerDisposable
innerDisposable.addDisposable {
// This is necessary to keep the observer long enough to
// even test the memory management.
sendNext(observer, 0)
}
}
weak var testSink: TestSink?
producer.startWithSignal { signal, _ in
var sink = TestSink()
testSink = sink
signal.observe(sink)
}
expect(testSink).toNot(beNil())
disposable.dispose()
expect(testSink).to(beNil())
}
it("should dispose of added disposables upon completion") {
let addedDisposable = SimpleDisposable()
var sink: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError>() { observer, disposable in
disposable.addDisposable(addedDisposable)
sink = observer
}
producer.start()
expect(addedDisposable.disposed).to(beFalsy())
sendCompleted(sink)
expect(addedDisposable.disposed).to(beTruthy())
}
it("should dispose of added disposables upon error") {
let addedDisposable = SimpleDisposable()
var sink: Signal<(), TestError>.Observer!
let producer = SignalProducer<(), TestError>() { observer, disposable in
disposable.addDisposable(addedDisposable)
sink = observer
}
producer.start()
expect(addedDisposable.disposed).to(beFalsy())
sendError(sink, .Default)
expect(addedDisposable.disposed).to(beTruthy())
}
it("should dispose of added disposables upon interruption") {
let addedDisposable = SimpleDisposable()
var sink: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError>() { observer, disposable in
disposable.addDisposable(addedDisposable)
sink = observer
}
producer.start()
expect(addedDisposable.disposed).to(beFalsy())
sendInterrupted(sink)
expect(addedDisposable.disposed).to(beTruthy())
}
it("should dispose of added disposables upon start() disposal") {
let addedDisposable = SimpleDisposable()
let producer = SignalProducer<(), TestError>() { _, disposable in
disposable.addDisposable(addedDisposable)
return
}
let startDisposable = producer.start()
expect(addedDisposable.disposed).to(beFalsy())
startDisposable.dispose()
expect(addedDisposable.disposed).to(beTruthy())
}
}
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("SignalProducer.buffer") {
it("should replay buffered events when started, then forward events as added") {
let (producer, sink) = SignalProducer<Int, NSError>.buffer()
sendNext(sink, 1)
sendNext(sink, 2)
sendNext(sink, 3)
var values: [Int] = []
var completed = false
producer.start(next: {
values.append($0)
}, completed: {
completed = true
})
expect(values).to(equal([1, 2, 3]))
expect(completed).to(beFalsy())
sendNext(sink, 4)
sendNext(sink, 5)
expect(values).to(equal([1, 2, 3, 4, 5]))
expect(completed).to(beFalsy())
sendCompleted(sink)
expect(values).to(equal([1, 2, 3, 4, 5]))
expect(completed).to(beTruthy())
}
it("should drop earliest events to maintain the capacity") {
let (producer, sink) = SignalProducer<Int, TestError>.buffer(1)
sendNext(sink, 1)
sendNext(sink, 2)
var values: [Int] = []
var error: TestError?
producer.start(next: {
values.append($0)
}, error: {
error = $0
})
expect(values).to(equal([2]))
expect(error).to(beNil())
sendNext(sink, 3)
sendNext(sink, 4)
expect(values).to(equal([2, 3, 4]))
expect(error).to(beNil())
sendError(sink, .Default)
expect(values).to(equal([2, 3, 4]))
expect(error).to(equal(TestError.Default))
}
it("should always replay termination event") {
let (producer, sink) = SignalProducer<Int, TestError>.buffer(0)
var completed = false
sendCompleted(sink)
producer.start(completed: {
completed = true
})
expect(completed).to(beTruthy())
}
it("should replay values after being terminated") {
let (producer, sink) = SignalProducer<Int, TestError>.buffer(1)
var value: Int?
var completed = false
sendNext(sink, 123)
sendCompleted(sink)
producer.start(next: {val in
value = val
}, completed: {
completed = true
})
expect(value).to(equal(123))
expect(completed).to(beTruthy())
}
it("should not deadlock when started while sending") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
sendNext(sink, 1)
sendNext(sink, 2)
sendNext(sink, 3)
var values: [Int] = []
producer.start(completed: {
values = []
producer.start(next: { value in
values.append(value)
})
})
sendCompleted(sink)
expect(values).to(equal([ 1, 2, 3 ]))
}
it("should buffer values before sending recursively to new observers") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
var values: [Int] = []
var lastBufferedValues: [Int] = []
producer.start(next: { newValue in
values.append(newValue)
var bufferedValues: [Int] = []
producer.start(next: { bufferedValue in
bufferedValues.append(bufferedValue)
})
expect(bufferedValues).to(equal(values))
lastBufferedValues = bufferedValues
})
sendNext(sink, 1)
expect(values).to(equal([ 1 ]))
expect(lastBufferedValues).to(equal(values))
sendNext(sink, 2)
expect(values).to(equal([ 1, 2 ]))
expect(lastBufferedValues).to(equal(values))
sendNext(sink, 3)
expect(values).to(equal([ 1, 2, 3 ]))
expect(lastBufferedValues).to(equal(values))
}
}
describe("SignalProducer.try") {
it("should run the operation once per start()") {
var operationRunTimes = 0
let operation: () -> Result<String, NSError> = {
operationRunTimes++
return .success("OperationValue")
}
SignalProducer.try(operation).start()
SignalProducer.try(operation).start()
expect(operationRunTimes).to(equal(2))
}
it("should send the value then complete") {
let operationReturnValue = "OperationValue"
let operation: () -> Result<String, NSError> = {
return .success(operationReturnValue)
}
let signalProducer = SignalProducer.try(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.try(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).to(beFalsy())
expect(value).to(beNil())
}
expect(started).to(beTruthy())
expect(value).to(equal(42))
}
it("should dispose of added disposables if disposed") {
let addedDisposable = SimpleDisposable()
var disposable: Disposable!
let producer = SignalProducer<Int, NoError>() { _, disposable in
disposable.addDisposable(addedDisposable)
return
}
producer |> startWithSignal { _, innerDisposable in
disposable = innerDisposable
}
expect(addedDisposable.disposed).to(beFalsy())
disposable.dispose()
expect(addedDisposable.disposed).to(beTruthy())
}
it("should send interrupted if disposed") {
var interrupted = false
var disposable: Disposable!
SignalProducer<Int, NoError>(value: 42)
|> startOn(TestScheduler())
|> startWithSignal { signal, innerDisposable in
signal.observe(interrupted: {
interrupted = true
})
disposable = innerDisposable
}
expect(interrupted).to(beFalsy())
disposable.dispose()
expect(interrupted).to(beTruthy())
}
it("should release signal observers if disposed") {
weak var testSink: TestSink?
var disposable: Disposable!
let producer = SignalProducer<Int, NoError>.never
producer.startWithSignal { signal, innerDisposable in
var sink = TestSink()
testSink = sink
signal.observe(sink)
disposable = innerDisposable
}
expect(testSink).toNot(beNil())
disposable.dispose()
expect(testSink).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).to(beFalsy())
expect(value).to(beNil())
disposable.dispose()
}
expect(started).to(beFalsy())
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).to(beFalsy())
signal.observe(interrupted: {
interrupted = true
})
disposable.dispose()
}
expect(interrupted).to(beTruthy())
}
it("should dispose of added disposables upon completion") {
let addedDisposable = SimpleDisposable()
var sink: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError>() { observer, disposable in
disposable.addDisposable(addedDisposable)
sink = observer
}
producer |> startWithSignal { _ in }
expect(addedDisposable.disposed).to(beFalsy())
sendCompleted(sink)
expect(addedDisposable.disposed).to(beTruthy())
}
it("should dispose of added disposables upon error") {
let addedDisposable = SimpleDisposable()
var sink: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError>() { observer, disposable in
disposable.addDisposable(addedDisposable)
sink = observer
}
producer |> startWithSignal { _ in }
expect(addedDisposable.disposed).to(beFalsy())
sendError(sink, .Default)
expect(addedDisposable.disposed).to(beTruthy())
}
}
describe("start") {
it("should immediately begin sending events") {
let producer = SignalProducer<Int, NoError>(values: [1, 2])
var values: [Int] = []
var completed = false
producer.start(next: {
values.append($0)
}, completed: {
completed = true
})
expect(values).to(equal([1, 2]))
expect(completed).to(beTruthy())
}
it("should send interrupted if disposed") {
let producer = SignalProducer<(), NoError>.never
var interrupted = false
let disposable = producer.start(interrupted: {
interrupted = true
})
expect(interrupted).to(beFalsy())
disposable.dispose()
expect(interrupted).to(beTruthy())
}
it("should release sink when disposed") {
weak var testSink: TestSink?
var disposable: Disposable!
var test: () -> () = {
let producer = SignalProducer<Int, NoError>.never
let sink = TestSink()
testSink = sink
disposable = producer.start(sink)
}
test()
expect(testSink).toNot(beNil())
disposable.dispose()
expect(testSink).to(beNil())
}
describe("trailing closure") {
it("receives next values") {
var values = [Int]()
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
producer.start { next in
values.append(next)
}
sendNext(sink, 1)
sendNext(sink, 2)
sendNext(sink, 3)
sendCompleted(sink)
expect(values).to(equal([1, 2, 3]))
}
}
}
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).to(equal(0))
producer.start()
expect(counter).to(equal(1))
producer.start()
expect(counter).to(equal(2))
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>(values: [1, 2, 3, 4])
let producer = baseProducer.lift(map { $0 * $0 })
let result = producer |> collect |> single
expect(result?.value).to(equal([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 zip(signal, otherSignal)
}
}
let producer = baseProducer.lift(transform)(otherProducer)
expect(counter).to(equal(0))
producer.start()
expect(counter).to(equal(1))
producer.start()
expect(counter).to(equal(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 zip(signal, otherSignal) |> map { first, second in first + second }
}
}
let producer = baseProducer.lift(transform)(otherProducer)
let result = producer |> collect |> single
expect(result?.value).to(equal([5, 7, 9]))
}
}
}
describe("sequence operators") {
var producerA: SignalProducer<Int, NoError>!
var producerB: SignalProducer<Int, NoError>!
beforeEach {
producerA = SignalProducer<Int, NoError>(values: [ 1, 2 ])
producerB = SignalProducer<Int, NoError>(values: [ 3, 4 ])
}
it("should combine the events to one array") {
let producer = combineLatest([producerA, producerB])
let result = producer |> collect |> single
expect(result?.value).to(equal([[1, 4], [2, 4]]))
}
it("should zip the events to one array") {
let producer = zip([producerA, producerB])
let result = producer |> collect |> single
expect(result?.value).to(equal([[1, 3], [2, 4]]))
}
}
describe("timer") {
it("should send the current date at the given interval") {
let scheduler = TestScheduler()
let producer = timer(1, onScheduler: scheduler, withLeeway: 0)
var dates: [NSDate] = []
producer.start(next: { dates.append($0) })
scheduler.advanceByInterval(0.9)
expect(dates).to(equal([]))
scheduler.advanceByInterval(1)
let firstTick = scheduler.currentDate
expect(dates).to(equal([firstTick]))
scheduler.advance()
expect(dates).to(equal([firstTick]))
scheduler.advanceByInterval(0.2)
let secondTick = scheduler.currentDate
expect(dates).to(equal([firstTick, secondTick]))
scheduler.advanceByInterval(1)
expect(dates).to(equal([firstTick, secondTick, scheduler.currentDate]))
}
it("should release the signal when disposed") {
let scheduler = TestScheduler()
let producer = timer(1, onScheduler: scheduler, withLeeway: 0)
weak var weakSignal: Signal<NSDate, NoError>?
producer.startWithSignal { signal, disposable in
weakSignal = signal
scheduler.schedule {
disposable.dispose()
}
}
expect(weakSignal).toNot(beNil())
scheduler.run()
expect(weakSignal).to(beNil())
}
}
describe("on") {
it("should attach event handlers to each started signal") {
let (baseProducer, sink) = SignalProducer<Int, TestError>.buffer()
var started = 0
var event = 0
var next = 0
var completed = 0
var terminated = 0
let producer = baseProducer
|> on(started: { () -> () in
started += 1
}, event: { (e: Event<Int, TestError>) -> () in
event += 1
}, next: { (n: Int) -> () in
next += 1
}, completed: { () -> () in
completed += 1
}, terminated: { () -> () in
terminated += 1
})
producer.start()
expect(started).to(equal(1))
producer.start()
expect(started).to(equal(2))
sendNext(sink, 1)
expect(event).to(equal(2))
expect(next).to(equal(2))
sendCompleted(sink)
expect(event).to(equal(4))
expect(completed).to(equal(2))
expect(terminated).to(equal(2))
}
}
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 |> startOn(scheduler) |> start()
expect(invoked).to(beFalsy())
scheduler.advance()
expect(invoked).to(beTruthy())
}
it("should forward events on their original scheduler") {
let startScheduler = TestScheduler()
let testScheduler = TestScheduler()
let producer = timer(2, onScheduler: testScheduler, withLeeway: 0)
var next: NSDate?
producer |> startOn(startScheduler) |> start(next: { next = $0 })
startScheduler.advanceByInterval(2)
expect(next).to(beNil())
testScheduler.advanceByInterval(1)
expect(next).to(beNil())
testScheduler.advanceByInterval(1)
expect(next).to(equal(testScheduler.currentDate))
}
}
describe("catch") {
it("should invoke the handler and start new producer for an error") {
let (baseProducer, baseSink) = SignalProducer<Int, TestError>.buffer()
sendNext(baseSink, 1)
sendError(baseSink, .Default)
var values: [Int] = []
var completed = false
baseProducer
|> catch { (error: TestError) -> SignalProducer<Int, TestError> in
expect(error).to(equal(TestError.Default))
expect(values).to(equal([1]))
let (innerProducer, innerSink) = SignalProducer<Int, TestError>.buffer()
sendNext(innerSink, 2)
sendCompleted(innerSink)
return innerProducer
}
|> start(next: {
values.append($0)
}, completed: {
completed = true
})
expect(values).to(equal([1, 2]))
expect(completed).to(beTruthy())
}
}
describe("flatten") {
describe("FlattenStrategy.Concat") {
describe("sequencing") {
var completePrevious: (Void -> Void)!
var sendSubsequent: (Void -> Void)!
var completeOuter: (Void -> Void)!
var subsequentStarted = false
beforeEach {
let (outerProducer, outerSink) = SignalProducer<SignalProducer<Int, NoError>, NoError>.buffer()
let (previousProducer, previousSink) = SignalProducer<Int, NoError>.buffer()
subsequentStarted = false
let subsequentProducer = SignalProducer<Int, NoError> { _ in
subsequentStarted = true
}
completePrevious = { sendCompleted(previousSink) }
sendSubsequent = { sendNext(outerSink, subsequentProducer) }
completeOuter = { sendCompleted(outerSink) }
(outerProducer |> flatten(.Concat)).start()
sendNext(outerSink, previousProducer)
}
it("should immediately start subsequent inner producer if previous inner producer has already completed") {
completePrevious()
sendSubsequent()
expect(subsequentStarted).to(beTruthy())
}
context("with queued producers") {
beforeEach {
// Place the subsequent producer into `concat`'s queue.
sendSubsequent()
expect(subsequentStarted).to(beFalsy())
}
it("should start subsequent inner producer upon completion of previous inner producer") {
completePrevious()
expect(subsequentStarted).to(beTruthy())
}
it("should start subsequent inner producer upon completion of previous inner producer and completion of outer producer") {
completeOuter()
completePrevious()
expect(subsequentStarted).to(beTruthy())
}
}
}
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)).start(error: { e in
error = e
})
expect(error).to(equal(TestError.Default))
}
it("should forward an error from the outer producer") {
let (outerProducer, outerSink) = SignalProducer<SignalProducer<Int, TestError>, TestError>.buffer()
var error: TestError?
(outerProducer |> flatten(.Concat)).start(error: { e in
error = e
})
sendError(outerSink, TestError.Default)
expect(error).to(equal(TestError.Default))
}
describe("completion") {
var completeOuter: (Void -> Void)!
var completeInner: (Void -> Void)!
var completed = false
beforeEach {
let (outerProducer, outerSink) = SignalProducer<SignalProducer<Int, NoError>, NoError>.buffer()
let (innerProducer, innerSink) = SignalProducer<Int, NoError>.buffer()
completeOuter = { sendCompleted(outerSink) }
completeInner = { sendCompleted(innerSink) }
completed = false
(outerProducer |> flatten(.Concat)).start(completed: {
completed = true
})
sendNext(outerSink, innerProducer)
}
it("should complete when inner producers complete, then outer producer completes") {
completeInner()
expect(completed).to(beFalsy())
completeOuter()
expect(completed).to(beTruthy())
}
it("should complete when outer producers completes, then inner producers complete") {
completeOuter()
expect(completed).to(beFalsy())
completeInner()
expect(completed).to(beTruthy())
}
}
}
describe("FlattenStrategy.Merge") {
describe("behavior") {
var completeA: (Void -> Void)!
var sendA: (Void -> Void)!
var completeB: (Void -> Void)!
var sendB: (Void -> Void)!
var outerCompleted = false
var recv = [Int]()
beforeEach {
let (outerProducer, outerSink) = SignalProducer<SignalProducer<Int, NoError>, NoError>.buffer()
let (producerA, sinkA) = SignalProducer<Int, NoError>.buffer()
let (producerB, sinkB) = SignalProducer<Int, NoError>.buffer()
completeA = { sendCompleted(sinkA) }
completeB = { sendCompleted(sinkB) }
var a = 0
sendA = { sendNext(sinkA, a++) }
var b = 100
sendB = { sendNext(sinkB, b++) }
sendNext(outerSink, producerA)
sendNext(outerSink, producerB)
(outerProducer |> flatten(.Merge)).start(next: { i in
recv.append(i)
}, error: { _ in () }, completed: {
outerCompleted = true
})
sendCompleted(outerSink)
}
it("should forward values from any inner signals") {
sendA()
sendA()
sendB()
sendA()
sendB()
expect(recv).to(equal([0, 1, 100, 2, 101]))
}
it("should complete when all signals have completed") {
completeA()
expect(outerCompleted).to(beFalsy())
completeB()
expect(outerCompleted).to(beTruthy())
}
}
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)).start(error: { e in
error = e
})
expect(error).to(equal(TestError.Default))
}
it("should forward an error from the outer signal") {
let (outerProducer, outerSink) = SignalProducer<SignalProducer<Int, TestError>, TestError>.buffer()
var error: TestError?
(outerProducer |> flatten(.Merge)).start(error: { e in
error = e
})
sendError(outerSink, TestError.Default)
expect(error).to(equal(TestError.Default))
}
}
}
describe("FlattenStrategy.Latest") {
it("should forward values from the latest inner signal") {
let (outer, outerSink) = SignalProducer<SignalProducer<Int, TestError>, TestError>.buffer()
let (firstInner, firstInnerSink) = SignalProducer<Int, TestError>.buffer()
let (secondInner, secondInnerSink) = SignalProducer<Int, TestError>.buffer()
var receivedValues: [Int] = []
var errored = false
var completed = false
(outer |> flatten(.Latest)).start(
next: {
receivedValues.append($0)
},
error: { _ in
errored = true
},
completed: {
completed = true
})
sendNext(firstInnerSink, 1)
sendNext(secondInnerSink, 2)
sendNext(outerSink, SignalProducer(value: 0))
sendNext(outerSink, firstInner)
sendNext(outerSink, secondInner)
sendCompleted(outerSink)
expect(receivedValues).to(equal([ 0, 1, 2 ]))
expect(errored).to(beFalsy())
expect(completed).to(beFalsy())
sendNext(firstInnerSink, 3)
sendCompleted(firstInnerSink)
sendNext(secondInnerSink, 4)
sendCompleted(secondInnerSink)
expect(receivedValues).to(equal([ 0, 1, 2, 4 ]))
expect(errored).to(beFalsy())
expect(completed).to(beTruthy())
}
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).to(equal(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).to(equal(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)).start(completed: {
completed = true
})
expect(completed).to(beTruthy())
}
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)).start(completed: {
completed = true
})
expect(completed).to(beTruthy())
}
it("should not deadlock") {
let result = SignalProducer<Int, NoError>(value: 1)
|> flatMap(.Latest) { _ in SignalProducer(value: 10) }
|> take(1)
|> last
expect(result?.value).to(equal(10))
}
}
describe("interruption") {
var innerSink: Signal<(), NoError>.Observer!
var outerSink: Signal<SignalProducer<(), NoError>, NoError>.Observer!
var execute: (FlattenStrategy -> Void)!
var interrupted = false
var completed = false
beforeEach {
let (innerProducer, innerObserver) = SignalProducer<(), NoError>.buffer()
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<(), NoError>, NoError>.buffer()
innerSink = innerObserver
outerSink = outerObserver
execute = { strategy in
interrupted = false
completed = false
outerProducer
|> flatten(strategy)
|> start(interrupted: { _ in
interrupted = true
}, completed: { _ in
completed = true
})
}
sendNext(outerSink, innerProducer)
}
describe("Concat") {
it("should drop interrupted from an inner producer") {
execute(.Concat)
sendInterrupted(innerSink)
expect(interrupted).to(beFalsy())
expect(completed).to(beFalsy())
sendCompleted(outerSink)
expect(completed).to(beTruthy())
}
it("should forward interrupted from the outer producer") {
execute(.Concat)
sendInterrupted(outerSink)
expect(interrupted).to(beTruthy())
}
}
describe("Latest") {
it("should drop interrupted from an inner producer") {
execute(.Latest)
sendInterrupted(innerSink)
expect(interrupted).to(beFalsy())
expect(completed).to(beFalsy())
sendCompleted(outerSink)
expect(completed).to(beTruthy())
}
it("should forward interrupted from the outer producer") {
execute(.Latest)
sendInterrupted(outerSink)
expect(interrupted).to(beTruthy())
}
}
describe("Merge") {
it("should drop interrupted from an inner producer") {
execute(.Merge)
sendInterrupted(innerSink)
expect(interrupted).to(beFalsy())
expect(completed).to(beFalsy())
sendCompleted(outerSink)
expect(completed).to(beTruthy())
}
it("should forward interrupted from the outer producer") {
execute(.Merge)
sendInterrupted(outerSink)
expect(interrupted).to(beTruthy())
}
}
}
}
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).to(equal([ 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).to(equal([ 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.tryWithResults(results)
let producer = original |> times(3)
let events = producer
|> materialize
|> collect
|> single
let result = events?.value
let expectedEvents: [Event<Int, TestError>] = [
.Next(Box(1)),
.Next(Box(2)),
.Error(Box(.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<T, E>.
expect(result![0] == expectedEvents[0]).to(beTruthy())
expect(result![1] == expectedEvents[1]).to(beTruthy())
expect(result![2] == expectedEvents[2]).to(beTruthy())
}
}
it("should evaluate lazily") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original |> times(Int.max)
let result = producer |> take(1) |> single
expect(result?.value).to(equal(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.tryWithResults(results)
let producer = original |> retry(2)
let result = producer |> single
expect(result?.value).to(equal(1))
}
it("should forward errors that occur after all retries") {
let results: [Result<Int, TestError>] = [
.failure(.Default),
.failure(.Error1),
.failure(.Error2),
]
let original = SignalProducer.tryWithResults(results)
let producer = original |> retry(2)
let result = producer |> single
expect(result?.error).to(equal(TestError.Error2))
}
it("should not retry upon completion") {
let results: [Result<Int, TestError>] = [
.success(1),
.success(2),
.success(3)
]
let original = SignalProducer.tryWithResults(results)
let producer = original |> retry(2)
let result = producer |> single
expect(result?.value).to(equal(1))
}
}
describe("then") {
it("should start the subsequent producer after the completion of the original") {
let (original, sink) = SignalProducer<Int, NoError>.buffer()
var subsequentStarted = false
let subsequent = SignalProducer<Int, NoError> { observer, _ in
subsequentStarted = true
}
let producer = original |> then(subsequent)
producer.start()
expect(subsequentStarted).to(beFalsy())
sendCompleted(sink)
expect(subsequentStarted).to(beTruthy())
}
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).to(equal(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).to(equal(TestError.Default))
}
it("should complete when both inputs have completed") {
let (original, originalSink) = SignalProducer<Int, NoError>.buffer()
let (subsequent, subsequentSink) = SignalProducer<String, NoError>.buffer()
let producer = original |> then(subsequent)
var completed = false
producer.start(completed: {
completed = true
})
sendCompleted(originalSink)
expect(completed).to(beFalsy())
sendCompleted(subsequentSink)
expect(completed).to(beTruthy())
}
}
describe("first") {
it("should start a signal then block on the first value") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
var result: Result<Int, NoError>?
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
result = producer |> first
}
expect(result).to(beNil())
sendNext(sink, 1)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
expect(result?.value).to(equal(1))
}
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).to(equal(1))
}
it("should return an error if one occurs before the first value") {
let result = SignalProducer<Int, TestError>(error: .Default) |> first
expect(result?.error).to(equal(TestError.Default))
}
}
describe("single") {
it("should start a signal then block until completion") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
var result: Result<Int, NoError>?
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
result = producer |> single
}
expect(result).to(beNil())
sendNext(sink, 1)
expect(result).to(beNil())
sendCompleted(sink)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
expect(result?.value).to(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).to(equal(TestError.Default))
}
}
describe("last") {
it("should start a signal then block until completion") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
var result: Result<Int, NoError>?
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
result = producer |> last
}
expect(result).to(beNil())
sendNext(sink, 1)
sendNext(sink, 2)
expect(result).to(beNil())
sendCompleted(sink)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
expect(result?.value).to(equal(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).to(equal(2))
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .Default) |> last
expect(result?.error).to(equal(TestError.Default))
}
}
describe("wait") {
it("should start a signal then block until completion") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
var result: Result<(), NoError>?
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
result = producer |> wait
}
expect(result).to(beNil())
sendCompleted(sink)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
expect(result?.value).toNot(beNil())
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .Default) |> wait
expect(result.error).to(equal(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
|> observeOn(TestScheduler())
|> startWithSignal { signal, innerDisposable in
downstreamDisposable = innerDisposable
}
expect(upstreamDisposable.disposed).to(beFalsy())
downstreamDisposable.dispose()
expect(upstreamDisposable.disposed).to(beTruthy())
}
}
}
}
/// Observer that can be weakly captured to monitor its lifetime
private final class TestSink : SinkType {
func put(x: Event<Int, NoError>) {}
}
extension SignalProducer {
/// 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.
private static func tryWithResults<C: CollectionType where C.Generator.Element == Result<T, E>, C.Index.Distance == Int>(results: C) -> SignalProducer<T, E> {
let resultCount = count(results)
var operationIndex = 0
precondition(resultCount > 0)
let operation: () -> Result<T, E> = {
if operationIndex < resultCount {
return results[advance(results.startIndex, operationIndex++)]
} else {
fail("Operation started too many times")
return results[advance(results.startIndex, 0)]
}
}
return SignalProducer.try(operation)
}
}
| mit | e398be5ed5c853b6fdd0f97d1af79034 | 26.567376 | 159 | 0.648759 | 3.840564 | false | true | false | false |
otoshimono/mamorio-reception | ReceptionKit/Helpers/Camera.swift | 1 | 5378 | //
// Camera.swift
// ReceptionKit
//
// Created by Andy Cho on 2016-06-12.
// Copyright © 2016 Andy Cho. All rights reserved.
//
import AVFoundation
class Camera: NSObject {
/// The last image captured from the camera
fileprivate var cameraImage: UIImage?
/// Keep a reference to the session so it doesn't get deallocated
private var captureSession: AVCaptureSession?
/**
Create a Camera instance and start streaming from the front facing camera
*/
override init() {
super.init()
setupCamera()
}
/**
Get a snapshot from the front facing camera
- returns: The most recent image from the camera, if one exists
*/
func takePhoto() -> UIImage? {
return cameraImage
}
// MARK: - Private methods
/**
Start streaming from the front facing camera
*/
private func setupCamera() {
guard let camera = getFrontFacingCamera() else {
Logger.error("Front facing camera not found")
return
}
guard let input = try? AVCaptureDeviceInput(device: camera) else {
Logger.error("Could not get the input stream for the camera")
return
}
let output = createCameraOutputStream()
captureSession = createCaptureSession(input: input, output: output)
captureSession?.startRunning()
}
/**
Get the front facing camera, if one exists
- returns: The front facing camera, an AVCaptureDevice, or `nil` if none exists.
*/
private func getFrontFacingCamera() -> AVCaptureDevice? {
let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
for device in devices! {
if (device as AnyObject).position == AVCaptureDevicePosition.front {
return device as? AVCaptureDevice
}
}
return nil
}
/**
Create a stream for the camera output
- returns: A camera output stream
*/
private func createCameraOutputStream() -> AVCaptureVideoDataOutput {
let queue = DispatchQueue(label: "cameraQueue", attributes: [])
let output = AVCaptureVideoDataOutput()
output.alwaysDiscardsLateVideoFrames = true
output.setSampleBufferDelegate(self, queue: queue)
let key = kCVPixelBufferPixelFormatTypeKey as NSString
let value = NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)
output.videoSettings = [key: value]
return output
}
/**
Create a photo capture session from the camera input and output streams
- parameter input: A camera input stream
- parameter output: A camera output stream
- returns: An AVCaptureSession that has not yet been started
*/
private func createCaptureSession(input: AVCaptureDeviceInput, output: AVCaptureVideoDataOutput) -> AVCaptureSession {
let captureSession = AVCaptureSession()
captureSession.addInput(input)
captureSession.addOutput(output)
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
captureSession.startRunning()
return captureSession
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension Camera: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
cameraImage = createImageFromBuffer(imageBuffer)
}
/**
Create a UIImage instance from a CVImageBuffer
- parameter buffer: An instance of a CVImageBuffer
- returns: An UIImage instance if one could be created, nil otherwise
*/
private func createImageFromBuffer(_ buffer: CVImageBuffer) -> UIImage? {
let noOption = CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))
CVPixelBufferLockBaseAddress(buffer, noOption)
defer {
CVPixelBufferUnlockBaseAddress(buffer, noOption)
}
let baseAddress = CVPixelBufferGetBaseAddress(buffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer)
let width = CVPixelBufferGetWidth(buffer)
let height = CVPixelBufferGetHeight(buffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue
let newContext = CGContext(
data: baseAddress,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo)
guard let newImage = newContext?.makeImage() else {
return nil
}
return UIImage(cgImage: newImage, scale: 1.0, orientation: getPhotoOrientation())
}
private func getPhotoOrientation() -> UIImageOrientation {
switch UIDevice.current.orientation {
case .landscapeLeft:
return .downMirrored
case .landscapeRight:
return .upMirrored
case .portrait:
return .leftMirrored
case .portraitUpsideDown:
return .rightMirrored
default:
return .rightMirrored
}
}
}
| mit | 3f9fa1c214d21385e345e67f8e787f1f | 31.005952 | 151 | 0.659104 | 5.654048 | false | false | false | false |
drewag/Swiftlier | Sources/Swiftlier/Coding/SpecDecoder.swift | 1 | 6436 | //
// SpecDecoder.swift
// drewag.me
//
// Created by Andrew J Wagner on 3/20/17.
//
//
import Foundation
/// Decode a JSON dictionary representing the properties and their types
/// of the given decodable type.
///
/// For example:
/// ```
/// struct MyType: Decodable {
/// let prop1: String
/// let prop2: Int?
/// }
/// ```
/// will produce:
/// { "prop1": "string", "prop2": "int?" }
public class SpecDecoder: Decoder {
fileprivate var specDict = [String:String]()
public let codingPath: [CodingKey] = []
public let userInfo: [CodingUserInfoKey:Any]
/// Generate a JSON spec from the given docodable type
///
/// - Parameters:
/// - type: Any decodable type to generate the spec for
/// - userInfo: Optional user info dict
///
/// - Returns: JSON string representation of the spec
public class func spec<D: Decodable>(forType type: D.Type, userInfo: [CodingUserInfoKey:Any] = [:]) throws -> String {
let decoder = SpecDecoder(userInfo: userInfo)
let _ = try D(from: decoder)
let data = try JSONSerialization.data(withJSONObject: decoder.specDict, options: .prettyPrinted)
return String(data: data, encoding: .utf8)!
}
fileprivate init(userInfo: [CodingUserInfoKey:Any] = [:]) {
self.userInfo = userInfo
}
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
return KeyedDecodingContainer(SpecDecodingContainer(decoder: self))
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an unkeyed container is not supported"))
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding a single value container is not supported"))
}
}
private class SpecDecodingContainer<MyKey: CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = MyKey
let codingPath: [CodingKey] = []
let decoder: SpecDecoder
var optionalKeys: [String:Bool] = [:]
init(decoder: SpecDecoder) {
self.decoder = decoder
}
var allKeys: [Key] {
return []
}
func contains(_ key: Key) -> Bool {
return true
}
func decodeNil(forKey key: Key) throws -> Bool {
self.optionalKeys[key.stringValue] = true
return false
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
self.recordType(named: "bool", for: key)
return true
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
self.recordType(named: "int", for: key)
return 0
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
self.recordType(named: "int8", for: key)
return 0
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
self.recordType(named: "int16", for: key)
return 0
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
self.recordType(named: "int32", for: key)
return 0
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
self.recordType(named: "int64", for: key)
return 0
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
self.recordType(named: "uint", for: key)
return 0
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
self.recordType(named: "uint8", for: key)
return 0
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
self.recordType(named: "uint16", for: key)
return 0
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
self.recordType(named: "uint32", for: key)
return 0
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
self.recordType(named: "uint64", for: key)
return 0
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
self.recordType(named: "float", for: key)
return 0
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
self.recordType(named: "double", for: key)
return 0
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
self.recordType(named: "string", for: key)
return ""
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Swift.Decodable {
if type == Date.self {
self.recordType(named: "date", for: key)
return Date.now as! T
}
else if type == Data.self {
self.recordType(named: "data", for: key)
return Data() as! T
}
else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "an unsupported type was found"))
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding nested containers is not supported"))
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding unkeyed containers is not supported"))
}
func superDecoder() throws -> Swift.Decoder {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super encoders containers is not supported"))
}
func superDecoder(forKey key: Key) throws -> Swift.Decoder {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super decoders is not supported"))
}
}
private extension SpecDecodingContainer {
func recordType(named name: String, for key: Key) {
let isOptional = self.optionalKeys[key.stringValue, default: false]
self.decoder.specDict[key.stringValue] = "\(name)\(isOptional ? "?" : "")"
}
}
| mit | 43961e9bb17cf6b1c2100cc4d084924d | 32.696335 | 166 | 0.643412 | 4.293529 | false | false | false | false |
AliceAponasko/LJReader | LJReader/Network/LJClient.swift | 1 | 3621 | //
// LJClient.swift
// LJReader
//
// Created by Alice Aponasko on 2/21/16.
// Copyright © 2016 aliceaponasko. All rights reserved.
//
import Foundation
import Alamofire
import AEXML
typealias LJCompletionHandler = (
success: Bool,
result: [FeedEntry]?,
error: NSError?) -> ()
class LJClient {
static let sharedInstance = LJClient()
func get(
author: String,
parameters: Dictionary<String, AnyObject>?,
completion: LJCompletionHandler) {
request(
.GET,
path: author,
parameters: parameters,
completion: completion)
}
func request(
method: Alamofire.Method,
path: String,
parameters: Dictionary<String, AnyObject>? = nil,
completion: LJCompletionHandler) {
let urlString = "https://\(path).livejournal.com/data/rss"
guard let fullURLString = NSURL(string: urlString)?.absoluteString else {
completion(
success: false,
result: nil,
error: nil)
return
}
Alamofire.request(method,
fullURLString,
parameters: parameters,
encoding: .JSON,
headers: nil)
.response(completionHandler: {
[unowned self] request, response, data, error in
log.debug(request!.URLString)
if error != nil || response?.statusCode != 200 {
log.error("Failed to load feed for request: " +
"\(request!.URLString) with error: \(error)")
completion(
success: false,
result: nil,
error: error)
}
guard let responseData = data else {
completion(
success: false,
result: nil,
error: error)
return
}
var resultArray = [FeedEntry]()
do {
resultArray = try self.parseData(responseData)
} catch {
log.error("Failed to parse feed for request: " +
"\(request!.URLString) with error: \(error)")
}
completion(
success: true,
result: resultArray,
error: nil)
})
}
private func parseData(
responseData: NSData) throws -> [FeedEntry] {
var resultArray = [FeedEntry]()
let xmlDoc = try AEXMLDocument(xmlData: responseData)
let channel = xmlDoc.root["channel"]
let author = channel["lj:journal"].stringValue
let avatar = channel["image"]["url"].stringValue
for item in channel.children {
if item.name == "item" {
var feedEntry = FeedEntry()
feedEntry.author = author
feedEntry.pubDate = item["pubDate"].stringValue
feedEntry.link = item["link"].stringValue
feedEntry.description = item["description"].stringValue
feedEntry.title = item["title"].stringValue
feedEntry.imageURL = avatar
resultArray.append(feedEntry)
}
}
return resultArray
}
}
| mit | a8cbcb9bf1375e94f27a1ce0ab231d71 | 29.166667 | 85 | 0.472652 | 5.746032 | false | false | false | false |
jianghuihon/DYZB | DYZB/Classes/Main/ViewModel/BaseViewModel.swift | 1 | 1117 | //
// BaseViewModel.swift
// DYZB
//
// Created by Enjoy on 2017/4/1.
// Copyright © 2017年 SZCE. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anthorGroups : [AuthorGroup] = [AuthorGroup]()
}
extension BaseViewModel {
func requestAnthorData(isGroupData : Bool, urlString : String, parameter : [String : Any]? = nil, finishedCallback : @escaping () -> ()){
NetworkToos.requestData(.get, URLString: urlString, parameters: parameter) { (result) in
guard let resultDict = result as? [String : NSObject] else { return }
guard let resultArr = resultDict["data"] as? [[String : Any]] else { return }
if isGroupData {
for dict in resultArr {
self.anthorGroups.append(AuthorGroup(dict: dict))
}
}else{
let anthorGroup = AuthorGroup()
for dict in resultArr {
anthorGroup.anthors.append(AnthorModel(dict: dict))
}
self.anthorGroups.append(anthorGroup)
}
finishedCallback()
}
}
}
| mit | b4078d6c4625b980dab15accf9fdc3f4 | 28.315789 | 141 | 0.583483 | 4.284615 | false | false | false | false |
MosheBerman/Precalc | Precalc/Precalc/Graph.swift | 1 | 6972 | //
// Graph.swift
// Precalc
//
// Created by Moshe Berman on 12/25/16.
// Copyright © 2016 Moshe Berman. All rights reserved.
//
import CoreGraphics
/*:
# The Graph
When we draw graphs on paper, we usually draw an x axis and a y axis. Then, we calculate and plot points using a given interval. The graph view works in a similar way. By defining our positive and negative x limits, we can easily draw a square graph that scales to fit the frame of the view, and fits the defined number of calculations in our range.
*/
class GraphView : UIView
{
fileprivate(set) var equations : [GraphableEquation] = []
var x1: CGFloat = -15.0
var x2: CGFloat = 15.0
var interval : CGFloat = 1.0
fileprivate let graphBackgroundColor = UIColor(red: 0.95, green: 0.95, blue: 1.0, alpha: 1.0)
fileprivate let graphLineColor = UIColor(red: 0.8, green: 0.9, blue: 1.0, alpha: 1.0)
fileprivate lazy var scale : CGFloat = self.frame.width / (max(self.x1, self.x2) - min(self.x1, self.x2))
fileprivate var numberOfLines : Int {
return Int(self.frame.width) / Int(scale)
}
// MARK: - Initializer
convenience init(withSmallerXBound x1: CGFloat, largerXBound x2: CGFloat, andInterval interval: CGFloat)
{
// If this isn't square, weird things will happen. Sorry!
self.init(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
self.x1 = x1
self.x2 = x2
self.interval = interval
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: - Adding Equations
func clear()
{
self.equations = []
self.setNeedsDisplay()
}
func addEquation(_ equation: GraphableEquation)
{
_ = equation.compute(withInterval: self.interval, between: self.x1, and: self.x2)
self.equations.append(equation)
self.setNeedsDisplay()
}
// MARK: - Drawing
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else
{
return
}
self.fillBackground(withContext: context, andRect: rect)
self.drawHorizontalLines(withContext: context)
self.drawVerticalLines(withContext: context)
for equation in self.equations
{
self.drawEquation(equation, withContext: context, inRect: rect)
}
}
// MARK: - Draw Equation
func drawEquation(_ equation: GraphableEquation, withContext context: CGContext, inRect rect: CGRect)
{
let coordinates = equation.compute(withInterval: self.interval, between: x1, and: x2)
self.drawLines(betweenCoordinates: coordinates, withContext: context, inRect: rect
, usingColor: equation.drawingColor.cgColor)
self.drawPoints(atCoordinates: coordinates, withContext: context, inRect: rect, usingColor: equation.drawingColor.cgColor)
}
// MARK: - Fill With Background Color
func fillBackground(withContext context: CGContext, andRect rect: CGRect)
{
context.setFillColor(self.graphBackgroundColor.cgColor)
context.fill(rect)
}
// MARK: - Draw Grid
func drawHorizontalLines(withContext context: CGContext)
{
var y : CGFloat = 0.0
context.setStrokeColor(self.graphLineColor.cgColor)
context.setLineWidth(0.5)
while y < self.frame.height
{
if context.isPathEmpty == false
{
context.strokePath()
// Stroke Axis
if y == self.frame.width/2.0
{
context.setLineWidth(2.0)
}
else
{
context.setLineWidth(1.0)
}
}
context.move(to: CGPoint(x: 0.0, y: y))
context.addLine(to: CGPoint(x: self.frame.height, y: y))
y = y + self.scale
}
context.strokePath()
}
func drawVerticalLines(withContext context: CGContext)
{
var x : CGFloat = 0.0
context.setStrokeColor(self.graphLineColor.cgColor)
context.setLineWidth(0.5)
while x < self.frame.height
{
if context.isPathEmpty == false
{
context.strokePath()
}
// Stroke Axis
if x == self.frame.height/2.0
{
context.setLineWidth(2.0)
}
else
{
context.setLineWidth(1.0)
}
context.move(to: CGPoint(x: x, y: 0.0))
context.addLine(to: CGPoint(x: x, y: self.frame.width))
x = x + self.scale
}
context.strokePath()
}
// MARK: - Draw the Graph
func drawPoints(atCoordinates coordinates: [Coordinate], withContext context: CGContext, inRect rect: CGRect, usingColor color: CGColor)
{
context.setStrokeColor(color)
context.setLineWidth(2.0)
for coordinate in coordinates
{
let translated = self.translated(coordinate: coordinate, toRect: rect)
context.move(to: translated)
self.drawCircle(inContext: context, atCoordinate: translated)
}
context.strokePath()
}
func drawLines(betweenCoordinates coordinates: [Coordinate], withContext context: CGContext, inRect rect: CGRect, usingColor color: CGColor)
{
context.setStrokeColor(color)
context.setLineWidth(1.0)
let translated = self.translated(coordinate: coordinates[0], toRect: rect)
context.move(to: translated)
for coordinate in coordinates
{
let translated = self.translated(coordinate: coordinate, toRect: rect)
context.addLine(to: translated)
context.move(to: translated)
}
context.strokePath()
}
// MARK: - Convert Coordinates to the CGContext
func translated(coordinate coord: Coordinate, toRect rect: CGRect) -> Coordinate
{
var coordinate : Coordinate = coord
let scale = self.scale
coordinate.x = (rect.width / 2.0) + (coordinate.x * scale)
coordinate.y = (rect.height / 2.0) + (-coordinate.y * scale)
return coordinate
}
// MARK: - Draw a Circle
func drawCircle(inContext context: CGContext, atCoordinate coordinate: Coordinate)
{
context.addArc(center: coordinate, radius: 1.0, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2.0, clockwise: false)
}
}
| mit | ec06f0f221390aca77bc3297e4d9918a | 28.918455 | 350 | 0.573662 | 4.511974 | false | false | false | false |
norio-nomura/qlplayground | qlplayground/Highlight.swift | 1 | 4208 | //
// highlight.swift
// qlplayground
//
// Created by 野村 憲男 on 9/19/15.
//
// Copyright (c) 2015 Norio Nomura
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class Highlight: NSObject {
/// read bundle
static let bundle = NSBundle(forClass: Highlight.self)
static let script = bundle.URLForResource("highlight.pack", withExtension: "js", subdirectory: "highlight")
.flatMap { try? String(contentsOfURL: $0)} ?? ""
static var css: String {
let style = NSUserDefaults(suiteName: bundle.bundleIdentifier)?.stringForKey("HighlightStyle") ?? "xcode"
return bundle.URLForResource(style, withExtension: "css", subdirectory: "highlight/styles")
.flatMap { try? String(contentsOfURL: $0)} ?? ""
}
/// create NSData from url pointing .swift or .playground
public static func data(URL url: NSURL) -> NSData? {
let fm = NSFileManager.defaultManager()
var isDirectory: ObjCBool = false
guard url.fileURL && url.path.map({ fm.fileExistsAtPath($0, isDirectory: &isDirectory) }) ?? false else {
return nil
}
func escapeHTML(string: String) -> String {
return NSXMLNode.textWithStringValue(string).XMLString
}
/// read contents.swift
let codes: String
if isDirectory {
let keys = [NSURLTypeIdentifierKey]
func isSwiftSourceURL(url: NSURL) -> Bool {
if let typeIdentifier = try? url.resourceValuesForKeys(keys)[NSURLTypeIdentifierKey] as? String
where typeIdentifier == "public.swift-source" {
return true
} else {
return false
}
}
let enumerator = fm.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: [], errorHandler: nil)
let swiftSources = anyGenerator { enumerator?.nextObject() as? NSURL }
.filter(isSwiftSourceURL)
let length = url.path!.characters.count
func subPath(url: NSURL) -> String {
return String(url.path!.characters.dropFirst(length))
}
codes = swiftSources.flatMap {
guard let content = try? String(contentsOfURL: $0) else { return nil }
return "<code>\(subPath($0))</code><pre><code class='swift'>\(escapeHTML(content))</code></pre>"
}
.joinWithSeparator("<hr>")
} else {
codes = (try? String(contentsOfURL: url))
.map {"<pre><code class='swift'>\(escapeHTML($0))</code></pre>"} ?? ""
}
let html = ["<!DOCTYPE html>",
"<html><meta charset=\"utf-8\" /><head>",
"<style>*{margin:0;padding:0}\(css)</style>",
"<script>\(script)</script>",
"<script>hljs.initHighlightingOnLoad();</script>",
"</head><body class=\"hljs\">\(codes)</body></html>"]
.joinWithSeparator("\n")
return html.dataUsingEncoding(NSUTF8StringEncoding)
}
}
| mit | 273e9aa7220a3b986a7e21092ef2053e | 42.75 | 118 | 0.613333 | 4.661487 | false | false | false | false |
hooliooo/Rapid | Source/Extensions/String+Kio.swift | 1 | 4382 | //
// Kio
// Copyright (c) Julio Miguel Alorro
//
// Licensed under the MIT license. See LICENSE file.
//
//
import class Foundation.NSString
import class Foundation.NSRegularExpression
import struct Foundation.Data
import struct Foundation.NSRange
import class Foundation.NSTextCheckingResult
/**
A DSL for String to access custom methods
*/
public struct KioStringDSL {
// MARK: Stored Propeties
/**
Underlying String instance
*/
public let string: String
}
public extension KioStringDSL {
/**
Checks if string contains a number
*/
var containsNumbers: Bool {
let regex: String = "[0-9]+"
let range: Range<String.Index>? = self.string.range(of: regex, options: String.CompareOptions.regularExpression)
return range != nil
}
/**
Checks if string contains an alphabetic character
*/
var isAlphabetic: Bool {
let regex: String = "^[a-zA-Z]+$"
let range: Range<String.Index>? = self.string.range(of: regex, options: String.CompareOptions.regularExpression)
return range != nil
}
/**
Checks if string is a valid email address
*/
var isValidEmail: Bool {
let regex: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let range: Range<String.Index>? = self.string.range(of: regex, options: String.CompareOptions.regularExpression)
return range != nil
}
/**
Checks if string is a valid phone number
*/
var isValidPhoneNum: Bool {
let regex: String = "^[0-9]{3}-[0-9]{3}-[0-9]{4}$"
let range: Range<String.Index>? = self.string.range(of: regex, options: String.CompareOptions.regularExpression)
return range != nil
}
/**
Returns the string as a base64 encoded string
*/
var base64Encoded: String? {
let encodedData: Data? = self.string.data(using: String.Encoding.utf8)
return encodedData?.base64EncodedString()
}
/**
Returns the string as a base64 decoded string if it was base64 encoded
*/
var base64Decoded: String? {
let base64Regex: String = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"
let range: Range<String.Index>? = self.string.range(of: base64Regex, options: NSString.CompareOptions.regularExpression)
if range != nil {
guard
let decodedData = Data(base64Encoded: self.string),
let decodedString = String(data: decodedData, encoding: String.Encoding.utf8)
else { return nil }
return decodedString
} else {
return nil
}
}
/**
Returns the string's ASCII value
*/
var asciiValue: String? {
let regexPattern: String = "(0x)?([0-9a-f]{2})"
do {
let regex: NSRegularExpression = try NSRegularExpression(
pattern: regexPattern,
options: NSRegularExpression.Options.caseInsensitive
)
let nsString: NSString = self.string as NSString
let characters: [Character] = regex
.matches(in: self.string, options: [], range: NSRange(location: 0, length: nsString.length)).lazy
.compactMap { UInt32(nsString.substring(with: $0.range(at: 2)), radix: 16) }
.compactMap(UnicodeScalar.init)
.compactMap(Character.init)
switch characters.isEmpty {
case true:
return nil
case false:
return String(characters)
}
} catch {
print(error)
return nil
}
}
/**
Checks if the string is a hex value
*/
var isHexValue: Bool {
let regexPattern: String = "[0-9A-F]+"
let range = self.string.range(of: regexPattern, options: NSString.CompareOptions.regularExpression)
return range != nil
}
/**
Returns the string's hex value
*/
var hexValue: String? {
guard let data = self.string.data(using: String.Encoding.utf8) else { return nil }
return data.map { String(format: "%02hhx", $0) }.joined()
}
}
public extension String {
/**
KioDoubleDSL instance to access custom methods
*/
var kio: KioStringDSL {
return KioStringDSL(string: self)
}
}
| mit | 78382d1c25b38ccf8484ff33e1bd790b | 27.828947 | 128 | 0.592195 | 4.173333 | false | false | false | false |
jkereako/MassStateKeno | Sources/Views/NumberViewController.swift | 1 | 2224 | //
// NumberViewController.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/18/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import UIKit
final class NumberViewController: UIViewController {
@IBOutlet private weak var gameIdentifier: UILabel!
@IBOutlet private weak var bonusMultiplier: UILabel!
@IBOutlet private weak var numberCollectionView: UICollectionView!
var viewModel: NumberViewModel?
init() {
super.init(nibName: "NumberView", bundle: Bundle(for: NumberViewController.self))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let layout = numberCollectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
assertionFailure("Expected a UICollectionViewFlowLayout")
return
}
numberCollectionView.dataSource = viewModel
numberCollectionView.delegate = viewModel
let adjustedScreenWidth = UIScreen.main.bounds.width - 70
let width = adjustedScreenWidth / 4
layout.itemSize = CGSize(width: width, height: width * 0.75)
title = viewModel?.title
gameIdentifier.text = viewModel?.gameIdentifier
bonusMultiplier.text = viewModel?.bonusMultiplier
let nib = UINib(
nibName: cellReuseIdentifier, bundle: Bundle(for: NumberCollectionViewCell.self)
)
numberCollectionView.register(
nib, forCellWithReuseIdentifier: cellReuseIdentifier
)
}
}
// MARK: - NumberViewModelDataSource
extension NumberViewController: NumberViewModelDataSource {
var cellReuseIdentifier: String {
return "NumberCollectionViewCell"
}
func configure(_ cell: UICollectionViewCell, with number: String) -> UICollectionViewCell {
guard let numberCollectionViewCell = cell as? NumberCollectionViewCell else {
return UICollectionViewCell()
}
numberCollectionViewCell.number = number
return numberCollectionViewCell
}
}
| mit | 07cd688d934793349aa0985d450c9ee0 | 29.875 | 106 | 0.663068 | 5.714653 | false | false | false | false |
colbylwilliams/Cognitive-Speech-iOS | CognitiveSpeech/CognitiveSpeech/ViewControllers/PipViewController.swift | 1 | 6372 | //
// PipViewController.swift
// CognitiveSpeech
//
// Created by Colby Williams on 6/15/17.
// Copyright © 2017 Colby Williams. All rights reserved.
//
import UIKit
import AVFoundation
struct PipStrings {
static let recording = "Recording..."
static let initializing = "Initializing..."
static let identifying = "Identifying..."
static let processing = "Processing..."
static let verifying = "Verifying..."
static let training = "Training..."
static let touchToStop = "Touch anywhere to finish recording."
static let touchToDismiss = "Touch anywhere to dismiss."
}
class PipViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var auxLabel: UILabel!
@IBOutlet weak var feedbackLabel: UILabel!
@IBOutlet weak var feedbackDetailLabel: UILabel!
@IBOutlet weak var backgroundView: UIVisualEffectView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var feedbackLabelVerticalConstraint: NSLayoutConstraint!
@IBOutlet weak var activityIdnicatorOffsetConstraint: NSLayoutConstraint!
var audioRecorder: AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
backgroundView.layer.cornerRadius = 5
backgroundView.layer.masksToBounds = true
updateFeedback(feedbackLabel: PipStrings.initializing)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startRecording()
}
@IBAction func viewTouched(_ sender: Any) {
if audioRecorder != nil && audioRecorder!.isRecording {
finishRecording(success: true)
} else if !activityIndicator.isAnimating {
updateAndDismiss()
}
}
func startRecording() {
print("Start recording...")
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.wav")
let settings = [
AVFormatIDKey: Int(kAudioFormatLinearPCM), // Encoding PCM
AVSampleRateKey: 16000, // Rate 16K
AVNumberOfChannelsKey: 1, // Channels Mono
AVEncoderBitRateKey: 16, // Sample Format 16 bit
AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder?.delegate = self
audioRecorder?.record()
updateFeedback(feedbackLabel: PipStrings.recording, auxLabel: PipStrings.touchToStop)
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
finishRecording(success: false)
}
}
func finishRecording(success: Bool) {
print("Stop recording...")
updateFeedback(feedbackLabel: PipStrings.processing)
audioRecorder?.stop()
// audioRecorder = nil
if success {
print("Recording succeeded")
} else {
print("Recording failed")
}
}
func updateFeedback(activityIndicator activity: Bool = true, feedbackLabel feedback: String, detailLabel detail: String? = nil, auxLabel aux: String? = nil) {
if activity != activityIndicator.isAnimating {
if activity {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
activityIndicator.isHidden = !activity
activityIdnicatorOffsetConstraint.constant = activity ? 9 : 0
}
auxLabel.text = aux
feedbackLabel.text = feedback
feedbackDetailLabel.text = detail
if feedback == PipStrings.recording {
activityIndicator.color = UIColor.red
feedbackLabel.textColor = UIColor.red
} else {
activityIndicator.color = UIColor.white
feedbackLabel.textColor = UIColor.white
}
feedbackLabelVerticalConstraint.constant = detail == nil ? 0 : 14
}
// MARK: - AVAudioRecorderDelegate
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("Audio Recorder Encode Error: \(error?.localizedDescription ?? "")")
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
print("Audio Recorder finished recording (\(flag ? "successfully" : "unsuccessfully"))")
if flag {
if SpeakerIdClient.shared.selectedProfile?.enrollmentStatus == .enrolled {
switch SpeakerIdClient.shared.selectedProfileType {
case .identification:
identifySpeaker(fileUrl: recorder.url)
case .verification:
verifySpeaker(fileUrl: recorder.url)
}
} else {
enrollSpeaker(fileUrl: recorder.url)
}
} else {
self.updateFeedback(activityIndicator: false, feedbackLabel: "Recording Error", auxLabel: PipStrings.touchToDismiss)
}
}
func identifySpeaker(fileUrl url: URL) {
updateFeedback(feedbackLabel: PipStrings.identifying)
SpeakerIdClient.shared.identifySpeaker(fileUrl: url, callback: { (result, profile) in
let details = result?.identificationResultDetails(profileName: profile?.name)
DispatchQueue.main.async {
self.updateFeedback(activityIndicator: false, feedbackLabel: details?.title ?? "Unknown error", detailLabel: details?.detail, auxLabel: PipStrings.touchToDismiss)
}
})
}
func verifySpeaker(fileUrl url: URL) {
updateFeedback(feedbackLabel: PipStrings.verifying)
SpeakerIdClient.shared.verifySpeaker(fileUrl: url, callback: { result in
let details = result?.verificationResultDetails
DispatchQueue.main.async {
self.updateFeedback(activityIndicator: false, feedbackLabel: details?.title ?? "Unknown error", detailLabel: details?.detail, auxLabel: PipStrings.touchToDismiss)
}
})
}
func enrollSpeaker(fileUrl url: URL) {
updateFeedback(feedbackLabel: PipStrings.training)
SpeakerIdClient.shared.createProfileEnrollment(fileUrl: url) { message in
DispatchQueue.main.async {
if let message = message {
self.updateFeedback(activityIndicator: false, feedbackLabel: "Error", detailLabel: message, auxLabel: PipStrings.touchToDismiss)
} else {
self.updateFeedback(activityIndicator: false, feedbackLabel: "Done!", auxLabel: PipStrings.touchToDismiss)
self.updateAndDismiss()
}
}
}
}
func updateAndDismiss() {
if let navController = self.presentingViewController as? UINavigationController, let startController = navController.viewControllers.first as? StartViewController {
startController.updateUIforSelectedProfile()
}
self.dismiss(animated: true, completion: nil)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
| mit | 20b3b83138344816d4610dad28df1d0e | 31.340102 | 166 | 0.745566 | 4.164052 | false | false | false | false |
iPantry/iPantry-iOS | Pantry/Models/SimpleUPC.swift | 1 | 1859 | //
// SimpleUPC.swift
// Pantry
//
// Created by Justin Oroz on 6/9/17.
// Copyright © 2017 Justin Oroz. All rights reserved.
//
// http://www.simpleupc.com/api/methods/FetchProductByUPC.php
import Alamofire
final class SimpleUPC: UPCDatabase {
static private let host = "api.simpleupc.com"
static private let path = "/v1.php"
static private let auth = (UIApplication.shared.delegate as? AppDelegate)?.apikeys?["SimpleUPC"]
static func lookup(by barcode: String, returned: (([UPCDatabaseItem]?, Error?) -> Void)?) {
guard let auth = self.auth else {
print("[ERROR]: No SimpleUPC API Key Found")
return
}
let method = "FetchImageByUPC"
let params = ["upc": barcode]
let request: [String: Any] = [
"auth": auth,
"method": method,
"params": params
]
let headers = ["Content-Type": "text/json"]
Alamofire.request("https://api.upcitemdb.com/prod/trial/lookup",
method: .post,
parameters: request,
encoding: JSONEncoding.default,
headers: headers).responseJSON { (response) in
guard response.error == nil,
let json = response.result.value as? [String: AnyObject]
else {
returned?(nil, response.error!)
print("SimpleUPC Lookup Error: \(response.error!)")
return
}
print("JSON: \(json)")
returned?([SimpleUPCItem(json)], nil)
}.resume()
}
}
struct SimpleUPCItem: UPCDatabaseItem {
subscript(index: String) -> AnyObject? {
return self.data[index]
}
init(_ json: [String : AnyObject]) {
self.data = json
}
private let data: [String : AnyObject]
var title: String?
var ean: String?
var description: String?
var brand: String?
var size: String?
var weight: String?
var imageURLs: [String]?
}
| agpl-3.0 | 7b1f5cca3e932817f847acbde7f986e5 | 21.658537 | 97 | 0.613025 | 3.50566 | false | false | false | false |
shamanskyh/Precircuiter | Precircuiter/Main/MainWindowController.swift | 1 | 2464 | //
// MainWindowController.swift
// Precircuiter
//
// Created by Harry Shamansky on 8/27/14.
// Copyright © 2014 Harry Shamansky. All rights reserved.
//
import Cocoa
protocol MainWindowControllerDelegate {
func assignMissingDimmers()
func assignAllDimmers()
func updateFilter(_ selection: PlotViewFilterType)
var shouldWarnAboutOverwrite: Bool { get }
var hasMissingDimmers: Bool { get }
}
/// An enumeration that corresponds to the segmented control layout
enum PlotViewFilterType: Int {
case lights = 0
case dimmers = 1
case both = 2
}
class MainWindowController: NSWindowController {
var delegate: MainWindowControllerDelegate? = nil
var overwriteOnImport: Bool = false
@IBOutlet weak var assignMissingToolbarItem: NSToolbarItem!
@IBOutlet weak var assignAllToolbarItem: NSToolbarItem!
@IBOutlet weak var viewFilter: NSSegmentedControl!
@IBOutlet weak var assignMissingTouchBarButton: NSButton!
@IBOutlet weak var viewFilterTouchBar: NSSegmentedControl!
override func windowDidLoad() {
super.windowDidLoad()
delegate = (self.contentViewController as! MainViewController)
updateToolbar()
}
func updateToolbar() {
let enabled = hasMissingDimmers
assignMissingToolbarItem.isEnabled = enabled
assignMissingTouchBarButton.isEnabled = enabled
}
func updateOtherSegmentedControl(sender: NSSegmentedControl, index: Int) {
if sender == viewFilter {
viewFilterTouchBar.integerValue = index
} else {
viewFilter.integerValue = index
}
}
@IBAction func assignMissingDimmers(_ sender: AnyObject) {
delegate?.assignMissingDimmers()
}
@IBAction func assignAllDimmers(_ sender: AnyObject) {
delegate?.assignAllDimmers()
}
@IBAction func changeFilter(_ sender: AnyObject) {
if let segmentedControl = sender as? NSSegmentedControl {
let index = segmentedControl.integerValue
if let filterType = PlotViewFilterType(rawValue: index) {
delegate?.updateFilter(filterType)
}
updateOtherSegmentedControl(sender: segmentedControl, index: index)
}
}
@objc var hasMissingDimmers: Bool {
if let delegate = delegate {
return delegate.hasMissingDimmers
} else {
return true
}
}
}
| mit | b96c076a51835f946abf151a2f3e6f8d | 29.036585 | 79 | 0.670727 | 5.016293 | false | false | false | false |
mqshen/SwiftForms | SwiftForms/cells/FormSwitchCell.swift | 1 | 1063 | //
// FormSwitchCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 21/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormSwitchCell: FormTitleCell {
// MARK: Cell views
public let switchView = UISwitch()
// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
switchView.addTarget(self, action: #selector(FormSwitchCell.valueChanged(_:)), forControlEvents: .ValueChanged)
accessoryView = switchView
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor?.title
if let value = rowDescriptor?.value as? Bool {
switchView.on = value
} else {
switchView.on = false
rowDescriptor?.value = false
}
}
// MARK: Actions
internal func valueChanged(_: UISwitch) {
rowDescriptor?.value = switchView.on
}
}
| mit | 7914f2b97a44c202736d172996234041 | 22.086957 | 119 | 0.587571 | 5.105769 | false | false | false | false |
vitorvmiguel/instaping | instaping/UserModel.swift | 1 | 785 | //
// UserModel.swift
// instaping
//
// Created by Vítor Vazquez Miguel on 26/06/17.
// Copyright © 2017 BTS. All rights reserved.
//
class UserModel {
var id: String?
var profileImage: String?
var followsArray = [String]()
var numberOfFollowers: String?
var followedByArray = [String]()
var numberOfFollowedBy: String?
init(id: String?, profileImage: String?, followsArray: [String], numberOfFollowers: String?, followedByArray: [String], numberOfFollowedBy: String?) {
self.id = id;
self.profileImage = profileImage;
self.followsArray = followsArray;
self.numberOfFollowers = numberOfFollowers;
self.followedByArray = followedByArray;
self.numberOfFollowedBy = numberOfFollowedBy;
}
}
| mit | db5cc35995dae76a1356a204e92cd8fd | 29.115385 | 154 | 0.673052 | 4.209677 | false | false | false | false |
Rivukis/Spry | Sources/Spry/StringRepresentable.swift | 1 | 1534 | //
// StringRepresentable.swift
// SpryExample
//
// Created by Brian Radebaugh on 7/7/17.
// Copyright © 2017 Brian Radebaugh. All rights reserved.
//
/**
This protocol is how the function name string gets converted to a type.
It's easiest to have an enum with a raw type of `String`. Said type only needs to say it conforms to this protocol.
## Example ##
```swift
enum Function: String, StringRepresentable {
// ...
}
```
*/
public protocol StringRepresentable: RawRepresentable {
var rawValue: String { get }
init?(rawValue: String)
init<T>(functionName: String, type: T.Type, file: String, line: Int)
}
private let singleUnnamedArgumentFunctionaSuffix = "(_:)"
public extension StringRepresentable {
init<T>(functionName: String, type: T.Type, file: String, line: Int) {
let hasUnnamedArgumentSuffix = functionName.hasSuffix(singleUnnamedArgumentFunctionaSuffix)
if let function = Self(rawValue: functionName) {
self = function
}
else if hasUnnamedArgumentSuffix,
let function = Self(rawValue: String(functionName.dropLast(singleUnnamedArgumentFunctionaSuffix.count))) {
self = function
}
else if !hasUnnamedArgumentSuffix,
let function = Self(rawValue: functionName + singleUnnamedArgumentFunctionaSuffix){
self = function
}
else {
Constant.FatalError.noFunctionFound(functionName: functionName, type: type, file: file, line: line)
}
}
}
| mit | 8a85e0b83f9b803f236232246e94c255 | 30.9375 | 118 | 0.672538 | 4.456395 | false | false | false | false |
huangboju/Moots | Examples/CIFilter/MetalFilters-master/MetalFilters/Views/MTScrollView.swift | 1 | 4299 | //
// MTScrollView.swift
// MetalFilters
//
// Created by xu.shuifeng on 2019/1/7.
// Copyright © 2019 shuifeng.me. All rights reserved.
//
import UIKit
class MTScrollView: UIScrollView {
var image: UIImage? {
didSet {
imageView.image = image
if let image = image {
imageView.frame.size = actualSizeFor(image)
contentSize = imageView.bounds.size
zoomScale = 1.0
minimumZoomScale = 1.0
maximumZoomScale = 5.0
let offset = CGPoint(x: (contentSize.width - bounds.width)/2, y: (contentSize.height - bounds.height)/2)
setContentOffset(offset, animated: false)
}
}
}
var croppedImage: UIImage? {
guard let image = image else { return nil }
var cropRect = CGRect.zero
let scaleX = image.size.width / contentSize.width
let scaleY = image.size.height / contentSize.height
cropRect.origin.x = contentOffset.x * scaleX
cropRect.origin.y = contentOffset.y * scaleY
cropRect.size.width = image.size.width * bounds.width / contentSize.width
cropRect.size.height = image.size.height * bounds.height / contentSize.height
if let cgImage = image.cgImage?.cropping(to: cropRect) {
return UIImage(cgImage: cgImage)
}
return nil
}
private lazy var imageView: UIImageView = {
let view = UIImageView()
return view
}()
private var gridView: MTGridView!
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
delegate = self
contentInsetAdjustmentBehavior = .never
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
delaysContentTouches = false
gridView = MTGridView(frame: bounds)
gridView.isUserInteractionEnabled = false
gridView.alpha = 0.0
addSubview(gridView)
let press = UILongPressGestureRecognizer(target: self, action: #selector(handlePress(_:)))
press.delegate = self
press.minimumPressDuration = 0
addGestureRecognizer(press)
}
@objc func handlePress(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
UIView.animate(withDuration: 0.2) {
self.gridView.alpha = 1.0
}
case .ended:
UIView.animate(withDuration: 0.2) {
self.gridView.alpha = 0.0
}
default:
break
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func actualSizeFor(_ image: UIImage) -> CGSize {
let viewSize = bounds.size
var actualWidth = image.size.width
var actualHeight = image.size.height
var imgRatio = actualWidth/actualHeight
let viewRatio = viewSize.width/viewSize.height
if imgRatio != viewRatio{
if(imgRatio > viewRatio){
imgRatio = viewSize.height / actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = viewSize.height
}
else{
imgRatio = viewSize.width / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = viewSize.width
}
}
else {
imgRatio = viewSize.width / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = viewSize.width
}
return CGSize(width: actualWidth, height: actualHeight)
}
}
extension MTScrollView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
gridView.frame = bounds
}
}
extension MTScrollView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | 9705832d8529621ab42fd9e95b75d77c | 30.144928 | 157 | 0.590507 | 5.306173 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | Tests/ReactiveSwiftTests/ActionSpec.swift | 1 | 12837 | //
// ActionSpec.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-12-11.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import Dispatch
import Nimble
import Quick
@testable import ReactiveSwift
class ActionSpec: QuickSpec {
override func spec() {
describe("Action") {
var action: Action<Int, String, NSError>!
var enabled: MutableProperty<Bool>!
var executionCount = 0
var completedCount = 0
var values: [String] = []
var errors: [NSError] = []
var scheduler: TestScheduler!
let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil)
beforeEach {
executionCount = 0
completedCount = 0
values = []
errors = []
enabled = MutableProperty(false)
scheduler = TestScheduler()
action = Action(enabledIf: enabled) { number in
return SignalProducer { observer, disposable in
executionCount += 1
if number % 2 == 0 {
observer.send(value: "\(number)")
observer.send(value: "\(number)\(number)")
disposable += scheduler.schedule {
observer.sendCompleted()
}
} else {
disposable += scheduler.schedule {
observer.send(error: testError)
}
}
}
}
action.values.observeValues { values.append($0) }
action.errors.observeValues { errors.append($0) }
action.completed.observeValues { _ in completedCount += 1 }
}
it("should retain the state property") {
var property: MutableProperty<Bool>? = MutableProperty(false)
weak var weakProperty = property
var action: Action<(), (), Never>? = Action(state: property!, enabledIf: { _ in true }) { _, _ in
return .empty
}
expect(weakProperty).toNot(beNil())
property = nil
expect(weakProperty).toNot(beNil())
action = nil
expect(weakProperty).to(beNil())
// Mute "unused variable" warning.
_ = action
}
it("should be disabled and not executing after initialization") {
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
it("should error if executed while disabled") {
var receivedError: ActionError<NSError>?
var disabledErrorsTriggered = false
action.disabledErrors.observeValues { _ in
disabledErrorsTriggered = true
}
action.apply(0).startWithFailed {
receivedError = $0
}
expect(receivedError).notTo(beNil())
expect(disabledErrorsTriggered) == true
if let error = receivedError {
let expectedError = ActionError<NSError>.disabled
expect(error == expectedError) == true
}
}
it("should enable and disable based on the given property") {
enabled.value = true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
enabled.value = false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
it("should not deadlock when its executing state affects its state property without constituting a feedback loop") {
enabled <~ action.isExecuting.negate()
expect(enabled.value) == true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
let disposable = action.apply(0).start()
expect(enabled.value) == false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == true
disposable.dispose()
expect(enabled.value) == true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
}
it("should not deadlock when its enabled state affects its state property without constituting a feedback loop") {
// Emulate control binding: When a UITextField is the first responder and
// is being disabled by an `Action`, the control events emitted might
// feedback into the availability of the `Action` synchronously, e.g.
// via a `MutableProperty` or `ValidatingProperty`.
var isFirstResponder = false
action.isEnabled.producer
.compactMap { isActionEnabled in !isActionEnabled && isFirstResponder ? () : nil }
.startWithValues { _ in enabled.value = false }
enabled.value = true
expect(enabled.value) == true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
isFirstResponder = true
let disposable = action.apply(0).start()
expect(enabled.value) == false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == true
disposable.dispose()
expect(enabled.value) == false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
enabled.value = true
expect(enabled.value) == true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
}
it("should not deadlock") {
final class ViewModel {
let action2 = Action<(), (), Never> { _ in SignalProducer(value: ()) }
}
let action1 = Action<(), ViewModel, Never> { _ in SignalProducer(value: ViewModel()) }
// Fixed in #267. (https://github.com/ReactiveCocoa/ReactiveSwift/pull/267)
//
// The deadlock happened as the observer disposable releases the closure
// `{ _ in viewModel }` here without releasing the mapped signal's
// `updateLock` first. The deinitialization of the closure triggered the
// propagation of terminal event of the `Action`, which eventually hit
// the mapped signal and attempted to acquire `updateLock` to transition
// the signal's state.
action1.values
.flatMap(.latest) { viewModel in viewModel.action2.values.map { _ in viewModel } }
.observeValues { _ in }
action1.apply().start()
action1.apply().start()
}
if #available(macOS 10.10, *) {
it("should not loop indefinitely") {
let condition = MutableProperty(1)
let action = Action<Void, Void, Never>(state: condition, enabledIf: { $0 == 0 }) { _, _ in
return .empty
}
var count = 0
action.isExecuting.producer
.startWithValues { _ in
condition.value = 10
count += 1
expect(count) == 1
}
}
}
describe("completed") {
beforeEach {
enabled.value = true
}
it("should send a value whenever the producer completes") {
action.apply(0).start()
expect(completedCount) == 0
scheduler.run()
expect(completedCount) == 1
action.apply(2).start()
scheduler.run()
expect(completedCount) == 2
}
it("should not send a value when the producer fails") {
action.apply(1).start()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the producer is interrupted") {
let disposable = action.apply(0).start()
disposable.dispose()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the action is disabled") {
enabled.value = false
action.apply(0).start()
scheduler.run()
expect(completedCount) == 0
}
}
describe("execution") {
beforeEach {
enabled.value = true
}
it("should execute successfully") {
var receivedValue: String?
action.apply(0)
.assumeNoErrors()
.startWithValues {
receivedValue = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
it("should execute with an error") {
var receivedError: ActionError<NSError>?
action.apply(1).startWithFailed {
receivedError = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(receivedError).notTo(beNil())
if let error = receivedError {
let expectedError = ActionError<NSError>.producerFailed(testError)
expect(error == expectedError) == true
}
expect(values) == []
expect(errors) == [ testError ]
}
}
describe("bindings") {
it("should execute successfully") {
var receivedValue: String?
let (signal, observer) = Signal<Int, Never>.pipe()
action.values.observeValues { receivedValue = $0 }
action <~ signal
enabled.value = true
expect(executionCount) == 0
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
observer.send(value: 0)
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
}
}
describe("using a property as input") {
let echo: (Int) -> SignalProducer<Int, Never> = SignalProducer.init(value:)
it("executes the action with the property's current value") {
let input = MutableProperty(0)
let action = Action(state: input, execute: echo)
var values: [Int] = []
action.values.observeValues { values.append($0) }
input.value = 1
action.apply().start()
input.value = 2
action.apply().start()
input.value = 3
action.apply().start()
expect(values) == [1, 2, 3]
}
it("allows a non-void input type") {
let state = MutableProperty(1)
let add = Action<Int, Int, Never>(state: state) { state, input in
SignalProducer(value: state + input)
}
var values: [Int] = []
add.values.observeValues { values.append($0) }
add.apply(2).start()
add.apply(3).start()
state.value = -1
add.apply(-10).start()
expect(values) == [3, 4, -11]
}
it("is disabled if the property is nil") {
let input = MutableProperty<Int?>(1)
let action = Action(unwrapping: input, execute: echo)
expect(action.isEnabled.value) == true
input.value = nil
expect(action.isEnabled.value) == false
}
it("allows a different input type while unwrapping an optional state property") {
let state = MutableProperty<Int?>(nil)
let add = Action<String, Int?, Never>(unwrapping: state) { state, input -> SignalProducer<Int?, Never> in
guard let input = Int(input) else { return SignalProducer(value: nil) }
return SignalProducer(value: state + input)
}
var values: [Int] = []
add.values.observeValues { output in
if let output = output {
values.append(output)
}
}
expect(add.isEnabled.value) == false
state.value = 1
expect(add.isEnabled.value) == true
add.apply("2").start()
add.apply("3").start()
state.value = -1
add.apply("-10").start()
expect(values) == [3, 4, -11]
}
it("is disabled if the validating property does not hold a valid value") {
enum TestValidationError: Error { case generic }
typealias PropertyType = ValidatingProperty<Int, TestValidationError>
let decisions: [PropertyType.Decision] = [.valid, .invalid(.generic), .coerced(10, nil)]
let input = PropertyType(0, { decisions[$0] })
let action = Action(validated: input, execute: echo)
expect(action.isEnabled.value) == true
expect(action.apply().single()?.value) == 0
input.value = 1
expect(action.isEnabled.value) == false
expect(action.apply().single()?.error).toNot(beNil())
input.value = 2
expect(action.isEnabled.value) == true
expect(action.apply().single()?.value) == 10
}
it("allows a different input type while using a validating property as its state") {
enum TestValidationError: Error { case generic }
let state = ValidatingProperty<Int?, TestValidationError>(nil, { $0 != nil ? .valid : .invalid(.generic) })
let add = Action<String, Int?, Never>(validated: state) { state, input -> SignalProducer<Int?, Never> in
guard let input = Int(input), let state = state else { return SignalProducer(value: nil) }
return SignalProducer(value: state + input)
}
var values: [Int] = []
add.values.observeValues { output in
if let output = output {
values.append(output)
}
}
expect(add.isEnabled.value) == false
state.value = 1
expect(add.isEnabled.value) == true
add.apply("2").start()
add.apply("3").start()
state.value = -1
add.apply("-10").start()
expect(values) == [3, 4, -11]
}
}
}
}
| mit | d9d99b3d21e38705cf85474222bdc009 | 26.906522 | 119 | 0.638467 | 3.725189 | false | false | false | false |
danielpunkass/Blockpass | Blockpass/RSKeychain.swift | 1 | 3043 | //
// RSKeychain.swift
// Blockpass
//
// Created by Daniel Jalkut on 8/31/18.
// Copyright © 2018 Daniel Jalkut. All rights reserved.
//
import Foundation
struct RSKeychain {
internal static func setSecureBytes(_ bytePointer: UnsafeRawPointer!, length byteLength: UInt, forItemName keychainItemName: String, accountName: String) {
var defaultKeychain: SecKeychain! = nil
if SecKeychainCopyDefault(&defaultKeychain) == noErr {
var shouldAddNewItem = true
let keychainItemNameCString = (keychainItemName as NSString).utf8String
let keychainItemNameLength = UInt32(strlen(keychainItemNameCString))
let accountNameCString = (accountName as NSString).utf8String
let accountNameLength = UInt32(strlen(accountNameCString))
// Update an existing item if we have one
var keychainItemRef: SecKeychainItem? = nil
if (SecKeychainFindGenericPassword(nil, keychainItemNameLength, keychainItemNameCString, accountNameLength, accountNameCString, nil, nil, &keychainItemRef) == noErr),
let keychainItemRef = keychainItemRef {
if SecKeychainItemModifyContent(keychainItemRef, nil, UInt32(byteLength), bytePointer) == noErr {
shouldAddNewItem = false
}
}
if shouldAddNewItem {
SecKeychainAddGenericPassword(defaultKeychain, keychainItemNameLength, keychainItemNameCString, accountNameLength, accountNameCString, UInt32(byteLength), bytePointer, nil)
}
}
}
public static func secureData(forItemName keychainItemName: String, accountName: String) -> Data? {
var foundData: Data? = nil
let keychainItemNameCString = (keychainItemName as NSString).utf8String
let keychainItemNameLength = UInt32(strlen(keychainItemNameCString))
let accountNameCString = (accountName as NSString).utf8String
let accountNameLength = UInt32(strlen(accountNameCString))
var secureDataLength: UInt32 = 0
var secureData: UnsafeMutableRawPointer? = nil
let secureErr = SecKeychainFindGenericPassword(nil, keychainItemNameLength, keychainItemNameCString, accountNameLength, accountNameCString, &secureDataLength, &secureData, nil)
if secureErr == noErr,
let secureData = secureData
{
foundData = Data(bytes: secureData, count: Int(secureDataLength))
}
else {
if secureErr != errSecItemNotFound {
NSLog("Got error %d trying to access password in keychain for %@/%@", secureErr, keychainItemName, accountName);
}
}
return foundData
}
public static func setSecureString(_ newString: String, forItemName keychainItemName: String, accountName: String) {
let secureString = (newString as NSString).utf8String
self.setSecureBytes(secureString, length: UInt(strlen(secureString)), forItemName: keychainItemName, accountName: accountName)
}
public static func secureString(forItemName keychainItemName: String, accountName: String) -> String? {
guard
let secureData = self.secureData(forItemName: keychainItemName, accountName: accountName),
let secureString = String(data: secureData, encoding: .utf8)
else {
return nil
}
return secureString
}
}
| mit | 2b6586aa5075803f7e0ee0ae9a2739d9 | 37.506329 | 178 | 0.771861 | 4.133152 | false | false | false | false |
bromas/Architect | UIArchitect/Blueprint.swift | 1 | 1476 | //
// Blueprints.swift
// LayoutArchitect
//
// Created by Brian Thomas on 7/11/14.
// Copyright (c) 2014 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
public class Blueprint {
}
public func assertSuperview(#forView: UIView) -> UIView {
let superview = forView.superview
switch superview {
case .Some(let found):
return found
case .None:
assert(false, "\(forView) did not have a required superview.")
}
return UIView()
}
public func assertCommonSuperview(forView: UIView, and andView: UIView) -> UIView {
let superview = commonSuperview(forView, andView)
switch superview {
case .Some(let found):
return found
case .None:
assert(false, "\(forView) and \(andView) do not share a common superview.")
}
return UIView()
}
public func commonSuperview(first: UIView, second: UIView) -> UIView?
{
var views = Set<UIView>()
var firstTree: UIView? = first
var secondTree: UIView? = second
while (firstTree != .None || secondTree != .None) {
switch firstTree {
case let .Some(view):
if views.contains(view) {
return view
}
views.insert(view)
firstTree = view.superview
case .None:
assert(true, "")
}
switch secondTree {
case let .Some(view):
if views.contains(view) {
return view
}
views.insert(view)
secondTree = view.superview
case .None:
assert(true, "")
}
}
return .None
}
| mit | 43c2fc041c72ddd00104a138eb386db9 | 20.085714 | 83 | 0.636856 | 3.823834 | false | false | false | false |
KrakenDev/PrediKit | Tests/PrediKitTests.swift | 1 | 20656 | //
// PrediKitTests.swift
// PrediKitTests
//
// Copyright © 2016 KrakenDev. All rights reserved.
//
import XCTest
import CoreData
@testable import PrediKit
class PrediKitTests: XCTestCase {
override func setUp() {
super.setUp()
}
func testEmptyBuilderBehavior() {
let predicate = NSPredicate(Kraken.self) { includeIf in
XCTAssertEqual(includeIf.predicateString, "")
}
XCTAssertEqual(predicate, NSPredicate(value: false))
}
func testCommonIncluders() {
let legendaryArray = ["Kraken", "Kraken", "Kraken", "Kraken", "Cthulhu", "Voldemort", "Ember", "Umber", "Voldemort"]
let legendarySet: Set<String> = ["Kraken", "Kraken", "Kraken", "Kraken", "Cthulhu", "Voldemort", "Ember", "Umber", "Voldemort"]
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.SELF.equalsNil()
XCTAssertEqual(includeIf.predicateString, "SELF == nil")
includeIf.string(.krakenTitle).equalsNil()
XCTAssertEqual(includeIf.predicateString, "title == nil")
!includeIf.string(.krakenTitle).equalsNil()
XCTAssertEqual(includeIf.predicateString, "!(title == nil)")
includeIf.SELF.matchesAnyValueIn(legendaryArray)
XCTAssertEqual(includeIf.predicateString, "SELF IN %@")
includeIf.SELF.matchesAnyValueIn(legendarySet)
XCTAssertEqual(includeIf.predicateString, "SELF IN %@")
includeIf.member(.bestElfFriend, ofType: Elf.self).matchesAnyValueIn(legendaryArray)
XCTAssertEqual(includeIf.predicateString, "bestElfFriend IN %@")
includeIf.string(.krakenTitle).matchesAnyValueIn(legendaryArray)
XCTAssertEqual(includeIf.predicateString, "title IN %@")
}
}
func testStringIncluders() {
let theKrakensTitle = "The Almighty Kraken"
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).isEmpty()
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title == \"\"", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).beginsWith(theKrakensTitle)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title BEGINSWITH %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).endsWith(theKrakensTitle)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title ENDSWITH %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).contains(theKrakensTitle)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title CONTAINS %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).matches(theKrakensTitle)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title MATCHES %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).equals(theKrakensTitle)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title == %@", theKrakensTitle).predicateFormat)
}
}
func testStringIncludersWithOptions() {
let theKrakensTitle = "The Almighty Kraken"
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).beginsWith(theKrakensTitle, options: .CaseInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title BEGINSWITH[c] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).endsWith(theKrakensTitle, options: .CaseInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title ENDSWITH[c] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).contains(theKrakensTitle, options: .CaseInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title CONTAINS[c] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).matches(theKrakensTitle, options: .CaseInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title MATCHES[c] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).beginsWith(theKrakensTitle, options: .DiacriticInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title BEGINSWITH[d] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).endsWith(theKrakensTitle, options: .DiacriticInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title ENDSWITH[d] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).contains(theKrakensTitle, options: .DiacriticInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title CONTAINS[d] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).matches(theKrakensTitle, options: .DiacriticInsensitive)
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title MATCHES[d] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).beginsWith(theKrakensTitle, options: [.CaseInsensitive, .DiacriticInsensitive])
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title BEGINSWITH[cd] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).endsWith(theKrakensTitle, options: [.CaseInsensitive, .DiacriticInsensitive])
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title ENDSWITH[cd] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).contains(theKrakensTitle, options: [.CaseInsensitive, .DiacriticInsensitive])
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title CONTAINS[cd] %@", theKrakensTitle).predicateFormat)
includeIf.string(.krakenTitle).matches(theKrakensTitle, options: [.CaseInsensitive, .DiacriticInsensitive])
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "title MATCHES[cd] %@", theKrakensTitle).predicateFormat)
}
}
func testNumberIncluders() {
let testAge = 5
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.number(.krakenAge).doesNotEqual(testAge)
XCTAssertEqual(includeIf.predicateString, "age != %@")
includeIf.number(.krakenAge).equals(testAge)
XCTAssertEqual(includeIf.predicateString, "age == %@")
includeIf.number(.krakenAge).isGreaterThan(testAge)
XCTAssertEqual(includeIf.predicateString, "age > %@")
includeIf.number(.krakenAge).isGreaterThanOrEqualTo(testAge)
XCTAssertEqual(includeIf.predicateString, "age >= %@")
includeIf.number(.krakenAge).isLessThan(testAge)
XCTAssertEqual(includeIf.predicateString, "age < %@")
includeIf.number(.krakenAge).isLessThanOrEqualTo(testAge)
XCTAssertEqual(includeIf.predicateString, "age <= %@")
}
}
func testDateIncluders() {
let rightNow = Date()
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.date(.krakenBirthdate).equals(rightNow)
XCTAssertEqual(includeIf.predicateString, "birthdate == %@")
includeIf.date(.krakenBirthdate).isEarlierThan(rightNow)
XCTAssertEqual(includeIf.predicateString, "birthdate < %@")
includeIf.date(.krakenBirthdate).isEarlierThanOrOn(rightNow)
XCTAssertEqual(includeIf.predicateString, "birthdate <= %@")
includeIf.date(.krakenBirthdate).isLaterThan(rightNow)
XCTAssertEqual(includeIf.predicateString, "birthdate > %@")
includeIf.date(.krakenBirthdate).isLaterThanOrOn(rightNow)
XCTAssertEqual(includeIf.predicateString, "birthdate >= %@")
}
}
func testBoolIncluders() {
let truePredicate = NSPredicate(Kraken.self) { includeIf in
includeIf.bool(.isAwesome).isTrue()
}
XCTAssertEqual(truePredicate.predicateFormat, NSPredicate(format: "isAwesome == true").predicateFormat)
let falsePredicate = NSPredicate(Kraken.self) { includeIf in
includeIf.bool(.isAwesome).isFalse()
}
XCTAssertEqual(falsePredicate.predicateFormat, NSPredicate(format: "isAwesome == false").predicateFormat)
}
func testCollectionIncluders() {
let _ = NSPredicate(Kraken.self) { includeIf in
includeIf.collection(.friends).isEmpty()
XCTAssertEqual(includeIf.predicateString, NSPredicate(format: "friends.@count == 0").predicateFormat)
}
}
func testSubqueryIncluders() {
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.collection(.friends).subquery(Cerberus.self) { includeIf in
includeIf.bool(.isHungry).isTrue() &&
includeIf.bool(.isAwesome).isTrue()
return .includeIfMatched(.amount(.equals(0)))
}
}
XCTAssertEqual(predicate.predicateFormat, NSPredicate(format: "SUBQUERY(friends, $CerberusItem, $CerberusItem.isHungry == true && $CerberusItem.isAwesome == true).@count == 0").predicateFormat)
}
func testSubqueryReturnTypeStrings() {
let match = MatchType.includeIfMatched
let amount = MatchType.FunctionType.amount
XCTAssertEqual(match(amount(.equals(0))).collectionQuery, "@count == 0")
XCTAssertEqual(match(amount(.isLessThan(0))).collectionQuery, "@count < 0")
XCTAssertEqual(match(amount(.isLessThanOrEqualTo(0))).collectionQuery, "@count <= 0")
XCTAssertEqual(match(amount(.isGreaterThan(0))).collectionQuery, "@count > 0")
XCTAssertEqual(match(amount(.isGreaterThanOrEqualTo(0))).collectionQuery, "@count >= 0")
let min = MatchType.FunctionType.minValue
XCTAssertEqual(match(min(.equals(0))).collectionQuery, "@min == 0")
XCTAssertEqual(match(min(.isLessThan(0))).collectionQuery, "@min < 0")
XCTAssertEqual(match(min(.isLessThanOrEqualTo(0))).collectionQuery, "@min <= 0")
XCTAssertEqual(match(min(.isGreaterThan(0))).collectionQuery, "@min > 0")
XCTAssertEqual(match(min(.isGreaterThanOrEqualTo(0))).collectionQuery, "@min >= 0")
let max = MatchType.FunctionType.maxValue
XCTAssertEqual(match(max(.equals(0))).collectionQuery, "@max == 0")
XCTAssertEqual(match(max(.isLessThan(0))).collectionQuery, "@max < 0")
XCTAssertEqual(match(max(.isLessThanOrEqualTo(0))).collectionQuery, "@max <= 0")
XCTAssertEqual(match(max(.isGreaterThan(0))).collectionQuery, "@max > 0")
XCTAssertEqual(match(max(.isGreaterThanOrEqualTo(0))).collectionQuery, "@max >= 0")
let avg = MatchType.FunctionType.averageValue
XCTAssertEqual(match(avg(.equals(0))).collectionQuery, "@avg == 0")
XCTAssertEqual(match(avg(.isLessThan(0))).collectionQuery, "@avg < 0")
XCTAssertEqual(match(avg(.isLessThanOrEqualTo(0))).collectionQuery, "@avg <= 0")
XCTAssertEqual(match(avg(.isGreaterThan(0))).collectionQuery, "@avg > 0")
XCTAssertEqual(match(avg(.isGreaterThanOrEqualTo(0))).collectionQuery, "@avg >= 0")
}
func testMemberIncluders() {
let elf = Elf()
let elfName = "Aragorn"
let enemyBirthdate = Date()
let predicate = NSPredicate(Kraken.self) { includeIf in
let bestElfFriend = includeIf.member(.bestElfFriend, ofType: Elf.self)
let bestElfFriendsMortalEnemy = bestElfFriend.member(.enemy, ofType: Cerberus.self)
!bestElfFriend.equalsNil() &&
bestElfFriend.equals(elf) &&
bestElfFriendsMortalEnemy.date(.cerberusBirthdate).equals(enemyBirthdate) &&
bestElfFriend.string(.elfTitle).equals(elfName)
}
XCTAssertEqual(predicate.predicateFormat, NSPredicate(format: "!(bestElfFriend == nil) && bestElfFriend == %@ && bestElfFriend.enemy.birthdate == %@ && bestElfFriend.title == %@", elf, enemyBirthdate as CVarArg, elfName).predicateFormat)
}
func testSimpleANDIncluderCombination() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).equals(theKrakensTitle) &&
includeIf.date(.krakenBirthdate).isEarlierThan(rightNow)
}
let expectedPredicate = NSPredicate(format: "title == %@ && birthdate < %@", theKrakensTitle, rightNow as CVarArg)
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testChainedANDIncluderCombination() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let isAwesome = true
let age = 5
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).equals(theKrakensTitle) &&
includeIf.date(.krakenBirthdate).isEarlierThan(rightNow) &&
includeIf.bool(.isAwesome).isTrue() &&
includeIf.number(.krakenAge).equals(age)
}
let expectedPredicate = NSPredicate(format: "title == %@ && birthdate < %@ && isAwesome == %@ && age == \(age)", theKrakensTitle, rightNow as CVarArg, NSNumber(value: isAwesome))
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testSimpleORIncluderCombination() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.date(.krakenBirthdate).isEarlierThan(rightNow)
}
let expectedPredicate = NSPredicate(format: "title == %@ || birthdate < %@", theKrakensTitle, rightNow as CVarArg)
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testChainedORIncluderCombination() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let isAwesome = true
let age = 5
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.date(.krakenBirthdate).isEarlierThan(rightNow) ||
includeIf.bool(.isAwesome).isTrue() ||
includeIf.number(.krakenAge).equals(age)
}
let expectedPredicate = NSPredicate(format: "title == %@ || birthdate < %@ || isAwesome == %@ || age == \(age)", theKrakensTitle, rightNow as CVarArg, NSNumber(value: isAwesome))
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testComplexIncluderCombinationsWithoutParentheses() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.string(.krakenTitle).equals(theKrakensTitle) &&
includeIf.date(.krakenBirthdate).equals(rightNow) ||
includeIf.bool(.isAwesome).isTrue() &&
includeIf.date(.krakenBirthdate).equals(rightNow) ||
includeIf.bool(.isAwesome).isTrue()
}
let expectedPredicate = NSPredicate(format: "title == %@ || title == %@ || title == %@ && birthdate == %@ || isAwesome == true && birthdate == %@ || isAwesome == true", theKrakensTitle, theKrakensTitle, theKrakensTitle, rightNow as CVarArg, rightNow as CVarArg)
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testComplexIncluderCombinationsWithParentheses() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = Date()
let predicate = NSPredicate(Kraken.self) { includeIf in
(includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.string(.krakenTitle).equals(theKrakensTitle) ||
includeIf.string(.krakenTitle).equals(theKrakensTitle))
&&
(includeIf.date(.krakenBirthdate).equals(rightNow) ||
includeIf.bool(.isAwesome).isTrue())
&&
(includeIf.date(.krakenBirthdate).equals(rightNow) ||
includeIf.bool(.isAwesome).isTrue())
}
let expectedPredicate = NSPredicate(format: "(title == %@ || title == %@ || title == %@) && (birthdate == %@ || isAwesome == true) && (birthdate == %@ || isAwesome == true)", theKrakensTitle, theKrakensTitle, theKrakensTitle, rightNow as CVarArg, rightNow as CVarArg)
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testComplexIncluderCombinationsWithSubquery() {
let theKrakensTitle = "The Almighty Kraken"
let theElfTitle = "The Lowly Elf"
let rightNow = Date()
let age = 5.5
let predicate = NSPredicate(Kraken.self) { includeIf in
includeIf.collection(.friends).subquery(Cerberus.self) { includeIf in
let isTheKraken = includeIf.string(.krakenTitle).equals(theKrakensTitle)
let isBirthedToday = includeIf.date(.krakenBirthdate).equals(rightNow)
let isHungry = includeIf.bool(.isHungry).isTrue()
let isOlderThan5AndAHalf = includeIf.number(.krakenAge).isGreaterThan(age)
let hasElfSubordinates = includeIf.collection(.subordinates).subquery(Elf.self) { includeIf in
includeIf.string(.elfTitle).equals(theElfTitle)
return .includeIfMatched(.amount(.isGreaterThan(0)))
}
let hasCerberusSubordinates = includeIf.collection(.subordinates).subquery(Cerberus.self) { includeIf in
let age = includeIf.number(.cerberusAge).equals(age)
let birthdate = includeIf.date(.cerberusBirthdate).equals(rightNow)
birthdate || age
return .includeIfMatched(.amount(.isGreaterThan(0)))
}
isTheKraken || isOlderThan5AndAHalf || isHungry || (isBirthedToday && !hasElfSubordinates && hasCerberusSubordinates)
return .includeIfMatched(.amount(.equals(0)))
}
}
let expectedPredicate = NSPredicate(format: "SUBQUERY(friends, $CerberusItem, $CerberusItem.title == \"The Almighty Kraken\" OR $CerberusItem.age > \(age) OR $CerberusItem.isHungry == true OR ($CerberusItem.birthdate == %@ AND (NOT SUBQUERY($CerberusItem.subordinates, $ElfItem, $ElfItem.title == \"The Lowly Elf\").@count > 0) && SUBQUERY($CerberusItem.subordinates, $CerberusItem, $CerberusItem.birthdate == %@ || $CerberusItem.age == \(age)).@count > 0)).@count == 0", rightNow as CVarArg, rightNow as CVarArg)
XCTAssertEqual(predicate.predicateFormat, expectedPredicate.predicateFormat)
}
func testCombiningNSPredicateOperators() {
let theKrakensTitle = "The Almighty Kraken"
let rightNow = "October 4"
let firstPredicate = NSPredicate(format: "title == %@ && birthdate == %@", theKrakensTitle, rightNow)
let secondPredicate = NSPredicate(format: "isAwesome == true && isHungry == true")
let combinedANDPredicate = firstPredicate && secondPredicate
let combinedORPredicate = firstPredicate || secondPredicate
XCTAssertEqual(combinedANDPredicate.predicateFormat, "(title == \"The Almighty Kraken\" AND birthdate == \"October 4\") AND (isAwesome == 1 AND isHungry == 1)")
XCTAssertEqual(combinedORPredicate.predicateFormat, "(title == \"The Almighty Kraken\" AND birthdate == \"October 4\") OR (isAwesome == 1 AND isHungry == 1)")
}
}
//MARK: Test Classes
class Kraken: NSObject {
@NSManaged var title: String
@NSManaged var age: Int64
@NSManaged var birthdate: Date
@NSManaged var isAwesome: Bool
@NSManaged var bestElfFriend: Elf
@NSManaged var friends: [Cerberus]
}
class Cerberus: NSObject {
@NSManaged var title: String
@NSManaged var age: Int64
@NSManaged var birthdate: Date
@NSManaged var isHungry: Bool
@NSManaged var subordinates: [Elf]
}
class Elf: NSObject {
@NSManaged var title: String
@NSManaged var enemy: Cerberus
}
| mit | 2c0480b3e4b9cd3d36cb8388826a5150 | 55.589041 | 521 | 0.667393 | 4.402174 | false | true | false | false |
raychrd/tada | tada/MK/MKTableViewCell.swift | 1 | 2471 | //
// MKTableViewCell.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/15/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class MKTableViewCell : UITableViewCell {
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var circleAniDuration: Float = 0.75
@IBInspectable var backgroundAniDuration: Float = 1.0
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var shadowAniEnabled: Bool = true
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.contentView.layer)
private var contentViewResized = false
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
func setupLayer() {
self.selectionStyle = .None
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(circleLayerColor)
mkLayer.circleGrowRatioMax = 1.2
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.anyObject() as? UITouch {
if !contentViewResized {
mkLayer.superLayerDidResize()
contentViewResized = true
}
mkLayer.didChangeTapLocation(firstTouch.locationInView(self.contentView))
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(circleAniDuration))
mkLayer.animateAlphaForBackgroundLayer(MKTimingFunction.Linear, duration: CFTimeInterval(backgroundAniDuration))
}
}
}
| mit | e7547c548e91764eede9910364d01d07 | 31.946667 | 152 | 0.660866 | 5.126556 | false | false | false | false |
cocoaheadsru/server | Tests/AppTests/Common/Helpers/Controllers/Registration/RegFieldRuleHelper.swift | 1 | 746 | import Vapor
import Fluent
@testable import App
final class RegFieldRuleHelper {
static func assertRegFieldRuleHasExpectedFields(_ rules: JSON) throws -> Bool {
return rules["id"]?.int != nil && rules["type"]?.string != nil
}
static func addRules(to regFields: [RegField]) throws -> [RegField]? {
guard let rules = Rule.rules else {
return nil
}
var result: [RegField]! = []
for regField in regFields {
let rule1 = rules[Int.randomValue(min: 0, max: 2)]
try regField.rules.add(rule1)
if Bool.randomValue {
let rule2 = rules[Int.randomValue(min: 3, max: 4)]
try regField.rules.add(rule2)
}
result.append(regField)
}
return result
}
}
| mit | eea486ca552380416fbb31da2e21c469 | 22.3125 | 81 | 0.617962 | 3.693069 | false | false | false | false |
tardieu/swift | test/IRGen/objc_protocols.swift | 3 | 10482 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import gizmo
import objc_protocols_Bas
// -- Protocol "Frungible" inherits only objc protocols and should have no
// out-of-line inherited witnesses in its witness table.
// CHECK: [[ZIM_FRUNGIBLE_WITNESS:@_T014objc_protocols3ZimCAA9FrungibleAAWP]] = hidden constant [1 x i8*] [
// CHECK: i8* bitcast (void (%C14objc_protocols3Zim*, %swift.type*, i8**)* @_T014objc_protocols3ZimCAA9FrungibleAaaDP6frungeyyFTW to i8*)
// CHECK: ]
protocol Ansible {
func anse()
}
class Foo : NSRuncing, NSFunging, Ansible {
@objc func runce() {}
@objc func funge() {}
@objc func foo() {}
func anse() {}
}
// CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Foo = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } {
// CHECK: i32 24, i32 3,
// CHECK: [3 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC:@[0-9]+]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC5runceyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC5fungeyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC3fooyyFTo to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
class Bar {
func bar() {}
}
// -- Bar does not directly have objc methods...
// CHECK-NOT: @_INSTANCE_METHODS_Bar
extension Bar : NSRuncing, NSFunging {
@objc func runce() {}
@objc func funge() {}
@objc func foo() {}
func notObjC() {}
}
// -- ...but the ObjC protocol conformances on its extension add some
// CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC14objc_protocols3Bar_$_objc_protocols" = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } {
// CHECK: i32 24, i32 3,
// CHECK: [3 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC5runceyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC5fungeyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC3fooyyFTo to i8*) }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// class Bas from objc_protocols_Bas module
extension Bas : NSRuncing {
// -- The runce() implementation comes from the original definition.
@objc public
func foo() {}
}
// CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas3Bas_$_objc_protocols" = private constant { i32, i32, [1 x { i8*, i8*, i8* }] } {
// CHECK: i32 24, i32 1,
// CHECK; [1 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas0C0C0a1_B0E3fooyyFTo to i8*) }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// -- Swift protocol refinement of ObjC protocols.
protocol Frungible : NSRuncing, NSFunging {
func frunge()
}
class Zim : Frungible {
@objc func runce() {}
@objc func funge() {}
@objc func foo() {}
func frunge() {}
}
// CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Zim = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } {
// CHECK: i32 24, i32 3,
// CHECK: [3 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC5runceyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC5fungeyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC3fooyyFTo to i8*) }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// class Zang from objc_protocols_Bas module
extension Zang : Frungible {
@objc public
func runce() {}
// funge() implementation from original definition of Zang
@objc public
func foo() {}
func frunge() {}
}
// CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas4Zang_$_objc_protocols" = private constant { i32, i32, [2 x { i8*, i8*, i8* }] } {
// CHECK: i32 24, i32 2,
// CHECK: [2 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas4ZangC0a1_B0E5runceyyFTo to i8*) },
// CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas4ZangC0a1_B0E3fooyyFTo to i8*) }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// -- Force generation of witness for Zim.
// CHECK: define hidden { %objc_object*, i8** } @_T014objc_protocols22mixed_heritage_erasure{{[_0-9a-zA-Z]*}}F
func mixed_heritage_erasure(_ x: Zim) -> Frungible {
return x
// CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* {{%.*}}, 0
// CHECK: insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[ZIM_FRUNGIBLE_WITNESS]], i32 0, i32 0), 1
}
// CHECK-LABEL: define hidden void @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T) {{.*}} {
func objc_generic<T : NSRuncing>(_ x: T) {
x.runce()
// CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]])
}
// CHECK-LABEL: define hidden void @_T014objc_protocols05call_A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T) {{.*}} {
// CHECK: call void @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object* %0, %swift.type* %T)
func call_objc_generic<T : NSRuncing>(_ x: T) {
objc_generic(x)
}
// CHECK-LABEL: define hidden void @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F(%objc_object*) {{.*}} {
func objc_protocol(_ x: NSRuncing) {
x.runce()
// CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]])
}
// CHECK: define hidden %objc_object* @_T014objc_protocols0A8_erasure{{[_0-9a-zA-Z]*}}F(%CSo7NSSpoon*) {{.*}} {
func objc_erasure(_ x: NSSpoon) -> NSRuncing {
return x
// CHECK: [[RES:%.*]] = bitcast %CSo7NSSpoon* {{%.*}} to %objc_object*
// CHECK: ret %objc_object* [[RES]]
}
// CHECK: define hidden void @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F(%objc_object*)
func objc_protocol_composition(_ x: NSRuncing & NSFunging) {
x.runce()
// CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]])
x.funge()
// CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]])
}
// CHECK: define hidden void @_T014objc_protocols0A27_swift_protocol_composition{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**)
func objc_swift_protocol_composition
(_ x: NSRuncing & Ansible & NSFunging) {
x.runce()
// CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]])
/* TODO: Abstraction difference from ObjC protocol composition to
* opaque protocol
x.anse()
*/
x.funge()
// CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]])
}
// TODO: Mixed class-bounded/fully general protocol compositions.
@objc protocol SettableProperty {
var reqt: NSRuncing { get set }
}
func instantiateArchetype<T: SettableProperty>(_ x: T) {
let y = x.reqt
x.reqt = y
}
// rdar://problem/21029254
@objc protocol Appaloosa { }
protocol Palomino {}
protocol Vanner : Palomino, Appaloosa { }
struct Stirrup<T : Palomino> { }
func canter<T : Palomino>(_ t: Stirrup<T>) {}
func gallop<T : Vanner>(_ t: Stirrup<T>) {
canter(t)
}
| apache-2.0 | aed15d69b9db9dbb0fe00ce7040dceb5 | 50.131707 | 288 | 0.610857 | 2.820016 | false | false | false | false |
czechboy0/Buildasaur | BuildaGitServer/GitHub/GitHubServer.swift | 2 | 25178 | //
// GitHubSource.swift
// Buildasaur
//
// Created by Honza Dvorsky on 12/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
import ReactiveCocoa
class GitHubServer : GitServer {
let endpoints: GitHubEndpoints
var latestRateLimitInfo: GitHubRateLimit?
let cache = InMemoryURLCache()
init(endpoints: GitHubEndpoints, http: HTTP? = nil) {
self.endpoints = endpoints
super.init(service: .GitHub, http: http)
}
}
//TODO: from each of these calls, return a "cancellable" object which can be used for cancelling
extension GitHubServer: SourceServerType {
func getBranchesOfRepo(repo: String, completion: (branches: [BranchType]?, error: ErrorType?) -> ()) {
self._getBranchesOfRepo(repo) { (branches, error) -> () in
completion(branches: branches?.map { $0 as BranchType }, error: error)
}
}
func getOpenPullRequests(repo: String, completion: (prs: [PullRequestType]?, error: ErrorType?) -> ()) {
self._getOpenPullRequests(repo) { (prs, error) -> () in
completion(prs: prs?.map { $0 as PullRequestType }, error: error)
}
}
func getPullRequest(pullRequestNumber: Int, repo: String, completion: (pr: PullRequestType?, error: ErrorType?) -> ()) {
self._getPullRequest(pullRequestNumber, repo: repo) { (pr, error) -> () in
completion(pr: pr, error: error)
}
}
func getRepo(repo: String, completion: (repo: RepoType?, error: ErrorType?) -> ()) {
self._getRepo(repo) { (repo, error) -> () in
completion(repo: repo, error: error)
}
}
func getStatusOfCommit(commit: String, repo: String, completion: (status: StatusType?, error: ErrorType?) -> ()) {
self._getStatusOfCommit(commit, repo: repo) { (status, error) -> () in
completion(status: status, error: error)
}
}
func postStatusOfCommit(commit: String, status: StatusType, repo: String, completion: (status: StatusType?, error: ErrorType?) -> ()) {
self._postStatusOfCommit(status as! GitHubStatus, sha: commit, repo: repo) { (status, error) -> () in
completion(status: status, error: error)
}
}
func postCommentOnIssue(comment: String, issueNumber: Int, repo: String, completion: (comment: CommentType?, error: ErrorType?) -> ()) {
self._postCommentOnIssue(comment, issueNumber: issueNumber, repo: repo) { (comment, error) -> () in
completion(comment: comment, error: error)
}
}
func getCommentsOfIssue(issueNumber: Int, repo: String, completion: (comments: [CommentType]?, error: ErrorType?) -> ()) {
self._getCommentsOfIssue(issueNumber, repo: repo) { (comments, error) -> () in
completion(comments: comments?.map { $0 as CommentType }, error: error)
}
}
func createStatusFromState(buildState: BuildState, description: String?, targetUrl: String?) -> StatusType {
let state = GitHubStatus.GitHubState.fromBuildState(buildState)
let context = "Buildasaur"
return GitHubStatus(state: state, description: description, targetUrl: targetUrl, context: context)
}
}
extension GitHubServer {
private func _sendRequestWithPossiblePagination(request: NSMutableURLRequest, accumulatedResponseBody: NSArray, completion: HTTP.Completion) {
self._sendRequest(request) {
(response, body, error) -> () in
if error != nil {
completion(response: response, body: body, error: error)
return
}
if let arrayBody = body as? [AnyObject] {
let newBody = accumulatedResponseBody.arrayByAddingObjectsFromArray(arrayBody)
if let links = response?.allHeaderFields["Link"] as? String {
//now parse page links
if let pageInfo = self._parsePageLinks(links) {
//here look at the links and go to the next page, accumulate the body from this response
//and pass it through
if let nextUrl = pageInfo[RelPage.Next] {
let newRequest = request.mutableCopy() as! NSMutableURLRequest
newRequest.URL = nextUrl
self._sendRequestWithPossiblePagination(newRequest, accumulatedResponseBody: newBody, completion: completion)
return
}
}
}
completion(response: response, body: newBody, error: error)
} else {
completion(response: response, body: body, error: error)
}
}
}
enum RelPage: String {
case First = "first"
case Next = "next"
case Previous = "previous"
case Last = "last"
}
private func _parsePageLinks(links: String) -> [RelPage: NSURL]? {
var linkDict = [RelPage: NSURL]()
for i in links.componentsSeparatedByString(",") {
let link = i.componentsSeparatedByString(";")
if link.count < 2 {
continue
}
//url
var urlString = link[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if urlString.hasPrefix("<") && urlString.hasSuffix(">") {
urlString = urlString[urlString.startIndex.successor() ..< urlString.endIndex.predecessor()]
}
//rel
let relString = link[1]
let relComps = relString.componentsSeparatedByString("=")
if relComps.count < 2 {
continue
}
var relName = relComps[1]
if relName.hasPrefix("\"") && relName.hasSuffix("\"") {
relName = relName[relName.startIndex.successor() ..< relName.endIndex.predecessor()]
}
if
let rel = RelPage(rawValue: relName),
let url = NSURL(string: urlString)
{
linkDict[rel] = url
}
}
return linkDict
}
private func _sendRequest(request: NSMutableURLRequest, completion: HTTP.Completion) {
let cachedInfo = self.cache.getCachedInfoForRequest(request)
if let etag = cachedInfo.etag {
request.setValue(etag, forHTTPHeaderField: "If-None-Match")
}
self.http.sendRequest(request, completion: { (response, body, error) -> () in
if let error = error {
completion(response: response, body: body, error: error)
return
}
if response == nil {
completion(response: nil, body: body, error: Error.withInfo("Nil response"))
return
}
if let response = response {
let headers = response.allHeaderFields
if
let resetTime = (headers["X-RateLimit-Reset"] as? NSString)?.doubleValue,
let limit = (headers["X-RateLimit-Limit"] as? NSString)?.integerValue,
let remaining = (headers["X-RateLimit-Remaining"] as? NSString)?.integerValue {
let rateLimitInfo = GitHubRateLimit(resetTime: resetTime, limit: limit, remaining: remaining)
self.latestRateLimitInfo = rateLimitInfo
} else {
Log.error("No X-RateLimit info provided by GitHub in headers: \(headers), we're unable to detect the remaining number of allowed requests. GitHub might fail to return data any time now :(")
}
}
if
let respDict = body as? NSDictionary,
let message = respDict["message"] as? String
where message == "Not Found" {
let url = request.URL ?? ""
completion(response: nil, body: nil, error: Error.withInfo("Not found: \(url)"))
return
}
//error out on special HTTP status codes
let statusCode = response!.statusCode
switch statusCode {
case 200...299: //good response, cache the returned data
let responseInfo = ResponseInfo(response: response!, body: body)
cachedInfo.update(responseInfo)
case 304: //not modified, return the cached response
let responseInfo = cachedInfo.responseInfo!
completion(response: responseInfo.response, body: responseInfo.body, error: nil)
return
case 400 ... 500:
let message = (body as? NSDictionary)?["message"] as? String ?? "Unknown error"
let resultString = "\(statusCode): \(message)"
completion(response: response, body: body, error: Error.withInfo(resultString, internalError: error))
return
default:
break
}
completion(response: response, body: body, error: error)
})
}
private func _sendRequestWithMethod(method: HTTP.Method, endpoint: GitHubEndpoints.Endpoint, params: [String: String]?, query: [String: String]?, body: NSDictionary?, completion: HTTP.Completion) {
var allParams = [
"method": method.rawValue
]
//merge the two params
if let params = params {
for (key, value) in params {
allParams[key] = value
}
}
do {
let request = try self.endpoints.createRequest(method, endpoint: endpoint, params: allParams, query: query, body: body)
self._sendRequestWithPossiblePagination(request, accumulatedResponseBody: NSArray(), completion: completion)
} catch {
completion(response: nil, body: nil, error: Error.withInfo("Couldn't create Request, error \(error)"))
}
}
/**
* GET all open pull requests of a repo (full name).
*/
private func _getOpenPullRequests(repo: String, completion: (prs: [GitHubPullRequest]?, error: NSError?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .PullRequests, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(prs: nil, error: error)
return
}
if
let body = body as? NSArray,
let prs: [GitHubPullRequest] = try? GitHubArray(body) {
completion(prs: prs, error: nil)
} else {
completion(prs: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET a pull requests of a repo (full name) by its number.
*/
private func _getPullRequest(pullRequestNumber: Int, repo: String, completion: (pr: GitHubPullRequest?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"pr": pullRequestNumber.description
]
self._sendRequestWithMethod(.GET, endpoint: .PullRequests, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(pr: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let pr = try? GitHubPullRequest(json: body)
{
completion(pr: pr, error: nil)
} else {
completion(pr: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET all open issues of a repo (full name).
*/
private func _getOpenIssues(repo: String, completion: (issues: [GitHubIssue]?, error: NSError?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .Issues, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(issues: nil, error: error)
return
}
if
let body = body as? NSArray,
let issues: [GitHubIssue] = try? GitHubArray(body) {
completion(issues: issues, error: nil)
} else {
completion(issues: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET an issue of a repo (full name) by its number.
*/
private func _getIssue(issueNumber: Int, repo: String, completion: (issue: GitHubIssue?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"issue": issueNumber.description
]
self._sendRequestWithMethod(.GET, endpoint: .Issues, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(issue: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let issue = try? GitHubIssue(json: body)
{
completion(issue: issue, error: nil)
} else {
completion(issue: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* POST a new Issue
*/
private func _postNewIssue(issueTitle: String, issueBody: String?, repo: String, completion: (issue: GitHubIssue?, error: NSError?) -> ()) {
let params = [
"repo": repo,
]
let body = [
"title": issueTitle,
"body": issueBody ?? ""
]
self._sendRequestWithMethod(.POST, endpoint: .Issues, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(issue: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let issue = try? GitHubIssue(json: body)
{
completion(issue: issue, error: nil)
} else {
completion(issue: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* Close an Issue by its number and repo (full name).
*/
private func _closeIssue(issueNumber: Int, repo: String, completion: (issue: GitHubIssue?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"issue": issueNumber.description
]
let body = [
"state": "closed"
]
self._sendRequestWithMethod(.PATCH, endpoint: .Issues, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(issue: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let issue = try? GitHubIssue(json: body)
{
completion(issue: issue, error: nil)
} else {
completion(issue: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET the status of a commit (sha) from a repo.
*/
private func _getStatusOfCommit(sha: String, repo: String, completion: (status: GitHubStatus?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"sha": sha
]
self._sendRequestWithMethod(.GET, endpoint: .Statuses, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(status: nil, error: error)
return
}
if
let body = body as? NSArray,
let statuses: [GitHubStatus] = try? GitHubArray(body)
{
//sort them by creation date
let mostRecentStatus = statuses.sort({ return $0.created! > $1.created! }).first
completion(status: mostRecentStatus, error: nil)
} else {
completion(status: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* POST a new status on a commit.
*/
private func _postStatusOfCommit(status: GitHubStatus, sha: String, repo: String, completion: (status: GitHubStatus?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"sha": sha
]
let body = status.dictionarify()
self._sendRequestWithMethod(.POST, endpoint: .Statuses, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(status: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let status = try? GitHubStatus(json: body)
{
completion(status: status, error: nil)
} else {
completion(status: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET comments of an issue - WARNING - there is a difference between review comments (on a PR, tied to code)
* and general issue comments - which appear in both Issues and Pull Requests (bc a PR is an Issue + code)
* This API only fetches the general issue comments, NOT comments on code.
*/
private func _getCommentsOfIssue(issueNumber: Int, repo: String, completion: (comments: [GitHubComment]?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"issue": issueNumber.description
]
self._sendRequestWithMethod(.GET, endpoint: .IssueComments, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(comments: nil, error: error)
return
}
if
let body = body as? NSArray,
let comments: [GitHubComment] = try? GitHubArray(body)
{
completion(comments: comments, error: nil)
} else {
completion(comments: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* POST a comment on an issue.
*/
private func _postCommentOnIssue(commentBody: String, issueNumber: Int, repo: String, completion: (comment: GitHubComment?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"issue": issueNumber.description
]
let body = [
"body": commentBody
]
self._sendRequestWithMethod(.POST, endpoint: .IssueComments, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(comment: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let comment = try? GitHubComment(json: body)
{
completion(comment: comment, error: nil)
} else {
completion(comment: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* PATCH edit a comment with id
*/
private func _editCommentOnIssue(commentId: Int, newCommentBody: String, repo: String, completion: (comment: GitHubComment?, error: NSError?) -> ()) {
let params = [
"repo": repo,
"comment": commentId.description
]
let body = [
"body": newCommentBody
]
self._sendRequestWithMethod(.PATCH, endpoint: .IssueComments, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(comment: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let comment = try? GitHubComment(json: body)
{
completion(comment: comment, error: nil)
} else {
completion(comment: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* POST merge a head branch/commit into a base branch.
* has a couple of different responses, a bit tricky
*/
private func _mergeHeadIntoBase(head head: String, base: String, commitMessage: String, repo: String, completion: (result: GitHubEndpoints.MergeResult?, error: NSError?) -> ()) {
let params = [
"repo": repo
]
let body = [
"head": head,
"base": base,
"commit_message": commitMessage
]
self._sendRequestWithMethod(.POST, endpoint: .Merges, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(result: nil, error: error)
return
}
if let response = response {
let code = response.statusCode
switch code {
case 201:
//success
completion(result: GitHubEndpoints.MergeResult.Success(body as! NSDictionary), error: error)
case 204:
//no-op
completion(result: GitHubEndpoints.MergeResult.NothingToMerge, error: error)
case 409:
//conflict
completion(result: GitHubEndpoints.MergeResult.Conflict, error: error)
case 404:
//missing
let bodyDict = body as! NSDictionary
let message = bodyDict["message"] as! String
completion(result: GitHubEndpoints.MergeResult.Missing(message), error: error)
default:
completion(result: nil, error: error)
}
} else {
completion(result: nil, error: Error.withInfo("Nil response"))
}
}
}
/**
* GET branches of a repo
*/
private func _getBranchesOfRepo(repo: String, completion: (branches: [GitHubBranch]?, error: NSError?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .Branches, params: params, query: nil, body: nil) {
(response, body, error) -> () in
if error != nil {
completion(branches: nil, error: error)
return
}
if
let body = body as? NSArray,
let branches: [GitHubBranch] = try? GitHubArray(body)
{
completion(branches: branches, error: nil)
} else {
completion(branches: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
* GET repo metadata
*/
private func _getRepo(repo: String, completion: (repo: GitHubRepo?, error: NSError?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .Repos, params: params, query: nil, body: nil) {
(response, body, error) -> () in
if error != nil {
completion(repo: nil, error: error)
return
}
if
let body = body as? NSDictionary,
let repository: GitHubRepo = try? GitHubRepo(json: body)
{
completion(repo: repository, error: nil)
} else {
completion(repo: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
}
| mit | 993c1638949a47d78ce7b3b0d55e6074 | 34.562147 | 209 | 0.505958 | 4.98673 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+DomainCredit.swift | 1 | 4212 | import Gridicons
import SwiftUI
import WordPressFlux
extension BlogDetailsViewController {
@objc func domainCreditSectionViewModel() -> BlogDetailsSection {
let image = UIImage.gridicon(.info)
let row = BlogDetailsRow(title: NSLocalizedString("Register Domain", comment: "Action to redeem domain credit."),
accessibilityIdentifier: "Register domain from site dashboard",
image: image,
imageColor: UIColor.warning(.shade20)) { [weak self] in
WPAnalytics.track(.domainCreditRedemptionTapped)
self?.showDomainCreditRedemption()
}
row.showsDisclosureIndicator = false
row.showsSelectionState = false
return BlogDetailsSection(title: nil,
rows: [row],
footerTitle: NSLocalizedString("All WordPress.com plans include a custom domain name. Register your free premium domain now.", comment: "Information about redeeming domain credit on site dashboard."),
category: .domainCredit)
}
@objc func showDomainCreditRedemption() {
guard let site = JetpackSiteRef(blog: blog) else {
DDLogError("Error: couldn't initialize `JetpackSiteRef` from blog with ID: \(blog.dotComID?.intValue ?? 0)")
let cancelActionTitle = NSLocalizedString(
"OK",
comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt."
)
let alertController = UIAlertController(
title: NSLocalizedString("Unable to register domain", comment: "Alert title when `JetpackSiteRef` cannot be initialized from a blog during domain credit redemption."),
message: NSLocalizedString("Something went wrong, please try again.", comment: "Alert message when `JetpackSiteRef` cannot be initialized from a blog during domain credit redemption."),
preferredStyle: .alert
)
alertController.addCancelActionWithTitle(cancelActionTitle, handler: nil)
present(alertController, animated: true, completion: nil)
return
}
let controller = RegisterDomainSuggestionsViewController
.instance(site: site, domainPurchasedCallback: { [weak self] domain in
WPAnalytics.track(.domainCreditRedemptionSuccess)
self?.presentDomainCreditRedemptionSuccess(domain: domain)
})
let navigationController = UINavigationController(rootViewController: controller)
present(navigationController, animated: true)
}
private func presentDomainCreditRedemptionSuccess(domain: String) {
let controller = DomainCreditRedemptionSuccessViewController(domain: domain, delegate: self)
present(controller, animated: true) { [weak self] in
self?.updateTableViewAndHeader()
}
}
}
extension BlogDetailsViewController: DomainCreditRedemptionSuccessViewControllerDelegate {
func continueButtonPressed() {
dismiss(animated: true) { [weak self] in
guard let email = self?.accountEmail() else {
return
}
let title = String(format: NSLocalizedString("Verify your email address - instructions sent to %@", comment: "Notice displayed after domain credit redemption success."), email)
ActionDispatcher.dispatch(NoticeAction.post(Notice(title: title)))
}
}
private func accountEmail() -> String? {
let context = ContextManager.sharedInstance().mainContext
let accountService = AccountService(managedObjectContext: context)
guard let defaultAccount = accountService.defaultWordPressComAccount() else {
return nil
}
return defaultAccount.email
}
}
// MARK: - Domains Dashboard access from My Site
extension BlogDetailsViewController {
@objc func makeDomainsDashboardViewController() -> UIViewController {
UIHostingController(rootView: DomainsDashboardView(blog: self.blog))
}
}
| gpl-2.0 | 12cd583ad9418fdf0fff0bc7da31db3e | 49.746988 | 234 | 0.652659 | 5.793673 | false | false | false | false |
AnRanScheme/MagiRefresh | MagiRefresh/Classes/MagiRefreshCore/MagiAlertLabel.swift | 3 | 2035 | //
// MagiAlertLabel.swift
// MagiRefresh
//
// Created by anran on 2018/9/3.
// Copyright © 2018年 anran. All rights reserved.
//
import UIKit
public class MagiAlertLabel: UILabel, CAAnimationDelegate {
// MARK: - 控件
fileprivate lazy var new: CAGradientLayer = {
let new = CAGradientLayer()
new.locations = [0.2,0.5,0.8]
new.startPoint = CGPoint(x: 0.0, y: 0.5)
new.endPoint = CGPoint(x: 1.0, y: 0.5)
return new
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
new.frame = CGRect(x: 0, y: 0, width: 0, height: magi_height)
new.position = CGPoint(x: magi_width/2.0, y: magi_height/2.0)
}
fileprivate func setupUI() {
layer.masksToBounds = true
layer.addSublayer(new)
}
public func startAnimating() {
UIView.animate(withDuration: 0.3) {
self.alpha = 1
}
new.colors = [textColor.withAlphaComponent(0.2).cgColor,
textColor.withAlphaComponent(0.1).cgColor,
textColor.withAlphaComponent(0.2).cgColor]
let animation = CABasicAnimation(keyPath: "bounds.size.width")
animation.fromValue = 0
animation.toValue = magi_width
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.fillMode = CAMediaTimingFillMode.forwards
animation.duration = 0.3
animation.isRemovedOnCompletion = false
animation.delegate = self
new.add(animation,
forKey: animation.keyPath)
}
public func stopAnimating() {
UIView.animate(withDuration: 0.3) {
self.alpha = 0.0
}
new.removeAllAnimations()
}
}
| mit | f7e15aed8cee506c3697dfade58e4189 | 27.166667 | 96 | 0.591716 | 4.36129 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/FoundationNetworking/NSURLRequest.swift | 1 | 24248 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
// -----------------------------------------------------------------------------
///
/// This header file describes the constructs used to represent URL
/// load requests in a manner independent of protocol and URL scheme.
/// Immutable and mutable variants of this URL load request concept
/// are described, named `NSURLRequest` and `NSMutableURLRequest`,
/// respectively. A collection of constants is also declared to
/// exercise control over URL content caching policy.
///
/// `NSURLRequest` and `NSMutableURLRequest` are designed to be
/// customized to support protocol-specific requests. Protocol
/// implementors who need to extend the capabilities of `NSURLRequest`
/// and `NSMutableURLRequest` are encouraged to provide categories on
/// these classes as appropriate to support protocol-specific data. To
/// store and retrieve data, category methods can use the
/// `propertyForKey(_:,inRequest:)` and
/// `setProperty(_:,forKey:,inRequest:)` class methods on
/// `URLProtocol`. See the `NSHTTPURLRequest` on `NSURLRequest` and
/// `NSMutableHTTPURLRequest` on `NSMutableURLRequest` for examples of
/// such extensions.
///
/// The main advantage of this design is that a client of the URL
/// loading library can implement request policies in a standard way
/// without type checking of requests or protocol checks on URLs. Any
/// protocol-specific details that have been set on a URL request will
/// be used if they apply to the particular URL being loaded, and will
/// be ignored if they do not apply.
///
// -----------------------------------------------------------------------------
/// A cache policy
///
/// The `NSURLRequestCachePolicy` `enum` defines constants that
/// can be used to specify the type of interactions that take place with
/// the caching system when the URL loading system processes a request.
/// Specifically, these constants cover interactions that have to do
/// with whether already-existing cache data is returned to satisfy a
/// URL load request.
extension NSURLRequest {
public enum CachePolicy : UInt {
/// Specifies that the caching logic defined in the protocol
/// implementation, if any, is used for a particular URL load request. This
/// is the default policy for URL load requests.
case useProtocolCachePolicy
/// Specifies that the data for the URL load should be loaded from the
/// origin source. No existing local cache data, regardless of its freshness
/// or validity, should be used to satisfy a URL load request.
case reloadIgnoringLocalCacheData
/// Specifies that not only should the local cache data be ignored, but that
/// proxies and other intermediates should be instructed to disregard their
/// caches so far as the protocol allows. Unimplemented.
case reloadIgnoringLocalAndRemoteCacheData // Unimplemented
/// Older name for `NSURLRequestReloadIgnoringLocalCacheData`.
public static var reloadIgnoringCacheData: CachePolicy { return .reloadIgnoringLocalCacheData }
/// Specifies that the existing cache data should be used to satisfy a URL
/// load request, regardless of its age or expiration date. However, if
/// there is no existing data in the cache corresponding to a URL load
/// request, the URL is loaded from the origin source.
case returnCacheDataElseLoad
/// Specifies that the existing cache data should be used to satisfy a URL
/// load request, regardless of its age or expiration date. However, if
/// there is no existing data in the cache corresponding to a URL load
/// request, no attempt is made to load the URL from the origin source, and
/// the load is considered to have failed. This constant specifies a
/// behavior that is similar to an "offline" mode.
case returnCacheDataDontLoad
/// Specifies that the existing cache data may be used provided the origin
/// source confirms its validity, otherwise the URL is loaded from the
/// origin source.
/// - Note: Unimplemented.
case reloadRevalidatingCacheData // Unimplemented
}
public enum NetworkServiceType : UInt {
case `default` // Standard internet traffic
case voip // Voice over IP control traffic
case video // Video traffic
case background // Background traffic
case voice // Voice data
case networkServiceTypeCallSignaling // Call Signaling
}
}
/// An `NSURLRequest` object represents a URL load request in a
/// manner independent of protocol and URL scheme.
///
/// `NSURLRequest` encapsulates basic data elements about a URL load request.
///
/// In addition, `NSURLRequest` is designed to be extended to support
/// protocol-specific data by adding categories to access a property
/// object provided in an interface targeted at protocol implementors.
///
/// Protocol implementors should direct their attention to the
/// `NSURLRequestExtensibility` category on `NSURLRequest` for more
/// information on how to provide extensions on `NSURLRequest` to
/// support protocol-specific request information.
///
/// Clients of this API who wish to create `NSURLRequest` objects to
/// load URL content should consult the protocol-specific `NSURLRequest`
/// categories that are available. The `NSHTTPURLRequest` category on
/// `NSURLRequest` is an example.
///
/// Objects of this class are used with the `URLSession` API to perform the
/// load of a URL.
open class NSURLRequest : NSObject, NSSecureCoding, NSCopying, NSMutableCopying {
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSURLRequest.self {
// Already immutable
return self
}
let c = NSURLRequest(url: url!)
c.setValues(from: self)
return c
}
public convenience init(url: URL) {
self.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
}
public init(url: URL, cachePolicy: NSURLRequest.CachePolicy, timeoutInterval: TimeInterval) {
self.url = url.absoluteURL
self.cachePolicy = cachePolicy
self.timeoutInterval = timeoutInterval
}
private func setValues(from source: NSURLRequest) {
self.url = source.url
self.mainDocumentURL = source.mainDocumentURL
self.cachePolicy = source.cachePolicy
self.timeoutInterval = source.timeoutInterval
self.httpMethod = source.httpMethod
self.allHTTPHeaderFields = source.allHTTPHeaderFields
self._body = source._body
self.networkServiceType = source.networkServiceType
self.allowsCellularAccess = source.allowsCellularAccess
self.httpShouldHandleCookies = source.httpShouldHandleCookies
self.httpShouldUsePipelining = source.httpShouldUsePipelining
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
let c = NSMutableURLRequest(url: url!)
c.setValues(from: self)
return c
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
super.init()
if let encodedURL = aDecoder.decodeObject(forKey: "NS.url") as? NSURL {
self.url = encodedURL as URL
}
if let encodedHeaders = aDecoder.decodeObject(forKey: "NS._allHTTPHeaderFields") as? NSDictionary {
self.allHTTPHeaderFields = encodedHeaders.reduce([String : String]()) { result, item in
var result = result
if let key = item.key as? NSString,
let value = item.value as? NSString {
result[key as String] = value as String
}
return result
}
}
if let encodedDocumentURL = aDecoder.decodeObject(forKey: "NS.mainDocumentURL") as? NSURL {
self.mainDocumentURL = encodedDocumentURL as URL
}
if let encodedMethod = aDecoder.decodeObject(forKey: "NS.httpMethod") as? NSString {
self.httpMethod = encodedMethod as String
}
let encodedCachePolicy = aDecoder.decodeObject(forKey: "NS._cachePolicy") as! NSNumber
self.cachePolicy = CachePolicy(rawValue: encodedCachePolicy.uintValue)!
let encodedTimeout = aDecoder.decodeObject(forKey: "NS._timeoutInterval") as! NSNumber
self.timeoutInterval = encodedTimeout.doubleValue
let encodedHttpBody: Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.httpBody") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
if let encodedHttpBody = encodedHttpBody {
self._body = .data(encodedHttpBody)
}
let encodedNetworkServiceType = aDecoder.decodeObject(forKey: "NS._networkServiceType") as! NSNumber
self.networkServiceType = NetworkServiceType(rawValue: encodedNetworkServiceType.uintValue)!
let encodedCellularAccess = aDecoder.decodeObject(forKey: "NS._allowsCellularAccess") as! NSNumber
self.allowsCellularAccess = encodedCellularAccess.boolValue
let encodedHandleCookies = aDecoder.decodeObject(forKey: "NS._httpShouldHandleCookies") as! NSNumber
self.httpShouldHandleCookies = encodedHandleCookies.boolValue
let encodedUsePipelining = aDecoder.decodeObject(forKey: "NS._httpShouldUsePipelining") as! NSNumber
self.httpShouldUsePipelining = encodedUsePipelining.boolValue
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.url?._bridgeToObjectiveC(), forKey: "NS.url")
aCoder.encode(self.allHTTPHeaderFields?._bridgeToObjectiveC(), forKey: "NS._allHTTPHeaderFields")
aCoder.encode(self.mainDocumentURL?._bridgeToObjectiveC(), forKey: "NS.mainDocumentURL")
aCoder.encode(self.httpMethod?._bridgeToObjectiveC(), forKey: "NS.httpMethod")
aCoder.encode(self.cachePolicy.rawValue._bridgeToObjectiveC(), forKey: "NS._cachePolicy")
aCoder.encode(self.timeoutInterval._bridgeToObjectiveC(), forKey: "NS._timeoutInterval")
if let httpBody = self.httpBody?._bridgeToObjectiveC() {
withExtendedLifetime(httpBody) {
let bytePtr = httpBody.bytes.bindMemory(to: UInt8.self, capacity: httpBody.length)
aCoder.encodeBytes(bytePtr, length: httpBody.length, forKey: "NS.httpBody")
}
}
//On macOS input stream is not encoded.
aCoder.encode(self.networkServiceType.rawValue._bridgeToObjectiveC(), forKey: "NS._networkServiceType")
aCoder.encode(self.allowsCellularAccess._bridgeToObjectiveC(), forKey: "NS._allowsCellularAccess")
aCoder.encode(self.httpShouldHandleCookies._bridgeToObjectiveC(), forKey: "NS._httpShouldHandleCookies")
aCoder.encode(self.httpShouldUsePipelining._bridgeToObjectiveC(), forKey: "NS._httpShouldUsePipelining")
}
open override func isEqual(_ object: Any?) -> Bool {
//On macOS this fields do not determine the result:
//allHTTPHeaderFields
//timeoutInterval
//httBody
//networkServiceType
//httpShouldUsePipelining
guard let other = object as? NSURLRequest else { return false }
return other === self
|| (other.url == self.url
&& other.mainDocumentURL == self.mainDocumentURL
&& other.httpMethod == self.httpMethod
&& other.cachePolicy == self.cachePolicy
&& other.httpBodyStream == self.httpBodyStream
&& other.allowsCellularAccess == self.allowsCellularAccess
&& other.httpShouldHandleCookies == self.httpShouldHandleCookies)
}
open override var hash: Int {
var hasher = Hasher()
hasher.combine(url)
hasher.combine(mainDocumentURL)
hasher.combine(httpMethod)
hasher.combine(httpBodyStream)
hasher.combine(allowsCellularAccess)
hasher.combine(httpShouldHandleCookies)
return hasher.finalize()
}
/// Indicates that NSURLRequest implements the NSSecureCoding protocol.
open class var supportsSecureCoding: Bool { return true }
/// The URL of the receiver.
/*@NSCopying */open fileprivate(set) var url: URL?
/// The main document URL associated with this load.
///
/// This URL is used for the cookie "same domain as main
/// document" policy. There may also be other future uses.
/*@NSCopying*/ open fileprivate(set) var mainDocumentURL: URL?
open internal(set) var cachePolicy: CachePolicy = .useProtocolCachePolicy
open internal(set) var timeoutInterval: TimeInterval = 60.0
internal var _httpMethod: String? = "GET"
/// Returns the HTTP request method of the receiver.
open fileprivate(set) var httpMethod: String? {
get { return _httpMethod }
set { _httpMethod = NSURLRequest._normalized(newValue) }
}
private class func _normalized(_ raw: String?) -> String {
guard let raw = raw else {
return "GET"
}
let nsMethod = NSString(string: raw)
for method in ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT"] {
if nsMethod.caseInsensitiveCompare(method) == .orderedSame {
return method
}
}
return raw
}
/// A dictionary containing all the HTTP header fields
/// of the receiver.
open internal(set) var allHTTPHeaderFields: [String : String]? = nil
/// Returns the value which corresponds to the given header field.
///
/// Note that, in keeping with the HTTP RFC, HTTP header field
/// names are case-insensitive.
/// - Parameter field: the header field name to use for the lookup
/// (case-insensitive).
/// - Returns: the value associated with the given header field, or `nil` if
/// there is no value associated with the given header field.
open func value(forHTTPHeaderField field: String) -> String? {
guard let f = allHTTPHeaderFields else { return nil }
return existingHeaderField(field, inHeaderFields: f)?.1
}
internal enum Body {
case data(Data)
case stream(InputStream)
}
internal var _body: Body?
open var httpBody: Data? {
if let body = _body {
switch body {
case .data(let data):
return data
case .stream:
return nil
}
}
return nil
}
open var httpBodyStream: InputStream? {
if let body = _body {
switch body {
case .data:
return nil
case .stream(let stream):
return stream
}
}
return nil
}
open internal(set) var networkServiceType: NetworkServiceType = .default
open internal(set) var allowsCellularAccess: Bool = true
open internal(set) var httpShouldHandleCookies: Bool = true
open internal(set) var httpShouldUsePipelining: Bool = true
open override var description: String {
let url = self.url?.description ?? "(null)"
return super.description + " { URL: \(url) }"
}
}
/// An `NSMutableURLRequest` object represents a mutable URL load
/// request in a manner independent of protocol and URL scheme.
///
/// This specialization of `NSURLRequest` is provided to aid
/// developers who may find it more convenient to mutate a single request
/// object for a series of URL loads instead of creating an immutable
/// `NSURLRequest` for each load. This programming model is supported by
/// the following contract stipulation between `NSMutableURLRequest` and the
/// `URLSession` API: `URLSession` makes a deep copy of each
/// `NSMutableURLRequest` object passed to it.
///
/// `NSMutableURLRequest` is designed to be extended to support
/// protocol-specific data by adding categories to access a property
/// object provided in an interface targeted at protocol implementors.
///
/// Protocol implementors should direct their attention to the
/// `NSMutableURLRequestExtensibility` category on
/// `NSMutableURLRequest` for more information on how to provide
/// extensions on `NSMutableURLRequest` to support protocol-specific
/// request information.
///
/// Clients of this API who wish to create `NSMutableURLRequest`
/// objects to load URL content should consult the protocol-specific
/// `NSMutableURLRequest` categories that are available. The
/// `NSMutableHTTPURLRequest` category on `NSMutableURLRequest` is an
/// example.
open class NSMutableURLRequest : NSURLRequest {
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(url: URL) {
self.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
}
public override init(url: URL, cachePolicy: NSURLRequest.CachePolicy, timeoutInterval: TimeInterval) {
super.init(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
}
open override func copy(with zone: NSZone? = nil) -> Any {
return mutableCopy(with: zone)
}
/*@NSCopying */ open override var url: URL? {
get { return super.url }
//TODO: set { super.URL = newValue.map{ $0.copy() as! NSURL } }
set { super.url = newValue }
}
/// The main document URL.
///
/// The caller should pass the URL for an appropriate main
/// document, if known. For example, when loading a web page, the URL
/// of the main html document for the top-level frame should be
/// passed. This main document will be used to implement the cookie
/// *only from same domain as main document* policy, and possibly
/// other things in the future.
/*@NSCopying*/ open override var mainDocumentURL: URL? {
get { return super.mainDocumentURL }
//TODO: set { super.mainDocumentURL = newValue.map{ $0.copy() as! NSURL } }
set { super.mainDocumentURL = newValue }
}
/// The HTTP request method of the receiver.
open override var httpMethod: String? {
get { return super.httpMethod }
set { super.httpMethod = newValue }
}
open override var cachePolicy: CachePolicy {
get { return super.cachePolicy }
set { super.cachePolicy = newValue }
}
open override var timeoutInterval: TimeInterval {
get { return super.timeoutInterval }
set { super.timeoutInterval = newValue }
}
open override var allHTTPHeaderFields: [String : String]? {
get { return super.allHTTPHeaderFields }
set { super.allHTTPHeaderFields = newValue }
}
/// Sets the value of the given HTTP header field.
///
/// If a value was previously set for the given header
/// field, that value is replaced with the given value. Note that, in
/// keeping with the HTTP RFC, HTTP header field names are
/// case-insensitive.
/// - Parameter value: the header field value.
/// - Parameter field: the header field name (case-insensitive).
open func setValue(_ value: String?, forHTTPHeaderField field: String) {
// Store the field name capitalized to match native Foundation
let capitalizedFieldName = field.capitalized
var f: [String : String] = allHTTPHeaderFields ?? [:]
if let old = existingHeaderField(capitalizedFieldName, inHeaderFields: f) {
f.removeValue(forKey: old.0)
}
f[capitalizedFieldName] = value
allHTTPHeaderFields = f
}
/// Adds an HTTP header field in the current header dictionary.
///
/// This method provides a way to add values to header
/// fields incrementally. If a value was previously set for the given
/// header field, the given value is appended to the previously-existing
/// value. The appropriate field delimiter, a comma in the case of HTTP,
/// is added by the implementation, and should not be added to the given
/// value by the caller. Note that, in keeping with the HTTP RFC, HTTP
/// header field names are case-insensitive.
/// - Parameter value: the header field value.
/// - Parameter field: the header field name (case-insensitive).
open func addValue(_ value: String, forHTTPHeaderField field: String) {
// Store the field name capitalized to match native Foundation
let capitalizedFieldName = field.capitalized
var f: [String : String] = allHTTPHeaderFields ?? [:]
if let old = existingHeaderField(capitalizedFieldName, inHeaderFields: f) {
f[old.0] = old.1 + "," + value
} else {
f[capitalizedFieldName] = value
}
allHTTPHeaderFields = f
}
open override var httpBody: Data? {
get {
if let body = _body {
switch body {
case .data(let data):
return data
case .stream:
return nil
}
}
return nil
}
set {
if let value = newValue {
_body = Body.data(value)
} else {
_body = nil
}
}
}
open override var httpBodyStream: InputStream? {
get {
if let body = _body {
switch body {
case .data:
return nil
case .stream(let stream):
return stream
}
}
return nil
}
set {
if let value = newValue {
_body = Body.stream(value)
} else {
_body = nil
}
}
}
open override var networkServiceType: NetworkServiceType {
get { return super.networkServiceType }
set { super.networkServiceType = newValue }
}
open override var allowsCellularAccess: Bool {
get { return super.allowsCellularAccess }
set { super.allowsCellularAccess = newValue }
}
open override var httpShouldHandleCookies: Bool {
get { return super.httpShouldHandleCookies }
set { super.httpShouldHandleCookies = newValue }
}
open override var httpShouldUsePipelining: Bool {
get { return super.httpShouldUsePipelining }
set { super.httpShouldUsePipelining = newValue }
}
// These properties are settable using URLProtocol's class methods.
var protocolProperties: [String: Any] = [:]
}
/// Returns an existing key-value pair inside the header fields if it exists.
private func existingHeaderField(_ key: String, inHeaderFields fields: [String : String]) -> (String, String)? {
for (k, v) in fields {
if k.lowercased() == key.lowercased() {
return (k, v)
}
}
return nil
}
extension NSURLRequest : _StructTypeBridgeable {
public typealias _StructType = URLRequest
public func _bridgeToSwift() -> URLRequest {
return URLRequest._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 4ac252e7a7ca337282665554dd805329 | 40.098305 | 112 | 0.649373 | 5.175667 | false | false | false | false |
maarten/Ximian | Ximian/AEXML/Element.swift | 1 | 9755 | //
// Element.swift
//
// Copyright (c) 2014-2016 Marko Tadić <[email protected]> http://tadija.net
//
// 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
/**
This is base class for holding XML structure.
You can access its structure by using subscript like this: `element["foo"]["bar"]` which would
return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `AEXMLElement` object.
*/
open class AEXMLElement {
// MARK: - Properties
/// Every `AEXMLElement` should have its parent element instead of `AEXMLDocument` which parent is `nil`.
open internal(set) weak var parent: AEXMLElement?
/// Child XML elements.
open internal(set) var children = [AEXMLElement]()
/// XML Element name.
open var name: String
/// XML Element value.
open var value: String?
/// XML Element attributes.
open var attributes: [String : String]
/// Error value (`nil` if there is no error).
open var error: AEXMLError?
/// String representation of `value` property (if `value` is `nil` this is empty String).
open var string: String { return value ?? String() }
/// Boolean representation of `value` property (if `value` is "true" or 1 this is `True`, otherwise `False`).
open var bool: Bool { return string.lowercased() == "true" || Int(string) == 1 ? true : false }
/// Integer representation of `value` property (this is **0** if `value` can't be represented as Integer).
open var int: Int { return Int(string) ?? 0 }
/// Double representation of `value` property (this is **0.00** if `value` can't be represented as Double).
open var double: Double { return Double(string) ?? 0.00 }
// MARK: - Lifecycle
/**
Designated initializer - all parameters are optional.
- parameter name: XML element name.
- parameter value: XML element value (defaults to `nil`).
- parameter attributes: XML element attributes (defaults to empty dictionary).
- returns: An initialized `AEXMLElement` object.
*/
public init(name: String, value: String? = nil, attributes: [String : String] = [String : String]()) {
self.name = name
self.value = value
self.attributes = attributes
}
// MARK: - XML Read
/// The first element with given name **(Empty element with error if not exists)**.
open subscript(key: String) -> AEXMLElement {
guard let
first = children.filter({ $0.name == key }).first
else {
let errorElement = AEXMLElement(name: key)
errorElement.error = AEXMLError.elementNotFound
return errorElement
}
return first
}
/// Returns all of the elements with equal name as `self` **(nil if not exists)**.
open var all: [AEXMLElement]? { return parent?.children.filter { $0.name == self.name } }
/// Returns the first element with equal name as `self` **(nil if not exists)**.
open var first: AEXMLElement? { return all?.first }
/// Returns the last element with equal name as `self` **(nil if not exists)**.
open var last: AEXMLElement? { return all?.last }
/// Returns number of all elements with equal name as `self`.
open var count: Int { return all?.count ?? 0 }
fileprivate func filter(withCondition condition: (AEXMLElement) -> Bool) -> [AEXMLElement]? {
guard let elements = all else { return nil }
var found = [AEXMLElement]()
for element in elements {
if condition(element) {
found.append(element)
}
}
return found.count > 0 ? found : nil
}
/**
Returns all elements with given value.
- parameter value: XML element value.
- returns: Optional Array of found XML elements.
*/
open func all(withValue value: String) -> [AEXMLElement]? {
let found = filter { (element) -> Bool in
return element.value == value
}
return found
}
/**
Returns all elements with given attributes.
- parameter attributes: Dictionary of Keys and Values of attributes.
- returns: Optional Array of found XML elements.
*/
open func all(withAttributes attributes: [String : String]) -> [AEXMLElement]? {
let found = filter { (element) -> Bool in
var countAttributes = 0
for (key, value) in attributes {
if element.attributes[key] == value {
countAttributes += 1
}
}
return countAttributes == attributes.count
}
return found
}
// MARK: - XML Write
/**
Adds child XML element to `self`.
- parameter child: Child XML element to add.
- returns: Child XML element with `self` as `parent`.
*/
@discardableResult open func addChild(_ child: AEXMLElement) -> AEXMLElement {
child.parent = self
children.append(child)
return child
}
/**
Adds child XML element to `self`.
- parameter name: Child XML element name.
- parameter value: Child XML element value (defaults to `nil`).
- parameter attributes: Child XML element attributes (defaults to empty dictionary).
- returns: Child XML element with `self` as `parent`.
*/
@discardableResult open func addChild(name: String,
value: String? = nil,
attributes: [String : String] = [String : String]()) -> AEXMLElement
{
let child = AEXMLElement(name: name, value: value, attributes: attributes)
return addChild(child)
}
/// Removes `self` from `parent` XML element.
open func removeFromParent() {
parent?.removeChild(self)
}
fileprivate func removeChild(_ child: AEXMLElement) {
if let childIndex = children.index(where: { $0 === child }) {
children.remove(at: childIndex)
}
}
fileprivate var parentsCount: Int {
var count = 0
var element = self
while let parent = element.parent {
count += 1
element = parent
}
return count
}
fileprivate func indent(withDepth depth: Int) -> String {
var count = depth
var indent = String()
while count > 0 {
indent += " "
count -= 1
}
return indent
}
/// Complete hierarchy of `self` and `children` in **XML** escaped and formatted String
open var xml: String {
var xml = String()
// open element
xml += indent(withDepth: parentsCount - 1)
xml += "<\(name)"
if attributes.count > 0 {
// insert attributes
for (key, value) in attributes {
xml += " \(key)=\"\(value.xmlEscaped)\""
}
}
if value == nil && children.count == 0 {
// close element
xml += " />"
} else {
if children.count > 0 {
// add children
xml += ">\n"
for child in children {
xml += "\(child.xml)\n"
}
// add indentation
xml += indent(withDepth: parentsCount - 1)
xml += "</\(name)>"
} else {
// insert string value and close element
xml += ">\(string.xmlEscaped)</\(name)>"
}
}
return xml
}
/// Same as `xmlString` but without `\n` and `\t` characters
open var xmlCompact: String {
let chars = CharacterSet(charactersIn: "\n\t")
return xml.components(separatedBy: chars).joined(separator: "")
}
}
public extension String {
/// String representation of self with XML special characters escaped.
public var xmlEscaped: String {
// we need to make sure "&" is escaped first. Not doing this may break escaping the other characters
var escaped = replacingOccurrences(of: "&", with: "&", options: .literal)
// replace the other four special characters
let escapeChars = ["<" : "<", ">" : ">", "'" : "'", "\"" : """]
for (char, echar) in escapeChars {
escaped = escaped.replacingOccurrences(of: char, with: echar, options: .literal)
}
return escaped
}
}
| mit | 3f96078b51588a8b928c0b5f9f35ee2f | 33.224561 | 114 | 0.578532 | 4.772016 | false | false | false | false |
SoufianeLasri/Sisley | Sisley/RecapView.swift | 1 | 2650 | //
// RecapView.swift
// Sisley
//
// Created by Soufiane Lasri on 06/01/2016.
// Copyright © 2016 Soufiane Lasri. All rights reserved.
//
import UIKit
protocol RecapViewDelegate : class {
func hideRecapView()
}
class RecapView: UIView {
var delegate: RecapViewDelegate?
init( frame: CGRect, text: [ String ] ) {
super.init( frame: frame )
var items: [ RecapEtiquetteView ] = []
let data = [
[
"title": "État",
"answer": text[ 0 ]
],
[
"title": "Fatigue",
"answer": text[ 1 ]
],
[
"title": "Humeur",
"answer": text[ 2 ]
]
]
let stressEtiquette = RecapEtiquetteView( frame: CGRect( x: 25, y: 255, width: 190, height: 95 ), data: data[ 0 ] )
stressEtiquette.alpha = 0.0
items.append( stressEtiquette )
self.addSubview( stressEtiquette )
let tirednessEtiquette = RecapEtiquetteView( frame: CGRect( x: self.frame.width - 215, y: 255, width: 190, height: 95 ), data: data[ 1 ] )
tirednessEtiquette.alpha = 0.0
items.append( tirednessEtiquette )
self.addSubview( tirednessEtiquette )
let moodEtiquette = RecapEtiquetteView( frame: CGRect( x: 25, y: 255, width: 190, height: 95 ), data: data[ 2 ] )
moodEtiquette.alpha = 0.0
items.append( moodEtiquette )
self.addSubview( moodEtiquette )
var delay = 1.5
for item in items {
item.alpha = 0.0
UIView.animateWithDuration( 4.0, delay: delay, options: .CurveLinear, animations: {
item.frame.origin.y -= 160
}, completion: nil )
UIView.animateWithDuration( 1.5, delay: delay + 0.5, options: .TransitionNone, animations: {
item.alpha = 1.0
}, completion: { finished in
UIView.animateWithDuration( 1.5, delay: 0.0, options: .TransitionNone, animations: {
item.alpha = 0.0
}, completion: nil )
} )
delay += 2.5
}
let chrono = 9.5 * Double( NSEC_PER_SEC )
let time = dispatch_time( DISPATCH_TIME_NOW, Int64( chrono ) )
dispatch_after( time, dispatch_get_main_queue() ) {
self.delegate?.hideRecapView()
self.hidden = true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 034e8c4b04ef6992b1be6fdd0285105a | 30.52381 | 146 | 0.52077 | 3.911374 | false | false | false | false |
hollyschilling/EssentialElements | EssentialElements/EssentialElements/ItemLists/Managers/ImageManager.swift | 1 | 3736 | //
// ImageManager.swift
// EssentialElements
//
// Created by Holly Schilling on 2/26/17.
// Copyright © 2017 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import Dispatch
open class ImageManager {
public static var shared: ImageManager = ImageManager()
private var activeTasks: [UIImageView: URLSessionTask] = [:]
private let syncQueue: DispatchQueue = DispatchQueue(label: "ImageManager SyncQueue")
public let session: URLSession
public init(session: URLSession = URLSession.shared) {
self.session = session
}
open func cancelTask(for imageView: UIImageView?) {
guard let imageView = imageView else {
return
}
syncQueue.sync {
guard let task = activeTasks.removeValue(forKey: imageView) else {
return
}
task.cancel()
}
}
open func load(url: NSURL?, for imageView: UIImageView?) {
load(url: url as URL?, for: imageView)
}
open func load(url: URL?, for imageView: UIImageView?) {
guard let imageView = imageView else {
return
}
guard let url = url else {
cancelTask(for: imageView)
ImageManager.updateImage(nil, for: imageView)
return
}
syncQueue.sync {
if let task = activeTasks.removeValue(forKey: imageView) {
task.cancel()
}
let task = session.dataTask(with: url) { (data, response, error) in
self.syncQueue.sync {
self.activeTasks[imageView] = nil
}
if let error = error {
print("Error loading image from URL (\(url)): \(error)")
ImageManager.updateImage(nil, for: imageView)
} else if let image = data.map({ UIImage(data: $0) }) {
ImageManager.updateImage(image, for: imageView)
} else {
print("Could not load image from URL (\(url)).")
ImageManager.updateImage(nil, for: imageView)
}
}
activeTasks[imageView] = task
task.resume()
}
}
private class func updateImage(_ image: UIImage?, for imageView: UIImageView) {
if OperationQueue.current == OperationQueue.main {
imageView.image = image
} else {
DispatchQueue.main.sync {
imageView.image = image
}
}
}
}
| mit | 9e80a28f805e6892a892894c4dd94984 | 34.235849 | 89 | 0.600268 | 4.986649 | false | false | false | false |
wdkk/CAIM | Basic/answer/caim04_1touch_A/basic/DrawingViewController.swift | 1 | 4137 | //
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
class DrawingViewController : CAIMViewController
{
// view_allを画面いっぱいのピクセル領域(screenPixelRect)の大きさで用意
var view_all:CAIMView = CAIMView(pixelFrame: CAIM.screenPixelRect)
// 画像データimg_allを画面のピクセルサイズ(screenPixelSize)に合わせて用意
var img_all:CAIMImage = CAIMImage(size: CAIM.screenPixelSize)
// 起動時に1度だけ呼ばれる(準備)
override func setup() {
// img_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// view_allの画像として、img_allを設定する
view_all.image = img_all
// view_allを画面に追加
self.view.addSubview( view_all )
/*
// view_all上のタッチ開始時の処理として、touchPressedOnView関数を指定
view_all.touchPressed = self.touchPressedOnView
// view_all上のタッチ移動時の処理として、touchMovedOnView関数を指定
view_all.touchMoved = self.touchMovedOnView
// view_all上のタッチ終了時の処理として、touchReleasedOnView関数を指定
view_all.touchReleased = self.touchReleasedOnView
*/
// view_all上のタッチ移動時の処理に、マルチタッチ対応したmultiTouchMovedOnView関数を指定
view_all.touchMoved = self.multiTouchMovedOnView
}
// viewのタッチ開始の時に呼び出す関数
func touchPressedOnView() {
// view_all上でのタッチ座標の1つ目を取得し、posに代入
let pos = view_all.touchPixelPos[0]
// posの位置に青円を描く
ImageToolBox.fillCircle(img_all, cx: Int(pos.x), cy: Int(pos.y), radius: 20,
color: CAIMColor(R: 0.0, G: 0.0, B: 1.0, A: 1.0), opacity: 1.0)
// 画像の内容を更新したので、view_allの表示も更新する
view_all.redraw()
}
// viewをタッチして指でなぞった時に呼び出す関数
func touchMovedOnView() {
// view_all上でのタッチ座標の1つ目を取得し、posに代入
let pos = view_all.touchPixelPos[0]
// posの位置に薄い赤円を描く
ImageToolBox.fillCircle(img_all, cx: Int(pos.x), cy: Int(pos.y), radius: 20,
color: CAIMColor(R: 1.0, G: 0.0, B: 0.0, A: 1.0), opacity: 0.2)
// 画像の内容を更新したので、view_allの表示も更新する
view_all.redraw()
}
// 指を離した時に呼ばれる
func touchReleasedOnView() {
// view_all上でのリリース座標の1つ目を取得し、posに代入
let pos = view_all.releasePixelPos[0]
// posの位置に緑円を描く
ImageToolBox.fillCircle(img_all, cx: Int(pos.x), cy: Int(pos.y), radius: 20,
color: CAIMColor(R: 0.0, G: 1.0, B: 0.0, A: 1.0), opacity: 1.0)
// 画像の内容を更新したので、view_allの表示も更新する
view_all.redraw()
}
// 指でなぞった時に呼ばれる
func multiTouchMovedOnView() {
// タッチしている指の数を取得
let count = view_all.touchPixelPos.count
// タッチしている指すべての位置を取得して、円を描く
for i in 0 ..< count {
// i本目の指のタッチ位置のピクセル座標posを取得
let pos = view_all.touchPixelPos[i]
// posの位置に薄い赤円を描く
ImageToolBox.fillCircle( img_all, cx: Int(pos.x), cy: Int(pos.y), radius: 20,
color: CAIMColor(R: 1.0, G: 0.0, B: 0.0, A: 1.0), opacity: 0.2)
}
// 画像の内容を更新したので、view_allの表示も更新する
view_all.redraw()
}
}
| mit | 8c5c9d981ba64d7501256663feb8dbe6 | 32.34375 | 89 | 0.611684 | 2.873429 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Shepard Tab/Shepard/ShepardPhotoFrameBorderView.swift | 1 | 854 | //
// ShepardPhotoFrameBorderView.swift
// MEGameTracker
//
// Created by Emily Ivie on 1/19/20.
// Copyright © 2020 Emily Ivie. All rights reserved.
//
import UIKit
@IBDesignable
class ShepardPhotoFrameBorderView: UIView {
@IBInspectable var cornerRadius: CGFloat = 10
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let maskLayer = CAShapeLayer()
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: [.topLeft, .topRight, .bottomLeft],
cornerRadii: CGSize(width: cornerRadius, height: 0.0))
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
}
| mit | af83c0327c3f81e319d1881e1bc24405 | 25.65625 | 90 | 0.603751 | 4.610811 | false | false | false | false |
nProdanov/FuelCalculator | Fuel economy smart calc./Fuel economy smart calc./GasStation.swift | 1 | 790 | //
// GasStation.swift
// Fuel economy smart calc.
//
// Created by Nikolay Prodanow on 3/27/17.
// Copyright © 2017 Nikolay Prodanow. All rights reserved.
//
import Foundation
class GasStation: NSObject
{
var address: String
var brandName: String
var city: String
var id: Int
var latitude: Double
var longtitude: Double
var name: String
var fullName: String {
return "\(brandName) \(name)"
}
init(address: String, brandName: String, city: String, id: Int, latitude: Double, longtitude: Double, name: String){
self.address = address
self.brandName = brandName
self.city = city
self.id = id
self.latitude = latitude
self.longtitude = longtitude
self.name = name
}
}
| mit | 09b6b23475cc26670f3dd1636b4f56fd | 22.205882 | 120 | 0.624842 | 4.06701 | false | false | false | false |
higherdotteam/kidbank | iOS/KidBank/FirstViewController.swift | 1 | 1614 | //
// FirstViewController.swift
// KidBank
//
// Created by A Arrow on 2/3/17.
// Copyright © 2017 higher.team. All rights reserved.
//
import UIKit
import MapKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// https://www.raywenderlich.com/146436/augmented-reality-ios-tutorial-location-based-2
var map: MKMapView?
map = super.view as! MKMapView?
NSLog("\(map)")
map!.mapType = MKMapType.standard
}
override func viewDidAppear(_ animated: Bool) {
var map: MKMapView?
map = super.view as! MKMapView?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let svc = appDelegate.window?.rootViewController?.childViewControllers[0] as! SecondViewController
var first : Bool
first = true
for (thing) in svc.listOfAtms {
let lat = thing["lat"] as! Double
let lon = thing["lon"] as! Double
let location = CLLocationCoordinate2DMake(lat, lon)
let annotation = PlaceAnnotation(location: location, title: "ATM")
map!.addAnnotation(annotation)
if first {
let span = MKCoordinateSpan(latitudeDelta: 0.014, longitudeDelta: 0.014)
let region = MKCoordinateRegion(center: location, span: span)
map!.region = region
first = false
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 8e2dbe7f4e15c90ed09c9e9f927c6d19 | 27.803571 | 106 | 0.596404 | 4.873112 | false | false | false | false |
jtbandes/swift | test/SILGen/generic_casts.swift | 10 | 10137 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s
protocol ClassBound : class {}
protocol NotClassBound {}
class C : ClassBound, NotClassBound {}
struct S : NotClassBound {}
struct Unloadable : NotClassBound { var x : NotClassBound }
// CHECK-LABEL: sil hidden @_T013generic_casts020opaque_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F
func opaque_archetype_to_opaque_archetype
<T:NotClassBound, U>(_ t:T) -> U {
return t as! U
// CHECK: bb0([[RET:%.*]] : $*U, {{%.*}}: $*T):
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to U in [[RET]] : $*U
}
// CHECK-LABEL: sil hidden @_T013generic_casts020opaque_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F
func opaque_archetype_is_opaque_archetype
<T:NotClassBound, U>(_ t:T, u:U.Type) -> Bool {
return t is U
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : $*T to U in [[DEST:%.*]] : $*U, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[Y:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: destroy_addr [[DEST]]
// CHECK: br [[CONT:bb[0-9]+]]([[Y]] : $Builtin.Int1)
// CHECK: [[NO]]:
// CHECK: [[N:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: br [[CONT]]([[N]] : $Builtin.Int1)
// CHECK: [[CONT]]([[I1:%.*]] : $Builtin.Int1):
// -- apply the _getBool library fn
// CHECK-NEXT: function_ref Swift._getBool
// CHECK-NEXT: [[GETBOOL:%.*]] = function_ref @_T0s8_getBoolSbBi1_F :
// CHECK-NEXT: [[RES:%.*]] = apply [[GETBOOL]]([[I1]])
// -- we don't consume the checked value
// CHECK: return [[RES]] : $Bool
}
// CHECK-LABEL: sil hidden @_T013generic_casts026opaque_archetype_to_class_D0{{[_0-9a-zA-Z]*}}F
func opaque_archetype_to_class_archetype
<T:NotClassBound, U:ClassBound> (_ t:T) -> U {
return t as! U
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U
// CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*U
// CHECK: return [[DOWNCAST]] : $U
}
// CHECK-LABEL: sil hidden @_T013generic_casts026opaque_archetype_is_class_D0{{[_0-9a-zA-Z]*}}F
func opaque_archetype_is_class_archetype
<T:NotClassBound, U:ClassBound> (_ t:T, u:U.Type) -> Bool {
return t is U
// CHECK: copy_addr {{.*}} : $*T
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to U
}
// CHECK-LABEL: sil hidden @_T013generic_casts019class_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F
func class_archetype_to_class_archetype
<T:ClassBound, U:ClassBound>(_ t:T) -> U {
return t as! U
// Error bridging can change the identity of class-constrained archetypes.
// CHECK-objc: unconditional_checked_cast_addr {{.*}} T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U
// CHECK-objc: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]]
// CHECK-objc: return [[DOWNCAST]] : $U
// CHECK-native: [[DOWNCAST:%.*]] = unconditional_checked_cast {{.*}} : $T to $U
}
// CHECK-LABEL: sil hidden @_T013generic_casts019class_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F
func class_archetype_is_class_archetype
<T:ClassBound, U:ClassBound>(_ t:T, u:U.Type) -> Bool {
return t is U
// Error bridging can change the identity of class-constrained archetypes.
// CHECK-objc: checked_cast_addr_br {{.*}} T in {{%.*}} : $*T to U in {{%.*}} : $*U
// CHECK-native: checked_cast_br {{.*}} : $T to $U
}
// CHECK-LABEL: sil hidden @_T013generic_casts38opaque_archetype_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F
func opaque_archetype_to_addr_only_concrete
<T:NotClassBound> (_ t:T) -> Unloadable {
return t as! Unloadable
// CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*T):
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to Unloadable in [[RET]] : $*Unloadable
}
// CHECK-LABEL: sil hidden @_T013generic_casts38opaque_archetype_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F
func opaque_archetype_is_addr_only_concrete
<T:NotClassBound> (_ t:T) -> Bool {
return t is Unloadable
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to Unloadable in
}
// CHECK-LABEL: sil hidden @_T013generic_casts37opaque_archetype_to_loadable_concrete{{[_0-9a-zA-Z]*}}F
func opaque_archetype_to_loadable_concrete
<T:NotClassBound>(_ t:T) -> S {
return t as! S
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to S in [[DOWNCAST_ADDR:%.*]] : $*S
// CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S
// CHECK: return [[DOWNCAST]] : $S
}
// CHECK-LABEL: sil hidden @_T013generic_casts37opaque_archetype_is_loadable_concrete{{[_0-9a-zA-Z]*}}F
func opaque_archetype_is_loadable_concrete
<T:NotClassBound>(_ t:T) -> Bool {
return t is S
// CHECK: checked_cast_addr_br take_always T in {{%.*}} : $*T to S in
}
// CHECK-LABEL: sil hidden @_T013generic_casts019class_archetype_to_C0{{[_0-9a-zA-Z]*}}F
func class_archetype_to_class
<T:ClassBound>(_ t:T) -> C {
return t as! C
// CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to $C
// CHECK: return [[DOWNCAST]] : $C
}
// CHECK-LABEL: sil hidden @_T013generic_casts019class_archetype_is_C0{{[_0-9a-zA-Z]*}}F
func class_archetype_is_class
<T:ClassBound>(_ t:T) -> Bool {
return t is C
// CHECK: checked_cast_br {{%.*}} to $C
}
// CHECK-LABEL: sil hidden @_T013generic_casts022opaque_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F
func opaque_existential_to_opaque_archetype
<T:NotClassBound>(_ p:NotClassBound) -> T {
return p as! T
// CHECK: bb0([[RET:%.*]] : $*T, [[ARG:%.*]] : $*NotClassBound):
// CHECK: [[TEMP:%.*]] = alloc_stack $NotClassBound
// CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[TEMP]]
// CHECK-NEXT: unconditional_checked_cast_addr take_always NotClassBound in [[TEMP]] : $*NotClassBound to T in [[RET]] : $*T
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: destroy_addr [[ARG]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]]
}
// CHECK-LABEL: sil hidden @_T013generic_casts022opaque_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F
func opaque_existential_is_opaque_archetype
<T:NotClassBound>(_ p:NotClassBound, _: T) -> Bool {
return p is T
// CHECK: checked_cast_addr_br take_always NotClassBound in [[CONTAINER:%.*]] : {{.*}} to T in
}
// CHECK-LABEL: sil hidden @_T013generic_casts37opaque_existential_to_class_archetype{{[_0-9a-zA-Z]*}}F
func opaque_existential_to_class_archetype
<T:ClassBound>(_ p:NotClassBound) -> T {
return p as! T
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T
// CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*T
// CHECK: return [[DOWNCAST]] : $T
}
// CHECK-LABEL: sil hidden @_T013generic_casts37opaque_existential_is_class_archetype{{[_0-9a-zA-Z]*}}F
func opaque_existential_is_class_archetype
<T:ClassBound>(_ p:NotClassBound, _: T) -> Bool {
return p is T
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to T in
}
// CHECK-LABEL: sil hidden @_T013generic_casts021class_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F
func class_existential_to_class_archetype
<T:ClassBound>(_ p:ClassBound) -> T {
return p as! T
// CHECK-objc: unconditional_checked_cast_addr {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T
// CHECK-objc: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]]
// CHECK-objc: return [[DOWNCAST]] : $T
// CHECK-native: [[DOWNCAST:%.*]] = unconditional_checked_cast {{.*}} : $ClassBound to $T
}
// CHECK-LABEL: sil hidden @_T013generic_casts021class_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F
func class_existential_is_class_archetype
<T:ClassBound>(_ p:ClassBound, _: T) -> Bool {
return p is T
// CHECK-objc: checked_cast_addr_br {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in {{%.*}} : $*T
// CHECK-native: checked_cast_br {{.*}} : $ClassBound to $T
}
// CHECK-LABEL: sil hidden @_T013generic_casts40opaque_existential_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F
func opaque_existential_to_addr_only_concrete(_ p: NotClassBound) -> Unloadable {
return p as! Unloadable
// CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*NotClassBound):
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in [[RET]] : $*Unloadable
}
// CHECK-LABEL: sil hidden @_T013generic_casts40opaque_existential_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F
func opaque_existential_is_addr_only_concrete(_ p: NotClassBound) -> Bool {
return p is Unloadable
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in
}
// CHECK-LABEL: sil hidden @_T013generic_casts39opaque_existential_to_loadable_concrete{{[_0-9a-zA-Z]*}}F
func opaque_existential_to_loadable_concrete(_ p: NotClassBound) -> S {
return p as! S
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to S in [[DOWNCAST_ADDR:%.*]] : $*S
// CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S
// CHECK: return [[DOWNCAST]] : $S
}
// CHECK-LABEL: sil hidden @_T013generic_casts39opaque_existential_is_loadable_concrete{{[_0-9a-zA-Z]*}}F
func opaque_existential_is_loadable_concrete(_ p: NotClassBound) -> Bool {
return p is S
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to S in
}
// CHECK-LABEL: sil hidden @_T013generic_casts021class_existential_to_C0{{[_0-9a-zA-Z]*}}F
func class_existential_to_class(_ p: ClassBound) -> C {
return p as! C
// CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to $C
// CHECK: return [[DOWNCAST]] : $C
}
// CHECK-LABEL: sil hidden @_T013generic_casts021class_existential_is_C0{{[_0-9a-zA-Z]*}}F
func class_existential_is_class(_ p: ClassBound) -> Bool {
return p is C
// CHECK: checked_cast_br {{%.*}} to $C
}
// CHECK-LABEL: sil hidden @_T013generic_casts27optional_anyobject_to_classAA1CCSgyXlSgF
// CHECK: checked_cast_br {{%.*}} : $AnyObject to $C
func optional_anyobject_to_class(_ p: AnyObject?) -> C? {
return p as? C
}
| apache-2.0 | 38f57cc27ab8d589da0dbe6c91244766 | 44.457399 | 146 | 0.64309 | 3.201832 | false | false | false | false |
sascha/DrawerController | KitchenSink/ExampleFiles/AppDelegate.swift | 1 | 5435 | // Copyright (c) 2017 evolved.io (http://evolved.io)
//
// 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 DrawerController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var drawerController: DrawerController!
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let leftSideDrawerViewController = ExampleLeftSideDrawerViewController()
let centerViewController = ExampleCenterTableViewController()
let rightSideDrawerViewController = ExampleRightSideDrawerViewController()
let navigationController = UINavigationController(rootViewController: centerViewController)
navigationController.restorationIdentifier = "ExampleCenterNavigationControllerRestorationKey"
let rightSideNavController = UINavigationController(rootViewController: rightSideDrawerViewController)
rightSideNavController.restorationIdentifier = "ExampleRightNavigationControllerRestorationKey"
let leftSideNavController = UINavigationController(rootViewController: leftSideDrawerViewController)
leftSideNavController.restorationIdentifier = "ExampleLeftNavigationControllerRestorationKey"
self.drawerController = DrawerController(centerViewController: navigationController, leftDrawerViewController: leftSideNavController, rightDrawerViewController: rightSideNavController)
self.drawerController.showsShadows = false
self.drawerController.restorationIdentifier = "Drawer"
self.drawerController.maximumRightDrawerWidth = 200.0
self.drawerController.openDrawerGestureModeMask = .all
self.drawerController.closeDrawerGestureModeMask = .all
self.drawerController.drawerVisualStateBlock = { (drawerController, drawerSide, fractionVisible) in
let block = ExampleDrawerVisualStateManager.sharedManager.drawerVisualStateBlock(for: drawerSide)
block?(drawerController, drawerSide, fractionVisible)
}
self.window = UIWindow(frame: UIScreen.main.bounds)
let tintColor = UIColor(red: 29 / 255, green: 173 / 255, blue: 234 / 255, alpha: 1.0)
self.window?.tintColor = tintColor
self.window?.rootViewController = self.drawerController
return true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window?.backgroundColor = UIColor.white
self.window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
if let key = identifierComponents.last as? String {
if key == "Drawer" {
return self.window?.rootViewController
} else if key == "ExampleCenterNavigationControllerRestorationKey" {
return (self.window?.rootViewController as! DrawerController).centerViewController
} else if key == "ExampleRightNavigationControllerRestorationKey" {
return (self.window?.rootViewController as! DrawerController).rightDrawerViewController
} else if key == "ExampleLeftNavigationControllerRestorationKey" {
return (self.window?.rootViewController as! DrawerController).leftDrawerViewController
} else if key == "ExampleLeftSideDrawerController" {
if let leftVC = (self.window?.rootViewController as? DrawerController)?.leftDrawerViewController {
if leftVC.isKind(of: UINavigationController.self) {
return (leftVC as! UINavigationController).topViewController
} else {
return leftVC
}
}
} else if key == "ExampleRightSideDrawerController" {
if let rightVC = (self.window?.rootViewController as? DrawerController)?.rightDrawerViewController {
if rightVC.isKind(of: UINavigationController.self) {
return (rightVC as! UINavigationController).topViewController
} else {
return rightVC
}
}
}
}
return nil
}
}
| mit | b96edc827f40a41efe46309c73fa56d8 | 46.675439 | 188 | 0.756394 | 5.769639 | false | false | false | false |
lucasmpaim/EasyRest | Sources/EasyRest/Classes/AuthenticableService.swift | 1 | 2106 | //
// AuthenticableService.swift
// Pods
//
// Created by Vithorio Polten on 3/25/16.
// Base on Tof Template
//
//
import Foundation
open class AuthenticableService<Auth: Authentication, R: Routable> : Service<R>, Authenticable {
var authenticator = Auth()
public override init() { super.init() }
open func getAuthenticator() -> Auth {
return authenticator
}
open override func builder<T : Codable>(_ routes: R, type: T.Type) throws -> APIBuilder<T> {
let builder = try super.builder(routes, type: type)
_ = builder.addInterceptor(authenticator.interceptor)
return builder
}
override open func call<E: Codable>(_ routes: R, type: E.Type, onSuccess: @escaping (Response<E>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) throws -> CancelationToken<E> {
let builder = try self.builder(routes, type: type)
if routes.rule.isAuthenticable && authenticator.getToken() == nil {
throw RestError(rawValue: RestErrorType.authenticationRequired.rawValue)
}
let token = CancelationToken<E>()
builder.cancelToken(token: token).build().execute(onSuccess, onError: onError, always: always)
return token
}
override open func upload<E: Codable>(_ routes: R, type: E.Type,
onProgress: @escaping (Float) -> Void,
onSuccess: @escaping (Response<E>?) -> Void,
onError: @escaping (RestError?) -> Void,
always: @escaping () -> Void) throws {
let builder = try self.builder(routes, type: type)
if routes.rule.isAuthenticable && authenticator.getToken() == nil {
throw RestError(rawValue: RestErrorType.authenticationRequired.rawValue)
}
builder.build().upload(
onProgress,
onSuccess: onSuccess,
onError: onError,
always: always)
}
}
| mit | 5276b72900a1a99ba288d8e17c6d171d | 34.694915 | 214 | 0.575973 | 4.618421 | false | false | false | false |
henriquecfreitas/diretop | Diretop/ViewController.swift | 1 | 2796 | //
// ViewController.swift
// Diretop
//
// Created by Henrique on 21/04/17.
// Copyright © 2017 Henrique. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
var bottomConstraintValue: CGFloat = 0
@IBOutlet weak var listContainer: UIView!
@IBOutlet weak var inputText: UITextField!
var embeddedViewController: ListPageController!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let childViewController = segue.destination as? ListPageController
if (segue.identifier == "delegationsListEmbedSegue") {
self.embeddedViewController = childViewController!
}
}
override func viewDidLoad() {
super.viewDidLoad()
bottomConstraintValue = bottomConstraint.constant
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
listContainer.addGestureRecognizer(tap)
}
deinit {
NotificationCenter.default.removeObserver(self);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func keyboardShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let tabBar = self.tabBarController?.tabBar
let tabBarHeight = tabBar?.frame.size.height
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.bottomConstraint.constant = self.bottomConstraintValue + keyboardFrame.size.height - tabBarHeight!
})
}
@objc func keyboardHide(notification: NSNotification) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.bottomConstraint.constant = self.bottomConstraintValue
})
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func addButton(_ sender: Any) {
let itenToInsert = inputText.text
if (itenToInsert?.isEmpty == false){
embeddedViewController.dataSource.addItenToDts(iten: itenToInsert!)
embeddedViewController.updateDataSource()
inputText.text = ""
}
}
}
| gpl-3.0 | 7a83cf7353d8f59632d6c722d5451040 | 34.833333 | 161 | 0.679785 | 5.243902 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/Optimizer/DataStructures/InstructionRange.swift | 3 | 5590 | //===--- InstructionRange.swift - a range of instructions -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// A range of instructions.
///
/// The `InstructionRange` defines a range from a dominating "begin" instruction to one or more "end" instructions.
/// The range is "exclusive", which means that the "end" instructions are not part of the range.
///
/// One or more "potential" end instructions can be inserted.
/// Though, not all inserted instructions end up as "end" instructions.
///
/// `InstructionRange` is useful for calculating the liferange of values.
///
/// The `InstructionRange` is similar to a `BasicBlockRange`, but defines the range
/// in a "finer" granularity, i.e. on instructions instead of blocks.
/// `InstructionRange` uses an underlying `BasicBlockRange` to compute the
/// involved blocks of the instruction range.
///
/// There are several kind of instructions:
/// * begin: it is a single instruction which dominates all instructions of the range
/// * ends: all inserted instruction which are at the end of the range
/// * exits: the first instructions of the exit blocks
/// * interiors: all inserted instructions which are not end instructions.
///
/// See also `BasicBlockRange` for more information.
///
/// This type should be a move-only type, but unfortunately we don't have move-only
/// types yet. Therefore it's needed to call `deinitialize()` explicitly to
/// destruct this data structure, e.g. in a `defer {}` block.
struct InstructionRange : CustomStringConvertible, CustomReflectable {
/// The dominating begin instruction.
let begin: Instruction
/// The underlying block range.
private(set) var blockRange: BasicBlockRange
private var insertedInsts: InstructionSet
init(begin beginInst: Instruction, _ context: PassContext) {
self.begin = beginInst
self.blockRange = BasicBlockRange(begin: beginInst.block, context)
self.insertedInsts = InstructionSet(context)
}
/// Insert a potential end instruction.
mutating func insert(_ inst: Instruction) {
insertedInsts.insert(inst)
blockRange.insert(inst.block)
}
/// Insert a sequence of potential end instructions.
mutating func insert<S: Sequence>(contentsOf other: S) where S.Element == Instruction {
for inst in other {
insert(inst)
}
}
/// Returns true if the exclusive range contains `inst`.
func contains(_ inst: Instruction) -> Bool {
let block = inst.block
if !blockRange.inclusiveRangeContains(block) { return false }
var inRange = false
if blockRange.contains(block) {
if block != blockRange.begin { return true }
inRange = true
}
for i in block.instructions.reversed() {
if i == inst { return inRange }
if insertedInsts.contains(i) { inRange = true }
if i == begin { return false }
}
fatalError("didn't find instruction in its block")
}
/// Returns true if the inclusive range contains `inst`.
func inclusiveRangeContains (_ inst: Instruction) -> Bool {
contains(inst) || insertedInsts.contains(inst)
}
/// Returns true if the range is valid and that's iff the begin instruction
/// dominates all instructions of the range.
var isValid: Bool {
blockRange.isValid &&
// Check if there are any inserted instructions before the begin instruction in its block.
!ReverseList(first: begin).dropFirst().contains { insertedInsts.contains($0) }
}
/// Returns the end instructions.
var ends: LazyMapSequence<LazyFilterSequence<Stack<BasicBlock>>, Instruction> {
blockRange.ends.map {
$0.instructions.reversed().first(where: { insertedInsts.contains($0)})!
}
}
/// Returns the exit instructions.
var exits: LazyMapSequence<LazySequence<FlattenSequence<
LazyMapSequence<LazyFilterSequence<Stack<BasicBlock>>,
LazyFilterSequence<SuccessorArray>>>>,
Instruction> {
blockRange.exits.lazy.map { $0.instructions.first! }
}
/// Returns the interior instructions.
var interiors: LazySequence<FlattenSequence<
LazyMapSequence<Stack<BasicBlock>,
LazyFilterSequence<ReverseList<Instruction>>>>> {
blockRange.inserted.lazy.flatMap {
var include = blockRange.contains($0)
return $0.instructions.reversed().lazy.filter {
if insertedInsts.contains($0) {
let isInterior = include
include = true
return isInterior
}
return false
}
}
}
var description: String {
return (isValid ? "" : "<invalid>\n") +
"""
begin: \(begin)
ends: \(ends.map { $0.description }.joined(separator: "\n "))
exits: \(exits.map { $0.description }.joined(separator: "\n "))
interiors:\(interiors.map { $0.description }.joined(separator: "\n "))
"""
}
var customMirror: Mirror { Mirror(self, children: []) }
/// TODO: once we have move-only types, make this a real deinit.
mutating func deinitialize() {
insertedInsts.deinitialize()
blockRange.deinitialize()
}
}
| apache-2.0 | 25a355b0aeb453a26df28e63decf0d5c | 36.516779 | 115 | 0.659571 | 4.472 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Settings/SettingsLinkTableCell.swift | 1 | 3899 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireCommonComponents
final class SettingsLinkTableCell: SettingsTableCellProtocol {
// MARK: - Properties
private let cellLinkLabel = CopyableLabel()
private let cellNameLabel: UILabel = {
let label = DynamicFontLabel(
fontSpec: .normalSemiboldFont,
color: .textForeground)
label.textColor = SemanticColors.Label.textDefault
label.numberOfLines = 0
label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
label.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
label.adjustsFontSizeToFitWidth = true
return label
}()
var titleText: String = "" {
didSet {
cellNameLabel.text = titleText
}
}
var linkText: NSAttributedString? {
didSet {
cellLinkLabel.attributedText = linkText
}
}
var preview: SettingsCellPreview = .none
var icon: StyleKitIcon?
var descriptor: SettingsCellDescriptorType?
// MARK: - Logic
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
private func setup() {
backgroundView = UIView()
selectedBackgroundView = UIView()
[cellNameLabel, cellLinkLabel].forEach {
contentView.addSubview($0)
}
cellLinkLabel.textColor = SemanticColors.Label.textDefault
cellLinkLabel.font = FontSpec(.normal, .light).font
cellLinkLabel.numberOfLines = 0
cellLinkLabel.lineBreakMode = .byClipping
createConstraints()
setupAccessibility()
backgroundView?.backgroundColor = SemanticColors.View.backgroundDefault
}
private func createConstraints() {
let leadingConstraint = cellNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16)
leadingConstraint.priority = .defaultHigh
[cellNameLabel, cellLinkLabel].prepareForLayout()
NSLayoutConstraint.activate([
leadingConstraint,
cellNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
cellNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
cellNameLabel.heightAnchor.constraint(equalToConstant: 32),
cellLinkLabel.topAnchor.constraint(equalTo: cellNameLabel.bottomAnchor, constant: 12),
cellLinkLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
cellLinkLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
cellLinkLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 112)
])
}
private func setupAccessibility() {
isAccessibilityElement = true
accessibilityTraits = .staticText
}
}
| gpl-3.0 | 3d387d060bf7c7d6727519021bccf6ae | 32.612069 | 120 | 0.694794 | 5.363136 | false | false | false | false |
twostraws/HackingWithSwift | Classic/project35.playground/Contents.swift | 1 | 2205 | //: Playground - noun: a place where people can play
import GameplayKit
import UIKit
print(arc4random())
print(arc4random())
print(arc4random())
print(arc4random())
print(arc4random() % 6)
print(arc4random_uniform(6))
func RandomInt(min: Int, max: Int) -> Int {
if max < min { return min }
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
print(RandomInt(min: 0, max: 6))
print(GKRandomSource.sharedRandom().nextInt())
print(GKRandomSource.sharedRandom().nextInt(upperBound: 6))
let arc4 = GKARC4RandomSource()
arc4.dropValues(1024)
arc4.nextInt(upperBound: 20)
let mersenne = GKMersenneTwisterRandomSource()
mersenne.nextInt(upperBound: 20)
let d6 = GKRandomDistribution.d6()
d6.nextInt()
let d20 = GKRandomDistribution.d20()
d20.nextInt()
let crazy = GKRandomDistribution(lowestValue: 1, highestValue: 11539)
crazy.nextInt()
// the below will cause a crash because we request a random number outside the range!
//let distribution = GKRandomDistribution(lowestValue: 10, highestValue: 20)
//print(distribution.nextInt(upperBound: 9))
let rand = GKMersenneTwisterRandomSource()
let distribution = GKRandomDistribution(randomSource: rand, lowestValue: 10, highestValue: 20)
print(distribution.nextInt())
let shuffled = GKShuffledDistribution.d6()
print(shuffled.nextInt())
print(shuffled.nextInt())
print(shuffled.nextInt())
print(shuffled.nextInt())
print(shuffled.nextInt())
print(shuffled.nextInt())
extension Array {
mutating func shuffle() {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swapAt(i, j)
}
}
}
let lotteryBalls = [Int](1...49)
let shuffledBalls = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: lotteryBalls)
print(shuffledBalls[0])
print(shuffledBalls[1])
print(shuffledBalls[2])
print(shuffledBalls[3])
print(shuffledBalls[4])
print(shuffledBalls[5])
let fixedLotteryBalls = [Int](1...49)
let fixedShuffledBalls = GKMersenneTwisterRandomSource(seed: 1001).arrayByShufflingObjects(in: fixedLotteryBalls)
print(fixedShuffledBalls[0])
print(fixedShuffledBalls[1])
print(fixedShuffledBalls[2])
print(fixedShuffledBalls[3])
print(fixedShuffledBalls[4])
print(fixedShuffledBalls[5])
| unlicense | 50cc32156d769ff411aedad0363738e9 | 23.775281 | 113 | 0.75737 | 3.295964 | false | false | false | false |
burla69/PayDay | PayDay/QRScanningViewController.swift | 1 | 7923 | //
// QRScanningViewController.swift
// PayDay
//
// Created by Oleksandr Burla on 3/15/16.
// Copyright © 2016 Oleksandr Burla. All rights reserved.
//
import UIKit
import AVFoundation
protocol QRScanningViewControllerDelegate {
func qrCodeFromQRViewController(string: String)
func goFromQRCode()
}
class QRScanningViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var cameraView: UIView!
var delegate: QRScanningViewControllerDelegate!
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var qrCodeFrameView: UIView?
var isFrontCamera = true
override func viewDidLoad() {
super.viewDidLoad()
guard
let captureDevice = (AVCaptureDevice.devices()
.filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back})
.first as? AVCaptureDevice
else { return }
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code]
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155)
cameraView.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor
qrCodeFrameView.layer.borderWidth = 3
cameraView.addSubview(qrCodeFrameView)
cameraView.bringSubviewToFront(qrCodeFrameView)
}
} catch {
print(error)
return
}
isFrontCamera = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if metadataObjects == nil || metadataObjects.count == 0 {
qrCodeFrameView?.frame = CGRectZero
print("QR Code is not detected")
return
}
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj)
qrCodeFrameView?.frame = barCodeObject!.bounds
var token: dispatch_once_t = 0
dispatch_once(&token) {
if metadataObj.stringValue != nil {
print("QR code\(metadataObj.stringValue)")
self.delegate.qrCodeFromQRViewController(metadataObj.stringValue)
}
self.dismissViewControllerAnimated(true, completion: {
self.delegate.goFromQRCode()
})
}
}
@IBAction func useKeyPadPressed(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func changeCamera(sender: AnyObject) {
if isFrontCamera {
guard
let captureDevice = (AVCaptureDevice.devices()
.filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back})
.first as? AVCaptureDevice
else { return }
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code]
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155)
cameraView.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor
qrCodeFrameView.layer.borderWidth = 3
cameraView.addSubview(qrCodeFrameView)
cameraView.bringSubviewToFront(qrCodeFrameView)
}
} catch {
print(error)
return
}
isFrontCamera = false
} else {
guard
let captureDevice = (AVCaptureDevice.devices()
.filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Front})
.first as? AVCaptureDevice
else { return }
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code]
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155)
cameraView.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor
qrCodeFrameView.layer.borderWidth = 3
cameraView.addSubview(qrCodeFrameView)
cameraView.bringSubviewToFront(qrCodeFrameView)
}
} catch {
print(error)
return
}
isFrontCamera = true
}
}
}
| mit | 9c2e8e94b35040cce5a49c25ac115c60 | 35.33945 | 162 | 0.577001 | 6.955224 | false | false | false | false |
CoderVan/iOS-Learning-materials | RacTest/Pods/ReactiveSwift/Sources/Flatten.swift | 5 | 34725 | //
// Flatten.swift
// ReactiveSwift
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case merge
/// The producers should be concatenated, so that their values are sent in
/// the order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed
/// of.
///
/// The resulting producer will complete only when the producer-of-producers
/// and the latest producer has completed.
case latest
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - note: `interrupted` events on inner producers will be treated like
/// `Completed events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner signal emits an error, the
/// returned signal will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned signal
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: Sequence {
/// Flattens the `sequence` value sent by `signal`.
public func flatten() -> Signal<Value.Iterator.Element, Error> {
return self.flatMap(.merge, transform: SignalProducer.init)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner signal emits an error, the
/// returned producer will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned producer
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` emits an error, the returned producer will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: Sequence {
/// Flattens the `sequence` value sent by `signal`.
public func flatten() -> SignalProducer<Value.Iterator.Element, Error> {
return self.flatMap(.merge, transform: SignalProducer.init)
}
}
extension SignalProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProducerProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted
/// from `signal`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers fail, the returned signal will
/// forward that failure immediately
///
/// - note: The returned signal completes only when `signal` and all
/// producers emitted from `signal` complete.
fileprivate func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeConcat(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = Atomic(ConcatState<Value.Value, Error>())
func startNextIfNeeded() {
while let producer = state.modify({ $0.dequeue() }) {
producer.startWithSignal { signal, inner in
let handle = disposable?.add(inner)
signal.observe { event in
switch event {
case .completed, .interrupted:
handle?.remove()
let shouldStart: Bool = state.modify {
$0.active = nil
return !$0.isStarting
}
if shouldStart {
startNextIfNeeded()
}
case .value, .failed:
observer.action(event)
}
}
}
state.modify { $0.isStarting = false }
}
}
return observe { event in
switch event {
case let .value(value):
state.modify { $0.queue.append(value.producer) }
startNextIfNeeded()
case let .failed(error):
observer.send(error: error)
case .completed:
state.modify { state in
state.queue.append(SignalProducer.empty.on(completed: observer.sendCompleted))
}
startNextIfNeeded()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted
/// from `producer`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers emit an error, the returned
/// producer will emit that error.
///
/// - note: The returned producer completes only when `producer` and all
/// producers emitted from `producer` complete.
fileprivate func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerProtocol {
/// `concat`s `next` onto `self`.
public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>([ self.producer, next ]).flatten(.concat)
}
/// `concat`s `value` onto `self`.
public func concat(value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
public func prefix<P: SignalProducerProtocol>(_ previous: P) -> SignalProducer<Value, Error>
where P.Value == Value, P.Error == Error
{
return previous.concat(self.producer)
}
/// `concat`s `self` onto initial `value`.
public func prefix(value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcatState<Value, Error: Swift.Error> {
typealias SignalProducer = ReactiveSwift.SignalProducer<Value, Error>
/// The active producer, if any.
var active: SignalProducer? = nil
/// The producers waiting to be started.
var queue: [SignalProducer] = []
/// Whether the active producer is currently starting.
/// Used to prevent deep recursion.
var isStarting: Bool = false
/// Dequeue the next producer if one should be started.
///
/// - note: The caller *must* set `isStarting` to false after the returned
/// producer has been started.
///
/// - returns: The `SignalProducer` to start or `nil` if no producer should
/// be started.
func dequeue() -> SignalProducer? {
if active != nil {
return nil
}
active = queue.first
if active != nil {
queue.removeFirst()
isStarting = true
}
return active
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeMerge(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let shouldComplete: Bool = inFlight.modify {
$0 -= 1
return $0 == 0
}
if shouldComplete {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .value(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 += 1 }
let handle = disposable.add(innerDisposable)
innerSignal.observe { event in
switch event {
case .completed, .interrupted:
handle.remove()
decrementInFlight()
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
decrementInFlight()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalProtocol {
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<Seq: Sequence, S: SignalProtocol>(_ signals: Seq) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer<S, Error>(signals)
.flatten(.merge)
.startAndRetrieveSignal()
}
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<S: SignalProtocol>(_ signals: S...) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error
{
return Signal.merge(signals)
}
}
extension SignalProducerProtocol {
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<Seq: Sequence, S: SignalProducerProtocol>(_ producers: Seq) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer(producers).flatten(.merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<S: SignalProducerProtocol>(_ producers: S...) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error
{
return SignalProducer.merge(producers)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
fileprivate func observeSwitchToLatest(_ observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .value(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents
// the generated Interrupted event from doing any work.
$0.replacingInnerSignal = true
}
latestInnerDisposable.inner = innerDisposable
state.modify {
$0.replacingInnerSignal = false
$0.innerSignalComplete = false
}
innerSignal.observe { event in
switch event {
case .interrupted:
// If interruption occurred as a result of a new
// producer arriving, we don't want to notify our
// observer.
let shouldComplete: Bool = state.modify { state in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return !state.replacingInnerSignal && state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.innerSignalComplete = true
return $0.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.outerSignalComplete = true
return $0.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable += latestInnerDisposable
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: Swift.Error> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalProtocol {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new property, then flattens the
/// resulting properties (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> Signal<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new property, then flattens the
/// resulting properties (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> SignalProducer<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol {
/// Catches any failure that may occur on the input signal, mapping to a new
/// producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
observer.send(value: value)
case let .failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.inner = disposable
signal.observe(observer)
}
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol {
/// Catches any failure that may occur on the input producer, mapping to a
/// new producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable += serialDisposable
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
_ = signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| apache-2.0 | 9c35ab1b896a4c7553e389962a496ea2 | 35.284222 | 185 | 0.705477 | 4.104977 | false | false | false | false |
AlmostDoneGames/BrickBreaker-iOS | Sprong/CreditScene.swift | 2 | 1089 | //
// CreditScene.swift
// MathBreaker
//
// Created by Cameron Bardell on 2015-11-18.
// Copyright © 2015 Jared McGrath. All rights reserved.
//
import UIKit
import SpriteKit
//Scene for credits
class CreditScene: SKScene {
var backButton = SKLabelNode()
override func didMoveToView(view: SKView) {
backButton = self.childNodeWithName("backButton") as! SKLabelNode
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("test")
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)
//if play button is tapped, begin game
if node.name == "backButton" {
let reveal : SKTransition = SKTransition.doorsOpenHorizontalWithDuration(0.5)
if let scene = MainMenu(fileNamed: "MainMenu"){
scene.scaleMode = .AspectFill
self.view?.presentScene(scene, transition: reveal)
}
}
}
}
} | apache-2.0 | f754f50c1c5b2b6567d6065f7fa00289 | 30.114286 | 93 | 0.602022 | 4.77193 | false | false | false | false |
fandongtongxue/Unsplash | Unsplash/ViewController.swift | 1 | 6424 | //
// ViewController.swift
// Unsplash
//
// Created by 范东 on 17/2/4.
// Copyright © 2017年 范东. All rights reserved.
//
import UIKit
import SDWebImage
import MBProgressHUD
import Alamofire
import MJExtension
let url = "https://api.unsplash.com/photos/?client_id=522f34661134a2300e6d94d344a7ab6424e028a51b31353363b7a8cce11d73b6&per_page=30&page="
let cellId = "UnsplashPictureCellID"
let statusBarHeight : CGFloat = 20
let screenWidth : CGFloat = UIScreen.main.bounds.size.width
let screenHeight : CGFloat = UIScreen.main.bounds.size.height
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
var page : NSInteger = 1
var refreshControl : UIRefreshControl!
//懒加载
lazy var dataArray:NSMutableArray = {
let dataArray = NSMutableArray.init()
return dataArray
}()
lazy var collectionView:UICollectionView = {
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = CGSize.init(width: UIScreen.main.bounds.size.width / 3, height: UIScreen.main.bounds.size.height / 3)
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: screenHeight - statusBarHeight), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.black
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UnsplashPictureCell.self, forCellWithReuseIdentifier:cellId)
return collectionView;
}()
//生命周期
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.black
self.view.addSubview(self.collectionView)
self.initRefresh()
self.requestFirstPageData(isNeedHUD: true)
}
func initRefresh() {
let refreshControl = UIRefreshControl.init()
refreshControl.tintColor = UIColor.white
refreshControl.addTarget(self, action: #selector(requestFirstPageData(isNeedHUD:)), for: UIControlEvents.valueChanged)
self.collectionView.addSubview(refreshControl)
self.refreshControl = refreshControl
self.collectionView.alwaysBounceVertical = true
}
//请求第一页数据
func requestFirstPageData(isNeedHUD : Bool) {
if isNeedHUD {
MBProgressHUD.showAdded(to: self.view, animated: true)
}
page = 1
let firstUrl = url + String.init(format: "%d", page)
log.info("请求地址:"+firstUrl)
Alamofire.request(firstUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON(queue: DispatchQueue.main, options: .mutableContainers) { (response) in
switch response.result{
case .success:
self.dataArray.removeAllObjects()
if let result = response.result.value{
let array = result as! NSMutableArray
let model = UnsplashPictureModel.mj_objectArray(withKeyValuesArray: array) as [AnyObject]
self.dataArray.addObjects(from: model)
self.collectionView.reloadData()
self.refreshControl.endRefreshing()
}
MBProgressHUD.hide(for: self.view, animated: true)
case.failure(let error):
self.refreshControl.endRefreshing()
log.error(error)
MBProgressHUD.hide(for: self.view, animated: true)
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.text
hud.label.text = String.init(format: "%@", error as CVarArg)
hud.label.numberOfLines = 0;
hud.hide(animated: true, afterDelay: 2)
}
}
}
func requestMorePageData(page:NSInteger) {
let firstUrl = url + String.init(format: "%d", page)
log.info("请求地址:"+firstUrl)
Alamofire.request(firstUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON(queue: DispatchQueue.main, options: .mutableContainers) { (response) in
switch response.result{
case .success:
if let result = response.result.value{
let array = result as! NSMutableArray
let model = UnsplashPictureModel.mj_objectArray(withKeyValuesArray: array) as [AnyObject]
self.dataArray.addObjects(from: model)
}
self.collectionView.reloadData()
case.failure(let error):
print(error)
}
}
}
//UICollectionViewDelegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UnsplashPictureCell
let model = self.dataArray[indexPath.row] as! UnsplashPictureModel
cell.setModel(model: model)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let model = self.dataArray[indexPath.row] as! UnsplashPictureModel
let vc = PictureViewController()
vc.model = model
self.present(vc, animated: true, completion: nil)
}
//UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height {
log.info("到底")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
}
| mit | c8ecb242fa9ed98e2616d0a54edd7cfa | 40.331169 | 196 | 0.657345 | 4.984338 | false | false | false | false |
DAloG/BlueCap | BlueCapKit/Utilities/Logger.swift | 1 | 546 | //
// Logger.swift
// BlueCap
//
// Created by Troy Stribling on 6/8/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
public class Logger {
public class func debug(message:String? = nil, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) {
#if DEBUG
if let message = message {
print("\(file):\(function):\(line): \(message)", terminator: "")
} else {
print("\(file):\(function):\(line)", terminator: "")
}
#endif
}
}
| mit | d0018e174742d8ee3aed3e947631de03 | 23.818182 | 132 | 0.565934 | 3.791667 | false | false | false | false |
frootloops/swift | test/type/types.swift | 1 | 7436 | // RUN: %target-typecheck-verify-swift
var a : Int
func test() {
var y : a // expected-error {{use of undeclared type 'a'}}
var z : y // expected-error {{use of undeclared type 'y'}}
var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}}
}
var b : (Int) -> Int = { $0 }
var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}}
var d2 : () -> Int = { 4 }
var d3 : () -> Float = { 4 }
var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}}
var e0 : [Int]
e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>),}}
var f0 : [Float]
var f1 : [(Int,Int)]
var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}}
var h0 : Int?
_ = h0 == nil // no-warning
var h1 : Int??
_ = h1! == nil // no-warning
var h2 : [Int?]
var h3 : [Int]?
var h3a : [[Int?]]
var h3b : [Int?]?
var h4 : ([Int])?
var h5 : ([([[Int??]])?])?
var h7 : (Int,Int)?
var h8 : ((Int) -> Int)?
var h9 : (Int?) -> Int?
var h10 : Int?.Type?.Type
var i = Int?(42)
func testInvalidUseOfParameterAttr() {
var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}}
func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}}
var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}}
func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}}
var bad_iow : (Int) -> (__owned Int, Int)
func bad_iow2(_ a: (__owned Int, Int)) {}
}
// <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
func test_array_construct<T>(_: T) {
_ = [T]() // 'T' is a local name
_ = [Int]() // 'Int is a global name'
_ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name.
_ = [UnsafeMutablePointer<Int?>]() // Nesting.
_ = [([UnsafeMutablePointer<Int>])]()
_ = [(String, Float)]()
}
extension Optional {
init() {
self = .none
}
}
// <rdar://problem/15295763> default constructing an optional fails to typecheck
func test_optional_construct<T>(_: T) {
_ = T?() // Local name.
_ = Int?() // Global name
_ = (Int?)() // Parenthesized name.
}
// Test disambiguation of generic parameter lists in expression context.
struct Gen<T> {}
var y0 : Gen<Int?>
var y1 : Gen<Int??>
var y2 : Gen<[Int?]>
var y3 : Gen<[Int]?>
var y3a : Gen<[[Int?]]>
var y3b : Gen<[Int?]?>
var y4 : Gen<([Int])?>
var y5 : Gen<([([[Int??]])?])?>
var y7 : Gen<(Int,Int)?>
var y8 : Gen<((Int) -> Int)?>
var y8a : Gen<[([Int]?) -> Int]>
var y9 : Gen<(Int?) -> Int?>
var y10 : Gen<Int?.Type?.Type>
var y11 : Gen<Gen<Int>?>
var y12 : Gen<Gen<Int>?>?
var y13 : Gen<Gen<Int?>?>?
var y14 : Gen<Gen<Int?>>?
var y15 : Gen<Gen<Gen<Int?>>?>
var y16 : Gen<Gen<Gen<Int?>?>>
var y17 : Gen<Gen<Gen<Int?>?>>?
var z0 = Gen<Int?>()
var z1 = Gen<Int??>()
var z2 = Gen<[Int?]>()
var z3 = Gen<[Int]?>()
var z3a = Gen<[[Int?]]>()
var z3b = Gen<[Int?]?>()
var z4 = Gen<([Int])?>()
var z5 = Gen<([([[Int??]])?])?>()
var z7 = Gen<(Int,Int)?>()
var z8 = Gen<((Int) -> Int)?>()
var z8a = Gen<[([Int]?) -> Int]>()
var z9 = Gen<(Int?) -> Int?>()
var z10 = Gen<Int?.Type?.Type>()
var z11 = Gen<Gen<Int>?>()
var z12 = Gen<Gen<Int>?>?()
var z13 = Gen<Gen<Int?>?>?()
var z14 = Gen<Gen<Int?>>?()
var z15 = Gen<Gen<Gen<Int?>>?>()
var z16 = Gen<Gen<Gen<Int?>?>>()
var z17 = Gen<Gen<Gen<Int?>?>>?()
y0 = z0
y1 = z1
y2 = z2
y3 = z3
y3a = z3a
y3b = z3b
y4 = z4
y5 = z5
y7 = z7
y8 = z8
y8a = z8a
y9 = z9
y10 = z10
y11 = z11
y12 = z12
y13 = z13
y14 = z14
y15 = z15
y16 = z16
y17 = z17
// Type repr formation.
// <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr)
let tupleTypeWithNames = (age:Int, count:Int)(4, 5)
let dictWithTuple = [String: (age:Int, count:Int)]()
// <rdar://problem/21684837> typeexpr not being formed for postfix !
let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}
// <rdar://problem/21560309> inout allowed on function return type
func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}}
r21560309 { x in x }
// <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
class r21949448 {
var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}}
}
// SE-0066 - Standardize function type argument syntax to require parentheses
let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
let _ : inout Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{18-18=)}}
func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}}
func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{38-38=)}}
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}}
class C {
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}}
func foo3() {
let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}}
let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}}
}
}
let _ : inout @convention(c) Int -> Int // expected-error {{'inout' may only be used on parameters}}
func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }}
// expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}}
func sr5505(arg: Int) -> String {
return "hello"
}
var _: sr5505 = sr5505 // expected-error {{use of undeclared type 'sr5505'}}
typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
// expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
// expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
| apache-2.0 | 97932aacbe1c3af4454507b36566afce | 37.329897 | 186 | 0.621167 | 3.238676 | false | false | false | false |
1aurabrown/eidolon | Kiosk/Auction Listings/ListingsCountdownManager.swift | 1 | 1941 | import UIKit
class ListingsCountdownManager: NSObject {
@IBOutlet weak var countdownLabel: UILabel!
@IBOutlet var countdownContainerView: UIView!
let formatter = NSNumberFormatter()
dynamic var sale: Sale?
let time = SystemTime()
override func awakeFromNib() {
formatter.minimumIntegerDigits = 2
time.syncSignal().subscribeNext { [weak self] (_) in
self?.startTimer()
return
}
}
func setLabelsHidden(hidden: Bool) {
countdownContainerView.hidden = hidden
}
func hideDenomenatorLabels() {
for subview in countdownContainerView.subviews as [UIView] {
subview.hidden = subview != countdownLabel
}
}
func startTimer() {
let timer = NSTimer(timeInterval: 0.49, target: self, selector: "tick:", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
self.tick(timer)
}
func tick(timer: NSTimer) {
if let sale = sale {
if time.inSync() == false { return }
if sale.id == "" { return }
let now = time.date()
if sale.isActive(time) {
self.setLabelsHidden(false)
let flags: NSCalendarUnit = .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond
let components = NSCalendar.currentCalendar().components(flags, fromDate: now, toDate: sale.endDate, options: nil)
self.countdownLabel.text = "\(formatter.stringFromNumber(components.hour)!) : \(formatter.stringFromNumber(components.minute)!) : \(formatter.stringFromNumber(components.second)!)"
} else {
self.countdownLabel.text = "CLOSED"
hideDenomenatorLabels()
timer.invalidate()
}
}
}
}
| mit | b697596890c7c055221174a4539a11d1 | 29.809524 | 196 | 0.58372 | 5.134921 | false | false | false | false |
itsjingun/govhacknz_mates | Mates/Controllers/MTSPropertyDetailsViewController.swift | 1 | 2205 | //
// MTSPropertyDetailsViewController.swift
// Mates
//
// Created by Eddie Chae on 4/07/15.
// Copyright (c) 2015 Governmen. All rights reserved.
//
import UIKit
class MTSPropertyDetailsViewController: MTSBaseViewController {
@IBOutlet weak var propertyImageView: UIImageView!
@IBOutlet weak var propertyRentLabel: UILabel!
@IBOutlet weak var propertyAddressLabel: UILabel!
@IBOutlet weak var propertySuburbLabel: UILabel!
@IBOutlet weak var noOfBedroomsLabel: UILabel!
@IBOutlet weak var noOfBathroomsLabel: UILabel!
@IBOutlet weak var isAllowedSmokingLabel: UILabel!
@IBOutlet weak var isAllowedPetsLabel: UILabel!
var property: MTSProperty?
override func viewDidLoad() {
super.viewDidLoad()
var propertyImagePath = ("../" + toString(property!.id!) + ".jpg").stringByReplacingOccurrencesOfString(" ", withString: "%20", options: nil, range: nil)
propertyImageView.image = UIImage(named: propertyImagePath)
propertyRentLabel.text = toString(property!.rent)
propertyAddressLabel.text = property!.address
propertySuburbLabel.text = property!.region!
noOfBedroomsLabel.text = toString( property!.roomCount! )
noOfBathroomsLabel.text = toString ( property!.bathroomCount! )
isAllowedSmokingLabel.text = "No"//(property!.isAllowedSmoking! ? "Yes": "No")
isAllowedPetsLabel.text = "Negotiable"//(property!.isAllowedPets! ? "Yes": "No")
// Do any additional setup after loading the view.
}
@IBAction func onWatchButtonTouchUpInside(sender:AnyObject) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | 1230fc88fdb5ea15c54901def6f50280 | 35.75 | 161 | 0.682993 | 4.73176 | false | false | false | false |
bi3mer/WorkSpace | Swift/Patterns/Bridge/Bridge/ComplexObject.swift | 1 | 655 | //
// ComplexObject.swift
// Bridge
//
// Created by colan biemer on 4/4/15.
// Copyright (c) 2015 colan biemer. All rights reserved.
//
import Foundation
class ComplexObject
{
var value: Int = 0
var numberOfStuff: Int = 0
var definition: String = ""
func print()
{
println("val: \(value), num: \(numberOfStuff), def: \(definition)")
}
func setVal(val: Int)
{
value = val
}
func getVal() -> Int
{
return value
}
func setNum(num: Int)
{
numberOfStuff = num
}
func getNum() -> Int
{
return numberOfStuff
}
func setDef(def: String)
{
definition = def
}
func getDef() -> String
{
return definition
}
} | mit | 1b43b97f2da2bb844be2727d62399e7a | 11.862745 | 69 | 0.619847 | 2.763713 | false | false | false | false |
qinting513/SwiftNote | PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/QQVideoRefreshHeader.swift | 1 | 2011 | //
// QQVideoRefreshHeader.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/8/1.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
class QQVideoRefreshHeader:UIView,RefreshableHeader{
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = CGRect(x: 0, y: 0, width: 27, height: 10)
imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0)
imageView.image = UIImage(named: "loading15")
addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - RefreshableHeader -
func heightForRefreshingState()->CGFloat{
return 50
}
func stateDidChanged(_ oldState: RefreshHeaderState, newState: RefreshHeaderState) {
if newState == .pulling{
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform.identity
})
}
if newState == .idle{
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform(translationX: 0, y: -50)
})
}
}
//松手即将刷新的状态
func didBeginRefreshingState(){
imageView.image = nil
let images = (0...29).map{return $0 < 10 ? "loading0\($0)" : "loading\($0)"}
imageView.animationImages = images.map{return UIImage(named:$0)!}
imageView.animationDuration = Double(images.count) * 0.04
imageView.startAnimating()
}
//刷新结束,将要隐藏header
func didBeginEndRefershingAnimation(_ result:RefreshResult){}
//刷新结束,完全隐藏header
func didCompleteEndRefershingAnimation(_ result:RefreshResult){
imageView.animationImages = nil
imageView.stopAnimating()
imageView.image = UIImage(named: "loading15")
}
}
| apache-2.0 | 3beea7c8acebfcd17f2df15767341657 | 33.280702 | 88 | 0.636643 | 4.313466 | false | false | false | false |
KrishMunot/swift | test/Sema/omit_needless_words.swift | 6 | 2127 | // RUN: %target-parse-verify-swift -Womit-needless-words
class C1 {
init(tasteString: String) { } // expected-warning{{'init(tasteString:)' could be named 'init(taste:)'}}{{8-8=taste }}
func processWithString(_ string: String, toInt: Int) { } // expected-warning{{'processWithString(_:toInt:)' could be named 'process(with:to:)'}}{{8-25=process}} {{26-27=with}} {{44-44=to }}
func processWithInt(_ value: Int) { } // expected-warning{{'processWithInt' could be named 'process(with:)'}}{{8-22=process}}
}
extension String {
static var randomString: String { return "" } // expected-warning{{'randomString' could be named 'random'}}{{14-26=random}}
var wonkycasedString: String { return self } // expected-warning{{'wonkycasedString' could be named 'wonkycased'}}{{7-23=wonkycased}}
}
func callSites(_ s: String) {
let c1 = C1(tasteString: "blah") // expected-warning{{'init(tasteString:)' could be named 'init(taste:)'}}{{15-26=taste}}
c1.processWithString("a", toInt: 1) // expected-warning{{'processWithString(_:toInt:)' could be named 'process(with:to:)'}}{{6-23=process}}{{29-34=to}}
c1.processWithInt(5) // expected-warning{{'processWithInt' could be named 'process(with:)'}}{{6-20=process}}
_ = String.randomString // expected-warning{{'randomString' could be named 'random'}}{{14-26=random}}
_ = s.wonkycasedString // expected-warning{{'wonkycasedString' could be named 'wonkycased'}}{{9-25=wonkycased}}
}
struct MagicNameString { }
extension String {
func appendStrings(_ strings: [String]) { } // expected-warning{{'appendStrings' could be named 'append'}}{{8-21=append}}
func appendObjects(_ objects: [AnyObject]) { } // expected-warning{{'appendObjects' could be named 'append'}}{{8-21=append}}
func appendMagicNameStrings(_ strings: [MagicNameString]) { } // expected-warning{{'appendMagicNameStrings' could be named 'append'}}{{8-30=append}}
}
class NSArray {
func arrayByAddingObject(_ x: AnyObject) -> NSArray { return NSArray() } // expected-warning{{'arrayByAddingObject' could be named 'adding' [-Womit-needless-words]}}{{8-27=adding}}
}
func emptyFirstParamName(_: Int) { }
| apache-2.0 | 4e47f6345cee557017a6e1dd35d5f8d3 | 61.558824 | 191 | 0.695816 | 3.545 | false | true | false | false |
divljiboy/IOSChatApp | Quick-Chat/Pods/BulletinBoard/Sources/Support/Views/Internal/Highlighter.swift | 1 | 2809 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/// An item that can be highlighted due to a touch event.
protocol HighlighterTarget: class {
/// Highlight the item.
func highlight()
/// Unhighlight the item.
func unhighlight()
}
/**
* An object that determines when an item (its target) needs to be highlighted in response to
* touch events.
*
* You must forward the target's `touchesBegan`, `touchesMoved` and `touchesEnded` to this highlighter.
*/
class Highlighter {
/// The control targeted for highlight.
weak var target: (UIControl & HighlighterTarget)?
// MARK: - Hit Area
private var _cachedHitArea: CGRect!
private func makeHitArea(bounds: CGRect) -> CGRect {
let scaleTransform = CGAffineTransform(scaleX: 5/3, y: 5/3)
let translateTransform = CGAffineTransform(translationX: -bounds.width/3, y: -bounds.height/3)
return bounds.applying(scaleTransform).applying(translateTransform)
}
private var hitArea: CGRect {
return _cachedHitArea ?? makeHitArea(bounds: target!.bounds)
}
// MARK: - Touch Handling
/**
* Call this method when the bounds of the target change.
*/
func updateBounds(_ bounds: CGRect) {
_cachedHitArea = makeHitArea(bounds: bounds)
}
/**
* Call this method when touches begin on the target.
*/
func handleTouchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
target?.highlight()
}
/**
* Call this method when touches move on the target.
*/
func handleTouchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let mainTouch = touches.first else {
return
}
let currentLocation = mainTouch.location(in: target!)
let previousLocation = mainTouch.previousLocation(in: target!)
let containsCurrentLocation = hitArea.contains(currentLocation)
let containsPreviousLocation = hitArea.contains(previousLocation)
let isEntering = !containsPreviousLocation && containsCurrentLocation
let isExiting = containsPreviousLocation && !containsCurrentLocation
if isEntering {
target?.highlight()
} else if isExiting {
target?.unhighlight()
}
}
/**
* Call this method when touches end on the target.
*/
func handleTouchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let mainTouch = touches.first else {
return
}
let currentLocation = mainTouch.location(in: target!)
if hitArea.contains(currentLocation) {
target?.sendActions(for: .touchUpInside)
}
target?.unhighlight()
}
}
| mit | ab2d4ef8008f23b59c7f45ecd19a1e93 | 24.536364 | 103 | 0.645069 | 4.705193 | false | false | false | false |
steve228uk/PeachKit | Post.swift | 1 | 3520 | //
// Post.swift
// Peach
//
// Created by Stephen Radford on 10/01/2016.
// Copyright © 2016 Cocoon Development Ltd. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
public class Post {
/// Unique ID of the post
public var id: String?
/// Array of messages relating to the post
public var message: [Message] = []
/// How many comments are on the post
public var commentCount: Int?
/// How many likes are on the post
public var likeCount: Int?
/// Array of comments
public var comments: [Comment] = []
/// Was this post liked by the logged in user
public var likedByMe: Bool = false
/// Is the post unread
public var isUnread: Bool = false
/// When was this post created
public var createdTime: Int64?
/// When was this post updated
public var updatedTime: Int64?
/**
Like the post on Peach
- parameter callback: Optional callback
*/
public func like(callback: ((NSError?) -> Void)?) {
if let postID = id {
if !likedByMe {
Alamofire.request(API.LikePost(postID))
.responseJSON { response in
self.likedByMe = true
if let count = self.likeCount {
self.likeCount = count + 1
}
callback?(response.result.error)
}
} else {
Alamofire.request(API.UnlikePost(postID))
.responseJSON { response in
self.likedByMe = false
if let count = self.likeCount {
self.likeCount = count - 1
}
callback?(response.result.error)
}
}
}
}
/**
Like the post on Peach
*/
public func like() {
like(nil)
}
}
extension Peach {
/**
Map a post from raw JSON to the Peach Post
- parameter json: SwiftyJSON
- returns: A Peach Post
*/
internal class func parsePost(json: JSON) -> Post {
let post = Post()
post.id = json["id"].string
post.commentCount = json["commentCount"].int
post.updatedTime = json["updatedTime"].int64
post.createdTime = json["createdTime"].int64
post.likeCount = json["likeCount"].int
if let liked = json["likedByMe"].bool {
post.likedByMe = liked
}
if let isUnread = json["isUnread"].bool {
post.isUnread = isUnread
}
if let msg = json["message"].array {
post.message = msg.map(parseMessage)
}
if let comments = json["comments"].array {
post.comments = comments.map(parseComments)
}
return post
}
/**
Create a new post on peach
- parameter messages: An array of messages to send to peach
- parameter callback: Catch any errors that may occur
*/
public class func createPost(messages: [Message], callback: (NSError?) -> Void) {
let msgs = ["message": messages.map { $0.dictionary }]
Alamofire.request(API.CreatePost(msgs))
.responseJSON { response in
callback(response.result.error)
}
}
}
| mit | ae8bcb260de4802459dcac8c95601649 | 25.261194 | 85 | 0.515203 | 4.921678 | false | false | false | false |
Darren-chenchen/yiyiTuYa | testDemoSwift/Share/CLShareView.swift | 1 | 8548 | //
// CLShareView.swift
// relex_swift
//
// Created by Darren on 16/10/23.
// Copyright © 2016年 darren. All rights reserved.
//
import UIKit
import MessageUI
class CLShareView: UIView {
var imgArr = [String]()
var titleArr = [String]()
// 分享内容
var shareContent = ""
// 分享url
var shareUrlStr:String?
// 分享标题
var shareTitle = ""
// 分享图片
var shareImage: UIImage!
var tipViews = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
// 创建一个阴影
let win = UIApplication.shared.keyWindow!
let cover = UIView(frame: UIScreen.main.bounds)
cover.backgroundColor = UIColor.black
cover.tag = 100
cover.alpha = 0.8
win.addSubview(cover)
// 创建一个提示框
let tipX: CGFloat = 0
let tipW: CGFloat = cover.frame.size.width - 2 * tipX
let tipH: CGFloat = 280
let tipViews = UIView(frame: CGRect(x: tipX, y: KScreenHeight, width: tipW, height: tipW))
tipViews.backgroundColor = UIColor(white: 1, alpha: 0.9)
win.addSubview(tipViews)
self.tipViews = tipViews
UIView.animate(withDuration: 0.25, animations: {
let tipY: CGFloat = (KScreenHeight - tipH)
tipViews.frame = CGRect(x: tipX, y: tipY, width: tipW, height: tipH)
}) { (finished: Bool) in
}
let lable = UILabel(frame: CGRect(x: 0, y: 10, width: tipViews.frame.size.width, height: 30))
lable.text = "分享到"
lable.textAlignment = .center
lable.font = UIFont.systemFont(ofSize: 15)
tipViews.addSubview(lable)
if (!WXApi.isWXAppInstalled() && QQApiInterface.isQQInstalled()) { // 没装微信 装qq
self.imgArr = ["share_qq", "share_qzone", "share_sina_on"]
self.titleArr = ["QQ好友", "QQ空间", "新浪微博"]
} else if !WXApi.isWXAppInstalled() && !QQApiInterface.isQQInstalled() { //没装微信 没装q
self.imgArr = ["share_sina_on"]
self.titleArr = ["新浪微博"]
} else if WXApi.isWXAppInstalled() && !QQApiInterface.isQQInstalled() { //装微信 没装qq
self.imgArr = ["share_wechat_icon", "share_wechat_timeline_icon", "share_wechat_favorite_icon", "share_sina_on"]
self.titleArr = ["微信好友", "微信朋友圈", "微信收藏", "新浪微博"]
} else if WXApi.isWXAppInstalled() && QQApiInterface.isQQInstalled() { //装微信 装q
self.imgArr = ["share_wechat_icon", "share_wechat_timeline_icon", "share_wechat_favorite_icon","share_qq", "share_qzone", "share_sina_on"]
self.titleArr = ["微信好友", "微信朋友圈", "微信收藏","QQ好友", "QQ空间","新浪微博"]
}
for i in 0..<self.titleArr.count {
let line = 3
let btnW: CGFloat = tipViews.frame.size.width/CGFloat(line)
let btnX: CGFloat = CGFloat(i%Int(line)) * btnW
let btnImageW:CGFloat = btnW*0.4
let btnImageH:CGFloat = btnImageW
let btnImageX:CGFloat = (btnW-btnImageW)*0.5
let btnImageY:CGFloat = 5
let btnH = btnImageH+5+20+5;
let btnY: CGFloat = CGFloat(i/line) * (btnH+5)
let btnShare = CLCoustomButton()
btnShare.initTitleFrameAndImageFrame(CGRect(x: btnX, y: 50+btnY, width: btnW, height: btnH), imageFrame: CGRect(x: btnImageX, y: btnImageY, width: btnImageW,height: btnImageH), titleFrame: CGRect(x: 0, y: btnImageH+5+5, width: btnW, height: 15))
btnShare.tag = i + 100
btnShare.imageView!.contentMode = .scaleAspectFit
btnShare.setTitle(self.titleArr[i], for: .normal)
btnShare.setImage(UIImage(named: self.imgArr[i])!, for: .normal)
btnShare.addTarget(self, action: #selector(self.clickBtn), for: .touchUpInside)
tipViews.addSubview(btnShare)
}
let cancelBtn = UIButton(frame: CGRect(x: (tipViews.frame.size.width - 80) * 0.5, y: tipViews.frame.size.height - 45, width: 80, height: 30))
cancelBtn.backgroundColor = UIColor.purple
cancelBtn.setTitle("取消分享", for: .normal)
cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
cancelBtn.layer.cornerRadius = 3
cancelBtn.layer.masksToBounds = true
cancelBtn.addTarget(self, action: #selector(self.clickCancel), for: .touchUpInside)
tipViews.addSubview(cancelBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func clickCancel() {
UIView.animate(withDuration: 0.25, animations: {
let tipY: CGFloat = KScreenHeight
self.tipViews.frame = CGRect(x: 0, y: tipY, width: KScreenWidth, height: 0)
}) { (finished: Bool) in
let win = UIApplication.shared.keyWindow!
win.subviews.last!.removeFromSuperview()
let win2 = UIApplication.shared.keyWindow!
win2.subviews.last!.removeFromSuperview()
let win3 = UIApplication.shared.keyWindow!
win3.subviews.last!.removeFromSuperview()
}
}
func clickBtn(_ btn: UIButton) {
self.initWithBtn(btn)
}
func initWithBtn(_ btn: UIButton) {
//创建分享参数
let shareParams = NSMutableDictionary()
shareParams.ssdkEnableUseClientShare()
guard let urlStr = self.shareUrlStr else {
return
}
shareParams.ssdkSetupShareParams(byText: self.shareContent, images: self.shareImage, url: NSURL(string:urlStr) as URL!, title: self.shareTitle, type: SSDKContentType.image)
if (btn.titleLabel!.text! == "QQ好友") {
//QQ
ShareSDK.share(.typeQQ, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "分享成功")
}
})
}
if (btn.titleLabel!.text! == "QQ空间") {
//QQ
ShareSDK.share(.subTypeQZone, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "分享成功")
}
})
}
if (btn.titleLabel!.text! == "微信好友") {
//QQ
ShareSDK.share(.typeWechat, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "分享成功")
}
})
}
if (btn.titleLabel!.text! == "微信朋友圈") {
//QQ
ShareSDK.share(.subTypeWechatTimeline, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "分享成功")
}
})
}
if (btn.titleLabel!.text! == "微信收藏") {
//QQ
ShareSDK.share(.subTypeWechatFav, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "收藏成功")
}
})
}
if (btn.titleLabel!.text! == "新浪微博") {
//QQ
ShareSDK.share(.typeSinaWeibo, parameters: shareParams, onStateChanged: { (state:SSDKResponseState, userData:[AnyHashable : Any]?, contentEntity:SSDKContentEntity?, error:Error?) in
if state == SSDKResponseState.success {
// SVProgressHUD.showSuccess(withStatus: "分享成功")
}
})
}
self.clickCancel()
}
}
| apache-2.0 | bf7779ae1492775a9c46ceecf819a7f2 | 41.448454 | 257 | 0.588707 | 4.05865 | false | false | false | false |
FuzzyHobbit/bitcoin-swift | BitcoinSwift/ExtendedECKey.swift | 1 | 4992 | //
// DeterministicECKey.swift
// BitcoinSwift
//
// Created by Kevin Greene on 12/20/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
/// An ExtendedECKey represents a key that is part of a DeterministicECKeyChain. It is just an
/// ECKey except an additional chainCode parameter and an index are used to derive the key.
/// Extended keys can be used to derive child keys.
/// BIP 32: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
public class ExtendedECKey : ECKey {
public let chainCode: SecureData
public let index: UInt32
/// Creates a new master extended key (both private and public).
/// Returns the key and the randomly-generated seed used to create the key.
public class func masterKey() -> (key: ExtendedECKey, seed: SecureData) {
var masterKey: ExtendedECKey? = nil
let randomData = SecureData(length: UInt(ECKey.privateKeyLength()))
var tries = 0
while masterKey == nil {
let result = SecRandomCopyBytes(kSecRandomDefault,
size_t(randomData.length),
UnsafeMutablePointer<UInt8>(randomData.mutableBytes))
assert(result == 0)
masterKey = ExtendedECKey.masterKeyWithSeed(randomData)
assert(++tries < 5)
}
return (masterKey!, randomData)
}
/// Can return nil in the (very very very very) unlikely case the randomly generated private key
/// is invalid. If nil is returned, retry.
public class func masterKeyWithSeed(seed: SecureData) -> ExtendedECKey? {
let indexHash = seed.HMACSHA512WithKeyData(ExtendedECKey.masterKeySeed())
let privateKey = indexHash[0..<32]
let chainCode = indexHash[32..<64]
let privateKeyInt = SecureBigInteger(secureData: privateKey)
if privateKeyInt.isEqual(BigInteger(0)) ||
privateKeyInt.greaterThanOrEqual(ECKey.curveOrder()) {
return nil
}
return ExtendedECKey(privateKey: privateKey, chainCode: chainCode)
}
/// Creates a new child key derived from self with index.
public func childKeyWithIndex(index: UInt32) -> ExtendedECKey? {
var data = SecureData()
if indexIsHardened(index) {
data.appendBytes([0] as [UInt8], length: 1)
data.appendSecureData(privateKey)
data.appendUInt32(index, endianness: .BigEndian)
} else {
data.appendData(publicKey)
data.appendUInt32(index, endianness: .BigEndian)
}
var indexHash = data.HMACSHA512WithKey(chainCode)
let indexHashLInt = SecureBigInteger(secureData: indexHash[0..<32])
let curveOrder = ECKey.curveOrder()
if indexHashLInt.greaterThanOrEqual(curveOrder) {
return nil
}
let childPrivateKeyInt = indexHashLInt.add(SecureBigInteger(secureData: privateKey),
modulo:curveOrder)
if childPrivateKeyInt.isEqual(BigInteger(0)) {
return nil
}
// The BigInteger might result in data whose length is less than expected, so we pad with 0's.
var childPrivateKey = SecureData()
let offset = ECKey.privateKeyLength() - Int32(childPrivateKeyInt.secureData.length)
assert(offset >= 0)
if offset > 0 {
let offsetBytes = [UInt8](count: Int(offset), repeatedValue: 0)
childPrivateKey.appendBytes(offsetBytes, length: UInt(offsetBytes.count))
}
childPrivateKey.appendSecureData(childPrivateKeyInt.secureData)
assert(Int32(childPrivateKey.length) == ECKey.privateKeyLength())
let childChainCode = indexHash[32..<64]
return ExtendedECKey(privateKey: childPrivateKey, chainCode: childChainCode, index: index)
}
public func childKeyWithHardenedIndex(index: UInt32) -> ExtendedECKey? {
return childKeyWithIndex(index + ExtendedECKey.hardenedIndexOffset())
}
/// Returns whether or not this key is hardened. A hardened key has more secure properties.
/// In general, you should always use a hardened key as the master key when deriving a
/// deterministic key chain where the keys in that chain will be published to the blockchain.
public var hardened: Bool {
return indexIsHardened(index)
}
/// Returns nil if the index is not hardened.
public var hardenedIndex: UInt32? {
return hardened ? index - ExtendedECKey.hardenedIndexOffset() : nil
}
// MARK: - Private Methods.
// TODO: Make this a class var instead of a func once Swift adds support for that.
private class func masterKeySeed() -> NSData {
return ("Bitcoin seed" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
}
// TODO: Make this a class var instead of a func once Swift adds support for that.
private class func hardenedIndexOffset() -> UInt32 {
return 0x80000000
}
private init(privateKey: SecureData, chainCode: SecureData, index: UInt32 = 0) {
self.chainCode = chainCode
self.index = index
super.init(privateKey: privateKey)
}
private func indexIsHardened(index: UInt32) -> Bool {
return index >= ExtendedECKey.hardenedIndexOffset()
}
}
| apache-2.0 | 73d68cf8f52ef36b71185e888c1af2a5 | 39.258065 | 98 | 0.705529 | 4.461126 | false | false | false | false |
joehour/ScratchCard | ScratchCard/ScratchView.swift | 1 | 8955 | //
// ScratchView.swift
// ScratchCard
//
// Created by JoeJoe on 2016/4/15.
// Copyright © 2016年 JoeJoe. All rights reserved.
//
import Foundation
import UIKit
var width: Int!
var height: Int!
var location: CGPoint!
var previousLocation: CGPoint!
var firstTouch: Bool!
//var scratchable: CGImage!
var scratched: CGImage!
var alphaPixels: CGContext!
var provider: CGDataProvider!
var pixelBuffer: UnsafeMutablePointer<UInt8>!
var couponImage: String!
var scratchWidth: CGFloat!
var contentLayer: CALayer!
var maskLayer: CAShapeLayer!
internal protocol ScratchViewDelegate: class {
func began(_ view: ScratchView)
func moved(_ view: ScratchView)
func ended(_ view: ScratchView)
}
open class ScratchView: UIView {
internal weak var delegate: ScratchViewDelegate!
internal var position: CGPoint!
override init(frame: CGRect) {
super.init(frame: frame)
self.Init()
}
init(frame: CGRect, CouponImage: String, ScratchWidth: CGFloat) {
super.init(frame: frame)
couponImage = CouponImage
scratchWidth = ScratchWidth
self.Init()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.InitXib()
}
fileprivate func Init() {
let image = processPixels(image: UIImage(named: couponImage)!)
if image != nil {
scratched = image?.cgImage
} else {
scratched = UIImage(named: couponImage)?.cgImage
}
width = (Int)(self.frame.width)
height = (Int)(self.frame.height)
self.isOpaque = false
let colorspace: CGColorSpace = CGColorSpaceCreateDeviceGray()
let pixels: CFMutableData = CFDataCreateMutable(nil, width * height)
alphaPixels = CGContext( data: CFDataGetMutableBytePtr(pixels), width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: colorspace, bitmapInfo: CGImageAlphaInfo.none.rawValue)
alphaPixels.setFillColor(UIColor.black.cgColor)
alphaPixels.setStrokeColor(UIColor.white.cgColor)
alphaPixels.setLineWidth(scratchWidth)
alphaPixels.setLineCap(CGLineCap.round)
//fix mask initialization error on simulator device(issue9)
pixelBuffer = alphaPixels.data?.bindMemory(to: UInt8.self, capacity: width * height)
var byteIndex: Int = 0
for _ in 0...width * height {
if pixelBuffer?[byteIndex] != 0 {
pixelBuffer?[byteIndex] = 0
}
byteIndex += 1
}
provider = CGDataProvider(data: pixels)
maskLayer = CAShapeLayer()
maskLayer.frame = CGRect(x:0, y:0, width:width, height:height)
maskLayer.backgroundColor = UIColor.clear.cgColor
contentLayer = CALayer()
contentLayer.frame = CGRect(x:0, y:0, width:width, height:height)
contentLayer.contents = scratched
contentLayer.mask = maskLayer
self.layer.addSublayer(contentLayer)
}
fileprivate func InitXib() {
}
override open func touchesBegan(_ touches: Set<UITouch>,
with event: UIEvent?) {
if let touch = touches.first {
firstTouch = true
location = CGPoint(x: touch.location(in: self).x, y: touch.location(in: self).y)
position = location
if self.delegate != nil {
self.delegate.began(self)
}
}
}
override open func touchesMoved(_ touches: Set<UITouch>,
with event: UIEvent?) {
if let touch = touches.first {
if firstTouch! {
firstTouch = false
previousLocation = CGPoint(x: touch.previousLocation(in: self).x, y: touch.previousLocation(in: self).y)
} else {
location = CGPoint(x: touch.location(in: self).x, y: touch.location(in: self).y)
previousLocation = CGPoint(x: touch.previousLocation(in: self).x, y: touch.previousLocation(in: self).y)
}
position = previousLocation
renderLineFromPoint(previousLocation, end: location)
if self.delegate != nil {
self.delegate.moved(self)
}
}
}
override open func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?) {
if let touch = touches.first {
if firstTouch! {
firstTouch = false
previousLocation = CGPoint(x: touch.previousLocation(in: self).x, y: touch.previousLocation(in: self).y)
position = previousLocation
renderLineFromPoint(previousLocation, end: location)
if self.delegate != nil {
self.delegate.ended(self)
}
}
}
}
// override open func draw(_ rect: CGRect) {
// UIGraphicsGetCurrentContext()?.saveGState()
// contentLayer.render(in: UIGraphicsGetCurrentContext()!)
// UIGraphicsGetCurrentContext()?.restoreGState()
//
// }
func renderLineFromPoint(_ start: CGPoint, end: CGPoint) {
alphaPixels.move(to: CGPoint(x: start.x, y: start.y))
alphaPixels.addLine(to: CGPoint(x: end.x, y: end.y))
alphaPixels.strokePath()
drawLine(onLayer: maskLayer, fromPoint: start, toPoint: end)
}
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
linePath.lineCapStyle = .round
line.lineWidth = scratchWidth
line.path = linePath.cgPath
line.opacity = 1
line.strokeColor = UIColor.white.cgColor
line.lineCap = "round"
layer.addSublayer(line)
}
internal func getAlphaPixelPercent() -> Double {
var byteIndex: Int = 0
var count: Double = 0
let data = UnsafePointer(pixelBuffer)
for _ in 0...width * height {
if data![byteIndex] != 0 {
count += 1
}
byteIndex += 1
}
return count / Double(width * height)
}
// iOS 11.2 error
// internal func getAlphaPixelPercent() -> Double {
// let pixelData = provider.data
// let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
// let imageWidth: size_t = alphaPixels.makeImage()!.width
// let imageHeight: size_t = alphaPixels.makeImage()!.height
//
// var byteIndex: Int = 0
// var count: Double = 0
//
// for _ in 0...imageWidth * imageHeight {
// if data[byteIndex] != 0 {
// count += 1
// }
// byteIndex += 1
// }
//
// return count / Double(imageWidth * imageHeight)
// }
func processPixels(image: UIImage) -> UIImage? {
guard let inputCGImage = image.cgImage else {
print("unable to get cgImage")
return nil
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let width = inputCGImage.width
let height = inputCGImage.height
let bytesPerPixel = 4
let bitsPerComponent = 8
let bytesPerRow = bytesPerPixel * width
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
return nil
}
context.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: width, height: height))
guard let buffer = context.data else {
return nil
}
let pixelBuffer = buffer.bindMemory(to: UInt8.self, capacity: width * height)
var byteIndex: Int = 0
for _ in 0...width * height {
if pixelBuffer[byteIndex] == 0 {
pixelBuffer[byteIndex] = 255
pixelBuffer[byteIndex+1] = 255
pixelBuffer[byteIndex+2] = 255
pixelBuffer[byteIndex+3] = 255
}
byteIndex += 4
}
let outputCGImage = context.makeImage()!
let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)
return outputImage
}
}
| mit | 7514102086c2bcdc6634b196570ca031 | 33.96875 | 205 | 0.568588 | 4.771855 | false | false | false | false |
suifengqjn/swiftDemo | 基本语法/6函数/函数.playground/Contents.swift | 1 | 6496 | //: Playground - noun: a place where people can play
import UIKit
///以 func 作为前缀。指定函数返回类型时,用返回箭头 ->(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示。
func sayHello() -> Void {
print("hello")
}
sayHello()
///参数:string 返回值:string
func sayhello(personName: String) -> String {
return "hello" + personName + "!"
}
var str = sayhello(personName: "Tom")
///无参函数
func sayHi() -> String {
return "hello , world!"
}
///多参数函数
func sayHell(personName:String, isalreadyGreet:Bool) -> String {
if isalreadyGreet {
return "a"
} else {
return "b"
}
}
print(sayHell(personName: "bbb", isalreadyGreet: true))
///无返回值函数
func sayGoodBye(personName: String) {
print("goodBye,\(personName)")
}
///多重返回值函数
//你可以用元组(tuple)类型让多个值作为一个复合值从函数中返回
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)
}
///可选元祖返回类型
func minMaxArr(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 = minMaxArr(array: [8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
///函数实际参数标签和形式参数名
func someFunction(firstParameterName: Int, secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument values for the first and second parameters.
}
someFunction(firstParameterName: 1, secondParameterName: 2)
///指定实际参数标签
func someFunction(argumentLabel parameterName: Int) {
// In the function body, parameterName refers to the argument value
// for that parameter.
}
//如果你为一个形式参数提供了实际参数标签,那么这个实际参数就必须在调用函数的时候使用标签。
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
///指定外部参数名
//你可以在局部参数名前指定外部参数名,中间以空格分隔:
func someFunction2(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
//如果你提供了外部参数名,那么函数在被调用时,必须使用外部参数名。
someFunction2(externalParameterName: 3)
///忽略外部参数名(一般很少会这么用吧)
//如果你不想为参数设置外部参数名,用一个下划线(_)代替一个明确的参数名。
func someFunction3(_ firstParameterName: Int, _ secondParameterName: Int) {
print(firstParameterName + secondParameterName)
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction3(1, 2)
func someFunction4(_ firstParameterName: Int, secondParameterName: Int) {
print(firstParameterName + secondParameterName)
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction4(1, secondParameterName:2)
///可变参数
///一个可变参数(variadic parameter)可以接受零个或多个值
///通过在变量类型名后面加入(...)的方式来定义可变参数
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(numbers: 1, 2, 3, 4, 5)
arithmeticMean(numbers: 1, 2.6, 3)
///输入输出形式参数
//这里有一个 swapTwoInts(_:_:)函数,它有两个输入输出整数形式参数 a和 b:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
///函数类型
//每一个函数都有一个特定的函数类型,它由形式参数类型,返回类型组成。
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
func printHelloWorld() {
print("hello, world")
}
/////使用函数类型
//你可以像使用 Swift 中的其他类型一样使用函数类型。例如,你可以给一个常量或变量定义一个函数类型,并且为变量指定一个相应的函数。
/// 简而言之,就是把一个函数用一个变量来代替,便于使用
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
///函数类型作为形式参数类型
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
///函数类型作为返回类型
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backwards: currentValue > 0)
////内嵌函数
func chooseStepFunction2(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
var currentValue2 = -4
let moveNearerToZero2 = chooseStepFunction(backwards: currentValue2 > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue2 != 0 {
print("\(currentValue2)... ")
currentValue2 = moveNearerToZero2(currentValue2)
}
| apache-2.0 | d5d8adfa0a7f4a6a5e81385c6b1c606c | 22.318966 | 77 | 0.68207 | 3.4791 | false | false | false | false |
dolphilia/swift-scripteditor-example | 01_start/nstextview-fontcolor-test/MyTextView.swift | 1 | 19912 | //
// MyTextView2.swift
// nstextview-fontcolor-test
//
// Created by dolphilia on 2016/01/21.
// Copyright © 2016年 dolphilia. All rights reserved.
//
import Foundation
import Cocoa
class MyTextView: NSTextView {
required init?(coder: NSCoder) {
super.init(coder: coder)
self.backgroundColor = NSColor.rgbColor(47,47,47) //背景色を設定する
self.insertionPointColor = NSColor.whiteColor()//カーソルバーの色を設定
self.selectedTextAttributes = [NSBackgroundColorAttributeName: NSColor.rgbColor(67,65,70)]//選択中の背景色の設定
self.linkTextAttributes = [NSForegroundColorAttributeName:NSColor.rgbColor(178,237,93)]//リンクの文字色の設定
}
override func awakeFromNib() {
self.textContainerInset = NSMakeSize(4,4)//テキストの位置を微調整する
self.lnv_setUpLineNumberView()//行番号を表示するビューを設定
//self.textContainer?.exclusionPaths = [NSBezierPath(rect: CGRectMake(0,0,40,self.frame.size.height))]//非表示領域を設定する
checkSyntax()
}
func setTextWithColor(text:String, _ red:Int, _ green:Int, _ blue:Int) -> NSAttributedString {//文字色付きのテキストを返す内部関数
let font: NSFont = NSFont(name: "Menlo Regular", size: 11.0)!
let attrStr = NSMutableAttributedString(
string: text,
attributes: [
NSForegroundColorAttributeName: NSColor(calibratedRed: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: 1.0), //文字色を設定する
])
let area = NSMakeRange(0, attrStr.length)
attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
return attrStr
}
func setTextWithColor(text:String, red:Float, green:Float, blue:Float) -> NSAttributedString {//文字色付きのテキストを返す内部関数
let font: NSFont = NSFont(name: "Menlo Regular", size: 11.0)!
let attrStr = NSMutableAttributedString(
string: text,
attributes: [
NSForegroundColorAttributeName: NSColor(calibratedRed: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: 1.0), //文字色を設定する
])
let area = NSMakeRange(0, attrStr.length)
attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
return attrStr
}
func checkSyntax() { //テキストの内容を調べて適切に色分けする
let cursorPosition:NSInteger = (self.selectedRanges.first?.rangeValue.location)!//カーソル位置を取得して保持する
let str = self.string//現在の文字列を保持する
//テキスト属性を初期化する
let font: NSFont = NSFont(name: "Menlo Regular", size: 11.0)!
let attrStr = NSMutableAttributedString(
string: str!,
attributes: [
NSForegroundColorAttributeName: NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 1.0),
])
let area = NSMakeRange(0, attrStr.length)
attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
self.textStorage!.setAttributedString(attrStr)
////各行をチェックして、属性を付けて挿入する
//str!.enumerateLines{ line, stop in
// if line.trim().substr(0, 2) == "//" || line.trim().substr(0,1) == ";" { //コメントだったら
// self.textStorage!.appendAttributedString( self.setTextWithColor(line+"\n", 139, 139, 139) )
// }
// else if line.trim().substr(0, 1) == "#" { //ラベルだったら
// self.textStorage!.appendAttributedString( self.setTextWithColor(line+"\n", 232, 191, 106) )
// }
// else if line.trim().substr(0, 1) == "*" && !line.trim().isMatch("[^0-9a-zA-Z_\\*]") { //ラベルだったら
// self.textStorage!.appendAttributedString( self.setTextWithColor(line+"\n", 225, 109, 91) )
// }
// else {
// self.textStorage!.appendAttributedString( self.setTextWithColor(line+"\n", 255, 255, 255) )
// }
//}
//文字の属性を設定する
//メモ
//ダブルクオートを除く半角記号
//[ -!#-/:-@\\[-\\`\\{-\\~]
var startIndex = 0
//文字列
startIndex=0
if self.string!.isMatch("\"[\\b\\t\\f\\rぁ-んァ-ヶーa-zA-Z0-9一-龠0-9_ -!#-/:-@\\[-\\`\\{-\\~、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓∈∋⊆⊇⊂⊃∪∩∧∨¬⇒⇔∀∃∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬ʼn♯♭♪†‡¶◯ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ�㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡㍻〝〟№㏍℡㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪]*\"") {
for word in self.string!.trim().matches("\"[\\b\\t\\f\\rぁ-んァ-ヶーa-zA-Z0-9一-龠0-9_ -!#-/:-@\\[-\\`\\{-\\~、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓∈∋⊆⊇⊂⊃∪∩∧∨¬⇒⇔∀∃∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬ʼn♯♭♪†‡¶◯ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ�㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡㍻〝〟№㏍℡㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪]*\"")! {
if startIndex >= self.string!.indexOf(word, startIndex: startIndex) {
continue
}
startIndex = self.string!.indexOf(word, startIndex: startIndex)
let range = NSMakeRange(startIndex, word.length)
self.textStorage!.replaceCharactersInRange(range, withAttributedString: self.setTextWithColor(word, 180, 156, 218))
startIndex += word.length
}
}
//複数行の文字列
startIndex=0
if self.string!.isMatch("\\{\"[\\n\\b\\t\\f\\rぁ-んァ-ヶーa-zA-Z0-9一-龠0-9_ -!#-/:-@\\[-\\`\\{-\\~、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓∈∋⊆⊇⊂⊃∪∩∧∨¬⇒⇔∀∃∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬ʼn♯♭♪†‡¶◯ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ�㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡㍻〝〟№㏍℡㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪]*\"\\}") {
for word in self.string!.trim().matches("\\{\"[\\n\\b\\t\\f\\rぁ-んァ-ヶーa-zA-Z0-9一-龠0-9_ -!#-/:-@\\[-\\`\\{-\\~、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓∈∋⊆⊇⊂⊃∪∩∧∨¬⇒⇔∀∃∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬ʼn♯♭♪†‡¶◯ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ�㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡㍻〝〟№㏍℡㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪]*\"\\}")! {
if startIndex >= self.string!.indexOf(word, startIndex: startIndex) {
continue
}
startIndex = self.string!.indexOf(word, startIndex: startIndex)
let range = NSMakeRange(startIndex, word.length)
self.textStorage!.replaceCharactersInRange(range, withAttributedString: self.setTextWithColor(word, 180, 156, 218))
startIndex += word.length
}
}
//コメントアウト
startIndex = 0
if self.string!.isMatch("/\\*[\\s\\S]*?\\*/|//.*") {
for word in self.string!.trim().matches("/\\*[\\s\\S]*?\\*/|//.*")! {
startIndex = self.string!.indexOf(word, startIndex: startIndex)
//コメントと思われるレンジが文字列かどうか、色で判断する
let r = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.redComponent
let g = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.greenComponent
let b = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.blueComponent
let a = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.alphaComponent
if(r<1&&g<1&&b<1&&a==1){ //文字色が完全な白でない場合:
continue
}
let range = NSMakeRange(startIndex, word.length)
self.textStorage!.replaceCharactersInRange(range, withAttributedString: self.setTextWithColor(word, red:0.54, green:0.54, blue:0.54))
startIndex += word.length
}
}
//キーワード
let keyword = [
"if",
"else",
"var",
"let",
"func",
"class",
"in"
]
var regex_keyword:String = ""
for word in keyword {
Swift.print(word)
regex_keyword += "^" + word + "\\s|\\s" + word + "\\s|"
}
regex_keyword = regex_keyword.substr(0, regex_keyword.length - 1)
Swift.print(regex_keyword)
startIndex = 0
if self.string!.isMatch(regex_keyword) {
for word in self.string!.trim().matches(regex_keyword)! {
startIndex = self.string!.indexOf(word, startIndex: startIndex)
//コメントと思われるレンジが文字列かどうか、色で判断する
let r = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.redComponent
let g = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.greenComponent
let b = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.blueComponent
let a = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.alphaComponent
if(
round(r*100)/100==0.54 && //小数点第三以下を四捨五入する
round(g*100)/100==0.54 &&
round(b*100)/100==0.54 &&
a==1
){ //文字色がコメント色の場合:
continue
}
let range = NSMakeRange(startIndex, word.length)
self.textStorage!.replaceCharactersInRange(range, withAttributedString: self.setTextWithColor(word, 178, 237, 93))
startIndex += word.length
}
}
//ラベル
startIndex = 0
if self.string!.isMatch("^\\*[a-zA-Z_]+|\\n\\*[a-zA-Z_]+") {
for word in self.string!.trim().matches("^\\*[a-zA-Z_]+|\\n\\*[a-zA-Z_]+")! {
startIndex = self.string!.indexOf(word, startIndex: startIndex)
//コメントと思われるレンジが文字列かどうか、色で判断する
let r = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.redComponent
let g = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.greenComponent
let b = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.blueComponent
let a = self.textStorage!.fontAttributesInRange(NSMakeRange(startIndex,1))["NSColor"]!.alphaComponent
if(
round(r*100)/100==0.54 && //小数点第三以下を四捨五入する
round(g*100)/100==0.54 &&
round(b*100)/100==0.54 &&
a==1
){ //文字色がコメント色の場合:
continue
}
let range = NSMakeRange(startIndex, word.length)
self.textStorage!.replaceCharactersInRange(range, withAttributedString: self.setTextWithColor(word, 225, 109, 91))
startIndex += word.length
}
}
self.setSelectedRange(NSMakeRange(cursorPosition, 0))//カーソルバーの位置を元に戻す
}
override func insertNewline(sender: AnyObject?) {//新しい行を挿入したときのイベントを設定する
//自動でタブを挿入する処理
let cursorPosition:NSInteger = (self.selectedRanges.first?.rangeValue.location)!//カーソル位置を取得して保持する
let str = self.string//現在の文字列を保持する
//現在のカーソル位置から遡って、最初の改行あるいは最初の文字を見つける
//最初の改行あるいは文字列の頭から続く文字がタブだった場合、タブの個数分タブを挿入する
let index = (str?.length)!-((str?.length)!-cursorPosition)
if index>0 {
for_i:
for i in 0..<index { //
if str![index-i-1]=="\n" {
super.insertNewline(sender) //行を挿入する
if str![index-1]=="{" {
super.insertTab(sender)
}
for n in 0..<i {
if str![index-i+n]=="\t" {
super.insertTab(sender)
}
else {
break for_i
}
}
break for_i
}
else if i==index-1 {
super.insertNewline(sender) //行を挿入する
if str![index-1]=="{" {
super.insertTab(sender)
}
for n in 0..<index {
if str![n]=="\t" {
super.insertTab(sender)
}
else {
break for_i
}
}
break for_i
}
else {}
}
}
else {
super.insertNewline(sender) //行を挿入する
}
checkSyntax()
}
override func insertText(aString: AnyObject, replacementRange: NSRange) {
//新しいテキストを挿入したときのイベントを設定する
super.insertText(aString, replacementRange: replacementRange)
checkSyntax()
}
override func deleteBackward(sender: AnyObject?) {
//Backspace時のイベントを設定する
super.deleteBackward(sender)
checkSyntax()
}
override func deleteForward(sender: AnyObject?) {
//Deleteキーを押した時のイベントを設定する
super.deleteForward(sender)
checkSyntax()
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
////行番号の矩形領域を描画する
//let rectangle = NSBezierPath(rect: CGRectMake(39,0,1,self.frame.size.height))
//NSColor(calibratedRed: 69/255, green: 69/255, blue: 69/255, alpha: 1).setFill() // stroke 色の設定
//rectangle.fill()
////行数を数える
//let count = self.string?.lineCount
//let fieldColor: NSColor = NSColor(calibratedRed: 113/255, green: 113/255, blue: 113/255, alpha: 1)
//let fieldFont = NSFont(name: "Menlo Regular", size: 9)
////行番号を描画する
//for i in 0..<count! {
// let text:NSString = NSString(string: String(i))
// let attributes: NSDictionary = [
// NSForegroundColorAttributeName: fieldColor,
// NSFontAttributeName: fieldFont!
// ]
// text.drawAtPoint(NSMakePoint(0,CGFloat(i)*9), withAttributes: attributes as! [String : AnyObject])
//}
}
////メモ
////テキスト属性の設定例
//let font: NSFont = NSFont(name: "Menlo Regular", size: 9.0)!
//let attrStr = NSMutableAttributedString(
// string: "my string",
// attributes: [
// NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.hashValue, //下線
// NSUnderlineColorAttributeName: NSColor(calibratedRed: 0.698, green: 0.929, blue: 0.364, alpha: 1.0), //下線の色
// NSLinkAttributeName: NSURL(string: "https://dolphilia.github.io")!, //リンク
// NSCursorAttributeName: NSCursor.pointingHandCursor()//カーソルを変更
// ])
//let area = NSMakeRange(0, attrStr.length)
//attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
//self.textStorage!.appendAttributedString(attrStr)
////テキスト属性の挿入メソッド
//func appendAttributedString(_ attrString: NSAttributedString)
//func insertAttributedString(_ attrString: NSAttributedString, atIndex loc: Int)
//func replaceCharactersInRange(_ range: NSRange, withAttributedString attrString: NSAttributedString)
//func setAttributedString(_ attrString: NSAttributedString)
} | mit | 9ea8f5514398cd49f026ab2a955cc509 | 49.766773 | 508 | 0.534961 | 2.603047 | false | false | false | false |
bartoszkrawczyk2/insta | ios/PhotoEditor.swift | 1 | 4081 | //
// PhotoEditor.swift
// Insta
//
// Created by Bartosz Krawczyk on 27.01.2016.
// Copyright © 2016 Facebook. All rights reserved.
//
import Foundation
@objc(PhotoEditor)
class PhotoEditor : NSObject {
/*
* Cropp UIImage to square -> UIImage
*/
private func cropToSquare(image originalImage: UIImage) -> UIImage {
let contextImage: UIImage = UIImage(CGImage: originalImage.CGImage!)
let contextSize: CGSize = contextImage.size
let posX: CGFloat
let posY: CGFloat
let width: CGFloat
let height: CGFloat
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
width = contextSize.height
height = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
width = contextSize.width
height = contextSize.width
}
let rect: CGRect = CGRectMake(posX, posY, width, height)
let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage!, rect)!
let image: UIImage = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
return image
}
/*
* Resize UIImage -> UIImage
*/
private func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/*
* Public
* Process Image method -> base64
*/
@objc func process(url: NSString, filterName: NSString, callback: (NSObject) -> ()) -> Void {
let image = UIImage(contentsOfFile: url as String)
let croppedImage: UIImage = cropToSquare(image: image!)
let resizedImage: UIImage = resizeImage(croppedImage, newWidth: 600)
let extractor = PixelExtractor()
extractor.load(resizedImage.CGImage!)
let filteredImage = extractor.applyFilter(filterName as String)
let thumbImage: UIImage = resizeImage(filteredImage, newWidth: 150)
let imageData = UIImagePNGRepresentation(filteredImage)
let imageDataThumb = UIImagePNGRepresentation(thumbImage)
callback( [[
"base64": imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"thumb": imageDataThumb!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
]])
}
@objc func filters(url: NSString, callback: (NSObject) -> ()) -> Void {
let image = UIImage(contentsOfFile: url as String)
let croppedImage: UIImage = cropToSquare(image: image!)
let resizedImage: UIImage = resizeImage(croppedImage, newWidth: 350)
let extractor = PixelExtractor();
extractor.load(resizedImage.CGImage!)
let f0 = extractor.applyFilter("0" as String)
let f1 = extractor.applyFilter("1" as String)
let f2 = extractor.applyFilter("2" as String)
let f3 = extractor.applyFilter("3" as String)
let f4 = extractor.applyFilter("4" as String)
let f5 = extractor.applyFilter("5" as String)
let f0data = UIImagePNGRepresentation(f0)
let f1data = UIImagePNGRepresentation(f1)
let f2data = UIImagePNGRepresentation(f2)
let f3data = UIImagePNGRepresentation(f3)
let f4data = UIImagePNGRepresentation(f4)
let f5data = UIImagePNGRepresentation(f5)
callback( [[
"f0": f0data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"f1": f1data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"f2": f2data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"f3": f3data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"f4": f4data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
"f5": f5data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
]])
}
} | mit | 81b8935a25b7272f636fd7209cc737d4 | 33.880342 | 124 | 0.704657 | 4.620612 | false | false | false | false |
BellAppLab/SwiftFileManager | Example/Pods/Backgroundable/Pod/Classes/ViewControllers+Backgroundable.swift | 1 | 4784 | //
// Backgroundable.swift
// Project
//
// Created by Bell App Lab on 05/08/15.
// Copyright (c) 2015 Bell App Lab. All rights reserved.
//
import UIKit
//MARK: - Backgroundable View Controller
public class BackgroundableViewController: UIViewController, Visibility
{
//MARK: Setup
deinit {
self.resignAppStatesHandler()
}
//MARK: Visibility
public var visible = false
public func willChangeVisibility() {
}
public func didChangeVisibility() {
}
//MARK: View Controller Life Cycle
override public func viewDidLoad() {
super.viewDidLoad()
self.becomeAppStatesHandler()
}
override public func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.willChangeVisibility()
self.visible = true
}
override public func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
self.didChangeVisibility()
}
override public func viewWillDisappear(animated: Bool)
{
self.willChangeVisibility()
self.visible = false
super.viewWillDisappear(animated)
}
override public func viewDidDisappear(animated: Bool)
{
self.didChangeVisibility()
super.viewDidDisappear(animated)
}
public final override func handleAppStateChange(toBackground: Bool) {
if (self.visible && toBackground) || (!self.visible && !toBackground) {
self.willChangeVisibility()
self.visible = !toBackground
self.didChangeVisibility()
}
}
}
//MARK: - Backgroundable Table View Controller
public class BackgroundableTableViewController: UITableViewController, Visibility
{
//MARK: Setup
deinit {
self.resignAppStatesHandler()
}
//MARK: Visibility
public var visible = false
public func willChangeVisibility() {
}
public func didChangeVisibility() {
}
//MARK: View Controller Life Cycle
override public func viewDidLoad() {
super.viewDidLoad()
self.becomeAppStatesHandler()
}
override public func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.willChangeVisibility()
self.visible = true
}
override public func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
self.didChangeVisibility()
}
override public func viewWillDisappear(animated: Bool)
{
self.willChangeVisibility()
self.visible = false
super.viewWillDisappear(animated)
}
override public func viewDidDisappear(animated: Bool)
{
self.didChangeVisibility()
super.viewDidDisappear(animated)
}
public final override func handleAppStateChange(toBackground: Bool) {
if (self.visible && toBackground) || (!self.visible && !toBackground) {
self.willChangeVisibility()
self.visible = !toBackground
self.didChangeVisibility()
}
}
}
//MARK: - Backgroundable Collection View Controller
public class BackgroundableCollectionViewController: UICollectionViewController, Visibility
{
//MARK: Setup
deinit {
self.resignAppStatesHandler()
}
//MARK: Visibility
public var visible = false
public func willChangeVisibility() {
}
public func didChangeVisibility() {
}
//MARK: View Controller Life Cycle
override public func viewDidLoad() {
super.viewDidLoad()
self.becomeAppStatesHandler()
}
override public func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.willChangeVisibility()
self.visible = true
}
override public func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
self.didChangeVisibility()
}
override public func viewWillDisappear(animated: Bool)
{
self.willChangeVisibility()
self.visible = false
super.viewWillDisappear(animated)
}
override public func viewDidDisappear(animated: Bool)
{
self.didChangeVisibility()
super.viewDidDisappear(animated)
}
public final override func handleAppStateChange(toBackground: Bool) {
if (self.visible && toBackground) || (!self.visible && !toBackground) {
self.willChangeVisibility()
self.visible = !toBackground
self.didChangeVisibility()
}
}
}
| mit | d740904680451a6edadeaee816fd136a | 22.111111 | 91 | 0.610786 | 5.339286 | false | false | false | false |
pmlbrito/QuickShotUtils | QuickShotUtils/Classes/UI/Views/QSUBasicLoadingIndicator.swift | 1 | 2040 | //
// QSUBasicLoadingIndicator.swift
// Pods
//
// Created by Pedro Brito on 22/06/16.
//
//
import UIKit
public class QSUBasicLoadingIndicator{
var overlayView: UIView?;
var activityIndicator: UIActivityIndicatorView?;
class var shared: QSUBasicLoadingIndicator {
struct Static {
static let instance: QSUBasicLoadingIndicator = QSUBasicLoadingIndicator()
}
return Static.instance
}
private init(){
let window = UIApplication.shared.windows.first!
overlayView = UIView(frame: window.frame);
overlayView?.backgroundColor = UIColor.black.withAlphaComponent(0.8);
overlayView?.clipsToBounds = true
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
activityIndicator?.activityIndicatorViewStyle = .whiteLarge
activityIndicator?.centerX = window.frame.size.width/2
activityIndicator?.centerY = window.frame.size.height/2
activityIndicator?.color = UIColor.white;
overlayView!.addSubview(activityIndicator!)
}
public func show() {
//without animations
// let window = UIApplication.sharedApplication().windows.first!
// window.addSubview(overlayView!)
// activityIndicator!.startAnimating()
//with animations
let window = UIApplication.shared.windows.first
window?.addSubview(self.overlayView!)
self.activityIndicator!.startAnimating()
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
self.overlayView!.alpha = 0.8
}, completion: { finished in
})
}
public func hide() {
//without animations
// activityIndicator!.stopAnimating()
// overlayView!.removeFromSuperview()
//with animations
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
self.overlayView!.alpha = 0.0
}, completion: { finished in
self.activityIndicator!.stopAnimating()
self.overlayView!.removeFromSuperview()
})
}
}
| mit | 5a6d159599e66634a8868d09fb159ef7 | 28.142857 | 97 | 0.689706 | 4.733179 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Logging/Parsers/PowerGameStateParser.swift | 1 | 23714 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 13/02/16.
*/
import Foundation
import CleanroomLogger
import RegexUtil
class PowerGameStateParser: LogEventParser {
let BlockStartRegex = RegexPattern(stringLiteral: ".*BLOCK_START.*BlockType=(POWER|TRIGGER)"
+ ".*id=(\\d*).*(cardId=(\\w*)).*Target=(.+)")
let CardIdRegex: RegexPattern = "cardId=(\\w+)"
let CreationRegex: RegexPattern = "FULL_ENTITY - Updating.*id=(\\d+).*zone=(\\w+).*CardID=(\\w*)"
let CreationTagRegex: RegexPattern = "tag=(\\w+) value=(\\w+)"
let GameEntityRegex: RegexPattern = "GameEntity EntityID=(\\d+)"
let PlayerEntityRegex: RegexPattern = "Player EntityID=(\\d+) PlayerID=(\\d+) GameAccountId=(.+)"
let PlayerNameRegex: RegexPattern = "id=(\\d) Player=(.+) TaskList=(\\d)"
let TagChangeRegex: RegexPattern = "TAG_CHANGE Entity=(.+) tag=(\\w+) value=(\\w+)"
let UpdatingEntityRegex: RegexPattern = "SHOW_ENTITY - Updating Entity=(.+) CardID=(\\w*)"
var tagChangeHandler = TagChangeHandler()
var currentEntity: Entity?
private unowned(unsafe) let eventHandler: PowerEventHandler
init(with eventHandler: PowerEventHandler) {
self.eventHandler = eventHandler
}
// MARK: - Entities
private var currentEntityId = 0
func resetCurrentEntity() {
currentEntityId = 0
}
// MARK - blocks
func blockStart() {
maxBlockId += 1
let blockId = maxBlockId
currentBlock = currentBlock?.createChild(blockId: blockId)
?? Block(parent: nil, id: blockId)
}
func blockEnd() {
currentBlock = currentBlock?.parent
if let entity = eventHandler.entities[currentEntityId] {
entity.info.hasOutstandingTagChanges = false
}
}
private var maxBlockId: Int = 0
private var currentBlock: Block?
// MARK - line handling
func handle(logLine: LogLine) {
var creationTag = false
// current game
if logLine.line.match(GameEntityRegex) {
if let match = logLine.line.matches(GameEntityRegex).first,
let id = Int(match.value) {
//print("**** GameEntityRegex id:'\(id)'")
let entity = Entity(id: id)
entity.name = "GameEntity"
eventHandler.add(entity: entity)
currentEntityId = id
eventHandler.set(currentEntity: id)
if eventHandler.determinedPlayers() {
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
}
return
}
}
// players
else if logLine.line.match(PlayerEntityRegex) {
if let match = logLine.line.matches(PlayerEntityRegex).first,
let id = Int(match.value) {
let entity = Entity(id: id)
eventHandler.add(entity: entity)
if eventHandler.wasInProgress {
//game.entities[id]?.name = game.getStoredPlayerName(id: id)
}
currentEntityId = id
eventHandler.set(currentEntity: id)
if eventHandler.determinedPlayers() {
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
}
return
}
} else if logLine.line.match(TagChangeRegex) {
let matches = logLine.line.matches(TagChangeRegex)
let rawEntity = matches[0].value
.replacingOccurrences(of: "UNKNOWN ENTITY ", with: "")
let tag = matches[1].value
let value = matches[2].value
if rawEntity.hasPrefix("[") && tagChangeHandler.isEntity(rawEntity: rawEntity) {
let entity = tagChangeHandler.parseEntity(entity: rawEntity)
if let id = entity.id {
tagChangeHandler.tagChange(eventHandler: eventHandler, rawTag: tag, id: id, rawValue: value)
}
} else if let id = Int(rawEntity) {
tagChangeHandler.tagChange(eventHandler: eventHandler, rawTag: tag, id: id, rawValue: value)
} else {
var entity = eventHandler.entities.map { $0.1 }.firstWhere { $0.name == rawEntity }
if let entity = entity {
tagChangeHandler.tagChange(eventHandler: eventHandler, rawTag: tag,
id: entity.id, rawValue: value)
} else {
let players = eventHandler.entities.map { $0.1 }
.filter { $0.has(tag: .player_id) }.take(2)
let unnamedPlayers = players.filter { $0.name.isBlank }
let unknownHumanPlayer = players
.first { $0.name == "UNKNOWN HUMAN PLAYER" }
if unnamedPlayers.count == 0 && unknownHumanPlayer != .none {
entity = unknownHumanPlayer
}
var tmpEntity = eventHandler.tmpEntities.firstWhere { $0.name == rawEntity }
if tmpEntity == .none {
tmpEntity = Entity(id: eventHandler.tmpEntities.count + 1)
tmpEntity!.name = rawEntity
eventHandler.tmpEntities.append(tmpEntity!)
}
if let _tag = GameTag(rawString: tag) {
let tagValue = tagChangeHandler.parseTag(tag: _tag, rawValue: value)
if unnamedPlayers.count == 1 {
entity = unnamedPlayers.first
} else if unnamedPlayers.count == 2 &&
_tag == .current_player && tagValue == 0 {
entity = eventHandler.entities.map { $0.1 }
.first { $0.has(tag: .current_player) }
}
if let entity = entity, let tmpEntity = tmpEntity {
entity.name = tmpEntity.name
tmpEntity.tags.forEach({ (gameTag, val) in
tagChangeHandler.tagChange(eventHandler: eventHandler,
tag: gameTag, id: entity.id,
value: val)
})
eventHandler.tmpEntities.remove(tmpEntity)
tagChangeHandler.tagChange(eventHandler: eventHandler,
rawTag: tag,
id: entity.id,
rawValue: value)
}
if let tmpEntity = tmpEntity, eventHandler.tmpEntities.contains(tmpEntity) {
tmpEntity[_tag] = tagValue
let player: Player? = eventHandler.player.name == tmpEntity.name
? eventHandler.player
: (eventHandler.opponent.name == tmpEntity.name ? eventHandler.opponent : nil)
if let _player = player,
let playerEntity = eventHandler.entities.map({$0.1}).first({
$0[.player_id] == _player.id
}) {
playerEntity.name = tmpEntity.name
tmpEntity.tags.forEach({ gameTag, val in
tagChangeHandler.tagChange(eventHandler: eventHandler,
tag: gameTag,
id: playerEntity.id,
value: val)
})
eventHandler.tmpEntities.remove(tmpEntity)
}
}
}
}
}
} else if logLine.line.match(CreationRegex) {
let matches = logLine.line.matches(CreationRegex)
let id = Int(matches[0].value)!
guard let zone = Zone(rawString: matches[1].value) else { return }
var cardId: String? = matches[2].value
if eventHandler.entities[id] == .none {
if cardId.isBlank && zone != .setaside {
if let blockId = currentBlock?.id,
let cards = eventHandler.knownCardIds[blockId] {
cardId = cards.first
if !cardId.isBlank {
Log.verbose?.message("Found known cardId "
+ "'\(String(describing: cardId))' for entity \(id)")
eventHandler.knownCardIds[id] = nil
}
}
}
let entity = Entity(id: id)
eventHandler.entities[id] = entity
}
if !cardId.isBlank {
eventHandler.entities[id]!.cardId = cardId!
}
currentEntityId = id
eventHandler.set(currentEntity: id)
if eventHandler.determinedPlayers() {
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
}
eventHandler.currentEntityHasCardId = !cardId.isBlank
eventHandler.currentEntityZone = zone
return
} else if logLine.line.match(UpdatingEntityRegex) {
let matches = logLine.line.matches(UpdatingEntityRegex)
let rawEntity = matches[0].value
let cardId = matches[1].value
var entityId: Int?
if rawEntity.hasPrefix("[") && tagChangeHandler.isEntity(rawEntity: rawEntity) {
let entity = tagChangeHandler.parseEntity(entity: rawEntity)
if let _entityId = entity.id {
entityId = _entityId
}
} else if let _entityId = Int(rawEntity) {
entityId = _entityId
}
if let entityId = entityId {
if eventHandler.entities[entityId] == .none {
let entity = Entity(id: entityId)
eventHandler.entities[entityId] = entity
}
eventHandler.entities[entityId]!.cardId = cardId
currentEntityId = entityId
eventHandler.set(currentEntity: entityId)
if eventHandler.determinedPlayers() {
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
}
}
if eventHandler.joustReveals > 0 {
if let currentEntity = eventHandler.entities[entityId!] {
if currentEntity.isControlled(by: eventHandler.opponent.id) {
eventHandler.opponentJoust(entity: currentEntity, cardId: cardId,
turn: eventHandler.turnNumber())
} else if currentEntity.isControlled(by: eventHandler.player.id) {
eventHandler.playerJoust(entity: currentEntity, cardId: cardId,
turn: eventHandler.turnNumber())
}
}
}
return
} else if logLine.line.match(CreationTagRegex)
&& !logLine.line.contains("HIDE_ENTITY") {
let matches = logLine.line.matches(CreationTagRegex)
let tag = matches[0].value
let value = matches[1].value
tagChangeHandler.tagChange(eventHandler: eventHandler, rawTag: tag, id: currentEntityId,
rawValue: value, isCreationTag: true)
creationTag = true
}
if logLine.line.contains("End Spectator") {
eventHandler.gameEnd()
} else if logLine.line.contains("BLOCK_START") {
blockStart()
if logLine.line.match(BlockStartRegex) {
let player = eventHandler.entities.map { $0.1 }
.firstWhere { $0.has(tag: .player_id) && $0[.player_id] == eventHandler.player.id }
let opponent = eventHandler.entities.map { $0.1 }
.firstWhere { $0.has(tag: .player_id) && $0[.player_id] == eventHandler.opponent.id }
let matches = logLine.line.matches(BlockStartRegex)
let type = matches[0].value
let actionStartingEntityId = Int(matches[1].value)!
var actionStartingCardId: String? = matches[3].value
if actionStartingCardId.isBlank {
if let actionEntity = eventHandler.entities[actionStartingEntityId] {
actionStartingCardId = actionEntity.cardId
}
}
if actionStartingCardId.isBlank {
return
}
if type == "TRIGGER" {
if let actionStartingCardId = actionStartingCardId {
switch actionStartingCardId {
case CardIds.Collectible.Rogue.TradePrinceGallywix:
if let lastCardPlayed = eventHandler.lastCardPlayed,
let entity = eventHandler.entities[lastCardPlayed] {
let cardId = entity.cardId
addKnownCardId(eventHandler: eventHandler, cardId: cardId)
}
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral
.TradePrinceGallywix_GallywixsCoinToken)
case CardIds.Collectible.Shaman.WhiteEyes:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Shaman
.WhiteEyes_TheStormGuardianToken)
case CardIds.Collectible.Hunter.RaptorHatchling:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Hunter
.RaptorHatchling_RaptorPatriarchToken)
case CardIds.Collectible.Warrior.DirehornHatchling:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Warrior
.DirehornHatchling_DirehornMatriarchToken)
default: break
}
}
} else {
if let actionStartingCardId = actionStartingCardId {
switch actionStartingCardId {
case CardIds.Collectible.Rogue.GangUp:
addKnownCardId(eventHandler: eventHandler,
cardId: getTargetCardId(matches: matches),
count: 3)
case CardIds.Collectible.Rogue.BeneathTheGrounds:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Rogue
.BeneaththeGrounds_AmbushToken,
count: 3)
case CardIds.Collectible.Warrior.IronJuggernaut:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Warrior
.IronJuggernaut_BurrowingMineToken)
case CardIds.Collectible.Druid.Recycle,
CardIds.Collectible.Mage.ManicSoulcaster:
addKnownCardId(eventHandler: eventHandler,
cardId: getTargetCardId(matches: matches))
case CardIds.Collectible.Mage.ForgottenTorch:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Mage
.ForgottenTorch_RoaringTorchToken)
case CardIds.Collectible.Warlock.CurseOfRafaam:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Warlock
.CurseofRafaam_CursedToken)
case CardIds.Collectible.Neutral.AncientShade:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral
.AncientShade_AncientCurseToken)
case CardIds.Collectible.Priest.ExcavatedEvil:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.Collectible.Priest.ExcavatedEvil)
case CardIds.Collectible.Neutral.EliseStarseeker:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral
.EliseStarseeker_MapToTheGoldenMonkeyToken)
case CardIds.NonCollectible.Neutral
.EliseStarseeker_MapToTheGoldenMonkeyToken:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral
.EliseStarseeker_GoldenMonkeyToken)
case CardIds.Collectible.Neutral.Doomcaller:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral.Cthun)
case CardIds.Collectible.Druid.JadeIdol:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.Collectible.Druid.JadeIdol,
count: 3)
case CardIds.NonCollectible.Hunter.TheMarshQueen_QueenCarnassaToken:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Hunter
.TheMarshQueen_CarnassasBroodToken,
count: 15)
case CardIds.Collectible.Neutral.EliseTheTrailblazer:
addKnownCardId(eventHandler: eventHandler,
cardId: CardIds.NonCollectible.Neutral
.ElisetheTrailblazer_UngoroPackToken)
default:
if let card = Cards.any(byId: actionStartingCardId) {
if (player != nil && player![.current_player] == 1
&& !eventHandler.playerUsedHeroPower)
|| (opponent != nil && opponent![.current_player] == 1
&& !eventHandler.opponentUsedHeroPower) {
if card.type == .hero_power {
if player != nil && player![.current_player] == 1 {
eventHandler.playerHeroPower(cardId: actionStartingCardId,
turn: eventHandler.turnNumber())
eventHandler.playerUsedHeroPower = true
} else if opponent != nil {
eventHandler.opponentHeroPower(cardId: actionStartingCardId,
turn: eventHandler.turnNumber())
eventHandler.opponentUsedHeroPower = true
}
}
}
}
}
}
}
} else if logLine.line.contains("BlockType=JOUST") {
eventHandler.joustReveals = 2
} else if eventHandler.gameTriggerCount == 0
&& logLine.line.contains("BLOCK_START BlockType=TRIGGER Entity=GameEntity") {
eventHandler.gameTriggerCount += 1
}
} else if logLine.line.contains("CREATE_GAME") {
tagChangeHandler.clearQueuedActions()
if Settings.autoDeckDetection {
if let currentMode = eventHandler.currentMode,
let deck = CoreManager.autoDetectDeck(mode: currentMode) {
eventHandler.set(activeDeckId: deck.deckId, autoDetected: true)
} else {
Log.warning?.message("could not autodetect deck")
eventHandler.set(activeDeckId: nil, autoDetected: false)
}
}
// indicate game start
maxBlockId = 0
currentBlock = nil
resetCurrentEntity()
eventHandler.gameStart(at: logLine.time)
} else if logLine.line.contains("BLOCK_END") {
if eventHandler.gameTriggerCount < 10 && (eventHandler.gameEntity?.has(tag: .turn) ?? false) {
eventHandler.gameTriggerCount += 10
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
eventHandler.setupDone = true
}
blockEnd()
}
if eventHandler.isInMenu { return }
if !creationTag && eventHandler.determinedPlayers() {
tagChangeHandler.invokeQueuedActions(eventHandler: eventHandler)
}
if !creationTag {
resetCurrentEntity()
}
}
private func getTargetCardId(matches: [Match]) -> String? {
let target = matches[4].value.trim()
guard target.hasPrefix("[") && tagChangeHandler.isEntity(rawEntity: target) else {
return nil
}
guard target.match(CardIdRegex) else { return nil }
let cardIdMatch = target.matches(CardIdRegex)
return cardIdMatch.first?.value.trim()
}
private func addKnownCardId(eventHandler: PowerEventHandler, cardId: String?, count: Int = 1) {
guard let cardId = cardId else { return }
if let blockId = currentBlock?.id {
for _ in 0 ..< count {
if eventHandler.knownCardIds[blockId] == nil {
eventHandler.knownCardIds[blockId] = []
}
eventHandler.knownCardIds[blockId]?.append(cardId)
}
}
}
private func reset() {
tagChangeHandler.clearQueuedActions()
}
}
| mit | d711d0cb5ff3422fc2e57ddaa5a5dfda | 48.404167 | 112 | 0.494138 | 5.68 | false | false | false | false |
milseman/swift | test/SILOptimizer/mandatory_inlining.swift | 6 | 4558 | // RUN: %target-swift-frontend -primary-file %s -emit-sil -o - -verify | %FileCheck %s
// These tests are deliberately shallow, because I do not want to depend on the
// specifics of SIL generation, which might change for reasons unrelated to this
// pass
func foo(_ x: Float) -> Float {
return bar(x);
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining3foo{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $Float):
// CHECK-NEXT: debug_value %0 : $Float, let, name "x"
// CHECK-NEXT: return %0
@_transparent func bar(_ x: Float) -> Float {
return baz(x)
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3bar{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: return
@_transparent func baz(_ x: Float) -> Float {
return x
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3baz{{[_0-9a-zA-Z]*}}F
// CHECK: return
func spam(_ x: Int) -> Int {
return x
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
@_transparent func ham(_ x: Int) -> Int {
return spam(x)
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3ham{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
func eggs(_ x: Int) -> Int {
return ham(x)
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining4eggs{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
@_transparent func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
func test_auto_closure_with_capture(_ x: Bool) -> Bool {
return call_auto_closure(x)
}
// This should be fully inlined and simply return x; however, there's a lot of
// non-SSA cruft that I don't want this test to depend on, so I'm just going
// to verify that it doesn't have any function applications left
// CHECK-LABEL: sil hidden @{{.*}}test_auto_closure_with_capture
// CHECK-NOT: = apply
// CHECK: return
func test_auto_closure_without_capture() -> Bool {
return call_auto_closure(false)
}
// This should be fully inlined and simply return false, which is easier to check for
// CHECK-LABEL: sil hidden @_T018mandatory_inlining33test_auto_closure_without_captureSbyF
// CHECK: [[FV:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[FALSE:%.*]] = struct $Bool ([[FV:%.*]] : $Builtin.Int1)
// CHECK: return [[FALSE]]
infix operator &&& : LogicalConjunctionPrecedence
infix operator ||| : LogicalDisjunctionPrecedence
@_transparent func &&& (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return rhs()
}
return false
}
@_transparent func ||| (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return true
}
return rhs()
}
func test_chained_short_circuit(_ x: Bool, y: Bool, z: Bool) -> Bool {
return x &&& (y ||| z)
}
// The test below just makes sure there are no uninlined [transparent] calls
// left (i.e. the autoclosure and the short-circuiting boolean operators are
// recursively inlined properly)
// CHECK-LABEL: sil hidden @_T018mandatory_inlining26test_chained_short_circuit{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: = apply [transparent]
// CHECK: return
// Union element constructors should be inlined automatically.
enum X {
case onetransp
case twotransp
}
func testInlineUnionElement() -> X {
return X.onetransp
// CHECK-LABEL: sil hidden @_T018mandatory_inlining22testInlineUnionElementAA1XOyF
// CHECK: enum $X, #X.onetransp!enumelt
// CHECK-NOT: = apply
// CHECK: return
}
@_transparent
func call_let_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
// CHECK: sil hidden @{{.*}}test_let_auto_closure_with_value_capture
// CHECK: bb0(%0 : $Bool):
// CHECK-NEXT: debug_value %0 : $Bool
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: return %0 : $Bool
func test_let_auto_closure_with_value_capture(_ x: Bool) -> Bool {
return call_let_auto_closure(x)
}
class C {}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
@_transparent
func class_constrained_generic<T : C>(_ o: T) -> AnyClass? {
// CHECK: return
return T.self
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining6invokeyAA1CCF : $@convention(thin) (@owned C) -> () {
func invoke(_ c: C) {
// CHECK-NOT: function_ref @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: apply
// CHECK: init_existential_metatype
_ = class_constrained_generic(c)
// CHECK: return
}
| apache-2.0 | 92b5dbe30008586d358750c5afefa94f | 26.792683 | 110 | 0.667179 | 3.178522 | false | true | false | false |
rustedivan/tapmap | tapmap/Rendering/InstanceBasedLineUtils.swift | 1 | 3468 | //
// InstanceBasedLineUtils.swift
// tapmap
//
// Created by Ivan Milles on 2022-10-02.
// Copyright © 2022 Wildbrain. All rights reserved.
//
import Metal
import simd
struct LineInstanceUniforms {
var a: simd_float2
var b: simd_float2
}
struct JoinInstanceUniforms {
var a: simd_float2
var b: simd_float2
var c: simd_float2
}
typealias LineSegmentPrimitive = RenderPrimitive
typealias JoinSegmentPrimitive = RenderPrimitive
func makeLineSegmentPrimitive(in device: MTLDevice, inside: Float, outside: Float) -> LineSegmentPrimitive {
let vertices: [Vertex] = [
Vertex(0.0, inside),
Vertex(1.0, inside),
Vertex(1.0, -outside),
Vertex(0.0, -outside)
]
let indices: [UInt16] = [
0, 1, 2, 0, 2, 3
]
return LineSegmentPrimitive( polygons: [vertices],
indices: [indices],
drawMode: .triangle,
device: device,
color: Color(r: 0.0, g: 0.0, b: 0.0, a: 1.0),
ownerHash: 0,
debugName: "Line segment primitive")
}
func makeBevelJoinPrimitive(in device: MTLDevice, width: Float) -> JoinSegmentPrimitive {
let vertices: [Vertex] = [
Vertex(0.0, 0.0),
Vertex(width, 0.0),
Vertex(0.0, width),
]
let indices: [UInt16] = [
0, 1, 2
]
return JoinSegmentPrimitive( polygons: [vertices],
indices: [indices],
drawMode: .triangle,
device: device,
color: Color(r: 0.0, g: 0.0, b: 0.0, a: 1.0),
ownerHash: 0,
debugName: "Bevel join primitive")
}
func generateContourLineGeometry(contours: [VertexRing], inside renderBox: Aabb) -> Array<LineInstanceUniforms> {
let segmentCount = contours.reduce(0) { $0 + $1.vertices.count }
var vertices = Array<LineInstanceUniforms>()
vertices.reserveCapacity(segmentCount)
for contour in contours {
for i in 0..<contour.vertices.count - 1 {
let a = contour.vertices[i]
let b = contour.vertices[i + 1]
if boxContains(renderBox, a) || boxContains(renderBox, b) {
vertices.append(LineInstanceUniforms(
a: simd_float2(x: a.x, y: a.y),
b: simd_float2(x: b.x, y: b.y)
))
}
}
let first = contour.vertices.first!
let last = contour.vertices.last!
if boxContains(renderBox, first) || boxContains(renderBox, last) {
vertices.append(LineInstanceUniforms(
a: simd_float2(last.x, last.y),
b: simd_float2(first.x, first.y)
))
}
}
return vertices
}
func generateContourJoinGeometry(contours: [VertexRing], inside renderBox: Aabb) -> Array<JoinInstanceUniforms> {
let segmentCount = contours.reduce(0) { $0 + $1.vertices.count }
var vertices = Array<JoinInstanceUniforms>()
vertices.reserveCapacity(segmentCount)
for contour in contours {
for i in 1..<contour.vertices.count - 1 {
let a = contour.vertices[i - 1]
let b = contour.vertices[i]
let c = contour.vertices[i + 1]
if boxContains(renderBox, b) {
vertices.append(JoinInstanceUniforms(
a: simd_float2(x: a.x, y: a.y),
b: simd_float2(x: b.x, y: b.y),
c: simd_float2(x: c.x, y: c.y)
))
}
}
if vertices.count >= 3 {
let first = contour.vertices.first!
let second = contour.vertices[1]
let last = contour.vertices.last!
if boxContains(renderBox, second) {
vertices.append(JoinInstanceUniforms(
a: simd_float2(last.x, last.y),
b: simd_float2(first.x, first.y),
c: simd_float2(second.x, second.y)
))
}
}
}
return vertices
}
| mit | 94c0527618f77eac7acab5ddff320505 | 26.959677 | 113 | 0.641477 | 3.009549 | false | false | false | false |
malczak/silicon | Examples/Simple/Simple/ViewController.swift | 1 | 3162 | //
// ViewController.swift
// Simple
//
// Created by Mateusz Malczak on 02/03/16.
// Copyright © 2016 ThePirateCat. All rights reserved.
//
import UIKit
import Silicon
class Obj {
}
class Obj1: Obj {
var a: Obj2?
}
class Obj2: Obj {
var value: Int = -1
var b: Obj3?
}
class Obj3: Obj {
var i: Int = 1
var c: Obj1?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var s = Silicon.sharedInstance
s.set(Services.OBJ_1, shared: true, count: 2, closure: { (si) in
print("fetch 1")
let o = Obj1()
o.a = (si.resolve(Services.OBJ_2)) as? Obj2
return o
})
s.set(Services.OBJ_2, shared: true, closure: { (si) in
print("fetch 2")
let o = Obj2()
o.value = 0
for i in 0...30000 {
o.value += i
DispatchQueue.main.sync{ print("Setting \(i)") }
}
// o.b = (si.resolve(Services.OBJ_3)) as? Obj3
return o
});
s.set(Services.OBJ_3) { (si) in
print("fetch 3")
let o = Obj3()
o.c = (si.resolve(Services.OBJ_1)) as? Obj1
return o
};
Silicon.set(Services.OBJ_4, shared:true, count: 2) { (si) in
print("fetch 2")
let o = Obj3()
o.i = Int(arc4random())
return o
};
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async{ print("q1") }
if let obj1 = s.get(Services.OBJ_1) as? Obj1 {
DispatchQueue.main.async{ print("q1 -> obj1 \(obj1.a?.value)") }
} else {
DispatchQueue.main.async{ print("q1 -> MISSING") }
}
DispatchQueue.main.async{ print("q1 -> DONE") }
}
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async{ print("q2") }
if let obj1 = s.get(Services.OBJ_1) as? Obj1 {
DispatchQueue.main.async{ print("q2 -> obj1 \(obj1.a?.value)") }
} else {
DispatchQueue.main.async{ print("q2 -> MISSING") }
}
DispatchQueue.main.async{ print("q2 -> DONE") }
}
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async{ print("q3") }
if let obj1 = s.get(Services.OBJ_1) as? Obj1 {
DispatchQueue.main.async{ print("q3 -> obj1 \(obj1.a?.value)") }
} else {
DispatchQueue.main.async{ print("q3 -> MISSING") }
}
DispatchQueue.main.async{ print("q3 -> DONE") }
}
// let o = [
// s.get(Services.OBJ_1),
// s.get(Services.OBJ_2),
// s.get(Services.OBJ_3),
// s.get(Services.OBJ_4),
// s.get("services")
// ]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | b5aa8b4bf24b31c572974647f39e4d0c | 25.563025 | 80 | 0.486555 | 3.710094 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Playlist/PlaylistViewController.swift | 1 | 7605 | //
// PlaylistViewController.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import XLPagerTabStrip
import RxSwift
import Action
import RxDataSources
import NSObject_Rx
class PlaylistViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate var initialIndicatorView = InitialActivityIndicatorView()
fileprivate var loadingIndicatorView = LoadingActivityIndicatorView()
lazy var categoryHeaderView: CategoryHeaderView = CategoryHeaderView(size: CGSize(
width: self.tableView.bounds.size.width,
height: CategoryHeaderView.defaultHeight
))
fileprivate var refreshControl = OnlineRefreshControl()
var store: PlaylistStore!
var action: PlaylistAction!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.addSubview(refreshControl)
bindStore()
bindAction()
}
fileprivate let PlaylistsSection = 1
fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<PlaylistCollectionSection> = { [weak self] in
let dataSource = RxTableViewSectionedReloadDataSource<PlaylistCollectionSection>()
dataSource.configureCell = { dataSource, tableView, indexPath, playlists in
guard let controller = self else { fatalError("Unexpected View Controller") }
return dataSource.configureCell(for: tableView, at: indexPath, in: controller, animated: controller.store.loadMoreEnabled.value) {
if indexPath.section == controller.PlaylistsSection {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistCell.self), for: indexPath)
if let cell = cell as? PlaylistCell {
cell.registerPreviewAction = controller.action.onRegisterPlaylistPreview()
cell.didSelectAction = controller.action.onPlaylistDidSelect()
cell.playAction = controller.action.onPlaylistPlayButtonTapped()
cell.playlists = playlists
}
return cell
}
fatalError("Unexpected Playlist Section")
}
}
dataSource.titleForHeaderInSection = { dataSource, section in dataSource[section].model }
return dataSource
}()
}
extension PlaylistViewController: UITableViewDelegate, PlaylistCellOptions {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == self.PlaylistsSection {
let categoryAction = CocoaAction {
return self.action.onCategoriesButtonTap.execute(()).map { _ in }
}
categoryHeaderView.configure(text: store.category.value.name, action: categoryAction)
return categoryHeaderView
}
return UIView()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == self.PlaylistsSection { return CategoryHeaderView.defaultHeight }
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let AdvertisementSection = 0
let PlaylistSection = 1
let LoadMoreSection = 2
switch indexPath.section {
case AdvertisementSection: return 50
case LoadMoreSection: return 44
case PlaylistSection:
let itemHeight = height(of: tableView)
let items = self.store.playlists.value.count
let lines = (items % itemsPerLine == 0) ? (items / itemsPerLine) : (items / itemsPerLine + 1)
return CGFloat(lines) * itemHeight + CGFloat(lines + 1) * itemPadding
default:
fatalError("Unexpected Row Height")
}
}
}
extension PlaylistViewController: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return "Playlist"
}
}
extension PlaylistViewController {
func bindStore() {
store.playlists.asObservable()
.filter { $0.count > 0 }
.do(onNext: { [weak self] _ in
self?.initialIndicatorView.stopAnimating()
self?.refreshControl.endRefreshing()
})
.map { playlists in PlaylistCollection(playlists: playlists) }
.map { collection -> [PlaylistCollectionSection] in [
PlaylistCollectionSection(model: "Advertisement", items: [PlaylistCollection(playlists: [
Playlist(id: "ad1", name: "Advertisement", singer: "Google", avatar: "not_found")
])]),
PlaylistCollectionSection(model: "Playlists", items: [collection]),
PlaylistCollectionSection(model: "Load More", items: [PlaylistCollection(playlists: [
Playlist(id: "load1", name: "Load More", singer: "Table View", avatar: "not_found")
])])
]}
.bind(to: tableView.rx.items(dataSource: dataSource))
.addDisposableTo(rx_disposeBag)
store.playlists.asObservable()
.filter { $0.count == 0 }
.subscribe(onNext: { [weak self] _ in
self?.initialIndicatorView.startAnimating(in: self?.view)
})
.addDisposableTo(rx_disposeBag)
store.category.asObservable()
.subscribe(onNext: { [weak self] category in
self?.categoryHeaderView.text = category.name
})
.addDisposableTo(rx_disposeBag)
store.playlistLoading.asObservable()
.skip(3)
.subscribe(onNext: { [weak self] loading in
if loading {
self?.loadingIndicatorView.startAnimation(in: self?.view); return
}
self?.loadingIndicatorView.stopAnimation()
self?.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
})
.addDisposableTo(rx_disposeBag)
}
func bindAction() {
action.onLoadCategories.execute(())
let initialCategoryLoading = store.category.asObservable()
.take(1)
.map { category in category.link }
let categoriesButtonTapLoading = action.onCategoriesButtonTap.elements
.filter { info in info != nil }
.map { category in category!.link }
.shareReplayLatestWhileConnected()
Observable.from([initialCategoryLoading, categoriesButtonTapLoading])
.merge()
.subscribe(action.onLoad.inputs)
.addDisposableTo(rx_disposeBag)
refreshControl.rx.controlEvent(.valueChanged)
.map { [weak self] _ in self!.store.category.value.link }
.subscribe(action.onPullToRefresh.inputs)
.addDisposableTo(rx_disposeBag)
tableView.rx.willDisplayCell
.filter { _, indexPath in indexPath.section == 2 }
.filter { [weak self] _, _ in self?.store.loadMoreEnabled.value ?? true }
.map { [weak self] _ in self!.store.category.value.link }
.subscribe(action.onLoadMore.inputs)
.addDisposableTo(rx_disposeBag)
}
}
| mit | 3d7daccb4eee3320750ae6d948a578ac | 37.974359 | 142 | 0.612368 | 5.463695 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/FNBJSocialFeed/FNBJSocialFeedFacebookCellTextOnly.swift | 1 | 1289 | //
// FacebookCell.swift
// FNBJSocialFeed
//
// Created by Felipe on 5/27/16.
// Copyright © 2016 Academic Technology Center. All rights reserved.
//
import UIKit
class FNBJSocialFeedFacebookCellTextOnly : UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var message: UILabel!
let defaults = NSUserDefaults.standardUserDefaults()
func build(post: FNBJSocialFeedFacebookPost){
self.message.text = post.message
self.name.text = post.fromName
if let profileImageLink = defaults.stringForKey(post.userID) {
let URL = NSURL(string: profileImageLink)
self.profileImage.hnk_setImageFromURL(URL!)
}else{
let controller = FNBJSocialFeedFacebookController(pageID: "itenwired")
controller.getUserProfile(post.userID, completion: { (user) in
print(user.profilePicture)
self.defaults.setObject(user.profilePicture, forKey: post.userID)
let URL = NSURL(string: user.profilePicture)
self.profileImage.hnk_setImageFromURL(URL!)
})
}
}
}
| bsd-2-clause | 8822c5694c52bf59bc49ba11e34b0132 | 28.272727 | 82 | 0.608696 | 4.934866 | false | false | false | false |
skillz/Cookie-Crunch-Adventure | CookieCrunch/Chain.swift | 1 | 2723 | /**
* Chain.swift
* CookieCrunch
* Copyright (c) 2017 Razeware LLC
*
* 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.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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.
*/
class Chain: Hashable, CustomStringConvertible {
var cookies: [Cookie] = []
var score = 0
enum ChainType: CustomStringConvertible {
case horizontal
case vertical
var description: String {
switch self {
case .horizontal: return "Horizontal"
case .vertical: return "Vertical"
}
}
}
var chainType: ChainType
init(chainType: ChainType) {
self.chainType = chainType
}
func add(cookie: Cookie) {
cookies.append(cookie)
}
func firstCookie() -> Cookie {
return cookies[0]
}
func lastCookie() -> Cookie {
return cookies[cookies.count - 1]
}
var length: Int {
return cookies.count
}
var description: String {
return "type:\(chainType) cookies:\(cookies)"
}
var hashValue: Int {
return cookies.reduce (0) { $0.hashValue ^ $1.hashValue }
}
/*
func hash(into hasher: (Int) -> Void) {
hasher(x)
hasher(y)
}
*/
static func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}
}
| mit | 9cd4900b78f6b2e994245c4eeabbe79d | 29.595506 | 82 | 0.702534 | 4.3568 | false | false | false | false |
balafd/SAC_iOS | SAC/SAC/API/SACWebService.swift | 1 | 6620 | //
// SACWebService.swift
// SAC
//
// Created by Bala on 19/08/17.
// Copyright © 2017 ShopAroundTheCorner. All rights reserved.
//
import Foundation
import Alamofire
class SACWebService: WebService {
func fetchShopDetail(shopID: Int, completion: @escaping (Shop?, [TrendingTag]?, [TrendingTag]?) -> Void) {
let path = hostURL + "shop/" + String(shopID)
Alamofire.request(
URL(string: path)!,
method: .post,
parameters: nil)
.validate()
.response(completionHandler: { (response) in
print("response :")
print(response)
})
.responseJSON { (response) -> Void in
guard response.result.isSuccess else {
print("Error while fetching shop details: \(String(describing: response.result.error))")
completion(nil, nil, nil)
return
}
guard let value = response.result.value as? [String: Any], let result = value["results"] as? [String: Any], let statusCode = value["status_code"] as? Int else {
completion(nil, nil, nil)
return
}
if statusCode != 200 {
completion(nil, nil, nil)
} else {
print("result : ")
print(result)
}
}
}
func registerShop(shop: Shop, description: String, tags: String, completion: @escaping (Int?) -> Void) {
let path = hostURL + "shop"
let params : [String: Any] = ["name": shop.name,
"latitude": shop.latitude,
"longitude": shop.longitude,
"description": description,
"address": shop.address,
"category_id": 1,
"phone": shop.phone,
"tags": tags
]
Alamofire.request(
URL(string: path)!,
method: .post,
parameters: params)
.validate()
.response(completionHandler: { (response) in
print("response :")
print(response)
})
.responseJSON { (response) -> Void in
guard response.result.isSuccess else {
print("Error while registering: \(String(describing: response.result.error))")
completion(nil)
return
}
guard let value = response.result.value as? [String: Any], let shopID = value["results"] as? Int, let statusCode = value["status_code"] as? Int else {
completion(nil)
return
}
if statusCode != 200 {
completion(nil)
} else {
completion(shopID)
}
}
}
var hostURL: String = "http://localhost:3006/"
func fetchShops(tagID: Int, latitude: Double, longitude: Double, completion: @escaping ([Shop]?) -> Void) {
let path = hostURL + "search"
let params : [String: Any] = ["tagId": tagID,
"latitude": latitude,
"longitude": longitude]
Alamofire.request(
URL(string: path)!,
method: .get,
parameters: params)
.validate()
.response(completionHandler: { (response) in
print("response :")
print(response)
})
.responseJSON { (response) -> Void in
guard response.result.isSuccess else {
print("Error while fetching remote rooms: \(String(describing: response.result.error))")
completion(nil)
return
}
guard let value = response.result.value as? [String: Any], let rows = value["results"] as? [[String:Any]], let statusCode = value["status_code"] as? Int else {
completion([Shop]())
return
}
if statusCode != 200 {
completion([Shop]())
return
} else {
print(value)
let shops = rows.flatMap({ (shopDict) -> Shop? in
do {
return try Shop(jsonDict: shopDict)
} catch {
print("Error : " + error.localizedDescription)
print(shopDict)
}
return nil
})
completion(shops)
}
}
}
func searchSuggestions(searchText: String, completion: @escaping ([Tag]?) -> Void) {
let path = hostURL + "search_suggest"
let params : [String: Any] = ["search_text": searchText]
Alamofire.request(
URL(string: path)!,
method: .get,
parameters: params)
.validate()
.response(completionHandler: { (response) in
print("response :")
print(response)
})
.responseJSON { (response) -> Void in
guard response.result.isSuccess else {
print("Error while fetching tags: \(String(describing: response.result.error))")
completion(nil)
return
}
guard let value = response.result.value as? [String: Any], let rows = value["results"] as? [[String:Any]], let statusCode = value["status_code"] as? Int else {
completion([Tag]())
return
}
print(value)
if statusCode != 200 {
completion([Tag]())
return
} else {
let tags = rows.flatMap({ (tagDict) -> Tag? in
do {
return try Tag(jsonDict: tagDict)
} catch {
print("Error : " + error.localizedDescription)
print(tagDict)
}
return nil
})
completion(tags)
}
}
}
}
| mit | 224f2c5da2e9d1f8757d9ea11011fefc | 37.04023 | 176 | 0.435262 | 5.492946 | false | false | false | false |
vadymmarkov/Kontena | Source/Container/Definition.swift | 1 | 696 | import Foundation
public class Definition
{
public enum Scope
{
case Singleton
case Prototype
}
public var scope: Scope
private let factory: () -> AnyObject
private var object: AnyObject?
public var instance: AnyObject?
{
if object == nil || scope == Scope.Prototype {
object = factory()
}
return object
}
public init(factory: () -> AnyObject, scope: Scope = Scope.Prototype)
{
self.factory = factory
self.scope = scope
}
public func asSingleton()
{
scope = Scope.Singleton
}
public func asPrototype()
{
scope = Scope.Prototype
}
}
| mit | c3c0d0f0ad1fc823baf274d88fc8a211 | 16.4 | 73 | 0.561782 | 4.767123 | false | false | false | false |
avielg/ExcelExport | Sources/ExcelExport/ExcelExport.swift | 1 | 12821 | /**
* ExcelExport
*
* Copyright (c) 2016 Aviel Gross. 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.
*/
#if os(OSX)
import AppKit
public typealias Color = NSColor
#else
import UIKit
public typealias Color = UIColor
#endif
public enum TextAttribute {
public enum FontStyle: Equatable {
case color(Color), bold
var parsed: String {
switch self {
case .bold: return "ss:Bold=\"1\""
case .color(let color): return "ss:Color=\"\(color.hexString())\""
}
}
public static func == (lhs: FontStyle, rhs: FontStyle) -> Bool {
switch (lhs, rhs) {
case (.bold, .bold): return true
case (.color(let lColor), .color(let rColor)): return lColor == rColor
default: return false
}
}
}
case backgroundColor(Color)
case font([FontStyle])
case format(String)
var parsed: String {
switch self {
case .backgroundColor(let color):
return "<Interior ss:Color=\"\(color.hexString())\" ss:Pattern=\"Solid\"/>"
case .format(let format):
return "<NumberFormat ss:Format=\"\(format)\"/>"
case .font(let styles):
return "<Font " + styles.map({$0.parsed}).joined(separator: " ") + "/>"
}
}
public static func a(lhs: TextAttribute, rhs: TextAttribute) -> Bool {
switch (lhs, rhs) {
case (.backgroundColor(let lColor), .backgroundColor(let rColor)): return lColor == rColor
case (.font(let lFont), .font(let rFont)): return lFont == rFont
case (.format(let lFormat), .format(let rFormat)): return lFormat == rFormat
default: return false
}
}
static func styleValue(for textAttributes: [TextAttribute]) -> String {
guard textAttributes.count > 0 else { return "" }
let parsedAttributes = textAttributes.map { $0.parsed }
return parsedAttributes.joined()
}
}
extension TextAttribute {
static let dateTimeTypeDateFormat = "1899-12-31T15:31:00.000"
}
public struct ExcelCell {
public let value: String
public let attributes: [TextAttribute]
public let colspan: Int?
public let rowspan: Int?
/**
This date formatter is used to format the date in the Data element for a DateTime cell.
It match what Excel is expecting.
*/
public static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return formatter
}()
public enum DataType: String { case string="String", dateTime="DateTime", number="Number" }
let type: DataType
public init(_ value: String, _ attributes: [TextAttribute], _ type: DataType = .string, colspan: Int? = nil,
rowspan: Int? = nil) {
self.value = value
self.attributes = attributes
self.colspan = colspan
self.type = type
self.rowspan = rowspan
}
public init(_ value: Double, _ attributes: [TextAttribute] = [], colspan: Int? = nil, rowspan: Int? = nil) {
self.init(String(format: "%f", arguments: [value]), attributes, .number, colspan: colspan, rowspan: rowspan)
}
/**
- Warnings: there is a default format (in attributes) as General Date.
If you want to specify other attributes, add the desired date format too.
*/
public init(_ value: Date, _ attributes: [TextAttribute] = [.format("General Date")], colspan: Int? = nil,
rowspan: Int? = nil) {
self.init( ExcelCell.dateFormatter.string(from: value), attributes, .dateTime, colspan: colspan,
rowspan: rowspan)
}
public init(_ value: String, _ attributes: [TextAttribute] = [], colspan: Int? = nil, rowspan: Int? = nil) {
self.init( value, attributes, .string, colspan: colspan, rowspan: rowspan)
}
public var dataElement: String {
return "<Data ss:Type=\"\(self.type.rawValue)\">\(self.value)</Data>"
}
public func cellElement(withStyleId styleId: String?, withIndexAttribute indexAttribute: String) -> String {
let mergeAcross = self.colspan.map { " ss:MergeAcross=\"\($0)\"" } ?? ""
let mergeDown = self.rowspan.map { " ss:MergeDown=\"\($0)\"" } ?? ""
let style = styleId != nil ? " ss:StyleID=\"\(styleId!)\"" : ""
let lead = "<Cell\(style)\(mergeAcross)\(mergeDown)\(indexAttribute)>"
let trail = "</Cell>"
return [lead, self.dataElement, trail].joined()
}
}
public struct ExcelRow {
public let cells: [ExcelCell]
public let height: Int?
public init(_ cells: [ExcelCell], height: Int? = nil) {
self.cells = cells
self.height = height
}
public var lead: String {
let rowOps = self.height.map { "ss:Height=\"\($0)\"" } ?? ""
let lead = "<Row \(rowOps)>"
return lead
}
public let trail: String = "</Row>"
}
public struct ExcelSheet {
public let rows: [ExcelRow]
public let name: String
public init(_ rows: [ExcelRow], name: String) {
self.rows = rows
self.name = name
}
public var lead: String {
return "<Worksheet ss:Name=\"\(self.name)\"><Table>"
}
public let trail = "</Table></Worksheet>"
}
public class ExcelExport {
private let workbookLead = """
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<?mso-application progid=\"Excel.Sheet\"?>\
<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" \
xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \
xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" \
xmlns:html=\"http://www.w3.org/TR/REC-html40\">
"""
private let workbookTrail = "</Workbook>"
private init() {
}
public class func export(_ sheets: [ExcelSheet], fileName: String, done: @escaping (URL?) -> Void) {
DispatchQueue.global(qos: .background).async {
let resultUrl = ExcelExport().performXMLExport(sheets, fileName: fileName)
DispatchQueue.main.async { done(resultUrl) }
}
}
private func performXMLExport(_ sheets: [ExcelSheet], fileName: String) -> URL? {
var sheetsValues = [String]()
for sheet in sheets {
// build sheet
var rows = [String]()
for row in sheet.rows {
var cells = [String]()
startRow()
for (cellIndex, cell) in row.cells.enumerated() {
computeCellIndex(cellIndex)
//style
let styleId = self.styleId(for: cell.attributes)
let indexAttribute = generateIndexAttribute(cellIndex)
cells.append(cell.cellElement(withStyleId: styleId, withIndexAttribute: indexAttribute))
setupMergeDownCells(cell)
}
decreaseRemainingRowSpanOnRemainingCells()
rows.append([row.lead, cells.joined(), row.trail].joined())
}
// combine rows on sheet
sheetsValues.append([sheet.lead, rows.joined(), sheet.trail].joined())
remainingSpan = [RemainingSpan]()
}
return writeToFile(name: fileName, sheets: sheetsValues, totalRows: sheets.flatMap { $0.rows }.count)
}
// MARK: - Output functions
private func writeToFile(name fileName: String, sheets sheetsValues: [String], totalRows: Int) -> URL? {
let file = fileUrl(name: fileName)
let content = [workbookLead, stylesValue, sheetsValues.joined(), workbookTrail].joined()
// write content to file
do {
try content.write(to: file, atomically: true, encoding: .utf8)
print("\(totalRows) Lines written to file")
return file
} catch {
print("Can't write \(totalRows) to file! [\(error)]")
return nil
}
}
private func fileUrl(name: String) -> URL {
let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return docsDir.appendingPathComponent("\(name).xls")
}
// MARK: - Styles feature utility properties and functions
// all styles for this workbook
private var styles = [String: String]() // id : value
// adds new style, returns it's ID
private func appendStyle(_ styleValue: String) -> String {
let id = "s\(styles.count)"
styles[id] = "<Style ss:ID=\"\(id)\">\(styleValue)</Style>"
return id
}
private func styleId(for attributes: [TextAttribute]) -> String? {
let styleValue = TextAttribute.styleValue(for: attributes)
let styleId: String?
if styleValue.isEmpty {
styleId = nil
} else if let id = styles.first(where: { _, value in value.contains(styleValue) })?.key {
styleId = id //reuse existing style
} else {
styleId = appendStyle(styleValue) //create new style
}
return styleId
}
private var stylesValue: String {
return "<Styles>\(styles.values.joined())</Styles>"
}
// MARK: - MergeDown feature utility types, properties and functions
struct RemainingSpan {
var remainingRows: Int
var colSpan: Int
var description: String {
return "remainingRows: \(remainingRows), colSpan: \(colSpan)"
}
}
private var vIndex: Int = 0
private var remainingSpan = [RemainingSpan]()
private func startRow() {
vIndex = 0
}
private func computeCellIndex(_ cellIndex: Int) {
while vIndex < remainingSpan.count && remainingSpan[vIndex].remainingRows > 0 {
remainingSpan[vIndex].remainingRows -= 1
vIndex += (remainingSpan[vIndex].colSpan + 1)
}
}
private func decreaseRemainingRowSpanOnRemainingCells() {
while vIndex < remainingSpan.count {
remainingSpan[vIndex].remainingRows -= 1
vIndex += 1
}
}
private func generateIndexAttribute(_ cellIndex: Int) -> String {
return vIndex != cellIndex ? " ss:Index=\"\(vIndex+1)\"": ""
}
private func setupMergeDownCells(_ cell: ExcelCell) {
// Setup mergeDown cells
if let newMergeDownCount = cell.rowspan {
while remainingSpan.count <= vIndex {
remainingSpan.append(RemainingSpan(remainingRows: 0, colSpan: 0))
}
remainingSpan[vIndex] = RemainingSpan(remainingRows: newMergeDownCount,
colSpan: cell.colspan ?? 0)
}
vIndex += 1
}
}
private extension Color {
/// Hex string of a UIColor instance.
///
/// - Parameter includeAlpha: Whether the alpha should be included.
/// - Returns: HEX, including the '#'
func hexString(_ includeAlpha: Bool = false) -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if includeAlpha {
return String(format: "#%02X%02X%02X%02X", Int(red * 255), Int(green * 255), Int(blue * 255),
Int(alpha * 255))
} else {
return String(format: "#%02X%02X%02X", Int(red * 255), Int(green * 255), Int(blue * 255))
}
}
}
| mit | cb94ea11dd82bb542e9646dd53fc98ed | 34.515235 | 116 | 0.592465 | 4.316835 | false | false | false | false |
CodaFi/PersistentStructure.swift | Persistent/AbstractPersistentMap.swift | 1 | 4382 | //
// AbstractPersistentMap.swift
// Persistent
//
// Created by Robert Widmann on 11/19/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
public class AbstractPersistentMap : IPersistentMap, IMap, IMapEquivalence, IHashEq {
var _hash : Int
var _hasheq : Int
init() {
_hash = -1
_hasheq = -1
}
public func cons(o : AnyObject) -> IPersistentCollection {
if let e = o as? IMapEntry {
return self.associateKey(e.key, withValue: e.val)
} else if let v = o as? IPersistentVector {
guard let k1 = v.objectAtIndex(0), v1 = v.objectAtIndex(1) else {
fatalError("Vector arg to map conj must be a pair")
}
return self.associateKey(k1, withValue: v1)
} else {
var ret : IPersistentMap = self
for var es : ISeq = Utils.seq(o); es.count != 0; es = es.next {
let e : IMapEntry = es.first as! IMapEntry
ret = ret.associateKey(e.key, withValue: e.val) as! IPersistentMap
}
return ret
}
}
func isEqual(obj : AnyObject) -> Bool {
return AbstractPersistentMap.mapisEqual(self, other: obj)
}
class func mapisEqual(m1: IPersistentMap, other obj: AnyObject) -> Bool {
if m1 === obj {
return true
}
if !(obj is IMap) {
return false
}
guard let m : IMap = obj as? IMap else {
return false
}
if m.count != m1.count {
return false
}
for var s = m1.seq; s.count != 0; s = s.next {
if let e = s.first as? IMapEntry {
let found: Bool = m.containsKey(e.key)
if !found || !Utils.isEqual(e.val, other: m.objectForKey(e.key)) {
return false
}
}
}
return true
}
public func equiv(obj: AnyObject) -> Bool {
if !(obj is IMap) {
return false
}
if !(obj is IPersistentMap) && !(obj is IMapEquivalence) {
return false
}
guard let m = obj as? IMap else {
return false
}
if m.count != self.count {
return false
}
for entry in self.seq.generate() {
if let e = entry as? IMapEntry {
let found = m.containsKey(e.key)
if !found || Utils.equiv(e.val, other: m.objectForKey(e.key)) {
return false
}
}
}
return true
}
var hash : UInt {
if _hash == -1 {
_hash = Int(AbstractPersistentMap.mapHash(self))
}
return UInt(_hash)
}
static func mapHash(m : IPersistentMap) -> UInt {
var hash : UInt = 0
for entry in m.seq.generate() {
let e : IMapEntry = entry as! IMapEntry
hash += UInt(e.key.hash ^ e.val.hash)
}
return hash
}
public var hasheq : Int {
if _hasheq == -1 {
_hasheq = AbstractPersistentMap.mapHasheq(self)
}
return _hasheq
}
static func mapHasheq(m : IPersistentMap) -> Int {
var hash : Int = 0
for entry in m.seq.generate() {
let e : IMapEntry = entry as! IMapEntry
hash += Int(Utils.hasheq(e.key) ^ Utils.hasheq(e.val))
}
return hash
}
public var empty : IPersistentCollection {
fatalError("\(__FUNCTION__) unimplemented")
}
public var seq : ISeq {
fatalError("\(__FUNCTION__) unimplemented")
}
public func associateKey(key : AnyObject, withValue value : AnyObject) -> IAssociative {
fatalError("\(__FUNCTION__) unimplemented")
}
public func entryForKey(key : AnyObject) -> IMapEntry? {
fatalError("\(__FUNCTION__) unimplemented")
}
public func associateEx(key : AnyObject, value : AnyObject) -> IPersistentMap {
fatalError("\(__FUNCTION__) unimplemented")
}
public func without(key : AnyObject) -> IPersistentMap {
fatalError("\(__FUNCTION__) unimplemented")
}
public var count : Int {
fatalError("\(__FUNCTION__) unimplemented")
}
public func objectForKey(key: AnyObject) -> AnyObject? {
fatalError("\(__FUNCTION__) unimplemented")
}
public func objectForKey(key : AnyObject, def : AnyObject) -> AnyObject {
fatalError("\(__FUNCTION__) unimplemented")
}
public func setObject(val: AnyObject, forKey key: AnyObject) -> AnyObject? {
fatalError("\(__FUNCTION__) unimplemented")
}
public func containsKey(key: AnyObject) -> Bool {
fatalError("\(__FUNCTION__) unimplemented")
}
public func containsValue(value: AnyObject) -> Bool {
fatalError("\(__FUNCTION__) unimplemented")
}
public var allEntries : ISet {
fatalError("\(__FUNCTION__) unimplemented")
}
public var isEmpty : Bool {
fatalError("\(__FUNCTION__) unimplemented")
}
public var allKeys : ISet {
fatalError("\(__FUNCTION__) unimplemented")
}
public var values : ICollection {
fatalError("\(__FUNCTION__) unimplemented")
}
}
| mit | 166e6abde44fd7f06b91c7033aef2f72 | 22.303191 | 89 | 0.645971 | 3.221324 | false | false | false | false |
practicalswift/swift | test/decl/protocol/protocol_with_superclass.swift | 1 | 10988 | // RUN: %target-typecheck-verify-swift
// Protocols with superclass-constrained Self.
class Concrete {
typealias ConcreteAlias = String
func concreteMethod(_: ConcreteAlias) {}
}
class Generic<T> : Concrete {
typealias GenericAlias = (T, T)
func genericMethod(_: GenericAlias) {}
}
protocol BaseProto {}
protocol ProtoRefinesClass : Generic<Int>, BaseProto {
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias)
// expected-note@-1 {{protocol requires function 'requirementUsesClassTypes' with type '(Generic<Int>.ConcreteAlias, Generic<Int>.GenericAlias) -> ()' (aka '(String, (Int, Int)) -> ()'); do you want to add a stub?}}
}
func duplicateOverload<T : ProtoRefinesClass>(_: T) {}
// expected-note@-1 {{'duplicateOverload' previously declared here}}
func duplicateOverload<T : ProtoRefinesClass & Generic<Int>>(_: T) {}
// expected-error@-1 {{invalid redeclaration of 'duplicateOverload'}}
// expected-warning@-2 {{redundant superclass constraint 'T' : 'Generic<Int>'}}
// expected-note@-3 {{superclass constraint 'T' : 'Generic<Int>' implied here}}
extension ProtoRefinesClass {
func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot convert value of type 'Self' to specified type 'Generic<String>'}}
}
}
func usesProtoRefinesClass1(_ t: ProtoRefinesClass) {
let x: ProtoRefinesClass.ConcreteAlias = "hi"
_ = ProtoRefinesClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesClass.GenericAlias = (1, 2)
_ = ProtoRefinesClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'ProtoRefinesClass' to specified type 'Generic<String>'}}
}
func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'T' to specified type 'Generic<String>'}}
}
class BadConformingClass1 : ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass1' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass1]}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-error@-1 {{use of undeclared type 'ConcreteAlias'}}
// expected-error@-2 {{use of undeclared type 'GenericAlias'}}
_ = ConcreteAlias.self
// expected-error@-1 {{use of unresolved identifier 'ConcreteAlias'}}
_ = GenericAlias.self
// expected-error@-1 {{use of unresolved identifier 'GenericAlias'}}
}
}
class BadConformingClass2 : Generic<String>, ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass2' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass2]}}
// expected-error@-3 {{type 'BadConformingClass2' does not conform to protocol 'ProtoRefinesClass'}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-note@-1 {{candidate has non-matching type '(BadConformingClass2.ConcreteAlias, BadConformingClass2.GenericAlias) -> ()' (aka '(String, (String, String)) -> ()')}}
_ = ConcreteAlias.self
_ = GenericAlias.self
}
}
class GoodConformingClass : Generic<Int>, ProtoRefinesClass {
func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
}
}
protocol ProtoRefinesProtoWithClass : ProtoRefinesClass {}
extension ProtoRefinesProtoWithClass {
func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot convert value of type 'Self' to specified type 'Generic<String>'}}
}
}
func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) {
let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi"
_ = ProtoRefinesProtoWithClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2)
_ = ProtoRefinesProtoWithClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'ProtoRefinesProtoWithClass' to specified type 'Generic<String>'}}
}
func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'T' to specified type 'Generic<String>'}}
}
class ClassWithInits<T> {
init(notRequiredInit: ()) {}
// expected-note@-1 6{{selected non-required initializer 'init(notRequiredInit:)'}}
required init(requiredInit: ()) {}
}
protocol ProtocolWithClassInits : ClassWithInits<Int> {}
func useProtocolWithClassInits1() {
_ = ProtocolWithClassInits(notRequiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolWithClassInits' cannot be instantiated}}
_ = ProtocolWithClassInits(requiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolWithClassInits' cannot be instantiated}}
}
func useProtocolWithClassInits2(_ t: ProtocolWithClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'ProtocolWithClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolWithClassInits = t.init(requiredInit: ())
}
func useProtocolWithClassInits3<T : ProtocolWithClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
protocol ProtocolRefinesClassInits : ProtocolWithClassInits {}
func useProtocolRefinesClassInits1() {
_ = ProtocolRefinesClassInits(notRequiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolRefinesClassInits' cannot be instantiated}}
_ = ProtocolRefinesClassInits(requiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolRefinesClassInits' cannot be instantiated}}
}
func useProtocolRefinesClassInits2(_ t: ProtocolRefinesClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'ProtocolRefinesClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolRefinesClassInits = t.init(requiredInit: ())
}
func useProtocolRefinesClassInits3<T : ProtocolRefinesClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
// Make sure that we don't require 'mutating' when the protocol has a superclass
// constraint.
protocol HasMutableProperty : Concrete {
var mutableThingy: Any? { get set }
}
extension HasMutableProperty {
func mutateThingy() {
mutableThingy = nil
}
}
// Some pathological examples -- just make sure they don't crash.
protocol RecursiveSelf : Generic<Self> {}
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self>' is recursive}}
protocol RecursiveAssociatedType : Generic<Self.X> {
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self.X>' is recursive}}
associatedtype X
}
protocol BaseProtocol {
typealias T = Int
}
class BaseClass : BaseProtocol {}
protocol RefinedProtocol : BaseClass {
func takesT(_: T)
}
func takesBaseProtocol(_: BaseProtocol) {}
func passesRefinedProtocol(_ r: RefinedProtocol) {
takesBaseProtocol(r)
}
class RefinedClass : BaseClass, RefinedProtocol {
func takesT(_: T) {
_ = T.self
}
}
class LoopClass : LoopProto {}
protocol LoopProto : LoopClass {}
class FirstClass {}
protocol FirstProtocol : FirstClass {}
class SecondClass : FirstClass {}
protocol SecondProtocol : SecondClass, FirstProtocol {}
class FirstConformer : FirstClass, SecondProtocol {}
// expected-error@-1 {{'SecondProtocol' requires that 'FirstConformer' inherit from 'SecondClass'}}
// expected-note@-2 {{requirement specified as 'Self' : 'SecondClass' [with Self = FirstConformer]}}
class SecondConformer : SecondClass, SecondProtocol {}
// Duplicate superclass
// FIXME: Duplicate diagnostics
protocol DuplicateSuper : Concrete, Concrete {}
// expected-note@-1 {{superclass constraint 'Self' : 'Concrete' written here}}
// expected-warning@-2 {{redundant superclass constraint 'Self' : 'Concrete'}}
// expected-error@-3 {{duplicate inheritance from 'Concrete'}}
// Ambigous name lookup situation
protocol Amb : Concrete {}
// expected-note@-1 {{'Amb' previously declared here}}
// expected-note@-2 {{found this candidate}}
protocol Amb : Concrete {}
// expected-error@-1 {{invalid redeclaration of 'Amb'}}
// expected-note@-2 {{found this candidate}}
extension Amb { // expected-error {{'Amb' is ambiguous for type lookup in this context}}
func extensionMethodUsesClassTypes() {
_ = ConcreteAlias.self
}
}
| apache-2.0 | c54f64557dd26f42d0cf0c149d5ca709 | 31.128655 | 217 | 0.7085 | 3.878574 | false | false | false | false |
samsara/samsara | clients/ios/Pod/Classes/SSPublisher.swift | 1 | 2436 | //
// SSPublisher.swift
// samsara-ios-sdk
//
// Created by Sathyavijayan Vittal on 13/04/2015.
// Copyright © 2015-2017 Samsara's authors.
//
import Foundation
public class SSPublisher : NSObject {
class func send(events: [(Int, SSEvent)], samsaraConfig: SSConfig, completionHandler: ([(Int, SSEvent)], Bool, String) -> Void) {
var items:[SSEvent] = events.map({$1})
send(items, samsaraConfig: samsaraConfig) {(e, err, err_msg) -> Void in
completionHandler(events, err, err_msg)
}
}
class func send(events: [SSEvent], samsaraConfig: SSConfig, completionHandler: ([SSEvent], Bool, String) -> Void) {
var eventsURL = NSURL(string: SSURLForPath("events", config: samsaraConfig))
if let url = eventsURL {
var req = NSMutableURLRequest(URL: url)
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
var timestamp = NSNumber(longLong: Int64(NSDate().timeIntervalSince1970 * 1000))
req.setValue(timestamp.stringValue, forHTTPHeaderField:"X-Samsara-publishedTimestamp")
req.HTTPMethod = "POST"
var body:String = SSJSONStringify(events, prettyPrinted: false)
req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(req) { (data,response,error) -> Void in
var isError = false
var errorMessage:String = ""
if let resp = response {
var httpResponse = resp as! NSHTTPURLResponse
if (httpResponse.statusCode != 202) {
isError = true
errorMessage = "Samsara returned HTTP:\(httpResponse.statusCode)"
NSLog("SSPublisher: Error: \(errorMessage)")
}
} else if let err = error {
isError = true
errorMessage = err.localizedDescription
NSLog("SSPublisher: Error: \(err.localizedDescription)")
}
completionHandler(events, isError, errorMessage)
}
task.resume()
} else {
NSLog("SSPublisher: Unable to create URL. This should never happen unless the URL passed is invalid.")
}
}
}
| apache-2.0 | 4163119b92feb004abac0f4268af0d5b | 37.650794 | 133 | 0.590554 | 4.728155 | false | true | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/StarNode.swift | 1 | 7093 | //
// StarNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
final class StarNodeProperties: NodePropertyMap, KeypathSearchable {
var keypathName: String
init(star: Star) {
self.keypathName = star.name
self.direction = star.direction
self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
self.outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
self.outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
if let innerRadiusKeyframes = star.innerRadius?.keyframes {
self.innerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: innerRadiusKeyframes))
} else {
self.innerRadius = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
}
if let innderRoundedness = star.innerRoundness?.keyframes {
self.innerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: innderRoundedness))
} else {
self.innerRoundedness = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
}
self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
self.points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
self.keypathProperties = [
"Position" : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
"Inner Radius" : innerRadius,
"Inner Roundedness" : innerRoundedness,
"Rotation" : rotation,
"Points" : points
]
self.properties = Array(keypathProperties.values)
}
let keypathProperties: [String : AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<Vector3D>
let outerRadius: NodeProperty<Vector1D>
let outerRoundedness: NodeProperty<Vector1D>
let innerRadius: NodeProperty<Vector1D>
let innerRoundedness: NodeProperty<Vector1D>
let rotation: NodeProperty<Vector1D>
let points: NodeProperty<Vector1D>
}
final class StarNode: AnimatorNode, PathNode {
let properties: StarNodeProperties
let pathOutput: PathOutputNode
init(parentNode: AnimatorNode?, star: Star) {
self.pathOutput = PathOutputNode(parent: parentNode?.outputNode)
self.properties = StarNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
return properties
}
let parentNode: AnimatorNode?
var hasLocalUpdates: Bool = false
var hasUpstreamUpdates: Bool = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled: Bool = true {
didSet{
self.pathOutput.isEnabled = self.isEnabled
}
}
/// Magic number needed for building path data
static let PolystarConstant: CGFloat = 0.47829
func rebuildOutputs(frame: CGFloat) {
let outerRadius = properties.outerRadius.value.cgFloatValue
let innerRadius = properties.innerRadius.value.cgFloatValue
let outerRoundedness = properties.outerRoundedness.value.cgFloatValue * 0.01
let innerRoundedness = properties.innerRoundedness.value.cgFloatValue * 0.01
let numberOfPoints = properties.points.value.cgFloatValue
let rotation = properties.rotation.value.cgFloatValue
let position = properties.position.value.pointValue
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = (2 * CGFloat.pi) / numberOfPoints
let halfAnglePerPoint = anglePerPoint / 2.0
let partialPointAmount = numberOfPoints - floor(numberOfPoints)
var point: CGPoint = .zero
var partialPointRadius: CGFloat = 0
if partialPointAmount != 0 {
currentAngle += halfAnglePerPoint * (1 - partialPointAmount)
partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius)
point.x = (partialPointRadius * cos(currentAngle))
point.y = (partialPointRadius * sin(currentAngle))
currentAngle += anglePerPoint * partialPointAmount / 2
} else {
point.x = (outerRadius * cos(currentAngle))
point.y = (outerRadius * sin(currentAngle))
currentAngle += halfAnglePerPoint
}
var vertices = [CurveVertex]()
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
var previousPoint = point
var longSegment = false
let numPoints: Int = Int(ceil(numberOfPoints) * 2)
for i in 0..<numPoints {
var radius = longSegment ? outerRadius : innerRadius
var dTheta = halfAnglePerPoint
if partialPointRadius != 0 && i == numPoints - 2 {
dTheta = anglePerPoint * partialPointAmount / 2
}
if partialPointRadius != 0 && i == numPoints - 1 {
radius = partialPointRadius
}
previousPoint = point
point.x = (radius * cos(currentAngle))
point.y = (radius * sin(currentAngle))
if innerRoundedness == 0 && outerRoundedness == 0 {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
} else {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta)
let cp1Dy = sin(cp1Theta)
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness
let cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness
let cp1Radius = longSegment ? innerRadius : outerRadius
let cp2Radius = longSegment ? outerRadius : innerRadius
var cp1 = CGPoint(x: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dx,
y: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dy)
var cp2 = CGPoint(x: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dx,
y: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dy)
if partialPointAmount != 0 {
if i == 0 {
cp1 = cp1 * partialPointAmount
} else if i == numPoints - 1 {
cp2 = cp2 * partialPointAmount
}
}
let previousVertex = vertices[vertices.endIndex-1]
vertices[vertices.endIndex-1] = CurveVertex(previousVertex.inTangent, previousVertex.point, previousVertex.point - cp1 + position)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
}
currentAngle += dTheta
longSegment = !longSegment
}
let reverse = properties.direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
pathOutput.setPath(path, updateFrame: frame)
}
}
| mit | c3fa648ab5da81be3e9b24f602748d89 | 37.759563 | 138 | 0.694206 | 4.314477 | false | false | false | false |
wolfposd/Caffeed | FeedbackBeaconContext/FeedbackBeaconContext/FeedbackSheet/View/LongListCell.swift | 1 | 2782 | //
// LongListModuleCell.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class LongListCell: ModuleCell, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: Properties
@IBOutlet var textField: UITextField!
let listPicker = UIPickerView()
override var module: FeedbackSheetModule? {
willSet {
if let list = newValue as? ListModule {
textField.placeholder = list.text
listPicker.reloadAllComponents()
}
}
}
// FIXME: Testing, current Bug in Xcode (Ambiguous use of module)
override func setModule(module: FeedbackSheetModule) {
self.module = module
}
// MARK: View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
textField.layer.borderColor = UIColor.grayColor().CGColor
textField.layer.borderWidth = 1.5
textField.layer.cornerRadius = 5
let doneButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "selectListElement")
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 44.0))
toolbar.setItems([flexibleSpace, doneButtonItem], animated: false)
listPicker.delegate = self
textField.inputAccessoryView = toolbar
textField.inputView = listPicker
}
// MARK: Actions
func selectListElement() {
textField.resignFirstResponder()
}
override func reloadWithResponseData(responseData: AnyObject) {
}
// MARK: UIPickerViewDataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let longList = module as? ListModule {
return longList.elements.count
} else {
return 0
}
}
// MARK: UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return (module as? ListModule)?.elements[row];
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
if let longList = module as? ListModule {
textField.text = longList.elements[row]
longList.responseData = longList.elements[row]
delegate?.moduleCell(self, didGetResponse: longList.responseData, forID: longList.ID)
}
}
}
| gpl-3.0 | eab7846ab41d82a99c42fd3266390afe | 29.911111 | 120 | 0.645579 | 4.959002 | false | false | false | false |
sman591/pegg | Pegg/SignupViewController.swift | 1 | 2112 | //
// SignupViewController.swift
// Pegg
//
// Created by Stuart Olivera on 2/4/15.
// Copyright (c) 2015 Henry Saniuk, Stuart Olivera, Brandon Hudson. All rights reserved.
//
import UIKit
import SwiftyJSON
class SignupController: UIViewController {
@IBOutlet weak var firstField: UITextField!
@IBOutlet weak var lastField: UITextField!
@IBOutlet weak var userField: UITextField!
@IBOutlet weak var passField: UITextField!
@IBOutlet weak var emailField: UITextField!
var clicked = false
@IBOutlet weak var signup: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
signup.layer.cornerRadius = 5
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
@IBAction func backToLogin(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func signupAction(sender: UIButton) {
let username = userField.text
let first = firstField.text
let last = lastField.text
let email = emailField.text
let password = passField.text
PeggAPI.signUp(first, last: last, email: email, username: username, password: password, completion: { json in
self.dismissViewControllerAnimated(true, completion: nil)
})
}
func keyboardWillShow(sender: NSNotification) {
if !clicked {
self.view.frame.origin.y -= 175
clicked = true
}
}
func keyboardWillHide(sender: NSNotification) {
if clicked {
self.view.frame.origin.y += 175
clicked = false
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 358f87f8b581851856d3e01d123d07d5 | 26.789474 | 144 | 0.66572 | 4.957746 | false | false | false | false |
nbhasin2/NBNavigationController | Example/GobstonesSwift/Utils/NetworkUtils.swift | 1 | 1630 | //
// NetworkUtils.swift
// GobstonesSwift
//
// Created by Nishant Bhasin on 2016-12-21.
// Copyright © 2016 Nishant Bhasin. All rights reserved.
//
import Foundation
import UIKit
enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
class NetworkUtils {
// func fetchRandomGif(completion: (_ label: UILabel) -> ()) {
//
// }
func fetchRandomGif(completion: @escaping (_ gifUrl: String) -> Void) {
let urlPath = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC"
guard let endpoint = URL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = URLRequest(url: endpoint)
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any> else {
throw JSONError.ConversionFailed
}
print(json.dictionaryValue("data").stringValue("image_original_url"))
completion(json.dictionaryValue("data").stringValue("image_original_url"))
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
}
| mit | 7b74342b12fafa354718c229e8e5e58e | 30.941176 | 125 | 0.558625 | 4.525 | false | false | false | false |
oklasoft/Multi-Matcher | Multi Matcher/ShellWrapper.swift | 1 | 4522 | //
// ShellWrapper.swift
// Multi Matcher
//
// Created by Stuart Glenn on 2015-04-03.
// Copyright (c) 2015 Stuart Glenn, Oklahoma Medical Research Foundation.
// All rights reserved.
// Use of this source code is governed by a 3 clause BSD style license.
// Full details can be found in the LICENSE file distributed with this software
//
import Foundation
protocol ShellWrapperDelegate {
func appendStdOut(wrapper: ShellWrapper, output: String)
func appendStdErr(wrapper: ShellWrapper, err: String)
func processStarted(wrapper: ShellWrapper)
func processFinished(wrapper: ShellWrapper, status: Int)
}
class ShellWrapper : NSObject {
enum OutputType {
case StdOut
case StdErr
}
var task: NSTask?
var delegate: ShellWrapperDelegate?
var path : String?
var args : [String]?
var stdout : NSFileHandle?
var stdoutEmpty = false
var stderr : NSFileHandle?
var stderrEmpty = false
var taskTerminated = false
convenience override init() {
self.init(path:"",args:[])
}
init(path: String, args: [String]) {
super.init()
self.path = path
self.args = args
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
func start() {
delegate?.processStarted(self)
task = NSTask()
task?.launchPath = self.path!
task?.arguments = self.args!
task?.standardOutput = NSPipe()
stdout = task?.standardOutput.fileHandleForReading
task?.standardError = NSPipe()
stderr = task?.standardError.fileHandleForReading
NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataArrived:", name: NSFileHandleReadCompletionNotification,
object: stdout)
stdoutEmpty = false
stdout?.readInBackgroundAndNotify()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataArrived:", name: NSFileHandleReadCompletionNotification,
object: stderr)
stderrEmpty = true
stderr?.readInBackgroundAndNotify()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "taskDidTerminate:", name: NSTaskDidTerminateNotification,
object: task)
taskTerminated = false
task?.launch()
}
func stop() {
task?.terminate()
}
func cleanup() {
var status = -1
if taskTerminated {
NSNotificationCenter.defaultCenter().removeObserver(self)
var data : NSData?
for data = stdout?.availableData; data?.length > 0; data = stdout?.availableData {
sendOutput(data!, destination: OutputType.StdOut)
}
for data = stderr?.availableData; data?.length > 0; data = stderr?.availableData {
sendOutput(data!, destination: OutputType.StdOut)
}
status = Int(task!.terminationStatus)
}
delegate?.processFinished(self, status: status)
delegate = nil
}
func sendOutput(data: NSData, destination: OutputType) {
var msg = NSString(data: data, encoding: NSUTF8StringEncoding)
switch destination {
case .StdErr:
delegate?.appendStdErr(self, err: msg! as String)
case .StdOut:
delegate?.appendStdOut(self, output: msg! as String)
}
}
func dataArrived(n: NSNotification) {
let obj = n.object as! NSFileHandle
let data = n.userInfo!["NSFileHandleNotificationDataItem"] as! NSData
if data.length > 0 {
if obj == stdout {
sendOutput(data, destination: OutputType.StdOut)
stdoutEmpty = false
} else if obj == stderr {
sendOutput(data, destination: OutputType.StdErr)
stderrEmpty = false
}
obj.readInBackgroundAndNotify()
} else {
if obj == stdout {
stdoutEmpty = true
} else if obj == stderr {
stderrEmpty = true
}
if stdoutEmpty && stderrEmpty && taskTerminated {
cleanup()
}
}
}
func taskDidTerminate(n: NSNotification) {
if taskTerminated {
return
}
taskTerminated = true
if stdoutEmpty && stderrEmpty {
cleanup()
}
}
} | bsd-3-clause | 49e5976af13df10c9f78e75df0aa538d | 29.560811 | 134 | 0.591995 | 5.013304 | false | false | false | false |
TsuiOS/LoveFreshBeen | LoveFreshBeenX/Class/Model/XNHeadResources.swift | 1 | 1141 | //
// XNHeadResources.swift
// LoveFreshBeenX
//
// Created by xuning on 16/6/15.
// Copyright © 2016年 hus. All rights reserved.
//
import UIKit
class XNHeadResources: Reflect {
var msg: String?
var reqid: String?
var data: HeadData?
class func loadHomeHeadData(completion:(model: XNHeadResources?, error: NSError?) -> Void) {
let path = NSBundle.mainBundle().pathForResource("首页焦点按钮", ofType: nil)
let data = NSData(contentsOfFile: path!)
if data != nil {
let dict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as! NSDictionary
let data = XNHeadResources.parse(dict: dict)
completion(model: data, error: nil)
}
}
}
class HeadData: Reflect {
var focus: [Activities]?
var icons: [Activities]?
var activities: [Activities]?
}
class Activities: Reflect {
var id: String?
var name: String?
var img: String?
var mimg: String?
var topimg: String?
var jptype: String?
var trackid: String?
}
| mit | 4e47c71216781ebc541c4c96728215e4 | 21.078431 | 118 | 0.60302 | 4.007117 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/Others/SMSValidPasscodeLogin/SMSValidation/ConfirmMobileValidationVC.swift | 1 | 5589 | //
// SMSValidationViewController.swift
// Yona
//
// Created by Chandan on 01/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
// THIS whole class system is becoming a mess
// we should spend 1-2 days on cleaning it up
// Anders Liebl
import UIKit
class ConfirmMobileValidationVC: ValidationMasterView {
@IBOutlet var resendConfirmCodeButton: UIButton!
var isFromUserProfile : Bool = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "ConfirmMobileValidationVC")
let builder = GAIDictionaryBuilder.createScreenView()
tracker?.send(builder?.build() as? [AnyHashable: Any])
self.navigationController?.isNavigationBarHidden = false
setBackgroundColour()
self.codeInputView.delegate = self
self.codeInputView.secure = true
codeView.addSubview(self.codeInputView)
//keyboard functions
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)) , name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@IBAction func resendConfirmationCodeAction(_ sender: UIButton) {
Loader.Show()
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "sendConfirmationCodeAgain", label: "Send confirmationCode again", value: nil).build() as? [AnyHashable: Any])
UserRequestManager.sharedInstance.resendConfirmationCodeMobile{ (success, message, code) in
if success {
Loader.Hide()
self.codeInputView.isUserInteractionEnabled = true
#if DEBUG
print ("pincode is \(YonaConstants.testKeys.testConfirmationCode)")
#endif
} else {
Loader.Hide()
if let message = message {
self.infoLabel.text = message
}
}
}
}
// Go Back To Previous VC
@IBAction func back(_ sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
}
extension ConfirmMobileValidationVC: CodeInputViewDelegate {
func handleNavigationFromProfileView() {
if UserDefaults.standard.bool(forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromProfile){
UserDefaults.standard.set(false, forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromProfile)
setViewControllerToDisplay(ViewControllerTypeString.login, key: YonaConstants.nsUserDefaultsKeys.screenToDisplay)
UserDefaults.standard.set(true, forKey: YonaConstants.nsUserDefaultsKeys.isLoggedIn)
}
self.navigationController?.popToRootViewController(animated: false)
}
func handleNavigationFromSignUpView() {
UserDefaults.standard.set(false, forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromSignUp)
setViewControllerToDisplay(ViewControllerTypeString.setPin, key: YonaConstants.nsUserDefaultsKeys.screenToDisplay)
self.performSegue(withIdentifier: R.segue.confirmMobileValidationVC.transToSetPincode, sender: self)
}
func codeInputView(_ codeInputView: CodeInputView, didFinishWithCode code: String) {
let body = [YonaConstants.jsonKeys.bodyCode: code]
Loader.Show()
UserRequestManager.sharedInstance.confirmMobileNumber(body as BodyDataDictionary,onCompletion: { (success, message, serverCode )in
Loader.Hide()
self.codeInputView.clear()
if (success) {
self.codeInputView.resignFirstResponder()
//Update flag
if self.isFromUserProfile {
self.handleNavigationFromProfileView()
} else {
self.handleNavigationFromSignUpView()
}
} else {
self.checkCodeMessageShowAlert(message, serverMessageCode: serverCode, codeInputView: codeInputView)
}
})
}
}
extension ConfirmMobileValidationVC: KeyboardProtocol {
@objc func keyboardWasShown (_ notification: Notification) {
if let activeField = self.resendConfirmCodeButton, let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect = self.view.bounds
aRect.origin.x = 64
aRect.size.height -= 64
aRect.size.height -= keyboardSize.size.height
if (!aRect.contains(activeField.frame.origin)) {
var frameToScrollTo = activeField.frame
frameToScrollTo.size.height += 30
self.scrollView.scrollRectToVisible(frameToScrollTo, animated: true)
}
}
}
@objc func keyboardWillBeHidden(_ notification: Notification) {
let contentInsets = UIEdgeInsets.zero
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
}
| mpl-2.0 | eb7b6f209ac2fd70508da0690539c72e | 42.317829 | 200 | 0.66947 | 5.462366 | false | false | false | false |
blinker13/Geometry | Sources/Shapes/Path.swift | 1 | 1092 |
public struct Path : Equatable, ExpressibleByArrayLiteral, Shape {
public enum Element : Equatable {
case move(to: Point)
case line(to: Point)
case quadCurve(to: Point, Point)
case cubicCurve(to: Point, Point, Point)
case close
}
public let elements: [Element]
public init(with elements: [Element]) {
self.elements = elements
}
public init(from decoder: Decoder) throws {
#warning("Needs Implementation")
elements = []
}
public func encode(to encoder: Encoder) throws {
#warning("Needs Implementation")
}
}
// MARK: -
public extension Path {
@inlinable var path: Path { self }
@inlinable init(with shape: Shape) {
self = shape.path
}
@inlinable init(with shapes: [Shape]) {
elements = shapes.flatMap(\.path.elements)
}
@inlinable init<Data : Sequence>(_ data: Data, build: (Data.Element) -> Shape) {
self.init(with: data.map(build))
}
@inlinable init(arrayLiteral elements: Element ...) {
self.elements = elements
}
@inlinable func transformed(by transform: Transform) -> Self {
#warning("Needs Implementation")
return self
}
}
| mit | 1fb4c1397a801dc6ad94cc6310c5e227 | 19.222222 | 81 | 0.687729 | 3.37037 | false | false | false | false |
NicholasTD07/SwiftDailyAPI | SwiftDailyAPITests/DecodingPerformanceTests.swift | 1 | 1193 | //
// PerformanceTests.swift
// SwiftDailyAPI
//
// Created by Nicholas Tian on 1/06/2015.
// Copyright (c) 2015 nickTD. All rights reserved.
//
import XCTest
import SwiftDailyAPI
import Argo
class DecodingPerformanceTests: XCTestCase {
func testDecodingDaily() {
measureDecodingModel(Daily.self, fromFile: "daily_news_20150525")
}
func testDecodingLatestDaily() {
measureDecodingModel(LatestDaily.self, fromFile: "latest_daily_news_20150527")
}
func testDecodingNews() {
measureDecodingModel(News.self, fromFile: "news_4770416")
}
func testDecodingNewsExtra() {
measureDecodingModel(NewsExtra.self, fromFile: "news_extra_4770416")
}
func testDecodingShortComments() {
measureDecodingModel(Comments.self, fromFile: "short_comments_4772308")
}
func testDecodingLongComments() {
measureDecodingModel(Comments.self, fromFile: "long_comments_4772308")
}
func measureDecodingModel<T: Decodable where T == T.DecodedType>(type: T.Type, fromFile file: String) {
let json: AnyObject = JSONFileReader.JSON(fromFile: file)!
measureBlock {
let model: T? = T.decode(JSON.parse(json)).value
assert(model != nil)
}
}
}
| mit | 4ce2d1f5f78f7e41d169f9e4f54269c9 | 24.934783 | 105 | 0.720034 | 3.728125 | false | true | false | false |
JonyFang/AnimatedDropdownMenu | Examples/Examples/MenuTypes/LeftTypeTreeViewController.swift | 1 | 3712 | //
// LeftTypeTreeViewController.swift
// AnimatedDropdownMenu
//
// Created by JonyFang on 17/3/3.
// Copyright © 2017年 JonyFang. All rights reserved.
//
import UIKit
import AnimatedDropdownMenu
class LeftTypeTreeViewController: UIViewController {
// MARK: - Properties
fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [
AnimatedDropdownMenu.Item.init("From | Photography",
UIImage(named: "icon_photography")!,
UIImage(named: "icon_photography_light")!
),
AnimatedDropdownMenu.Item.init("From | Artwork",
UIImage(named: "icon_artwork")!,
UIImage(named: "icon_artwork_light")!
),
AnimatedDropdownMenu.Item.init("Others",
UIImage(named: "icon_other")!,
UIImage(named: "icon_other_light")!
)
]
fileprivate var selectedStageIndex: Int = 0
fileprivate var lastStageIndex: Int = 0
fileprivate var dropdownMenu: AnimatedDropdownMenu!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupAnimatedDropdownMenu()
view.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetNavigationBarColor()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
dropdownMenu.show()
}
// MARK: - Private Methods
fileprivate func setupAnimatedDropdownMenu() {
let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems)
dropdownMenu.cellBackgroundColor = UIColor.menuPurpleColor()
dropdownMenu.menuTitleColor = UIColor.menuLightTextColor()
dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor()
dropdownMenu.cellTextColor = UIColor.init(white: 1.0, alpha: 0.3)
dropdownMenu.cellTextSelectedColor = UIColor.menuLightTextColor()
dropdownMenu.cellSeparatorColor = UIColor.init(white: 1.0, alpha: 0.1)
dropdownMenu.cellTextAlignment = .left
dropdownMenu.didSelectItemAtIndexHandler = {
[weak self] selectedIndex in
guard let strongSelf = self else {
return
}
strongSelf.lastStageIndex = strongSelf.selectedStageIndex
strongSelf.selectedStageIndex = selectedIndex
guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else {
return
}
//Configure Selected Action
strongSelf.selectedAction()
}
self.dropdownMenu = dropdownMenu
navigationItem.titleView = dropdownMenu
}
private func selectedAction() {
print("\(dropdownItems[selectedStageIndex].title)")
}
fileprivate func resetNavigationBarColor() {
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.barTintColor = UIColor.menuPurpleColor()
let textAttributes: [String: Any] = [
NSForegroundColorAttributeName: UIColor.menuLightTextColor(),
NSFontAttributeName: UIFont.navigationBarTitleFont()
]
navigationController?.navigationBar.titleTextAttributes = textAttributes
}
}
| mit | 75ad67c4b92d3402262fde1b0af10d33 | 33.027523 | 169 | 0.605554 | 6.21273 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/ScheduleComponent/View/UIKit/DaysHorizontalPickerView.swift | 1 | 5094 | import ComponentBase
import UIKit
protocol DaysHorizontalPickerViewDelegate: AnyObject {
func daysHorizontalPickerView(_ pickerView: DaysHorizontalPickerView, didSelectDayAt index: Int)
}
class DaysHorizontalPickerView: UIView {
private lazy var collectionView: UICollectionView = {
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.minimumInteritemSpacing = 0
collectionViewLayout.minimumLineSpacing = 0
collectionViewLayout.scrollDirection = .horizontal
collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
let smallFrameSoCollectionViewWillLayout = CGRect(x: 0, y: 0, width: 1, height: 1)
return UICollectionView(frame: smallFrameSoCollectionViewWillLayout, collectionViewLayout: collectionViewLayout)
}()
weak var delegate: DaysHorizontalPickerViewDelegate?
func bind(numberOfDays: Int, using binder: ScheduleDaysBinder) {
daysController = DaysController(
numberOfDays: numberOfDays,
binder: binder,
onDaySelected: dayPickerDidSelectDay
)
}
func selectDay(at index: Int) {
collectionView.selectItem(
at: IndexPath(item: index, section: 0),
animated: true,
scrollPosition: .centeredHorizontally
)
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override var bounds: CGRect {
didSet {
collectionView.collectionViewLayout.invalidateLayout()
}
}
private func setUp() {
backgroundColor = .clear
collectionView.backgroundColor = .clear
collectionView.clipsToBounds = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.translatesAutoresizingMaskIntoConstraints = false
let cellName = String(describing: ScheduleDayCollectionViewCell.self)
let cellNib = UINib(nibName: cellName, bundle: .module)
collectionView.register(cellNib, forCellWithReuseIdentifier: cellName)
addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: topAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
private var daysController: DaysController? {
didSet {
collectionView.dataSource = daysController
collectionView.delegate = daysController
}
}
private func dayPickerDidSelectDay(_ index: Int) {
delegate?.daysHorizontalPickerView(self, didSelectDayAt: index)
}
private class DaysController: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private let numberOfDays: Int
private let binder: ScheduleDaysBinder
private let onDaySelected: (Int) -> Void
init(numberOfDays: Int, binder: ScheduleDaysBinder, onDaySelected: @escaping (Int) -> Void) {
self.numberOfDays = numberOfDays
self.binder = binder
self.onDaySelected = onDaySelected
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfDays
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeue(ScheduleDayCollectionViewCell.self, for: indexPath)
binder.bind(cell, forDayAt: indexPath.item)
return cell
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let availableWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
let sensibleMinimumWidth: CGFloat = 84
let numberOfItems = collectionView.numberOfItems(inSection: indexPath.section)
let itemWidth = max(sensibleMinimumWidth, availableWidth / CGFloat(numberOfItems))
let itemHeight = max(0, collectionView.bounds.height - 8)
return CGSize(width: itemWidth, height: itemHeight)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
onDaySelected(indexPath.item)
}
}
}
| mit | 0e5baf6a905e60e4e1c08990233d56a2 | 35.913043 | 120 | 0.655477 | 6.071514 | false | false | false | false |
OpenStreetMap-Monitoring/iOsMo | iOsmo/Track.swift | 2 | 2033 | //
// Track.swift
// iOsMo
//
// Created by Alexey Sirotkin on 16.04.17.
// Copyright © 2017 Alexey Sirotkin. All rights reserved.
//
import Foundation
import MapKit
open class Track: Equatable {
var u: Int
var groupId: Int = 0
var type: String = "0"
var descr: String = ""
var km: String = ""
var color: String = "#ffffff"
var name: String = ""
var url: String = ""
var size: Int = 0
var start: Date?
var finish: Date?
init (json: Dictionary<String, AnyObject>) {
self.u = json["u"] as? Int ?? Int(json["u"] as? String ?? "0")!
self.size = json["size"] as? Int ?? Int(json["size"] as? String ?? "0")!
self.name = json["name"] as? String ?? ""
self.descr = json["description"] as? String ?? ""
self.color = json["color"] as? String ?? "#ffffff"
self.url = json["url"] as? String ?? ""
self.type = json["type"] as? String ?? ("\(json["type"] as? Int ?? 0)")
}
init (track: History) {
self.u = track.u
self.groupId = 0
self.color = "#0000ff"
self.km = "\(track.distantion / 1000.0)"
self.name = track.name
self.url = track.gpx_optimal
self.start = track.start
self.finish = track.end
}
open func getTrackData() -> XML? {
let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true);
let filename = "\(groupId)-\(u).gpx"
let path = "\(paths[0])/channelsgpx/"
let file: FileHandle? = FileHandle(forReadingAtPath: "\(path)\(filename)")
if file != nil {
// Read all the data
let data = file?.readDataToEndOfFile()
// Close the file
file?.closeFile()
let xml = XML(data: data!)
return xml;
} else {
return nil
}
}
public static func == (left: Track, right: Track) -> Bool {
return left.u == right.u
}
}
| gpl-3.0 | dc8f7d57d7fe016c5788748183331a84 | 28.449275 | 97 | 0.524114 | 3.89272 | false | false | false | false |
dengJunior/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSceneCell.swift | 1 | 1368 | //
// CBSceneCell.swift
// TestKitchen
//
// Created by 邓江洲 on 16/8/22.
// Copyright © 2016年 邓江洲. All rights reserved.
//
import UIKit
class CBSceneCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
func configTitle(title: String){
nameLabel.text = title
}
class func createSceneCell(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBSceneCell{
let cellId = "sceneCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBSceneCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBSceneCell", owner: nil, options: nil).last as? CBSceneCell
}
if let title = listModel.title{
cell?.configTitle(title)
}
return cell!
}
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
}
}
| mit | 2c908c44c19e4f9842d670d9e17ddbd1 | 17.791667 | 159 | 0.54915 | 5.264591 | false | false | false | false |
manavgabhawala/swift | test/IRGen/metadata_dominance.swift | 1 | 3242 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -O -emit-ir -primary-file %s | %FileCheck %s --check-prefix=CHECK-OPT
func use_metadata<F>(_ f: F) {}
func voidToVoid() {}
func intToInt(_ x: Int) -> Int { return x }
func cond() -> Bool { return true }
// CHECK: define hidden swiftcc void @_TF18metadata_dominance5test1FT_T_()
func test1() {
// CHECK: call swiftcc i1 @_TF18metadata_dominance4condFT_Sb()
if cond() {
// CHECK: [[T0:%.*]] = call %swift.type* @_TMaFT_T_()
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]])
use_metadata(voidToVoid)
// CHECK: call swiftcc i1 @_TF18metadata_dominance4condFT_Sb()
// CHECK-NOT: @_TMaFT_T_
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]])
if cond() {
use_metadata(voidToVoid)
} else {
// CHECK-NOT: @_TMaFT_T_
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]])
use_metadata(voidToVoid)
}
}
// CHECK: [[T1:%.*]] = call %swift.type* @_TMaFT_T_()
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T1]])
use_metadata(voidToVoid)
}
// CHECK: define hidden swiftcc void @_TF18metadata_dominance5test2FT_T_()
func test2() {
// CHECK: call swiftcc i1 @_TF18metadata_dominance4condFT_Sb()
if cond() {
// CHECK: call swiftcc i1 @_TF18metadata_dominance4condFT_Sb()
// CHECK: [[T0:%.*]] = call %swift.type* @_TMaFT_T_()
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]])
if cond() {
use_metadata(voidToVoid)
} else {
// CHECK: [[T1:%.*]] = call %swift.type* @_TMaFT_T_()
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T1]])
use_metadata(voidToVoid)
}
}
// CHECK: [[T2:%.*]] = call %swift.type* @_TMaFT_T_()
// CHECK: call swiftcc void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T2]])
use_metadata(voidToVoid)
}
protocol P {
func makeFoo() -> Foo
}
class Foo: P {
func makeFoo() -> Foo {
fatalError()
}
}
class SubFoo: Foo {
final override func makeFoo() -> Foo {
// Check that it creates an instance of type Foo,
// and not an instance of a Self type involved
// in this protocol conformance.
return Foo()
}
}
@inline(never)
func testMakeFoo(_ p: P) -> Foo.Type {
let foo = p.makeFoo()
return type(of: foo)
}
// The protocol witness for metadata_dominance.P.makeFoo () -> metadata_dominance.Foo in
// conformance metadata_dominance.Foo : metadata_dominance.P should not use the Self type
// as the type of the object to be created. It should dynamically obtain the type.
// CHECK-OPT-LABEL: define hidden swiftcc %T18metadata_dominance3FooC* @_TTWC18metadata_dominance3FooS_1PS_FS1_7makeFoofT_S0_
// CHECK-OPT-NOT: tail call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* %Self
| apache-2.0 | 61647bbf12ec927dd7f2a4060161026e | 37.595238 | 142 | 0.663788 | 3.147573 | false | true | false | false |
MFaarkrog/Apply | Apply/Classes/Extensions/UIScrollView+Apply.swift | 1 | 3618 | //
// Created by Morten Faarkrog
//
import UIKit
public extension UIScrollView {
@discardableResult public func apply<T: UIScrollView>(bounces: Bool) -> T {
self.bounces = bounces
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(canCancelContentTouches: Bool) -> T {
self.canCancelContentTouches = canCancelContentTouches
return self as! T
}
@available(iOS 11.0, *)
@discardableResult public func apply<T: UIScrollView>(contentInsetAdjustmentBehavior: UIScrollView.ContentInsetAdjustmentBehavior) -> T {
self.contentInsetAdjustmentBehavior = contentInsetAdjustmentBehavior
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(contentInset: UIEdgeInsets) -> T {
self.contentInset = contentInset
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(contentOffset: CGPoint) -> T {
self.contentOffset = contentOffset
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(contentSize: CGSize) -> T {
self.contentSize = contentSize
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(decelerationRate: CGFloat) -> T {
self.decelerationRate = UIScrollView.DecelerationRate(rawValue: decelerationRate)
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(delaysContentTouches: Bool) -> T {
self.delaysContentTouches = delaysContentTouches
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(delegate: UIScrollViewDelegate?) -> T {
self.delegate = delegate
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(isPagingEnabled: Bool) -> T {
self.isPagingEnabled = isPagingEnabled
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(isScrollEnabled: Bool) -> T {
self.isScrollEnabled = isScrollEnabled
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(maximumZoomScale: CGFloat) -> T {
self.maximumZoomScale = maximumZoomScale
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(minimumZoomScale: CGFloat) -> T {
self.minimumZoomScale = minimumZoomScale
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(scrollIndicatorInsets: UIEdgeInsets) -> T {
self.scrollIndicatorInsets = scrollIndicatorInsets
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(showsHorizontalScrollIndicator: Bool) -> T {
self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(showsVerticalScrollIndicator: Bool) -> T {
self.showsVerticalScrollIndicator = showsVerticalScrollIndicator
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(showsScrollIndicator: Bool) -> T {
self.showsHorizontalScrollIndicator = showsScrollIndicator
self.showsVerticalScrollIndicator = showsScrollIndicator
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(zoomScale: CGFloat) -> T {
self.zoomScale = zoomScale
return self as! T
}
@discardableResult public func apply<T: UIScrollView>(bouncesZoom: Bool) -> T {
self.bouncesZoom = bouncesZoom
return self as! T
}
@available(iOS 10.0, *)
@discardableResult public func apply<T: UIScrollView>(refreshControl: UIRefreshControl) -> T {
self.refreshControl = refreshControl
return self as! T
}
}
| mit | 1e1c62177cd7cd56ba5245a59775c5af | 31.303571 | 139 | 0.72775 | 5.046025 | false | false | false | false |
Norod/Filterpedia | Filterpedia/customFilters/CustomFilters.swift | 1 | 52552 | //
// CustomFilters.swift
// Filterpedia
//
// Created by Simon Gladman on 15/01/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
import CoreImage
let CategoryCustomFilters = "Custom Filters"
class CustomFiltersVendor: NSObject, CIFilterConstructor
{
static func registerFilters()
{
CIFilter.registerName(
"ThresholdFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ThresholdToAlphaFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CRTFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"VignetteNoirFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MercurializeFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"VintageVignette",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"RGBChannelCompositing",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"RGBChannelGaussianBlur",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"RGBChannelToneCurve",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"PseudoColor",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"KuwaharaFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MetalPixellateFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MetalKuwaharaFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MetalPerlinNoise",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"StarBurstFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ChromaticAberration",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"RGBChannelBrightnessAndContrast",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"VHSTrackingLines",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"EightBit",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"TechnicolorFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"BleachBypassFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CarnivalMirror",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"BayerDitherFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CompoundEye",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"DifferenceOfGaussians",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"AdvancedMonochrome",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"RefractedTextFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"SobelEdgeDetection5x5",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"SobelEdgeDetection3x3",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MultiBandHSV",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"PolarPixellate",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ModelIOSkyGenerator",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ModelIOColorScalarNoise",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ModelIOColorFromTemperature",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CausticRefraction",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CausticNoise",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ColorDirectedBlur",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CMYKRegistrationMismatch",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CMYKLevels",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CMYKToneCurves",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"SmoothThreshold",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"VoronoiNoise",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"NormalMap",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"HistogramSpecification",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ContrastStretch",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"HistogramEqualization",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"SimpleSky",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"LensFlare",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"HexagonalBokehFilter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MaskedVariableCircularBokeh",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"MaskedVariableHexagonalBokeh",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"CircularBokeh",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"EndsInContrastStretch",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"HomogeneousColorBlur",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"SimplePlasma",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ConcentricSineWaves",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"Scatter",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"ScatterWarp",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"TransverseChromaticAberration",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
CIFilter.registerName(
"Flame",
constructor: CustomFiltersVendor(),
classAttributes: [
kCIAttributeFilterCategories: [CategoryCustomFilters]
])
}
func filter(withName name: String) -> CIFilter?
{
switch name
{
case "ThresholdFilter":
return ThresholdFilter()
case "ThresholdToAlphaFilter":
return ThresholdToAlphaFilter()
case "CRTFilter":
return CRTFilter()
case "VignetteNoirFilter":
return VignetteNoirFilter()
case "MercurializeFilter":
return MercurializeFilter()
case "VintageVignette":
return VintageVignette()
case "RGBChannelCompositing":
return RGBChannelCompositing()
case "RGBChannelGaussianBlur":
return RGBChannelGaussianBlur()
case "RGBChannelToneCurve":
return RGBChannelToneCurve()
case "PseudoColor":
return PseudoColor()
case "KuwaharaFilter":
return KuwaharaFilter()
case "StarBurstFilter":
return StarBurstFilter()
case "ChromaticAberration":
return ChromaticAberration()
case "RGBChannelBrightnessAndContrast":
return RGBChannelBrightnessAndContrast()
case "VHSTrackingLines":
return VHSTrackingLines()
case "EightBit":
return EightBit()
case "TechnicolorFilter":
return TechnicolorFilter()
case "BleachBypassFilter":
return BleachBypassFilter()
case "CarnivalMirror":
return CarnivalMirror()
case "BayerDitherFilter":
return BayerDitherFilter()
case "CompoundEye":
return CompoundEye()
case "DifferenceOfGaussians":
return DifferenceOfGaussians()
case "AdvancedMonochrome":
return AdvancedMonochrome()
case "RefractedTextFilter":
return RefractedTextFilter()
case "SobelEdgeDetection5x5":
return SobelEdgeDetection5x5()
case "SobelEdgeDetection3x3":
return SobelEdgeDetection3x3()
case "PolarPixellate":
return PolarPixellate()
case "MultiBandHSV":
return MultiBandHSV()
case "ModelIOSkyGenerator":
return ModelIOSkyGenerator()
case "ModelIOColorScalarNoise":
return ModelIOColorScalarNoise()
case "ModelIOColorFromTemperature":
return ModelIOColorFromTemperature()
case "ColorDirectedBlur":
return ColorDirectedBlur()
case "HomogeneousColorBlur":
return HomogeneousColorBlur()
case "CMYKRegistrationMismatch":
return CMYKRegistrationMismatch()
case "CMYKLevels":
return CMYKLevels()
case "CMYKToneCurves":
return CMYKToneCurves()
case "SmoothThreshold":
return SmoothThreshold()
case "VoronoiNoise":
return VoronoiNoise()
case "CausticRefraction":
return CausticRefraction()
case "CausticNoise":
return CausticNoise()
case "NormalMap":
return NormalMapFilter()
case "HistogramSpecification":
return HistogramSpecification()
case "ContrastStretch":
return ContrastStretch()
case "HistogramEqualization":
return HistogramEqualization()
case "SimpleSky":
return SimpleSky()
case "LensFlare":
return LensFlare()
case "CircularBokeh":
return CircularBokeh()
case "MaskedVariableCircularBokeh":
return MaskedVariableCircularBokeh()
case "MaskedVariableHexagonalBokeh":
return MaskedVariableHexagonalBokeh()
case "EndsInContrastStretch":
return EndsInContrastStretch()
case "SimplePlasma":
return SimplePlasma()
case "ConcentricSineWaves":
return ConcentricSineWaves()
case "Scatter":
return Scatter()
case "ScatterWarp":
return ScatterWarp()
case "TransverseChromaticAberration":
return TransverseChromaticAberration()
case "Flame":
return Flame()
case "MetalPixellateFilter":
#if !arch(i386) && !arch(x86_64)
return MetalPixellateFilter()
#else
return nil
#endif
case "MetalKuwaharaFilter":
#if !arch(i386) && !arch(x86_64)
return MetalKuwaharaFilter()
#else
return nil
#endif
case "MetalPerlinNoise":
#if !arch(i386) && !arch(x86_64)
return MetalPerlinNoise()
#else
return nil
#endif
case "HexagonalBokehFilter":
#if !arch(i386) && !arch(x86_64)
return HexagonalBokehFilter()
#else
return nil
#endif
default:
return nil
}
}
}
// MARK: PseudoColor
/// This filter isn't dissimilar to Core Image's own False Color filter
/// but it accepts five input colors and uses `mix()` and `smoothstep()`
/// to transition between them based on an image's luminance. The
/// balance between linear and Hermite interpolation is controlled by
/// the `inputSmoothness` parameter.
class PseudoColor: CIFilter
{
var inputImage: CIImage?
var inputSmoothness = CGFloat(0.5)
var inputColor0 = CIColor(red: 1, green: 0, blue: 1)
var inputColor1 = CIColor(red: 0, green: 0, blue: 1)
var inputColor2 = CIColor(red: 0, green: 1, blue: 0)
var inputColor3 = CIColor(red: 1, green: 0, blue: 1)
var inputColor4 = CIColor(red: 0, green: 1, blue: 1)
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Pseudo Color Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputSmoothness": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDescription: "Controls interpolation between colors. Range from 0.0 (Linear) to 1.0 (Hermite).",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Smoothness",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputColor0": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIColor",
kCIAttributeDisplayName: "Color One",
kCIAttributeDefault: CIColor(red: 1, green: 0, blue: 1),
kCIAttributeType: kCIAttributeTypeColor],
"inputColor1": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIColor",
kCIAttributeDisplayName: "Color Two",
kCIAttributeDefault: CIColor(red: 0, green: 0, blue: 1),
kCIAttributeType: kCIAttributeTypeColor],
"inputColor2": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIColor",
kCIAttributeDisplayName: "Color Three",
kCIAttributeDefault: CIColor(red: 0, green: 1, blue: 0),
kCIAttributeType: kCIAttributeTypeColor],
"inputColor3": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIColor",
kCIAttributeDisplayName: "Color Four",
kCIAttributeDefault: CIColor(red: 1, green: 0, blue: 1),
kCIAttributeType: kCIAttributeTypeColor],
"inputColor4": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIColor",
kCIAttributeDisplayName: "Color Five",
kCIAttributeDefault: CIColor(red: 0, green: 1, blue: 1),
kCIAttributeType: kCIAttributeTypeColor]
]
}
let pseudoColorKernel = CIColorKernel(string:
"vec4 getColor(vec4 color0, vec4 color1, float edge0, float edge1, float luma, float smoothness) \n" +
"{ \n" +
" vec4 smoothColor = color0 + ((color1 - color0) * smoothstep(edge0, edge1, luma)); \n" +
" vec4 linearColor = mix(color0, color1, (luma - edge0) * 4.0); \n" +
" return mix(linearColor, smoothColor, smoothness); \n" +
"} \n" +
"kernel vec4 pseudoColor(__sample image, float smoothness, vec4 inputColor0, vec4 inputColor1, vec4 inputColor2, vec4 inputColor3, vec4 inputColor4) \n" +
"{ \n" +
" float luma = dot(image.rgb, vec3(0.2126, 0.7152, 0.0722)); \n" +
" if (luma < 0.25) \n" +
" { return getColor(inputColor0, inputColor1, 0.0, 0.25, luma, smoothness); } \n" +
" else if (luma >= 0.25 && luma < 0.5) \n" +
" { return getColor(inputColor1, inputColor2, 0.25, 0.5, luma, smoothness); } \n" +
" else if (luma >= 0.5 && luma < 0.75) \n" +
" { return getColor(inputColor2, inputColor3, 0.5, 0.75, luma, smoothness); } \n" +
" { return getColor(inputColor3, inputColor4, 0.75, 1.0, luma, smoothness); } \n" +
"}"
)
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
let pseudoColorKernel = pseudoColorKernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage, inputSmoothness, inputColor0, inputColor1, inputColor2, inputColor3, inputColor4] as [Any]
return pseudoColorKernel.apply(withExtent: extent, arguments: arguments)
}
}
// MARK: Vintage vignette
/// This is the VintageVignette filter from my book, Core Image for Swift,
/// and is an example of a very simple composite custom filter.
class VintageVignette: CIFilter
{
var inputImage : CIImage?
var inputVignetteIntensity: CGFloat = 1
var inputVignetteRadius: CGFloat = 1
var inputSepiaToneIntensity: CGFloat = 1
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Vintage Vignette",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputVignetteIntensity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Vignette Intensity",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
"inputVignetteRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Vignette Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSepiaToneIntensity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Sepia Tone Intensity",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputVignetteIntensity = 1
inputVignetteRadius = 1
inputSepiaToneIntensity = 1
}
override var outputImage: CIImage!
{
guard let inputImage = inputImage else
{
return nil
}
let finalImage = inputImage
.applyingFilter("CIVignette",
withInputParameters: [
kCIInputIntensityKey: inputVignetteIntensity,
kCIInputRadiusKey: inputVignetteRadius])
.applyingFilter("CISepiaTone",
withInputParameters: [
kCIInputIntensityKey: inputSepiaToneIntensity])
return finalImage
}
}
// MARK: Difference of Gaussians
class DifferenceOfGaussians: CIFilter
{
var inputImage : CIImage?
var inputSigma0: CGFloat = 0.75
var inputSigma1: CGFloat = 3.25
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Difference of Gaussians",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputSigma0": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Sigma One",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 4,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSigma1": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 3.25,
kCIAttributeDisplayName: "Sigma Two",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 4,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override var outputImage: CIImage!
{
guard let inputImage = inputImage else
{
return nil
}
let blurred0 = DifferenceOfGaussians.gaussianBlurWithSigma(inputSigma0, image: inputImage)
.cropping(to: inputImage.extent)
let blurred1 = DifferenceOfGaussians.gaussianBlurWithSigma(inputSigma1, image: inputImage)
.cropping(to: inputImage.extent)
return blurred0
.applyingFilter("CISubtractBlendMode",
withInputParameters: ["inputBackgroundImage": blurred1])
.applyingFilter("CIColorMatrix",
withInputParameters: ["inputBiasVector": CIVector(x: 0, y: 0, z: 0, w: 1)])
.cropping(to: inputImage.extent)
}
static func gaussianBlurWithSigma(_ sigma: CGFloat, image: CIImage) -> CIImage
{
let weightsArray: [CGFloat] = stride(from: (-4), through: 4, by: 1).map
{
CGFloat(DifferenceOfGaussians.gaussian(CGFloat($0), sigma: sigma))
}
let weightsVector = CIVector(values: weightsArray,
count: weightsArray.count).normalize()
let horizontalBluredImage = CIFilter(name: "CIConvolution9Horizontal",
withInputParameters: [
kCIInputWeightsKey: weightsVector,
kCIInputImageKey: image])!.outputImage!
let verticalBlurredImage = CIFilter(name: "CIConvolution9Vertical",
withInputParameters: [
kCIInputWeightsKey: weightsVector,
kCIInputImageKey: horizontalBluredImage])!.outputImage!
return verticalBlurredImage
}
static func gaussian(_ x: CGFloat, sigma: CGFloat) -> CGFloat
{
let variance = max(sigma * sigma, 0.00001)
return (1.0 / sqrt(CGFloat(M_PI) * 2 * variance)) * pow(CGFloat(M_E), -pow(x, 2) / (2 * variance))
}
}
// MARK: Starburst
class StarBurstFilter: CIFilter
{
var inputImage : CIImage?
var inputThreshold: CGFloat = 0.9
var inputRadius: CGFloat = 20
var inputAngle: CGFloat = 0
var inputBeamCount: Int = 3
var inputStarburstBrightness: CGFloat = 0
let thresholdFilter = ThresholdToAlphaFilter()
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Starburst Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputThreshold": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.9,
kCIAttributeDisplayName: "Threshold",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 20,
kCIAttributeDisplayName: "Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar],
"inputAngle": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Angle",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: M_PI,
kCIAttributeType: kCIAttributeTypeScalar],
"inputStarburstBrightness": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Starburst Brightness",
kCIAttributeMin: -1,
kCIAttributeSliderMin: -1,
kCIAttributeSliderMax: 0.5,
kCIAttributeType: kCIAttributeTypeScalar],
"inputBeamCount": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 3,
kCIAttributeDisplayName: "Beam Count",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeInteger]
]
}
override var outputImage: CIImage!
{
guard let inputImage = inputImage else
{
return nil
}
thresholdFilter.inputThreshold = inputThreshold
thresholdFilter.inputImage = inputImage
let thresholdImage = thresholdFilter.outputImage!
let starBurstAccumulator = CIImageAccumulator(extent: thresholdImage.extent,
format: kCIFormatARGB8)
for i in 0 ..< inputBeamCount
{
let angle = CGFloat((M_PI / Double(inputBeamCount)) * Double(i))
let starburst = thresholdImage.applyingFilter("CIMotionBlur",
withInputParameters: [
kCIInputRadiusKey: inputRadius,
kCIInputAngleKey: inputAngle + angle])
.cropping(to: thresholdImage.extent)
.applyingFilter("CIAdditionCompositing",
withInputParameters: [
kCIInputBackgroundImageKey: (starBurstAccumulator?.image())!])
starBurstAccumulator?.setImage(starburst)
}
let adjustedStarBurst = starBurstAccumulator?.image()
.applyingFilter("CIColorControls",
withInputParameters: [kCIInputBrightnessKey: inputStarburstBrightness])
let final = inputImage.applyingFilter("CIAdditionCompositing",
withInputParameters: [kCIInputBackgroundImageKey: adjustedStarBurst!])
return final
}
}
// MARK: ThresholdToAlphaFilter
class ThresholdToAlphaFilter: ThresholdFilter
{
override var attributes: [String : Any]
{
var superAttributes = super.attributes
superAttributes[kCIAttributeFilterDisplayName] = "Threshold To Alpha Filter"
return superAttributes
}
override init()
{
super.init()
thresholdKernel = CIColorKernel(string:
"kernel vec4 thresholdFilter(__sample image, float threshold)" +
"{" +
" float luma = dot(image.rgb, vec3(0.2126, 0.7152, 0.0722));" +
" return vec4(image.rgb, image.a * step(threshold, luma));" +
"}"
)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
// MARK: Advanced Monochrome
class AdvancedMonochrome: CIFilter
{
var inputImage : CIImage?
var inputRedBalance: CGFloat = 1
var inputGreenBalance: CGFloat = 1
var inputBlueBalance: CGFloat = 1
var inputClamp: CGFloat = 0
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Advanced Monochrome",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputRedBalance": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Red Balance",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputGreenBalance": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Green Balance",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputBlueBalance": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Blue Balance",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputClamp": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Clamp",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
let kernel = CIColorKernel(string:
"kernel vec4 advancedMonochrome(__sample pixel, float redBalance, float greenBalance, float blueBalance, float clamp)" +
"{" +
" float scale = 1.0 / (redBalance + greenBalance + blueBalance);" +
" float red = pixel.r * redBalance * scale;" +
" float green = pixel.g * greenBalance * scale;" +
" float blue = pixel.b * blueBalance * scale;" +
" vec3 grey = vec3(red + green + blue);" +
" grey = mix(grey, smoothstep(0.0, 1.0, grey), clamp); " +
" return vec4(grey, pixel.a);" +
"}")
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
let kernel = kernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage, inputRedBalance, inputGreenBalance, inputBlueBalance, inputClamp] as [Any]
return kernel.apply(withExtent: extent, arguments: arguments)
}
}
// MARK: SmoothThreshold
class SmoothThreshold: CIFilter
{
var inputImage : CIImage?
var inputEdgeO: CGFloat = 0.25
var inputEdge1: CGFloat = 0.75
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Smooth Threshold Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputEdgeO": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.25,
kCIAttributeDisplayName: "Edge 0",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputEdge1": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Edge 1",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
let colorKernel = CIColorKernel(string:
"kernel vec4 color(__sample pixel, float inputEdgeO, float inputEdge1)" +
"{" +
" float luma = dot(pixel.rgb, vec3(0.2126, 0.7152, 0.0722));" +
" float threshold = smoothstep(inputEdgeO, inputEdge1, luma);" +
" return vec4(threshold, threshold, threshold, 1.0);" +
"}"
)
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
let colorKernel = colorKernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage,
min(inputEdgeO, inputEdge1),
max(inputEdgeO, inputEdge1),] as [Any] as [Any]
return colorKernel.apply(withExtent: extent,
arguments: arguments)
}
}
// MARK: Threshold
class ThresholdFilter: CIFilter
{
var inputImage : CIImage?
var inputThreshold: CGFloat = 0.75
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Threshold Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputThreshold": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Threshold",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputThreshold = 0.75
}
override init()
{
super.init()
thresholdKernel = CIColorKernel(string:
"kernel vec4 thresholdFilter(__sample image, float threshold)" +
"{" +
" float luma = dot(image.rgb, vec3(0.2126, 0.7152, 0.0722));" +
" return vec4(step(threshold, luma));" +
"}"
)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var thresholdKernel: CIColorKernel?
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
let thresholdKernel = thresholdKernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage, inputThreshold] as [Any]
return thresholdKernel.apply(withExtent: extent, arguments: arguments)
}
}
// MARK: Polar Pixellate
// based on https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImagePolarPixellateFilter.m
class PolarPixellate: CIFilter
{
var inputImage : CIImage?
var inputCenter = CIVector(x: 320, y: 320)
var inputPixelArc = CGFloat(M_PI / 15)
var inputPixelLength = CGFloat(50)
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Polar Pixellate",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputPixelArc": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: CGFloat(M_PI / 15),
kCIAttributeDisplayName: "Pixel Arc",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: CGFloat(M_PI),
kCIAttributeType: kCIAttributeTypeScalar],
"inputPixelLength": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 50,
kCIAttributeDisplayName: "Pixel Length",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 250,
kCIAttributeType: kCIAttributeTypeScalar],
"inputCenter": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIVector",
kCIAttributeDisplayName: "Center",
kCIAttributeDefault: CIVector(x: 320, y: 320),
kCIAttributeType: kCIAttributeTypePosition],
]
}
override func setDefaults()
{
inputPixelArc = CGFloat(M_PI / 15)
inputPixelLength = 50
inputCenter = CIVector(x: 320, y: 320)
}
let warpKernel = CIWarpKernel(string:
"kernel vec2 polarPixellate(vec2 center, vec2 pixelSize)" +
"{" +
" vec2 normCoord = 2.0 * destCoord() - 1.0;" +
" vec2 normCenter = 2.0 * center - 1.0;" +
" normCoord -= normCenter; " +
" float r = length(normCoord);" +
" float phi = atan(normCoord.y, normCoord.x);" +
" r = r - mod(r, pixelSize.x) + 0.03;" +
" phi = phi - mod(phi, pixelSize.y);" +
" normCoord.x = r * cos(phi);" +
" normCoord.y = r * sin(phi);" +
" normCoord += normCenter;" +
" return normCoord / 2.0 + 0.5;" +
"}"
)
override var outputImage : CIImage!
{
if let inputImage = inputImage, let kernel = warpKernel
{
let extent = inputImage.extent
let pixelSize = CIVector(x: inputPixelLength, y: inputPixelArc)
return kernel.apply(withExtent: extent,
roiCallback:
{
(index, rect) in
return rect
},
inputImage: inputImage,
arguments: [inputCenter, pixelSize])
}
return nil
}
}
// MARK: VignetteNoir
class VignetteNoirFilter: CIFilter
{
var inputImage: CIImage?
var inputRadius: CGFloat = 1
var inputIntensity: CGFloat = 2
var inputEdgeBrightness: CGFloat = -0.3
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Vignette Noir Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
"inputIntensity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Intensity",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeScalar],
"inputEdgeBrightness": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: -0.3,
kCIAttributeDisplayName: "Edge Brightness",
kCIAttributeMin: -1,
kCIAttributeSliderMin: -1,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputRadius = 1
inputIntensity = 2
inputEdgeBrightness = -0.3
}
override var outputImage: CIImage!
{
guard let inputImage = inputImage else
{
return nil
}
let mask = CIImage(color: CIColor(red: 1, green: 1, blue: 1))
.cropping(to: inputImage.extent)
.applyingFilter("CIVignette", withInputParameters: [
kCIInputRadiusKey: inputRadius,
kCIInputIntensityKey: inputIntensity])
let noir = inputImage
.applyingFilter("CIPhotoEffectNoir",withInputParameters: nil)
.applyingFilter("CIColorControls", withInputParameters: [
kCIInputBrightnessKey: inputEdgeBrightness])
let blendWithMaskFilter = CIFilter(name: "CIBlendWithMask", withInputParameters: [
kCIInputImageKey: inputImage,
kCIInputBackgroundImageKey: noir,
kCIInputMaskImageKey: mask])
return blendWithMaskFilter?.outputImage
}
}
// MARK: Normal Map Filter
/// NormalMapFilter - converts a bump map to a normal map
class NormalMapFilter: CIFilter
{
var inputImage: CIImage?
var inputContrast = CGFloat(2)
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Normal Map",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputContrast": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Contrast",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 6,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
let normalMapKernel = CIKernel(string:
"float lumaAtOffset(sampler source, vec2 origin, vec2 offset)" +
"{" +
" vec3 pixel = sample(source, samplerTransform(source, origin + offset)).rgb;" +
" float luma = dot(pixel, vec3(0.2126, 0.7152, 0.0722));" +
" return luma;" +
"}" +
"kernel vec4 normalMap(sampler image) \n" +
"{ " +
" vec2 d = destCoord();" +
" float northLuma = lumaAtOffset(image, d, vec2(0.0, -1.0));" +
" float southLuma = lumaAtOffset(image, d, vec2(0.0, 1.0));" +
" float westLuma = lumaAtOffset(image, d, vec2(-1.0, 0.0));" +
" float eastLuma = lumaAtOffset(image, d, vec2(1.0, 0.0));" +
" float horizontalSlope = ((westLuma - eastLuma) + 1.0) * 0.5;" +
" float verticalSlope = ((northLuma - southLuma) + 1.0) * 0.5;" +
" return vec4(horizontalSlope, verticalSlope, 1.0, 1.0);" +
"}"
)
override var outputImage: CIImage?
{
guard let inputImage = inputImage,
let normalMapKernel = normalMapKernel else
{
return nil
}
return normalMapKernel.apply(withExtent: inputImage.extent,
roiCallback:
{
(index, rect) in
return rect
},
arguments: [inputImage])?
.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: inputContrast])
}
}
| gpl-3.0 | b15626436a1e1ecadef83af8e7e2fa99 | 33.124026 | 163 | 0.558334 | 5.618024 | false | false | false | false |
MJSR-Developer/Rush | Rush/Classes/APIError.swift | 1 | 3424 | //
// APIError.swift
// Rush
//
// Created by MJ Roldan on 06/07/2017.
// Copyright © 2017 Mark Joel Roldan. All rights reserved.
//
import Foundation
public enum APIErrorCode {
case serverIssue
case requestTimeout
case otherError
case invalidToken
case invalidURL
case invalidAppKeySecret
case invalidData
case invalidParameter
case noInternet
}
public struct APIError {
static func urlErrorDomain(_ error: NSError) -> APIErrorCode {
var apiError: APIErrorCode!
switch error.code {
// Invalid URL
case NSURLErrorBadURL,
NSURLErrorUnsupportedURL,
NSURLErrorCannotFindHost,
NSURLErrorDNSLookupFailed:
apiError = .invalidURL
break
// Request Time Out
case NSURLErrorTimedOut,
NSURLErrorCannotConnectToHost,
NSURLErrorRequestBodyStreamExhausted,
NSURLErrorBackgroundSessionWasDisconnected:
apiError = .requestTimeout
break
// Invalid Data
case NSURLErrorDataLengthExceedsMaximum,
NSURLErrorResourceUnavailable,
NSURLErrorZeroByteResource,
NSURLErrorCannotDecodeRawData,
NSURLErrorCannotDecodeContentData,
NSURLErrorFileDoesNotExist,
NSURLErrorFileIsDirectory,
NSURLErrorNoPermissionsToReadFile:
apiError = .invalidData
break
// No Internet
case NSURLErrorNetworkConnectionLost,
NSURLErrorNotConnectedToInternet,
NSURLErrorInternationalRoamingOff,
NSURLErrorDataNotAllowed,
NSURLErrorCannotLoadFromNetwork:
apiError = .noInternet
break
// Server error
case NSURLErrorHTTPTooManyRedirects,
NSURLErrorRedirectToNonExistentLocation,
NSURLErrorBadServerResponse,
NSURLErrorUserCancelledAuthentication,
NSURLErrorUserAuthenticationRequired,
NSURLErrorSecureConnectionFailed,
NSURLErrorServerCertificateHasBadDate,
NSURLErrorServerCertificateUntrusted,
NSURLErrorServerCertificateHasUnknownRoot,
NSURLErrorServerCertificateNotYetValid,
NSURLErrorClientCertificateRejected,
NSURLErrorClientCertificateRequired:
apiError = .serverIssue
break
default: // Other errors
apiError = .otherError
break
}
return apiError
}
static func responseStatus(_ response: HTTPURLResponse) -> APIErrorCode? {
var apiError: APIErrorCode?
switch response.statusCodeEnum {
case .ok: apiError = nil
break
case .requestTimeout,
.gatewayTimeout,
.nginxNoResponse:
apiError = .requestTimeout
break
case .notModified,
.badRequest,
.notFound,
.gone,
.movedPermanently:
apiError = .invalidURL
break
case .internalServerError,
.serviceUnavailable,
.forbidden,
.unauthorized,
.badGateway:
apiError = .serverIssue
break
default: apiError = .otherError
break
}
return apiError
}
}
| mit | dd114596146fed527bcf0e6f53f79f96 | 29.837838 | 78 | 0.60707 | 7.116424 | false | false | false | false |
wuyingminhui/HiPay | HiPay/Classes/UPPaySDK/HiPayUPService.swift | 1 | 1511 | //
// HiPayUPService.swift
// HiPay
//
// Created by Jason on 16/6/17.
// Copyright © 2016年 [email protected]. All rights reserved.
//
// 银联支付
import Foundation
public class HiPayUPService: BaseHiPay {
private var payCallBack: HiPayCompletedBlock?
private static let _sharedInstance = HiPayUPService()
override public class var sharedInstance: HiPayUPService {
return _sharedInstance
}
override public func sendPay(channel: HiPayChannel, callBack: HiPayCompletedBlock) {
payCallBack = callBack
if case .upPay(let order) = channel {
UPPaymentControl.defaultControl().startPay(order.tn, fromScheme: order.appScheme, mode: order.mode, viewController: order.viewController)
}
}
override public func handleOpenURL(url: NSURL) {
guard "uppayresult" == url.host else { return }
UPPaymentControl.defaultControl().handlePaymentResult(url) { [unowned self] stringCode, resultDic in
switch stringCode {
case "success":
self.payCallBack?(HiPayStatusCode.PaySuccess(wxPayResult: nil, aliPayResult: nil, upPayResult: resultDic as! [String:AnyObject]?))
case "cancel":
self.payCallBack?(HiPayStatusCode.PayErrCodeUserCancel)
case "fail":
self.payCallBack?(HiPayStatusCode.PayErrPayFail)
default:
self.payCallBack?(HiPayStatusCode.PayErrUnKnown)
}
}
}
} | mit | f85c53f1f7b805407e3b85b3ea6a5511 | 34.738095 | 149 | 0.656667 | 4.132231 | false | false | false | false |
PaystackHQ/paystack-ios | Example/Paystack iOS Example/ViewController.swift | 1 | 8294 | //
// ViewController.swift
// Paystack iOS Exampe (Simple)
//
import UIKit
import Paystack
class ViewController: UIViewController, PSTCKPaymentCardTextFieldDelegate {
// MARK: REPLACE THESE
// Replace these values with your application's keys
// Find this at https://dashboard.paystack.co/#/settings/developer
let paystackPublicKey = ""
// let paystackPublicKey = "pk_live_ed8a7004bb85bf636a0a22c635ad9d1788caa5de"
// To set this up, see https://github.com/PaystackHQ/sample-charge-card-backend
let backendURLString = ""
// let backendURLString = "https://calm-scrubland-33409.herokuapp.com"
let card : PSTCKCard = PSTCKCard()
// MARK: Overrides
override func viewDidLoad() {
// hide token label and email box
tokenLabel.text=nil
chargeCardButton.isEnabled = false
// clear text from card details
// comment these to use the sample data set
super.viewDidLoad();
}
// MARK: Helpers
func showOkayableMessage(_ title: String, message: String){
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertController.Style.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func dismissKeyboardIfAny(){
// Dismiss Keyboard if any
cardDetailsForm.resignFirstResponder()
}
// MARK: Properties
@IBOutlet weak var cardDetailsForm: PSTCKPaymentCardTextField!
@IBOutlet weak var chargeCardButton: UIButton!
@IBOutlet weak var tokenLabel: UILabel!
// MARK: Actions
@IBAction func cardDetailsChanged(_ sender: PSTCKPaymentCardTextField) {
chargeCardButton.isEnabled = sender.isValid
}
@IBAction func chargeCard(_ sender: UIButton) {
dismissKeyboardIfAny()
// Make sure public key has been set
if (paystackPublicKey == "" || !paystackPublicKey.hasPrefix("pk_")) {
showOkayableMessage("You need to set your Paystack public key.", message:"You can find your public key at https://dashboard.paystack.co/#/settings/developer .")
// You need to set your Paystack public key.
return
}
Paystack.setDefaultPublicKey(paystackPublicKey)
if cardDetailsForm.isValid {
if backendURLString != "" {
fetchAccessCodeAndChargeCard()
return
}
showOkayableMessage("Backend not configured", message:"To run this sample, please configure your backend.")
// chargeWithSDK(newCode:"");
}
}
func outputOnLabel(str: String){
DispatchQueue.main.async {
if let former = self.tokenLabel.text {
self.tokenLabel.text = former + "\n" + str
} else {
self.tokenLabel.text = str
}
}
}
func fetchAccessCodeAndChargeCard(){
if let url = URL(string: backendURLString + "/new-access-code") {
self.makeBackendRequest(url: url, message: "fetching access code", completion: { str in
self.outputOnLabel(str: "Fetched access code: "+str)
self.chargeWithSDK(newCode: str as NSString)
})
}
}
func chargeWithSDK(newCode: NSString){
let transactionParams = PSTCKTransactionParams.init();
transactionParams.access_code = newCode as String;
//transactionParams.additionalAPIParameters = ["enforce_otp": "true"];
// transactionParams.email = "[email protected]";
// transactionParams.amount = 2000;
// let dictParams: NSMutableDictionary = [
// "recurring": true
// ];
// let arrParams: NSMutableArray = [
// "0","go"
// ];
// do {
// try transactionParams.setMetadataValueDict(dictParams, forKey: "custom_filters");
// try transactionParams.setMetadataValueArray(arrParams, forKey: "custom_array");
// } catch {
// print(error)
// }
// use library to create charge and get its reference
PSTCKAPIClient.shared().chargeCard(self.cardDetailsForm.cardParams, forTransaction: transactionParams, on: self, didEndWithError: { (error, reference) in
self.outputOnLabel(str: "Charge errored")
// what should I do if an error occured?
print(error)
if error._code == PSTCKErrorCode.PSTCKExpiredAccessCodeError.rawValue{
// access code could not be used
// we may as well try afresh
}
if error._code == PSTCKErrorCode.PSTCKConflictError.rawValue{
// another transaction is currently being
// processed by the SDK... please wait
}
if let errorDict = (error._userInfo as! NSDictionary?){
if let errorString = errorDict.value(forKeyPath: "com.paystack.lib:ErrorMessageKey") as! String? {
if let reference=reference {
self.showOkayableMessage("An error occured while completing "+reference, message: errorString)
self.outputOnLabel(str: reference + ": " + errorString)
self.verifyTransaction(reference: reference)
} else {
self.showOkayableMessage("An error occured", message: errorString)
self.outputOnLabel(str: errorString)
}
}
}
self.chargeCardButton.isEnabled = true;
}, didRequestValidation: { (reference) in
self.outputOnLabel(str: "requested validation: " + reference)
}, willPresentDialog: {
// make sure dialog can show
// if using a "processing" dialog, please hide it
self.outputOnLabel(str: "will show a dialog")
}, dismissedDialog: {
// if using a processing dialog, please make it visible again
self.outputOnLabel(str: "dismissed dialog")
}) { (reference) in
self.outputOnLabel(str: "succeeded: " + reference)
self.chargeCardButton.isEnabled = true;
self.verifyTransaction(reference: reference)
}
return
}
func verifyTransaction(reference: String){
if let url = URL(string: backendURLString + "/verify/" + reference) {
makeBackendRequest(url: url, message: "verifying " + reference, completion:{(str) -> Void in
self.outputOnLabel(str: "Message from paystack on verifying " + reference + ": " + str)
})
}
}
func makeBackendRequest(url: URL, message: String, completion: @escaping (_ result: String) -> Void){
let session = URLSession(configuration: URLSessionConfiguration.default)
self.outputOnLabel(str: "Backend: " + message)
session.dataTask(with: url, completionHandler: { data, response, error in
let successfulResponse = (response as? HTTPURLResponse)?.statusCode == 200
if successfulResponse && error == nil && data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
completion(str as String)
} else {
self.outputOnLabel(str: "<Unable to read response> while "+message)
print("<Unable to read response>")
}
} else {
if let error = error {
print(error.localizedDescription)
self.outputOnLabel(str: error.localizedDescription)
} else {
// There was no error returned though status code was not 200
print("There was an error communicating with your payment backend.")
self.outputOnLabel(str: "There was an error communicating with your payment backend while "+message)
}
}
}).resume()
}
}
| mit | aad15d5fcb3f40572afc0879fd408612 | 40.47 | 172 | 0.589945 | 4.847458 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/USXParagraphProcessor.swift | 1 | 4199 | //
// USXParagraphParser.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 10.10.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
class USXParagraphProcessor: USXContentProcessor
{
typealias Generated = Paragraph
typealias Processed = Para
// ATTRIBUTES ------------
private let bookId: String
private let chapterIndex: Int
private let sectionIndex: Int
private let paragraphIndex: Int
private let userId: String
private var paragraphStyleFound = false
private var sectionHeadingFound = false
private var contentParsed = false
// INIT --------------------
init(userId: String, bookId: String, chapterIndex: Int, sectionIndex: Int, paragraphIndex: Int)
{
self.userId = userId
self.bookId = bookId
self.chapterIndex = chapterIndex
self.sectionIndex = sectionIndex
self.paragraphIndex = paragraphIndex
}
// Creates a new xml parser that is used for parsing the contents of a single paragraph.
// The starting point for the parser should be at a para element.
// The parser will stop at the new chapter marker or before that, once a paragraph has been parsed
static func createParagraphParser(caller: XMLParserDelegate, userId: String, bookId: String, chapterIndex: Int, sectionIndex: Int, paragraphIndex: Int, targetPointer: UnsafeMutablePointer<[Paragraph]>, using errorHandler: @escaping ErrorHandler) -> USXContentParser<Paragraph, Para>
{
let parser = USXContentParser<Paragraph, Para>(caller: caller, containingElement: .usx, lowestBreakMarker: .chapter, targetPointer: targetPointer, using: errorHandler)
parser.processor = AnyUSXContentProcessor(USXParagraphProcessor(userId: userId, bookId: bookId, chapterIndex: chapterIndex, sectionIndex: sectionIndex, paragraphIndex: paragraphIndex))
return parser
}
// USX PROCESSING --------
func getParser(_ caller: USXContentParser<Paragraph, Para>, forElement elementName: String, attributes: [String : String], into targetPointer: UnsafeMutablePointer<[Para]>, using errorHandler: @escaping ErrorHandler) -> (XMLParserDelegate, Bool)?
{
if elementName == USXContainerElement.para.rawValue
{
// Parses the para style
var style = ParaStyle.normal
if let styleAttribute = attributes["style"]
{
style = ParaStyle.value(of: styleAttribute)
}
// Stops parsing if
// a) Section heading was found previously and receives something other than a heading description
// b) Paragraph style was found previously and receives another pararaph style
// c) Some content was read and receives a section header
if (sectionHeadingFound && !style.isHeaderDescriptionStyle()) || (paragraphStyleFound && style.isParagraphStyle()) || (contentParsed && style.isSectionHeadingStyle())
{
caller.stopsAfterCurrentParse = true
return nil
}
// Otherwise parses normally uning a para parser
else
{
if style.isSectionHeadingStyle()
{
sectionHeadingFound = true
}
if style.isParagraphStyle()
{
paragraphStyleFound = true
}
contentParsed = true
return (USXParaProcessor.createParaParser(caller: caller, style: style, targetPointer: targetPointer, using: errorHandler), false)
}
}
else
{
print("ERROR: ParagraphProcessor received element '\(elementName)'")
return nil
}
}
func generate(from content: [Para], using errorHandler: @escaping ErrorHandler) -> Paragraph?
{
/*
for para in content
{
print("USX: \((para.range?.description).or("no range")) --- \(para.verses.map { $0.range }))")
}*/
// Clears the status for reuse
contentParsed = false
paragraphStyleFound = false
// Wraps the para content into a paragraph
return Paragraph(bookId: bookId, chapterIndex: chapterIndex, sectionIndex: sectionIndex, index: paragraphIndex, content: content, creatorId: userId)
}
func getCharacterParser(_ caller: USXContentParser<Paragraph, Para>, forCharacters string: String, into targetPointer: UnsafeMutablePointer<[Para]>, using errorHandler: @escaping ErrorHandler) -> XMLParserDelegate?
{
// This parser doesn't handle character data. All character data should be inside para elements.
return nil
}
}
| mit | d1359aec66028340e611368de1bdd867 | 33.694215 | 283 | 0.732253 | 4.115686 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/WhistlesVsZombies/Zombie/Strategy/MOptionWhistlesVsZombiesZombieStrategy.swift | 1 | 1860 | import Foundation
class MOptionWhistlesVsZombiesZombieStrategy:MGameStrategy<
MOptionWhistlesVsZombiesZombie,
MOptionWhistlesVsZombies>
{
private(set) var waitTime:TimeInterval
private(set) var spawnRate:UInt32
private var lastElapsedTime:TimeInterval?
override init(model:MOptionWhistlesVsZombiesZombie)
{
waitTime = 0
spawnRate = 0
super.init(model:model)
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
updateSpawn(
elapsedTime:elapsedTime,
scene:scene)
updateItems(
elapsedTime:elapsedTime,
scene:scene)
}
//MARK: private
private func updateSpawn(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
if let lastElapsedTime:TimeInterval = self.lastElapsedTime
{
let deltaTime:TimeInterval = abs(elapsedTime - lastElapsedTime)
if deltaTime > waitTime
{
self.lastElapsedTime = elapsedTime
trySpawnZombie(scene:scene)
}
}
else
{
lastElapsedTime = elapsedTime
}
}
private func updateItems(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
for item:MOptionWhistlesVsZombiesZombieItem in model.items
{
item.update(
elapsedTime:elapsedTime,
scene:scene)
}
}
private func trySpawnZombie(scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
let random:UInt32 = arc4random_uniform(spawnRate)
if random == 0
{
model.spawnZombie(scene:scene)
}
}
}
| mit | 0814398804d9e9abb73e92701d43768a | 24.479452 | 78 | 0.595699 | 5.486726 | false | false | false | false |
DingSoung/CCExtension | Sources/Foundation/SCNetworkReachability/SCNetworkReachability+update.swift | 2 | 2537 | // Created by Songwen Ding on 2016/7/18.
// Copyright © 2019 DingSoung. All rights reserved.
#if canImport(SystemConfiguration)
import SystemConfiguration
#if canImport(Foundation)
import Foundation
extension SCNetworkReachability {
public typealias UpdateBlock = @convention(block) (SCNetworkReachability) -> Void
private static let association = Association<NSMapTable<NSString, AnyObject>>()
private var blocks: NSMapTable<NSString, AnyObject> {
if let blocks = SCNetworkReachability.association[self] {
return blocks
} else {
let blocks = NSMapTable<NSString, AnyObject>(keyOptions: .weakMemory, valueOptions: .weakMemory)
SCNetworkReachability.association[self] = blocks
return blocks
}
}
public func addObserve(uid: String, updateBlock: @escaping UpdateBlock) {
let object = unsafeBitCast(updateBlock, to: AnyObject.self)
blocks.setObject(object, forKey: uid as NSString)
}
public func removeObserve(uid: String) {
blocks.removeObject(forKey: uid as NSString)
}
@discardableResult
public func start() -> Bool {
let info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
var context = SCNetworkReachabilityContext(version: 0,
info: info,
retain: nil,
release: nil,
copyDescription: nil)
let callback: SCNetworkReachabilityCallBack = { _, _, info in
guard let info = info else {
return
}
let networkReachability = Unmanaged<SCNetworkReachability>.fromOpaque(info).takeUnretainedValue()
as SCNetworkReachability
let enumerator = networkReachability.blocks.objectEnumerator()
while let object: AnyObject = enumerator?.nextObject() as AnyObject? {
let block = unsafeBitCast(object, to: UpdateBlock.self)
block(networkReachability)
}
}
return SCNetworkReachabilitySetCallback(self, callback, &context)
&& SCNetworkReachabilityScheduleWithRunLoop(self, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
}
public func stop() {
SCNetworkReachabilityUnscheduleFromRunLoop(self, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
}
}
#endif
#endif
| mit | b740743423ad098cda83ebdc53b49745 | 40.57377 | 120 | 0.629338 | 5.829885 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Model/Messages/ZMClientMessageTests+LinkAttachments.swift | 1 | 3299 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireTesting
class ZMClientMessageTests_LinkAttachments: BaseZMClientMessageTests {
func testThatItMatchesMessageNeedingUpdate() throws {
// GIVEN
let sender = ZMUser.insertNewObject(in: uiMOC)
sender.remoteIdentifier = .create()
let message1 = try! conversation.appendText(content: "Hello world") as! ZMMessage
message1.sender = sender
let message2 = try! conversation.appendText(content: "Hello world", fetchLinkPreview: false) as! ZMMessage
message2.sender = sender
uiMOC.saveOrRollback()
// WHEN
let fetchRequest = NSFetchRequest<ZMMessage>(entityName: ZMMessage.entityName())
fetchRequest.predicate = ZMMessage.predicateForMessagesThatNeedToUpdateLinkAttachments()
let fetchedMessages = try uiMOC.fetch(fetchRequest)
// THEN
XCTAssertEqual(fetchedMessages, [message1])
}
func testThatItSavesLinkAttachmentsAfterAssigning() throws {
// GIVEN
let sender = ZMUser.insertNewObject(in: uiMOC)
sender.remoteIdentifier = .create()
let nonce = UUID()
let thumbnail = URL(string: "https://i.ytimg.com/vi/hyTNGkBSjyo/hqdefault.jpg")!
var attachment: LinkAttachment! = LinkAttachment(type: .youTubeVideo, title: "Pingu Season 1 Episode 1",
permalink: URL(string: "https://www.youtube.com/watch?v=hyTNGkBSjyo")!,
thumbnails: [thumbnail],
originalRange: NSRange(location: 20, length: 43))
var message: ZMClientMessage? = try? conversation.appendText(content: "Hello world", nonce: nonce) as? ZMClientMessage
message?.sender = sender
message?.linkAttachments = [attachment]
uiMOC.saveOrRollback()
uiMOC.refresh(message!, mergeChanges: false)
message = nil
attachment = nil
// WHEN
let fetchedMessage = ZMMessage.fetch(withNonce: nonce, for: conversation, in: uiMOC)
let fetchedAttachment = fetchedMessage?.linkAttachments?.first
// THEN
XCTAssertEqual(fetchedAttachment?.type, .youTubeVideo)
XCTAssertEqual(fetchedAttachment?.title, "Pingu Season 1 Episode 1")
XCTAssertEqual(fetchedAttachment?.permalink, URL(string: "https://www.youtube.com/watch?v=hyTNGkBSjyo")!)
XCTAssertEqual(fetchedAttachment?.thumbnails, [thumbnail])
XCTAssertEqual(fetchedAttachment?.originalRange, NSRange(location: 20, length: 43))
}
}
| gpl-3.0 | 1becd8412fa0dd32ce345f30a992fc60 | 40.759494 | 128 | 0.668384 | 4.733142 | false | true | false | false |
Ben21hao/edx-app-ios-new | Source/TabContainerView.swift | 3 | 3228 | //
// TabContainerView.swift
// edX
//
// Created by Akiva Leffert on 4/5/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
struct TabItem {
let name : String
let view : UIView
let identifier : String
}
// Simple tab view with a segmented control at the top
class TabContainerView : UIView {
private let control = UISegmentedControl()
private let stackView = TZStackView()
private var activeTabBodyView : UIView? = nil
private var currentIdentifier : String?
override init(frame: CGRect) {
super.init(frame: frame)
stackView.insertArrangedSubview(control, atIndex: 0)
stackView.axis = .Vertical
stackView.alignment = .Fill
stackView.spacing = StandardVerticalMargin
addSubview(stackView)
stackView.snp_makeConstraints {make in
make.leading.equalTo(self.snp_leadingMargin)
make.trailing.equalTo(self.snp_trailingMargin)
make.top.equalTo(self.snp_topMargin)
make.bottom.equalTo(self.snp_bottomMargin)
}
control.oex_addAction({[weak self] control in
let index = (control as! UISegmentedControl).selectedSegmentIndex
self?.showTabAtIndex(index)
}, forEvents: .ValueChanged)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var items : [TabItem] = [] {
didSet {
control.removeAllSegments()
for (index, item) in items.enumerate() {
control.insertSegmentWithTitle(item.name, atIndex: control.numberOfSegments, animated: false)
if item.identifier == currentIdentifier {
showTabAtIndex(index)
}
}
if control.selectedSegmentIndex == UISegmentedControlNoSegment && items.count > 0 {
showTabAtIndex(0)
}
else {
currentIdentifier = nil
}
control.hidden = items.count < 2
}
}
private func showTabAtIndex(index: Int) {
guard index != UISegmentedControlNoSegment else {
return
}
activeTabBodyView?.removeFromSuperview()
let item = items[index]
control.selectedSegmentIndex = index
currentIdentifier = item.identifier
stackView.addArrangedSubview(item.view)
activeTabBodyView = item.view
}
private func indexOfItemWithIdentifier(identifier : String) -> Int? {
return items.firstIndexMatching {$0.identifier == identifier }
}
func showTabWithIdentifier(identifier : String) {
if let index = indexOfItemWithIdentifier(identifier) {
showTabAtIndex(index)
}
}
}
// Only used for testing
extension TabContainerView {
func t_isShowingViewForItem(item : TabItem) -> Bool {
let viewsMatch = stackView.arrangedSubviews == [control, item.view]
let indexMatches = indexOfItemWithIdentifier(item.identifier) == control.selectedSegmentIndex
let identifierMatches = currentIdentifier == item.identifier
return viewsMatch && indexMatches && identifierMatches
}
} | apache-2.0 | 6c900ca041bc5a1909276ffe40fc6bf8 | 29.45283 | 109 | 0.634025 | 5.073899 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.