repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ArinaYauk/WetterApp
|
WetterApp/WetterApp/DailyViewController.swift
|
1
|
2321
|
//
// DailyViewController.swift
// WetterApp
//
// Created by student on 10.02.16.
// Copyright © 2016 student. All rights reserved.
//
import UIKit
class DailyViewController: UITableViewController {
private var forecast: [Daily] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecast.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let daily = forecast[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! DailyTableViewCell
cell.setDailyForecast(daily)
cell.backgroundColor = UIColor.clearColor()
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
/*var dailies = [Daily]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// self.dailies = [Daily(name: "Sonnig", temp: 23.0), Daily(name: "Wolkig", temp: 23.0), Daily(name: "Neblich", temp: 23.0), Daily(name: "Regen", temp: 22.0)]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dailies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("SecondCell", forIndexPath: indexPath) as UITableViewCell
var daily : Daily
daily = dailies[indexPath.row]
cell.textLabel?.text = daily.name
//cell.textLabel?.text = "\(daily.temp)"
return cell
}*/
}
|
apache-2.0
|
238c5c693ae11a8a5df041f2e99cfc86
| 29.933333 | 165 | 0.652155 | 5.010799 | false | false | false | false |
societymedia/SwiftyContainer
|
Pods/Nimble/Nimble/Utils/Async.swift
|
15
|
13314
|
import Foundation
import Dispatch
private let timeoutLeeway: UInt64 = NSEC_PER_MSEC
private let pollLeeway: UInt64 = NSEC_PER_MSEC
/// Stores debugging information about callers
internal struct WaitingInfo: CustomStringConvertible {
let name: String
let file: String
let lineNumber: UInt
var description: String {
return "\(name) at \(file):\(lineNumber)"
}
}
internal protocol WaitLock {
func acquireWaitingLock(fnName: String, file: String, line: UInt)
func releaseWaitingLock()
func isWaitingLocked() -> Bool
}
internal class AssertionWaitLock: WaitLock {
private var currentWaiter: WaitingInfo? = nil
init() { }
func acquireWaitingLock(fnName: String, file: String, line: UInt) {
let info = WaitingInfo(name: fnName, file: file, lineNumber: line)
nimblePrecondition(
NSThread.isMainThread(),
"InvalidNimbleAPIUsage",
"\(fnName) can only run on the main thread."
)
nimblePrecondition(
currentWaiter == nil,
"InvalidNimbleAPIUsage",
"Nested async expectations are not allowed to avoid creating flaky tests.\n\n" +
"The call to\n\t\(info)\n" +
"triggered this exception because\n\t\(currentWaiter!)\n" +
"is currently managing the main run loop."
)
currentWaiter = info
}
func isWaitingLocked() -> Bool {
return currentWaiter != nil
}
func releaseWaitingLock() {
currentWaiter = nil
}
}
internal enum AwaitResult<T> {
/// Incomplete indicates None (aka - this value hasn't been fulfilled yet)
case Incomplete
/// TimedOut indicates the result reached its defined timeout limit before returning
case TimedOut
/// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger
/// the timeout code.
///
/// This may also mean the async code waiting upon may have never actually ran within the
/// required time because other timers & sources are running on the main run loop.
case BlockedRunLoop
/// The async block successfully executed and returned a given result
case Completed(T)
/// When a Swift Error is thrown
case ErrorThrown(ErrorType)
/// When an Objective-C Exception is raised
case RaisedException(NSException)
func isIncomplete() -> Bool {
switch self {
case .Incomplete: return true
default: return false
}
}
func isCompleted() -> Bool {
switch self {
case .Completed(_): return true
default: return false
}
}
}
/// Holds the resulting value from an asynchronous expectation.
/// This class is thread-safe at receiving an "response" to this promise.
internal class AwaitPromise<T> {
private(set) internal var asyncResult: AwaitResult<T> = .Incomplete
private var signal: dispatch_semaphore_t
init() {
signal = dispatch_semaphore_create(1)
}
/// Resolves the promise with the given result if it has not been resolved. Repeated calls to
/// this method will resolve in a no-op.
///
/// @returns a Bool that indicates if the async result was accepted or rejected because another
/// value was recieved first.
func resolveResult(result: AwaitResult<T>) -> Bool {
if dispatch_semaphore_wait(signal, DISPATCH_TIME_NOW) == 0 {
self.asyncResult = result
return true
} else {
return false
}
}
}
internal struct AwaitTrigger {
let timeoutSource: dispatch_source_t
let actionSource: dispatch_source_t?
let start: () throws -> Void
}
/// Factory for building fully configured AwaitPromises and waiting for their results.
///
/// This factory stores all the state for an async expectation so that Await doesn't
/// doesn't have to manage it.
internal class AwaitPromiseBuilder<T> {
let awaiter: Awaiter
let waitLock: WaitLock
let trigger: AwaitTrigger
let promise: AwaitPromise<T>
internal init(
awaiter: Awaiter,
waitLock: WaitLock,
promise: AwaitPromise<T>,
trigger: AwaitTrigger) {
self.awaiter = awaiter
self.waitLock = waitLock
self.promise = promise
self.trigger = trigger
}
func timeout(timeoutInterval: NSTimeInterval, forcefullyAbortTimeout: NSTimeInterval) -> Self {
// = Discussion =
//
// There's a lot of technical decisions here that is useful to elaborate on. This is
// definitely more lower-level than the previous NSRunLoop based implementation.
//
//
// Why Dispatch Source?
//
//
// We're using a dispatch source to have better control of the run loop behavior.
// A timer source gives us deferred-timing control without having to rely as much on
// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
// which is ripe for getting corrupted by application code.
//
// And unlike dispatch_async(), we can control how likely our code gets prioritized to
// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
//
// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
// highest priority over normal application / test code when possible.
//
//
// Run Loop Management
//
// In order to properly interrupt the waiting behavior performed by this factory class,
// this timer stops the main run loop to tell the waiter code that the result should be
// checked.
//
// In addition, stopping the run loop is used to halt code executed on the main run loop.
dispatch_source_set_timer(
trigger.timeoutSource,
dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutInterval * Double(NSEC_PER_SEC))),
DISPATCH_TIME_FOREVER,
timeoutLeeway
)
dispatch_source_set_event_handler(trigger.timeoutSource) {
guard self.promise.asyncResult.isIncomplete() else { return }
let timedOutSem = dispatch_semaphore_create(0)
let semTimedOutOrBlocked = dispatch_semaphore_create(0)
dispatch_semaphore_signal(semTimedOutOrBlocked)
let runLoop = CFRunLoopGetMain()
CFRunLoopPerformBlock(runLoop, kCFRunLoopDefaultMode) {
if dispatch_semaphore_wait(semTimedOutOrBlocked, DISPATCH_TIME_NOW) == 0 {
dispatch_semaphore_signal(timedOutSem)
dispatch_semaphore_signal(semTimedOutOrBlocked)
if self.promise.resolveResult(.TimedOut) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
// potentially interrupt blocking code on run loop to let timeout code run
CFRunLoopStop(runLoop)
let now = dispatch_time(DISPATCH_TIME_NOW, Int64(forcefullyAbortTimeout * Double(NSEC_PER_SEC)))
let didNotTimeOut = dispatch_semaphore_wait(timedOutSem, now) != 0
let timeoutWasNotTriggered = dispatch_semaphore_wait(semTimedOutOrBlocked, 0) == 0
if didNotTimeOut && timeoutWasNotTriggered {
if self.promise.resolveResult(.BlockedRunLoop) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
return self
}
/// Blocks for an asynchronous result.
///
/// @discussion
/// This function must be executed on the main thread and cannot be nested. This is because
/// this function (and it's related methods) coordinate through the main run loop. Tampering
/// with the run loop can cause undesireable behavior.
///
/// This method will return an AwaitResult in the following cases:
///
/// - The main run loop is blocked by other operations and the async expectation cannot be
/// be stopped.
/// - The async expectation timed out
/// - The async expectation succeeded
/// - The async expectation raised an unexpected exception (objc)
/// - The async expectation raised an unexpected error (swift)
///
/// The returned AwaitResult will NEVER be .Incomplete.
func wait(fnName: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) -> AwaitResult<T> {
waitLock.acquireWaitingLock(
fnName,
file: file,
line: line)
let capture = NMBExceptionCapture(handler: ({ exception in
self.promise.resolveResult(.RaisedException(exception))
}), finally: ({
self.waitLock.releaseWaitingLock()
}))
capture.tryBlock {
do {
try self.trigger.start()
} catch let error {
self.promise.resolveResult(.ErrorThrown(error))
}
dispatch_resume(self.trigger.timeoutSource)
while self.promise.asyncResult.isIncomplete() {
// Stopping the run loop does not work unless we run only 1 mode
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture())
}
dispatch_suspend(self.trigger.timeoutSource)
dispatch_source_cancel(self.trigger.timeoutSource)
if let asyncSource = self.trigger.actionSource {
dispatch_source_cancel(asyncSource)
}
}
return promise.asyncResult
}
}
internal class Awaiter {
let waitLock: WaitLock
let timeoutQueue: dispatch_queue_t
let asyncQueue: dispatch_queue_t
internal init(
waitLock: WaitLock,
asyncQueue: dispatch_queue_t,
timeoutQueue: dispatch_queue_t) {
self.waitLock = waitLock
self.asyncQueue = asyncQueue
self.timeoutQueue = timeoutQueue
}
private func createTimerSource(queue: dispatch_queue_t) -> dispatch_source_t {
return dispatch_source_create(
DISPATCH_SOURCE_TYPE_TIMER,
0,
DISPATCH_TIMER_STRICT,
queue
)
}
func performBlock<T>(
closure: ((T) -> Void) throws -> Void) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
var completionCount = 0
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
try closure() {
completionCount += 1
nimblePrecondition(
completionCount < 2,
"InvalidNimbleAPIUsage",
"Done closure's was called multiple times. waitUntil(..) expects its " +
"completion closure to only be called once.")
if promise.resolveResult(.Completed($0)) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
func poll<T>(pollInterval: NSTimeInterval, closure: () throws -> T?) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
let asyncSource = createTimerSource(asyncQueue)
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
let interval = UInt64(pollInterval * Double(NSEC_PER_SEC))
dispatch_source_set_timer(asyncSource, DISPATCH_TIME_NOW, interval, pollLeeway)
dispatch_source_set_event_handler(asyncSource) {
do {
if let result = try closure() {
if promise.resolveResult(.Completed(result)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
} catch let error {
if promise.resolveResult(.ErrorThrown(error)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
dispatch_resume(asyncSource)
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
}
internal func pollBlock(
pollInterval pollInterval: NSTimeInterval,
timeoutInterval: NSTimeInterval,
file: String,
line: UInt,
fnName: String = __FUNCTION__,
expression: () throws -> Bool) -> AwaitResult<Bool> {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let result = awaiter.poll(pollInterval) { () throws -> Bool? in
do {
if try expression() {
return true
}
return nil
} catch let error {
throw error
}
}.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval / 2.0).wait(fnName, file: file, line: line)
return result
}
|
apache-2.0
|
e430081e563706c2ad3f81757850885f
| 36.612994 | 118 | 0.60673 | 4.920177 | false | false | false | false |
sprint84/RFCalculatorKeyboard
|
CalculatorKeyboard/CalculatorKeyboard.swift
|
2
|
5103
|
//
// CalculatorKeyboard.swift
// CalculatorKeyboard
//
// Created by Guilherme Moura on 8/15/15.
// Copyright (c) 2015 Reefactor, Inc. All rights reserved.
//
import UIKit
public protocol CalculatorDelegate: class {
func calculator(_ calculator: CalculatorKeyboard, didChangeValue value: String)
}
enum CalculatorKey: Int {
case zero = 1
case one
case two
case three
case four
case five
case six
case seven
case eight
case nine
case decimal
case clear
case delete
case multiply
case divide
case subtract
case add
case equal
}
open class CalculatorKeyboard: UIView {
open weak var delegate: CalculatorDelegate?
open var numbersBackgroundColor = UIColor(white: 0.97, alpha: 1.0) {
didSet {
adjustLayout()
}
}
open var numbersTextColor = UIColor.black {
didSet {
adjustLayout()
}
}
open var operationsBackgroundColor = UIColor(white: 0.75, alpha: 1.0) {
didSet {
adjustLayout()
}
}
open var operationsTextColor = UIColor.white {
didSet {
adjustLayout()
}
}
open var equalBackgroundColor = UIColor(red:0.96, green:0.5, blue:0, alpha:1) {
didSet {
adjustLayout()
}
}
open var equalTextColor = UIColor.white {
didSet {
adjustLayout()
}
}
open var showDecimal = true {
didSet {
processor.automaticDecimal = !showDecimal
adjustLayout()
}
}
var view: UIView!
fileprivate var processor = CalculatorProcessor()
@IBOutlet weak var zeroDistanceConstraint: NSLayoutConstraint!
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadXib()
}
public override init(frame: CGRect) {
super.init(frame: frame)
loadXib()
}
open override func awakeFromNib() {
super.awakeFromNib()
adjustLayout()
}
fileprivate func loadXib() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
adjustLayout()
addSubview(view)
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CalculatorKeyboard", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
adjustButtonConstraint()
return view
}
fileprivate func adjustLayout() {
if viewWithTag(CalculatorKey.decimal.rawValue) != nil {
adjustButtonConstraint()
}
for i in 1...CalculatorKey.decimal.rawValue {
if let button = self.view.viewWithTag(i) as? UIButton {
button.tintColor = numbersBackgroundColor
button.setTitleColor(numbersTextColor, for: UIControlState())
}
}
for i in CalculatorKey.clear.rawValue...CalculatorKey.add.rawValue {
if let button = self.view.viewWithTag(i) as? UIButton {
button.tintColor = operationsBackgroundColor
button.setTitleColor(operationsTextColor, for: UIControlState())
button.tintColor = operationsTextColor
}
}
if let button = self.view.viewWithTag(CalculatorKey.equal.rawValue) as? UIButton {
button.tintColor = equalBackgroundColor
button.setTitleColor(equalTextColor, for: UIControlState())
}
}
fileprivate func adjustButtonConstraint() {
let width = UIScreen.main.bounds.width / 4.0
zeroDistanceConstraint.constant = showDecimal ? width + 2.0 : 1.0
layoutIfNeeded()
}
@IBAction func buttonPressed(_ sender: UIButton) {
switch (sender.tag) {
case (CalculatorKey.zero.rawValue)...(CalculatorKey.nine.rawValue):
let output = processor.storeOperand(sender.tag-1)
delegate?.calculator(self, didChangeValue: output)
case CalculatorKey.decimal.rawValue:
let output = processor.addDecimal()
delegate?.calculator(self, didChangeValue: output)
case CalculatorKey.clear.rawValue:
let output = processor.clearAll()
delegate?.calculator(self, didChangeValue: output)
case CalculatorKey.delete.rawValue:
let output = processor.deleteLastDigit()
delegate?.calculator(self, didChangeValue: output)
case (CalculatorKey.multiply.rawValue)...(CalculatorKey.add.rawValue):
let output = processor.storeOperator(sender.tag)
delegate?.calculator(self, didChangeValue: output)
case CalculatorKey.equal.rawValue:
let output = processor.computeFinalValue()
delegate?.calculator(self, didChangeValue: output)
break
default:
break
}
}
}
|
mit
|
70660c389fc62493e792a248c0f7eee4
| 29.195266 | 101 | 0.609837 | 4.925676 | false | false | false | false |
John-Connolly/SwiftQ
|
Sources/SwiftQ/Task/ScheduledBox.swift
|
1
|
541
|
//
// ScheduledTask.swift
// SwiftQ
//
// Created by John Connolly on 2017-07-06.
//
//
import Foundation
struct ScheduledBox: ZSettable {
let score: String
let uuid: String
let task: Data
init(_ task: Task, when time: Time) throws {
let time = Date().unixTime + time.unixTime
let data = try task.data()
self.uuid = task.storage.uuid
self.score = time.description
self.task = data
}
}
protocol Boxable {
var task: Data { get }
}
|
mit
|
f4a8aff2c39d624a2297a9d81830b73d
| 14.457143 | 50 | 0.560074 | 3.705479 | false | false | false | false |
davejlong/ResponseDetective
|
ResponseDetective Tests/Source Files/JSONInterceptorSpec.swift
|
1
|
2056
|
//
// JSONInterceptorSpec.swift
//
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
class JSONInterceptorSpec: QuickSpec {
override func spec() {
describe("JSONInterceptor") {
var stream: BufferOutputStream!
var sut: JSONInterceptor!
let uglyFixtureString = "{\"foo\":\"bar\"\n,\"baz\":true }"
let uglyFixtureData = uglyFixtureString.dataUsingEncoding(NSUTF8StringEncoding)!
let prettyFixtureString = "{\n \"foo\" : \"bar\",\n \"baz\" : true\n}"
let fixtureRequest = RequestRepresentation( {
let mutableRequest = NSMutableURLRequest()
mutableRequest.URL = NSURL(string: "https://httpbin.org/post")!
mutableRequest.HTTPMethod = "POST"
mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = uglyFixtureData
return mutableRequest
}())!
let fixtureResponse = ResponseRepresentation(NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/post")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: [
"Content-Type": "application/json"
]
)!, uglyFixtureData)!
beforeEach {
stream = BufferOutputStream()
sut = JSONInterceptor(outputStream: stream)
}
it("should be able to intercept application/json requests") {
expect(sut.canInterceptRequest(fixtureRequest)).to(beTrue())
}
it("should be able to intercept application/json responses") {
expect(sut.canInterceptResponse(fixtureResponse)).to(beTrue())
}
it("should output a correct string when intercepting a application/json request") {
sut.interceptRequest(fixtureRequest)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
it("should output a correct string when intercepting a application/json response") {
sut.interceptResponse(fixtureResponse)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
}
}
}
|
mit
|
79e0304f431c11e013673e61e14da74a
| 28.371429 | 99 | 0.713035 | 3.953846 | false | false | false | false |
gkaimakas/ReactiveBluetooth
|
Example/ReactiveBluetooth/Views/ActionButton.swift
|
1
|
1690
|
//
// ActionButton.swift
// ReactiveBluetooth_Example
//
// Created by George Kaimakas on 06/03/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import ReactiveCocoa
import ReactiveSwift
import Result
import UIKit
public class ActionButton: UIButton {
fileprivate let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
override public init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
addSubview(activityIndicator)
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.hidesWhenStopped = true
activityIndicator.color = tintColor
bringSubview(toFront: activityIndicator)
layer.borderColor = tintColor.cgColor
layer.borderWidth = 0.5
contentEdgeInsets = UIEdgeInsets(top: 8, left: 32, bottom: 8, right: 32)
}
override public func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = self.frame.height/2
activityIndicator.frame = CGRect(x: frame.width-28, y: (frame.height - 24)/2, width: 24, height: 24)
}
}
extension Reactive where Base: ActionButton {
public var action: CocoaAction<Base>? {
get {
return self.pressed
}
nonmutating set {
self.pressed = newValue
if let _action = newValue {
base.activityIndicator.reactive.isAnimating <~ _action.isExecuting.producer
}
}
}
}
|
mit
|
d1f66a9b4f4de941f5cec265d776267c
| 24.984615 | 113 | 0.646536 | 4.771186 | false | false | false | false |
1000copy/fin
|
Controller/MoreViewController.swift
|
1
|
3375
|
import UIKit
class MoreViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("more")
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none;
regClass(self.tableView, cell: BaseDetailTableViewCell.self)
view.backgroundColor = V2EXColor.colors.v2_backgroundColor
tableView.reloadData()
// self.thmemChangedHandler = {[weak self] (style) -> Void in
// self?.view.backgroundColor = V2EXColor.colors.v2_backgroundColor
// self?.tableView.reloadData()
// }
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 9
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return [30,50,12,50,50,12,50,50,50][indexPath.row]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(tableView, cell: BaseDetailTableViewCell.self, indexPath: indexPath)
cell.selectionStyle = .none
//设置标题
cell.titleLabel.text = [
"",
NSLocalizedString("viewOptions"),
"",
NSLocalizedString("rateV2ex"),
NSLocalizedString("reportAProblem"),
"",
NSLocalizedString("followThisProjectSourceCode"),
NSLocalizedString("open-SourceLibraries"),
NSLocalizedString("version")][indexPath.row]
//设置颜色
if [0,2,5].contains(indexPath.row) {
cell.backgroundColor = self.tableView.backgroundColor
}
else{
cell.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor
}
//设置右侧箭头
if [0,2,5,8].contains(indexPath.row) {
cell.detailMarkHidden = true
}
else {
cell.detailMarkHidden = false
}
//设置右侧文本
if indexPath.row == 8 {
cell.detailLabel.text = "Version " + (Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)
+ " (Build " + (Bundle.main.infoDictionary!["CFBundleVersion"] as! String ) + ")"
}
else {
cell.detailLabel.text = ""
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
Msg.send("pushSettingsTableViewController")
}
else if indexPath.row == 3 {
let str = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=1078157349"
openURL(str)
}
else if indexPath.row == 4 {
openURL("http://finb.github.io/blog/2016/02/01/v2ex-ioske-hu-duan-bug-and-jian-yi/")
}
else if indexPath.row == 6 {
openURL("https://github.com/Finb/V2ex-Swift")
}
else if indexPath.row == 7 {
Msg.send("pushPodsTableViewController")
}
}
func openURL(_ url : String){
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string:url)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string:url)!)
}
}
}
|
mit
|
87f52f8bbdf4e8e6353ca86e54b8502a
| 38.702381 | 119 | 0.5991 | 4.606354 | false | false | false | false |
eBardX/XestiMonitors
|
Tests/Mock/MockFileSystemObject.swift
|
1
|
1699
|
//
// MockFileSystemObject.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2018-02-21.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
import Foundation
@testable import XestiMonitors
internal class MockFileSystemObject: FileSystemObjectProtocol {
init(fileDescriptor: Int32,
eventMask: DispatchSource.FileSystemEvent,
queue: DispatchQueue?) {
self.data = []
self.handle = fileDescriptor
self.mask = eventMask
self.queue = queue ?? .global()
}
private(set) var data: DispatchSource.FileSystemEvent
func cancel() {
if let handler = cancelHandler {
queue.async(execute: handler)
}
}
func resume() {
}
func setCancelHandler(qos: DispatchQoS,
flags: DispatchWorkItemFlags,
handler: DispatchSourceProtocol.DispatchSourceHandler?) {
cancelHandler = handler
}
func setEventHandler(qos: DispatchQoS,
flags: DispatchWorkItemFlags,
handler: DispatchSourceProtocol.DispatchSourceHandler?) {
eventHandler = handler
}
// MARK: -
func updateData(for eventMask: DispatchSource.FileSystemEvent) {
data = mask.intersection(eventMask)
if !data.isEmpty,
let handler = eventHandler {
queue.async(execute: handler)
}
}
private let queue: DispatchQueue
private var cancelHandler: DispatchSourceProtocol.DispatchSourceHandler?
private var eventHandler: DispatchSourceProtocol.DispatchSourceHandler?
private var handle: Int32
private var mask: DispatchSource.FileSystemEvent
}
|
mit
|
00182f68946909650884aae2c8cf29c3
| 25.952381 | 83 | 0.637809 | 5.176829 | false | false | false | false |
lotz84/__.swift
|
__.swift/Collections/__Collections.swift
|
1
|
8253
|
//
// __Collections.swift
// __.swift
//
// Copyright (c) 2014 Tatsuya Hirose
//
// 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 extension __ {
/**
* Collection Functions (Arrays or Dictionaries)
*/
public class func each<T : SequenceType>(seq: T, _ iterator: T.Generator.Element -> Any){
var gen = seq.generate()
while let elem = gen.next() {
iterator(elem)
}
}
// alias for each
public class func forEach<T : SequenceType>(seq: T, _ iterator: T.Generator.Element -> Any){
__.each(seq, iterator)
}
public class func reduceRight<T : SequenceType, U>(seq: T, initial: U, combine: (T.Generator.Element, U) -> U) -> U {
var array : [T.Generator.Element] = []
var gen = seq.generate()
while let elem = gen.next() {
array.append(elem)
}
return array.reverse().reduce(initial, combine: { combine($1,$0) } )
}
public class func foldr<T : SequenceType, U>(seq: T, initial: U, combine: (T.Generator.Element, U) -> U) -> U {
return __.reduceRight(seq, initial: initial, combine: combine)
}
public class func find<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool) -> T.Generator.Element? {
var gen = seq.generate()
while let elem = gen.next() {
if predicate(elem) {
return elem
}
}
return nil
}
// alias for find
public class func detect<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool) -> T.Generator.Element? {
return __.find(seq, predicate: predicate)
}
public class func `where`<K,V: Equatable>(array: [[K:V]], _ properties: [K:V]) -> [[K:V]] {
var result : [[K:V]] = []
for dict in array {
if __.hasSubDictionary(dict, subDictionary: properties) {
result.append(dict)
}
}
return result
}
public class func findWhere<K,V: Equatable>(array: [[K:V]], _ properties: [K:V]) -> [K:V]? {
for dict in array {
if __.hasSubDictionary(dict, subDictionary: properties) {
return dict
}
}
return nil
}
public class func reject<T : SequenceType>(seq: T, _ condition: T.Generator.Element -> Bool) -> [T.Generator.Element] {
return Array(filter(seq, { !condition($0) }))
}
public class func every<L: BooleanType>(array: [L]) -> Bool {
return __.every(array, predicate: { $0.boolValue })
}
public class func every<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool ) -> Bool {
return __.find(seq, predicate: { !predicate($0) }) == nil ? true : false
}
// alias for every
public class func all<L: BooleanType>(array: [L]) -> Bool {
return __.every(array)
}
// alias for every
public class func all<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool) -> Bool {
return __.every(seq, predicate: predicate)
}
public class func some<L: BooleanType>(array: [L]) -> Bool {
return __.some(array, predicate: { $0.boolValue })
}
public class func some<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool) -> Bool {
return __.find(seq, predicate: predicate) == nil ? false : true
}
// alias for some
public class func any<L: BooleanType>(array: [L]) -> Bool {
return __.some(array)
}
// alias for some
public class func any<T : SequenceType>(seq: T, predicate: T.Generator.Element -> Bool) -> Bool {
return __.some(seq, predicate: predicate)
}
public class func pluck<K, V>(array: [[K:V]], key: K) -> [V] {
var result : [V] = []
for item in array {
if let value = item[key] {
result.append(value)
}
}
return result
}
// quick sort
public class func sortBy<T : SequenceType, C: Comparable>(seq: T, transform: T.Generator.Element -> C) -> [T.Generator.Element] {
var gen = seq.generate()
if let first = gen.next() {
var smaller : [T.Generator.Element] = []
var bigger : [T.Generator.Element] = []
while let elem = gen.next() {
if transform(first) < transform(elem) {
bigger.append(elem)
} else {
smaller.append(elem)
}
}
var result = sortBy(smaller, transform: transform)
result.append(first)
result += sortBy(bigger, transform: transform)
return result
} else {
return []
}
}
public class func groupBy<K, V>(array: [V], transform: V -> K) -> [K:[V]] {
var result : [K:[V]] = [:]
for item in array {
let key = transform(item)
if let array = result[key] {
result[key] = array + [item]
} else {
result[key] = [item]
}
}
return result
}
public class func indexBy<K, V>(array: [[K:V]], key: K) -> [V:[K:V]] {
var result = [V:[K:V]]()
for item in array {
result[item[key]!] = item
}
return result
}
public class func countBy<T, U>(array: [T], transform: T -> U) -> [U:Int] {
var result : [U:Int] = [:]
for item in array {
if let count = result[transform(item)] {
result[transform(item)] = count + 1
} else {
result[transform(item)] = 1
}
}
return result
}
public class func shuffle<T>(array: [T]) -> [T] {
let length = array.count
var random = Array(0..<length)
for i in 1..<length {
let j = Int(arc4random() % UInt32(i+1))
swap(&random[i], &random[j])
}
return random.map { array[$0] }
}
public class func sample<T>(array: [T]) -> T {
let index = Int(arc4random() % UInt32(array.count))
return array[index]
}
public class func sample<T>(array: [T], _ n:Int) -> [T] {
var result : [T] = []
let random = __.shuffle(Array(0..<array.count))
for i in 0..<n {
result.append(array[random[i]])
}
return result
}
public class func size<T : SequenceType>(seq: T) -> Int {
var count = 0
var gen = seq.generate()
while gen.next() != nil {
count += 1
}
return count
}
private class func hasSubDictionary<K, V: Equatable>(dict:[K:V], subDictionary: [K:V]) -> Bool {
let eqList = map(subDictionary) { (key: K, value: V) -> Bool in
if let v = dict[key] {
return v == value
} else {
return false
}
}
return Array(eqList).reduce(true) { $0 && $1 }
}
}
|
mit
|
fb105756b905a0f1c72612e56eed8771
| 32.012 | 133 | 0.535442 | 4.027818 | false | false | false | false |
Davidde94/StemCode_iOS
|
StemCode/StemCode/Code/Core Data Stores/ColourProfilesDataStore.swift
|
1
|
852
|
//
// ColourProfilesDataStore.swift
// StemCode
//
// Created by David Evans on 08/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
import CoreData
class ColourProfileDataStore {
private init() {}
static var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "StemCode")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
NSLog("Error loading container: %s", error.localizedDescription)
}
})
return container
}()
static func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
0ba4000f7d9a0da9fbcbf4bf9d1cd3a6
| 21.394737 | 82 | 0.707403 | 3.95814 | false | false | false | false |
shajrawi/swift
|
test/decl/var/property_wrappers_synthesis.swift
|
1
|
1250
|
// RUN: %target-swift-frontend -typecheck -dump-ast %s | %FileCheck %s
@_propertyWrapper
struct Wrapper<T> {
var value: T
init(initialValue: T) {
self.value = initialValue
}
}
protocol DefaultInit {
init()
}
// CHECK: struct_decl{{.*}}"UseWrapper"
struct UseWrapper<T: DefaultInit> {
// CHECK: var_decl{{.*}}"wrapped"
// CHECK: accessor_decl{{.*}}get_for=wrapped
// CHECK: member_ref_expr{{.*}}UseWrapper.$wrapped
// CHECK: accessor_decl{{.*}}set_for=wrapped
// CHECK: member_ref_expr{{.*}}UseWrapper.$wrapped
// CHECK: accessor_decl{{.*}}_modify_for=wrapped
// CHECK: yield_stmt
// CHECK: member_ref_expr{{.*}}UseWrapper.wrapped
@Wrapper
var wrapped = T()
// CHECK: pattern_binding_decl implicit
// CHECK-NEXT: pattern_typed implicit type='Wrapper<T>'
// CHECK-NEXT: pattern_named implicit type='Wrapper<T>' '$wrapped'
// CHECK: constructor_ref_call_expr
// CHECK-NEXT: declref_expr{{.*}}Wrapper.init(initialValue:)
init() { }
}
struct UseWillSetDidSet {
// CHECK: var_decl{{.*}}"z"
// CHECK: accessor_decl{{.*}}set_for=z
// CHECK: member_ref_expr{{.*}}UseWillSetDidSet.$z
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
|
apache-2.0
|
73accfa17a0aadf81e9c056ddf2c53af
| 21.727273 | 70 | 0.6328 | 3.531073 | false | false | false | false |
february29/Learning
|
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Take.swift
|
94
|
5371
|
//
// Take.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Returns a specified number of contiguous elements from the start of an observable sequence.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter count: The number of elements to return.
- returns: An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
public func take(_ count: Int)
-> Observable<E> {
if count == 0 {
return Observable.empty()
}
else {
return TakeCount(source: asObservable(), count: count)
}
}
}
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
public func take(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// count version
final fileprivate class TakeCountSink<O: ObserverType> : Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = TakeCount<E>
private let _parent: Parent
private var _remaining: Int
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_remaining = parent._count
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
if _remaining > 0 {
_remaining -= 1
forwardOn(.next(value))
if _remaining == 0 {
forwardOn(.completed)
dispose()
}
}
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
}
final fileprivate class TakeCount<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
_source = source
_count = count
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
// time version
final fileprivate class TakeTimeSink<ElementType, O: ObserverType>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType where O.E == ElementType {
typealias Parent = TakeTime<ElementType>
typealias E = ElementType
fileprivate let _parent: Parent
let _lock = RecursiveLock()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next(let value):
forwardOn(.next(value))
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
func tick() {
_lock.lock(); defer { _lock.unlock() }
forwardOn(.completed)
dispose()
}
func run() -> Disposable {
let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) {
self.tick()
return Disposables.create()
}
let disposeSubscription = _parent._source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
final fileprivate class TakeTime<Element> : Producer<Element> {
typealias TimeInterval = RxTimeInterval
fileprivate let _source: Observable<Element>
fileprivate let _duration: TimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) {
_source = source
_scheduler = scheduler
_duration = duration
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
|
mit
|
f640f682e509bb1159d6e03e38a69749
| 28.833333 | 145 | 0.609125 | 4.811828 | false | false | false | false |
P9SOFT/HJPhotoAlbumManager
|
Sources/P9PhotoAlbumManager.swift
|
1
|
29845
|
//
// P9PhotoAlbumManager.swift
//
//
// Created by Tae Hyun Na on 2019. 3. 19.
// Copyright (c) 2014, P9 SOFT, Inc. All rights reserved.
//
// Licensed under the MIT license.
import UIKit
import Photos
extension Notification.Name {
static let P9PhotoAlbumManager = Notification.Name("P9PhotoAlbumManagerNotification")
}
@objc extension NSNotification {
public static let P9PhotoAlbumManager = Notification.Name.P9PhotoAlbumManager
}
open class P9PhotoAlbumManager: NSObject {
@objc public static let NotificationOperationObjcKey = "P9PhotoAlbumManagerNotificationOperationObjcKey"
@objc public static let NotificationStatusObjcKey = "P9PhotoAlbumManagerNotificationStatusObjcKey"
public static let NotificationOperationKey = "P9PhotoAlbumManagerNotificationOperationKey"
public static let NotificationStatusKey = "P9PhotoAlbumManagerNotificationStatusKey"
@objc public static let maximumImageSize = PHImageManagerMaximumSize
@objc(P9PhotoAlbumManagerOperation) public enum Operation: Int {
case authorization
case requestAlbums
case requestMedias
case createAlbum
case deleteAlbum
case renameAlbum
case saveMediaToAlbum
case deleteMediaFromAlbum
case reload
case clearCache
case appWillEnterForeground
}
@objc(P9PhotoAlbumManagerStatus) public enum Status: Int {
case accessDenied
case succeed
case failed
}
@objc(P9PhotoAlbumManagerPredefinedAlbumType) public enum PredefinedAlbumType: Int {
case cameraRoll
case favorite
case recentlyAdded
case screenshots
case videos
case regular
case customCollectionType
}
@objc(P9PhotoAlbumManagerMediaType) public enum MediaType: Int {
case unknown
case image
case video
case audio
}
@objc(P9PhotoAlbumManagerContentMode) public enum ContentMode: Int {
case aspectFit
case aspectFill
}
@objc(P9PhotoAlbumManagerAlbumInfo) public class AlbumInfo : NSObject {
var collectionType:PHAssetCollectionType = .smartAlbum
var collectionTypeSubtype:PHAssetCollectionSubtype = .smartAlbumUserLibrary
var mediaTypes:[MediaType] = [.image]
var ascending:Bool = false
@objc public convenience init(type:Int) {
let convertedType = PredefinedAlbumType(rawValue: type) ?? .cameraRoll
self.init(type: convertedType, mediaTypes: [.image], ascending: false)
}
public convenience init(type:PredefinedAlbumType) {
self.init(type: type, mediaTypes: [.image], ascending: false)
}
@objc public convenience init(type:Int, mediaTypes:[Int], ascending:Bool) {
let convertedType = PredefinedAlbumType(rawValue: type) ?? .cameraRoll
let convertedMediaTypes = mediaTypes.map({ MediaType(rawValue: $0) ?? .unknown})
self.init(type: convertedType, mediaTypes: convertedMediaTypes, ascending: ascending)
}
public convenience init(type:PredefinedAlbumType, mediaTypes:[MediaType], ascending:Bool) {
self.init()
switch type {
case .cameraRoll :
self.collectionType = .smartAlbum
self.collectionTypeSubtype = .smartAlbumUserLibrary
case .favorite :
self.collectionType = .smartAlbum
self.collectionTypeSubtype = .smartAlbumFavorites
case .recentlyAdded :
self.collectionType = .smartAlbum
self.collectionTypeSubtype = .smartAlbumRecentlyAdded
case .screenshots :
if #available(iOS 9.0, *) {
self.collectionType = .smartAlbum
self.collectionTypeSubtype = .smartAlbumScreenshots
}
case .videos :
self.collectionType = .smartAlbum
self.collectionTypeSubtype = .smartAlbumVideos
case .regular :
self.collectionType = .album
self.collectionTypeSubtype = .albumRegular
default :
break
}
self.mediaTypes = mediaTypes
self.ascending = ascending
}
@objc public convenience init(collectionType:Int, collectionTypeSubtype:Int, mediaTypes:[Int], ascending:Bool) {
let convertedCollectionType = PHAssetCollectionType(rawValue: collectionType) ?? .smartAlbum
let convertedCollectionTypeSubtype = PHAssetCollectionSubtype(rawValue: collectionType) ?? .smartAlbumUserLibrary
let convertedMediaTypes = mediaTypes.map({ MediaType(rawValue: $0) ?? .unknown})
self.init(collectionType: convertedCollectionType, collectionTypeSubtype: convertedCollectionTypeSubtype, mediaTypes: convertedMediaTypes, ascending: ascending)
}
public convenience init(collectionType:PHAssetCollectionType, collectionTypeSubtype:PHAssetCollectionSubtype, mediaTypes:[MediaType], ascending:Bool) {
self.init()
self.collectionType = collectionType
self.collectionTypeSubtype = collectionTypeSubtype
self.mediaTypes = mediaTypes
self.ascending = ascending
}
}
public typealias P9PhotoAlbumManagerCompletionBlock = (_ operation:Operation, _ status:Status) -> Void
private let serialQueue = DispatchQueue(label: "p9photoalbummanager")
private let dispatchGroup = DispatchGroup()
private var albumInfos:[AlbumInfo] = []
private var albums:[PHAssetCollection] = []
private var assetsAtAlbumIndex:[Int:[PHAsset]] = [:]
@objc public var autoReloadWhenAppWillEnterForeground:Bool = true
@objc public static let shared = P9PhotoAlbumManager()
public override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundHandler(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc fileprivate func applicationWillEnterForegroundHandler(notification:Notification) {
self.postNotify(operation: .appWillEnterForeground, status: .succeed, completion: nil)
if autoReloadWhenAppWillEnterForeground == true {
reload(nil)
}
}
@objc public var authorized:Bool {
get {
return (PHPhotoLibrary.authorizationStatus() == .authorized)
}
}
@objc public func authorization(completion:P9PhotoAlbumManagerCompletionBlock?) {
if PHPhotoLibrary.authorizationStatus() == .authorized {
postNotify(operation: .authorization, status: .succeed, completion: completion)
return
}
PHPhotoLibrary.requestAuthorization { (status) in
self.postNotify(operation: .authorization, status: (status == .authorized ? .succeed : .failed), completion: completion)
}
}
@objc public func requestAlbums(byInfos infos:[AlbumInfo], completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, infos.count > 0 else {
postNotify(operation: .requestAlbums, status: .failed, completion: completion)
return
}
serialQueue.async {
self.albumInfos.removeAll()
self.albums.removeAll()
self.assetsAtAlbumIndex.removeAll()
for info in infos {
let result = PHAssetCollection.fetchAssetCollections(with: info.collectionType, subtype: info.collectionTypeSubtype, options: nil)
result.enumerateObjects { (collection, index, stop) in
self.albumInfos.append(info)
self.albums.append(collection)
}
}
self.postNotify(operation: .requestAlbums, status: .succeed, completion: completion)
}
}
public func requestMedia(atAlbumIndex albumIndex:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
postNotify(operation: .requestMedias, status: .failed, completion: completion)
return
}
serialQueue.async {
var assets:[PHAsset] = []
let result = self.fetchResultAssetForAlbumIndex(albumIndex)
result.enumerateObjects({ (asset, index, stop) in
assets.append(asset)
})
self.assetsAtAlbumIndex[albumIndex] = assets
self.postNotify(operation: .requestMedias, status: .succeed, completion: completion)
}
}
@objc(createAlbumTitle:mediaTypes:ascending:completion:)
public func objc_createAlbum(title:String, mediaTypes:[Int], ascending:Bool, completion:P9PhotoAlbumManagerCompletionBlock?) {
createAlbum(title: title, mediaTypes: mediaTypes.map({ MediaType(rawValue: $0) ?? .unknown}), ascending: ascending, completion: completion)
}
public func createAlbum(title:String, mediaTypes:[MediaType], ascending:Bool, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, title.count > 0, mediaTypes.count > 0 else {
self.postNotify(operation: .createAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)
}) { (succeed, error) in
if succeed == true {
let options = PHFetchOptions.init()
options.predicate = NSPredicate.init(format: "title = %@", title)
let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: options)
if let assetCollection = result.lastObject {
self.albumInfos.append(AlbumInfo.init(type: .regular, mediaTypes: mediaTypes, ascending: ascending))
self.albums.append(assetCollection)
}
}
self.postNotify(operation: .createAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func deleteAlbum(index:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= index, index < albums.count else {
postNotify(operation: .deleteAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.deleteAssetCollections([self.albums[index]] as NSFastEnumeration)
}) { (succeed, error) in
if succeed == true {
self.albumInfos.remove(at: index)
self.albums.remove(at: index)
self.assetsAtAlbumIndex.removeValue(forKey: index)
}
self.postNotify(operation: .deleteAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func renameAlbum(index:Int, title:String, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= index, index < albums.count, title.count > 0 else {
postNotify(operation: .deleteAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
PHPhotoLibrary.shared().performChanges({
let request = PHAssetCollectionChangeRequest(for: self.albums[index])
request?.title = title
}) { (succeed, error) in
if succeed == true {
let result = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [self.albums[index].localIdentifier], options: nil)
if let collection = result.lastObject {
self.albums[index] = collection
}
}
self.postNotify(operation: .renameAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func savePhotoImage(image:UIImage, toAlbumIndex albumIndex:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
postNotify(operation: .saveMediaToAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
var placeHolder:PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let mediaRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
placeHolder = mediaRequest.placeholderForCreatedAsset
if self.predefineTypeOfAlbum(forIndex: albumIndex) == .regular {
if let placeHolder = placeHolder, let albumRequest = PHAssetCollectionChangeRequest(for: self.albums[albumIndex]) {
albumRequest.addAssets([placeHolder] as NSFastEnumeration)
}
}
}) { (succeed, error) in
if succeed == true, let placeHolder = placeHolder {
let result = PHAsset.fetchAssets(withLocalIdentifiers: [placeHolder.localIdentifier], options: nil)
if let asset = result.lastObject {
if self.albumInfos[albumIndex].ascending == true {
self.assetsAtAlbumIndex[albumIndex]?.append(asset)
} else {
self.assetsAtAlbumIndex[albumIndex]?.insert(asset, at: 0)
}
}
}
self.postNotify(operation: .saveMediaToAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func saveMediaFile(url:URL, mediaType:MediaType, toAlbumIndex albumIndex:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, url.isFileURL == true, 0 <= albumIndex, albumIndex < albums.count else {
postNotify(operation: .saveMediaToAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
var placeHolder:PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
var mediaRequest:PHAssetChangeRequest?
switch mediaType {
case .image :
mediaRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
case .video, .audio :
mediaRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
default :
break
}
if let mediaRequest = mediaRequest {
placeHolder = mediaRequest.placeholderForCreatedAsset
if self.predefineTypeOfAlbum(forIndex: albumIndex) == .regular {
if let placeHolder = placeHolder, let albumRequest = PHAssetCollectionChangeRequest(for: self.albums[albumIndex]) {
albumRequest.addAssets([placeHolder] as NSFastEnumeration)
}
}
}
}) { (succeed, error) in
if succeed == true, let placeHolder = placeHolder {
let result = PHAsset.fetchAssets(withLocalIdentifiers: [placeHolder.localIdentifier], options: nil)
if let asset = result.lastObject {
if self.albumInfos[albumIndex].ascending == true {
self.assetsAtAlbumIndex[albumIndex]?.append(asset)
} else {
self.assetsAtAlbumIndex[albumIndex]?.insert(asset, at: 0)
}
}
}
self.postNotify(operation: .saveMediaToAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func deleteMedia(index:Int, fromAlbumIndex albumIndex:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count, let assets = assetsAtAlbumIndex[albumIndex], 0 <= index, index < assets.count else {
postNotify(operation: .deleteMediaFromAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets([assets[index]] as NSFastEnumeration)
}) { (succeed, error) in
if succeed == true {
self.assetsAtAlbumIndex[albumIndex]?.remove(at: index)
}
self.postNotify(operation: .deleteMediaFromAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func deleteMedia(indices:[Int], fromAlbumIndex albumIndex:Int, completion:P9PhotoAlbumManagerCompletionBlock?) {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count, let assets = assetsAtAlbumIndex[albumIndex], indices.count > 0 else {
postNotify(operation: .deleteMediaFromAlbum, status: .failed, completion: completion)
return
}
serialQueue.async {
var deleteAssets:[PHAsset] = []
for index in indices {
if 0 <= index, index < assets.count {
deleteAssets.append(assets[index])
}
}
if deleteAssets.count == 0 {
self.postNotify(operation: .deleteMediaFromAlbum, status: .failed, completion: completion)
return
}
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(deleteAssets as NSFastEnumeration)
}) { (succeed, error) in
if succeed == true {
let reverseOrderIndices = indices.sorted(by: >)
for index in reverseOrderIndices {
self.assetsAtAlbumIndex[albumIndex]?.remove(at: index)
}
}
self.postNotify(operation: .deleteMediaFromAlbum, status: (succeed == true ? .succeed : .failed), completion: completion)
}
}
}
@objc public func reload(_ completion:P9PhotoAlbumManagerCompletionBlock?) {
serialQueue.async {
var albumInfos:[AlbumInfo] = []
var albums:[PHAssetCollection] = []
var assetsAtAlbumIndex:[Int:[PHAsset]] = [:]
for i in 0..<self.albums.count {
let result = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [self.albums[i].localIdentifier], options: nil)
if let lastObject = result.lastObject {
albumInfos.append(self.albumInfos[i])
albums.append(lastObject)
if self.assetsAtAlbumIndex[i] != nil, let info = albumInfos.last, let collection = albums.last {
let options = PHFetchOptions.init()
if let predicates = self.predicateFromMediaType(mediaTypes: info.mediaTypes) {
options.predicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: predicates)
}
options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: info.ascending)]
let result = PHAsset.fetchAssets(in: collection, options: options)
var assets:[PHAsset] = []
result.enumerateObjects({ (asset, index, stop) in
assets.append(asset)
})
assetsAtAlbumIndex[albumInfos.count-1] = assets
}
}
}
self.albumInfos = albumInfos
self.albums = albums
self.assetsAtAlbumIndex = assetsAtAlbumIndex
self.postNotify(operation: .reload, status: .succeed, completion: completion)
}
}
@objc public func clearCache() {
serialQueue.async {
self.albumInfos.removeAll()
self.albums.removeAll()
self.assetsAtAlbumIndex.removeAll()
self.postNotify(operation: .clearCache, status: .succeed, completion: nil)
}
}
@objc public func numberOfAlbums() -> Int {
guard authorized == true else {
return 0
}
return albums.count
}
@objc public func titleOfAlbum(forIndex index:Int) -> String? {
guard authorized == true, 0 <= index, index < albums.count else {
return nil
}
return albums[index].localizedTitle
}
@objc(predefineTypeOfAlbum:)
public func objc_predefineTypeOfAlbum(forIndex index:Int) -> Int {
return predefineTypeOfAlbum(forIndex: index)?.rawValue ?? PredefinedAlbumType.customCollectionType.rawValue
}
public func predefineTypeOfAlbum(forIndex index:Int) -> PredefinedAlbumType? {
guard authorized == true, 0 <= index, index < albums.count else {
return nil
}
switch albums[index].assetCollectionType {
case .album :
switch albums[index].assetCollectionSubtype {
case .albumRegular :
return .regular
default :
break
}
break
case .smartAlbum :
switch albums[index].assetCollectionSubtype {
case .smartAlbumUserLibrary :
return .cameraRoll
case .smartAlbumFavorites :
return .favorite
case .smartAlbumRecentlyAdded :
return .recentlyAdded
case .smartAlbumScreenshots :
return .screenshots
case .smartAlbumVideos :
return .videos
default :
break
}
break
case .moment :
break
default :
break
}
return .customCollectionType
}
@objc public func infoOfAlbum(forIndex index:Int) -> AlbumInfo? {
guard authorized == true, 0 <= index, index < albums.count else {
return nil
}
return albumInfos[index]
}
@objc public func numberOfMediaAtAlbum(forIndex index:Int) -> Int {
guard authorized == true, 0 <= index, index < albums.count else {
return 0
}
if let assets = assetsAtAlbumIndex[index] {
return assets.count
}
let options = PHFetchOptions.init()
if let predicates = predicateFromMediaType(mediaTypes: albumInfos[index].mediaTypes) {
options.predicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: predicates)
}
return PHAsset.fetchAssets(in: albums[index], options: options).count
}
@objc public func mediaTypeOfMedia(forIndex mediaIndex:Int, atAlbumIndex albumIndex:Int) -> MediaType {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
return .unknown
}
if let asset = assetOfMedia(forIndex: mediaIndex, atAlbumIndex: albumIndex) {
switch asset.mediaType {
case .image :
return .image
case .video :
return .video
case .audio :
return .audio
default :
break
}
}
return .unknown
}
@objc public func imageOfMedia(forIndex mediaIndex:Int, atAlbumIndex albumIndex:Int, targetSize:CGSize, contentMode:ContentMode) -> UIImage? {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
return nil
}
let mode:PHImageContentMode = (contentMode == .aspectFit) ? .aspectFit : .aspectFill
let options = PHImageRequestOptions.init()
options.isSynchronous = true
options.resizeMode = .exact
var foundImage:UIImage?
var asset:PHAsset?
if let assets = assetsAtAlbumIndex[albumIndex], 0 <= mediaIndex, mediaIndex < assets.count {
asset = assets[mediaIndex]
} else {
let result = fetchResultAssetForAlbumIndex(albumIndex)
if 0 <= mediaIndex, mediaIndex < result.count {
asset = result[mediaIndex]
}
}
if let asset = asset {
PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: mode, options: options) { (image, info) in
foundImage = image
}
}
return foundImage
}
@objc public func fileUrlOfMedia(forIndex mediaIndex:Int, atAlbumIndex albumIndex:Int) -> URL? {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
return nil
}
var fileUrl:URL?
if let asset = assetOfMedia(forIndex: mediaIndex, atAlbumIndex: albumIndex) {
switch asset.mediaType {
case .image :
let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
return true
}
dispatchGroup.enter()
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (contentEditingInput, info) in
if let url = contentEditingInput?.fullSizeImageURL {
fileUrl = url
}
self.dispatchGroup.leave()
}
dispatchGroup.wait()
case .video, .audio :
dispatchGroup.enter()
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil) { (asset, audioMix, info) in
if let urlAsset = asset as? AVURLAsset {
fileUrl = urlAsset.url
}
self.dispatchGroup.leave()
}
dispatchGroup.wait()
default :
break
}
}
return fileUrl
}
@objc public func assetOfMedia(forIndex mediaIndex:Int, atAlbumIndex albumIndex:Int) -> PHAsset? {
guard authorized == true, 0 <= albumIndex, albumIndex < albums.count else {
return nil
}
var asset:PHAsset?
if let assets = assetsAtAlbumIndex[albumIndex], 0 <= mediaIndex, mediaIndex < assets.count {
asset = assets[mediaIndex]
} else {
let result = fetchResultAssetForAlbumIndex(albumIndex)
if 0 <= mediaIndex, mediaIndex < result.count {
asset = result[mediaIndex]
}
}
return asset
}
private func postNotify(operation:Operation, status:Status, completion:P9PhotoAlbumManagerCompletionBlock?) {
DispatchQueue.main.async {
if let completion = completion {
completion(operation, status)
}
NotificationCenter.default.post(name: .P9PhotoAlbumManager, object: self, userInfo: [P9PhotoAlbumManager.NotificationOperationKey:operation, P9PhotoAlbumManager.NotificationStatusKey:status, P9PhotoAlbumManager.NotificationOperationObjcKey:operation.rawValue, P9PhotoAlbumManager.NotificationStatusObjcKey:status.rawValue])
}
}
private func predicateFromMediaType(mediaTypes:[MediaType]) -> [NSPredicate]? {
var predicates:[NSPredicate] = []
for type in mediaTypes {
switch type {
case .image :
predicates.append(NSPredicate(format: "mediaType = %i", PHAssetMediaType.image.rawValue))
case .video :
predicates.append(NSPredicate(format: "mediaType = %i", PHAssetMediaType.video.rawValue))
case .audio :
predicates.append(NSPredicate(format: "mediaType = %i", PHAssetMediaType.audio.rawValue))
default :
break
}
}
return (predicates.count > 0 ? predicates : nil)
}
private func fetchResultAssetForAlbumIndex(_ albumIndex:Int) -> PHFetchResult<PHAsset> {
let options = PHFetchOptions.init()
if let predicates = predicateFromMediaType(mediaTypes: albumInfos[albumIndex].mediaTypes) {
options.predicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: predicates)
}
options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: albumInfos[albumIndex].ascending)]
return PHAsset.fetchAssets(in: albums[albumIndex], options: options)
}
}
|
mit
|
170442264c756fd84f1010dd992badc4
| 41.574893 | 335 | 0.594069 | 5.418482 | false | false | false | false |
QuarkX/Quark
|
Tests/QuarkTests/HTTP/Parser/RequestParserTests.swift
|
1
|
8827
|
import XCTest
@testable import Quark
import CHTTPParser
let requestCount = [
1,
2,
5
]
let bufferSizes = [
1,
2,
4,
32,
512,
2048
]
let methods: [Quark.Method] = [
.delete,
.get,
.head,
.post,
.put,
.options,
.trace,
.patch,
.other(method: "COPY"),
.other(method: "LOCK"),
.other(method: "MKCOL"),
.other(method: "MOVE"),
.other(method: "PROPFIND"),
.other(method: "PROPPATCH"),
.other(method: "SEARCH"),
.other(method: "UNLOCK"),
.other(method: "BIND"),
.other(method: "REBIND"),
.other(method: "UNBIND"),
.other(method: "ACL"),
.other(method: "REPORT"),
.other(method: "MKACTIVITY"),
.other(method: "CHECKOUT"),
.other(method: "MERGE"),
.other(method: "M-SEARCH"),
.other(method: "NOTIFY"),
.other(method: "SUBSCRIBE"),
.other(method: "UNSUBSCRIBE"),
.other(method: "PURGE"),
.other(method: "MKCALENDAR"),
.other(method: "LINK"),
.other(method: "UNLINK"),
]
class RequestParserTests : XCTestCase {
func testInvalidMethod() {
let data = "INVALID / HTTP/1.1\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
XCTAssertThrowsError(try parser.parse())
}
func testInvalidURI() {
let data = "GET huehue HTTP/1.1\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
XCTAssertThrowsError(try parser.parse())
}
func testNoURI() {
let data = "GET HTTP/1.1\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
XCTAssertThrowsError(try parser.parse())
}
func testInvalidHTTPVersion() {
let data = "GET / HUEHUE\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
XCTAssertThrowsError(try parser.parse())
}
func testInvalidDoubleConnectMethod() {
let data = "CONNECT / HTTP/1.1\r\n\r\nCONNECT / HTTP/1.1\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
XCTAssertThrowsError(try parser.parse())
}
func testConnectMethod() throws {
let data = "CONNECT / HTTP/1.1\r\n\r\n"
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream)
let request = try parser.parse()
XCTAssert(request.method == .connect)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers.count == 0)
}
func check(request: String, count: Int, bufferSize: Int, test: (Request) -> Void) throws {
var data = ""
for _ in 0 ..< count {
data += request
}
let stream = Drain(buffer: data)
let parser = RequestParser(stream: stream, bufferSize: bufferSize)
for _ in 0 ..< count {
try test(parser.parse())
}
}
func testShortRequests() throws {
for bufferSize in bufferSizes {
for count in requestCount {
for method in methods {
let request = "\(method) / HTTP/1.1\r\n\r\n"
try check(request: request, count: count, bufferSize: bufferSize) { request in
XCTAssert(request.method == method)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers.count == 0)
}
}
}
}
}
func testMediumRequests() throws {
for bufferSize in bufferSizes {
for count in requestCount {
for method in methods {
let request = "\(method) / HTTP/1.1\r\nHost: zewo.co\r\n\r\n"
try check(request: request, count: count, bufferSize: bufferSize) { request in
XCTAssert(request.method == method)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers["Host"] == "zewo.co")
}
}
}
}
}
func testCookiesRequest() throws {
for bufferSize in bufferSizes {
for count in requestCount {
for method in methods {
let request = "\(method) / HTTP/1.1\r\nHost: zewo.co\r\nCookie: server=zewo, lang=swift\r\n\r\n"
try check(request: request, count: count, bufferSize: bufferSize) { request in
XCTAssert(request.method == method)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers["Host"] == "zewo.co")
XCTAssert(request.headers["Cookie"] == "server=zewo, lang=swift")
}
}
}
}
}
func testBodyRequest() throws {
for bufferSize in bufferSizes {
for count in requestCount {
for method in methods {
let request = "\(method) / HTTP/1.1\r\nContent-Length: 4\r\n\r\nZewo"
try check(request: request, count: count, bufferSize: bufferSize) { request in
XCTAssert(request.method == method)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers["Content-Length"] == "4")
XCTAssert(request.body == .buffer(Data("Zewo")))
}
}
}
}
}
func testManyRequests() {
var request = ""
for _ in 0 ..< 100 {
request += "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nZewo"
}
measure {
do {
try self.check(request: request, count: 1, bufferSize: 4096) { request in
XCTAssert(request.method == .post)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers["Content-Length"] == "4")
XCTAssert(request.body == .buffer(Data("Zewo")))
}
} catch {
XCTFail()
}
}
}
func testErrorDescription() {
XCTAssertEqual(String(describing: HPE_OK), "success")
}
func testUnknownMethod() {
XCTAssertEqual(Quark.Method(code: 1969), .other(method: "UNKNOWN"))
}
func testDuplicateHeaders() throws {
for bufferSize in bufferSizes {
for count in requestCount {
for method in methods {
let request = "\(method) / HTTP/1.1\r\nX-Custom-Header: foo\r\nX-Custom-Header: bar\r\n\r\n"
try check(request: request, count: count, bufferSize: bufferSize) { request in
XCTAssert(request.method == method)
XCTAssert(request.uri.path == "/")
XCTAssert(request.version.major == 1)
XCTAssert(request.version.minor == 1)
XCTAssert(request.headers["X-Custom-Header"] == "foo, bar")
}
}
}
}
}
}
extension RequestParserTests {
static var allTests: [(String, (RequestParserTests) -> () throws -> Void)] {
return [
("testInvalidMethod", testInvalidMethod),
("testInvalidURI", testInvalidURI),
("testNoURI", testNoURI),
("testInvalidHTTPVersion", testInvalidHTTPVersion),
("testInvalidDoubleConnectMethod", testInvalidDoubleConnectMethod),
("testConnectMethod", testConnectMethod),
("testShortRequests", testShortRequests),
("testMediumRequests", testMediumRequests),
("testCookiesRequest", testCookiesRequest),
("testBodyRequest", testBodyRequest),
("testManyRequests", testManyRequests),
("testErrorDescription", testErrorDescription),
("testUnknownMethod", testUnknownMethod),
("testDuplicateHeaders", testDuplicateHeaders),
]
}
}
|
mit
|
786c1b6242b895fc42cbd7140b91c7a4
| 33.480469 | 116 | 0.525773 | 4.473898 | false | true | false | false |
huangboju/GesturePassword
|
Example/GesturePassword/Lock.swift
|
1
|
2271
|
//
// Copyright © 2016年 cmcaifu.com. All rights reserved.
//
import GesturePassword
let AppLock = Lock.shared
class Lock {
static let shared = Lock()
private init() {
// 在这里自定义你的UI
LockCenter.passwordKeySuffix = "user1"
// LockCenter.usingKeychain = true
// LockCenter.lineWidth = 2
// LockCenter.lineWarnColor = .blue
}
func set(controller: UIViewController) {
if hasPassword {
print("密码已设置")
print("🍀🍀🍀 \(password) 🍀🍀🍀")
} else {
showSetPattern(in: controller).successHandle = {
LockCenter.set($0)
}
}
}
func verify(controller: UIViewController) {
guard hasPassword else {
print("❌❌❌ 还没有设置密码 ❌❌❌")
return
}
print("密码已设置")
print("🍀🍀🍀 \(password) 🍀🍀🍀")
showVerifyPattern(in: controller).successHandle {
$0.dismiss()
}.overTimesHandle {
LockCenter.removePassword()
$0.dismiss()
assertionFailure("你必须做错误超限后的处理")
}.forgetHandle {
$0.dismiss()
assertionFailure("忘记密码,请做相应处理")
}
}
func modify(controller: UIViewController) {
guard hasPassword else {
print("❌❌❌ 还没有设置密码 ❌❌❌")
return
}
print("密码已设置")
print("🍀🍀🍀 \(password) 🍀🍀🍀")
showModifyPattern(in: controller).forgetHandle { _ in
}.overTimesHandle { _ in
}.resetSuccessHandle {
print("🍀🍀🍀 \($0) 🍀🍀🍀")
}
}
var hasPassword: Bool {
// 这里密码后缀可以自己传值,默认为上面设置的passwordKeySuffix
return LockCenter.hasPassword()
}
var password: String {
return LockCenter.password() ?? ""
}
func removePassword() {
// 这里密码后缀可以自己传值,默认为上面设置的passwordKeySuffix
LockCenter.removePassword()
}
}
|
mit
|
d1370ef3238e47cd44fc8f031ab9a3f8
| 22.710843 | 61 | 0.515244 | 3.975758 | false | false | false | false |
900116/GodEyeClear
|
Classes/Model/RecordBaseModel.swift
|
1
|
5331
|
//
// RecordBaseModel.swift
// TK_IGS_iPad_Swift
//
// Created by 51Talk_zhaoguanghui on 2017/5/24.
// Copyright © 2017年 AC. All rights reserved.
//
import UIKit
import RealmSwift
private var kShowAll = "\(#file)+\(#line)"
private var kAddCount = "\(#file)+\(#line)"
protocol RecordORMProtocol : class {
//static func configure(tableBuilder:AnyObject)
static var type:RecordType { get }
func attributeString() -> NSAttributedString
}
extension RecordORMProtocol {
static func delete(complete:@escaping (_ success:Bool)->()) {
}
internal static var addCount: Int {
get {
return objc_getAssociatedObject(self, &kAddCount) as? Int ?? 0
}
set {
objc_setAssociatedObject(self, &kAddCount, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
internal var showAll: Bool {
get {
return objc_getAssociatedObject(self, &kShowAll) as? Bool ?? true
}
set {
objc_setAssociatedObject(self, &kShowAll, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
static var realClass:AnyClass! {
switch self.type {
case .anr:
return ANRRecordModel.self
case .command:
return CommandRecordModel.self
case .crash:
return CrashRecordModel.self
case .leak:
return LeakRecordModel.self
case .log:
return LogRecordModel.self
case .network:
return NetworkRecordModel.self
}
}
static func getRealm() -> Realm?
{
let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask, true)
let dirPath = documentPaths[0] + "/RealmDB"
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: dirPath){
try! fileManager.createDirectory(atPath: dirPath, withIntermediateDirectories: false, attributes: nil)
}
let dbPath = dirPath + "/Realm.sqlite"
return try? Realm(fileURL: URL(fileURLWithPath: dbPath))
}
static func select(at index:Int,_ success:@escaping ([Any]?)->()) {
DispatchQueue.main.async {
let realm:Realm? = self.getRealm()
if realm != nil {
let arr = Array<Object>(realm!.objects(self.realClass as! Object.Type))
DispatchQueue.main.async {
success(arr)
}
}
else {
DispatchQueue.main.async {
success([])
}
}
}
}
static func create() {
}
// fileprivate static var queue: DispatchQueue {
// get {
// var key = "\(#file)+\(#line)"
// guard let result = objc_getAssociatedObject(self, &key) as? DispatchQueue else {
// let result = DispatchQueue(label: "RecordDB")
// objc_setAssociatedObject(self, &key, result, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return result
// }
// return result
// }
// }
//
func insertSync() -> Bool {
let realm:Realm? = Self.getRealm()
if realm != nil{
try! realm?.write {
realm?.add(self as! Object)
}
return true
}
else {
return false
}
}
func insert(complete:@escaping (_ success:Bool)->()) {
DispatchQueue.main.async {
let realm:Realm? = Self.getRealm()
if realm != nil {
try! realm?.write {
realm?.add(self as! Object)
}
DispatchQueue.main.async {
complete(true)
}
}
}
}
func attributes() -> Dictionary<String, Any>{
return
[NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName:UIFont.courier(with: 12)]
}
func contentString(with prefex:String?,content:String?,newline:Bool = false,color:UIColor = UIColor(hex: 0x3D82C7)) -> NSAttributedString {
let pre = prefex != nil ? "[\(prefex!)]:" : ""
let line = newline == true ? "\n" : (pre == "" ? "" : " ")
let str = "\(pre)\(line)\(content ?? "nil")\n"
let result = NSMutableAttributedString(string: str, attributes: self.attributes())
let range = str.NS.range(of: pre)
if range.location != NSNotFound {
result.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
return result
}
func headerString(with prefex:String,content:String? = nil,color:UIColor) -> NSAttributedString {
let header = "> \(prefex): \(content ?? "")\n"
let result = NSMutableAttributedString(string: header, attributes: self.attributes())
let range = header.NS.range(of: prefex)
if range.location + range.length <= header.NS.length {
result.addAttributes([NSForegroundColorAttributeName: color], range: range)
}
return result
}
}
|
mit
|
1aff079c9b33d58966eac9942542a021
| 30.714286 | 143 | 0.549362 | 4.757143 | false | false | false | false |
xivol/Swift-CS333
|
playgrounds/uiKit/uiKitCatalog/UIKitCatalog/PageControlViewController.swift
|
3
|
1758
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to use UIPageControl.
*/
import UIKit
class PageControlViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var colorView: UIView!
/// Colors that correspond to the selected page. Used as the background color for `colorView`.
let colors = [
UIColor.black,
UIColor.gray,
UIColor.red,
UIColor.green,
UIColor.blue,
UIColor.cyan,
UIColor.yellow,
UIColor.magenta,
UIColor.orange,
UIColor.purple
]
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()
pageControlValueDidChange()
}
// MARK: - Configuration
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
pageControl.numberOfPages = colors.count
pageControl.currentPage = 2
pageControl.tintColor = UIColor.applicationBlueColor
pageControl.pageIndicatorTintColor = UIColor.applicationGreenColor
pageControl.currentPageIndicatorTintColor = UIColor.applicationPurpleColor
pageControl.addTarget(self, action: #selector(PageControlViewController.pageControlValueDidChange), for: .valueChanged)
}
// MARK: - Actions
func pageControlValueDidChange() {
NSLog("The page control changed its current page to \(pageControl.currentPage).")
colorView.backgroundColor = colors[pageControl.currentPage]
}
}
|
mit
|
3d864aa51d0e34451106d8a1fbb21a3a
| 27.322581 | 127 | 0.682232 | 5.419753 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/BLEMakingScience/SensorConfigPinSelectorView.swift
|
1
|
1669
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
/// An option selector view for selecting a Making Science BLE pin.
class SensorConfigPinSelectorView: OptionSelectorView {
override var headerLabelText: String {
return String.deviceOptionsCustomSensorPinLabelText
}
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
/// The selected pin type.
var pinType = PinType.default
override func dropDownButtonPressed() {
let pins = PinType.knownPins
let actions = pins.map { (pin) in
return PopUpMenuAction(title: pin.string) { (_) in
self.pinType = pin
self.selectionLabel.text = pin.string
}
}
optionSelectorDelegate?.optionSelectorView(self,
didPressShowOptions: actions,
coveringView: selectionLabel)
}
private func configureView() {
selectionLabel.text = pinType.string
}
}
|
apache-2.0
|
af18c3a823596baeb2f2cfb1d13ed3a7
| 28.280702 | 76 | 0.673457 | 4.43883 | false | true | false | false |
davidjhodge/main-repository
|
LocalNotificationTutorial/LocalNotificationTutorial/AppDelegate.swift
|
1
|
4763
|
//
// AppDelegate.swift
// LocalNotificationTutorial
//
// Created by David Hodge on 2/24/15.
// Copyright (c) 2015 Genesis Apps, LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Local Notification Actions
var firstAction: UIMutableUserNotificationAction = createAction(
identifier: "FIRST_ACTION",
title: "First Action",
backgroundActivation: true,
destructive: true,
authenticationRequired: false)
var secondAction: UIMutableUserNotificationAction = createAction(
identifier: "SECOND_ACTION",
title: "Second Action",
backgroundActivation: false,
destructive: false,
authenticationRequired: false)
var thirdAction: UIMutableUserNotificationAction = createAction(
identifier: "THIRD_ACTION",
title: "Third Action",
backgroundActivation: true,
destructive: false,
authenticationRequired: false)
//Category
var firstCategory: UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
firstCategory.identifier = "FIRST_CATEGORY"
let defaultActions: NSArray = [firstAction, secondAction, thirdAction]
let minimalActions: NSArray = [firstAction, secondAction]
firstCategory.setActions(defaultActions as! [AnyObject], forContext: UIUserNotificationActionContext.Default)
firstCategory.setActions(minimalActions as! [AnyObject], forContext: UIUserNotificationActionContext.Minimal)
//NSSet of all our categories
let categories: Set<NSObject> = Set(arrayLiteral: [firstCategory])
//Register for Local Notifications
let types: UIUserNotificationType = .Alert | .Badge
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: categories)
application.registerUserNotificationSettings(settings)
return true
}
func createAction(identifier actionIdentifier: String, title actionTitle: String, backgroundActivation background: Bool, destructive destructiveValue: Bool, authenticationRequired auth: Bool) -> UIMutableUserNotificationAction
{
var action: UIMutableUserNotificationAction = UIMutableUserNotificationAction()
action.identifier = actionIdentifier
action.title = actionTitle
if background == false
{
action.activationMode = UIUserNotificationActivationMode.Foreground
} else if background == true
{
action.activationMode = UIUserNotificationActivationMode.Background
}
action.destructive = destructiveValue
action.authenticationRequired = auth
return action
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
apache-2.0
|
e31f42c41890e55c6e56b3525af7af66
| 43.514019 | 285 | 0.707117 | 5.976161 | false | false | false | false |
inamiy/VTree
|
Tests/Fixtures/VPhantom.swift
|
1
|
769
|
import VTree
import Flexbox
/// Phantom type for `VTree` without `Message` type (for testing).
public final class VPhantom<👻>: VTree
{
public let key: Key?
public let props: [String: Any] = [:] // NOTE: `Segmentation fault: 11` if removing this line
public let flexbox: Flexbox.Node? = nil
public let children: [AnyVTree<NoMsg>]
public init(
key: Key? = nil,
children: [AnyVTree<NoMsg>] = []
)
{
self.key = key
self.children = children
}
public func createView<Msg2: Message>(_ msgMapper: @escaping (NoMsg) -> Msg2) -> View
{
let view = View()
for child in self.children {
view.addSubview(child.createView(msgMapper))
}
return view
}
}
|
mit
|
7ab36bab7d31c3cf62cde398db27fe02
| 23.709677 | 98 | 0.588773 | 3.736585 | false | false | false | false |
ArtKirillov/PDFReader
|
PDFReader/PDFThumbnailCollectionViewController.swift
|
1
|
2990
|
//
// PDFThumbnailCollectionViewController.swift
// PDFReader
//
// Created by Artem Kirillov on 24.02.17.
// Copyright © 2017 Artem Kirillov. All rights reserved.
//
import UIKit
/// Delegate that handles thumbnail collection view selections
protocol PDFThumbnailControllerDelegate: class {
func didSelectIndexPath(_ indexPath: IndexPath)
}
internal final class PDFThumbnailCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var document: PDFDocument!
var currentPageIndex: Int = 0 {
didSet {
guard let collectionView = collectionView else { return }
let curentPageIndexPath = IndexPath(row: currentPageIndex, section: 0)
collectionView.scrollToItem(at: curentPageIndexPath, at: .centeredHorizontally, animated: true)
collectionView.reloadData()
}
}
weak var delegate: PDFThumbnailControllerDelegate?
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let count = document.pageCount
if UIDevice.current.orientation.isLandscape {
return count / 2 + 1
} else {
return count
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PDFThumbnailCell
let isCurrentPage = indexPath.row != currentPageIndex
if indexPath.row == 0 {
cell.setup(indexPath.row, document: document, isCurrentPage: isCurrentPage)
return cell
}
if UIDevice.current.orientation.isLandscape {
cell.setup(indexPath.row * 2 - 1, document: document, isCurrentPage: isCurrentPage)
return cell
} else {
cell.setup(indexPath.row, document: document, isCurrentPage: isCurrentPage)
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if UIDevice.current.orientation.isLandscape && indexPath.row != 0 && indexPath.row != document.pageCount / 2 {
return PDFThumbnailCell.landscapeCellSize
} else {
return PDFThumbnailCell.portraitCellSize
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelectIndexPath(indexPath)
}
}
|
mit
|
c927b8a94b357fce8d12d109a98b66a8
| 37.818182 | 175 | 0.690867 | 5.803883 | false | false | false | false |
beeth0ven/BNKit
|
BNKit/Source/UIKit+/TipView/TipView.swift
|
1
|
3219
|
//
// TipView.swift
// WorkMap
//
// Created by luojie on 16/10/22.
// Copyright © 2016年 LuoJie. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
open class TipView: UIView, IsInBundle {
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var textLabel: UILabel!
let state = Variable(State.spinnerOnly)
let delayDismiss = Variable<Double?>(nil)
override open func awakeFromNib() {
super.awakeFromNib()
state.asDriver()
.drive(stateOberver)
.disposed(by: disposeBag)
delayDismiss.asObservable()
.flatMapLatest { delay -> Observable<Void> in
switch delay {
case nil:
return .empty()
case let delay?:
return Observable<Int64>.interval(delay, scheduler: MainScheduler.instance)
.take(1)
.map { _ in }
}
}
.bind(to: rx_remove)
.disposed(by: disposeBag)
}
private var stateOberver: AnyObserver<State> {
return UIBindingObserver(UIElement: self){ (tipView, state) in
switch state {
case .spinnerOnly:
tipView.spinner.isShowed = true
tipView.textLabel.isShowed = false
case .spinnerWithText(let text):
tipView.spinner.isShowed = true
tipView.textLabel.isShowed = true
tipView.textLabel.text = text
case .textOnly(let text):
tipView.spinner.isShowed = false
tipView.textLabel.isShowed = true
tipView.textLabel.text = text
}
}.asObserver()
}
private var rx_remove: AnyObserver<Void> {
return UIBindingObserver(UIElement: self, binding: { (view, _) in
view.superview?.isUserInteractionEnabled = true
view.superview?.animateUpdate { view.removeFromSuperview() }
}).asObserver()
}
public enum State {
case spinnerOnly
case spinnerWithText(String)
case textOnly(String)
}
}
extension TipView {
public static func show(state: State, delayDismiss: TimeInterval? = nil, in view: UIView = UIApplication.shared.keyWindow!) {
shared.state.value = state
shared.delayDismiss.value = delayDismiss
shared.translatesAutoresizingMaskIntoConstraints = false
view.animateUpdate {
view.isUserInteractionEnabled = false
view.addSubview(shared)
view.addConstraints([
shared.centerXAnchor.constraint(equalTo: view.centerXAnchor),
shared.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
public static func update(state: State, delayDismiss: TimeInterval? = 2) {
shared.state.value = state
shared.delayDismiss.value = delayDismiss
}
public static func remove() {
shared.superview?.animateUpdate { shared.removeFromSuperview() }
}
@nonobjc static let shared = TipView.fromNib()
}
|
mit
|
be2c28669d17faf4c4dc40bbca38d508
| 30.529412 | 129 | 0.579913 | 5.048666 | false | false | false | false |
euronautic/cosmos
|
code/sorting/pigeonhole_sort/pigeonhole_sort.swift
|
1
|
707
|
/* Part of Cosmos by OpenGenus Foundation */
//
// pigeonhole_sort.swift
// Created by DaiPei on 2017/10/18.
//
import Foundation
func pigeonhole_sort(_ array: inout [Int]) {
var max = Int.min
var min = Int.max
for item in array {
if item > max {
max = item
}
if item < min {
min = item
}
}
let range = max - min + 1
var hole = [Int](repeatElement(0, count: range))
for item in array {
hole[item - min] += 1
}
var index = 0
for i in 0..<range {
var count = hole[i]
while count > 0 {
array[index] = i + min
index += 1
count -= 1
}
}
}
|
gpl-3.0
|
355348a907c742adc5aedf4f47d7fa22
| 19.2 | 52 | 0.480905 | 3.570707 | false | false | false | false |
stripe/stripe-ios
|
StripeIdentity/StripeIdentity/Source/NativeComponents/Views/IdentityHTMLView/HTMLTextView.swift
|
1
|
4607
|
//
// HTMLTextView.swift
// StripeIdentity
//
// Created by Mel Ludowise on 2/25/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeUICore
import UIKit
final class HTMLTextView: UIView {
struct ViewModel {
enum Style {
/// Text should render as HTML
/// - `makeStyle`: Computes the style to apply for the current size category
case html(makeStyle: () -> HTMLStyle)
/// Text should render as plain text
/// - `font`: The font to apply to the text
/// - `textColor`: The color to apply to the text
case plainText(font: UIFont, textColor: UIColor)
}
let text: String
let style: Style
let didOpenURL: (URL) -> Void
}
private lazy var textView: UITextView = {
let textView: UITextView
// iOS 13 requires that the TextView be editable for links to open but
// iOS 14 does not.
if #available(iOS 14, *) {
textView = UITextView()
textView.isEditable = false
} else {
// Remove the spelling rotor so the voice over doesn't say,
// "use the rotor to access misspelled words"
textView = TextViewWithoutSpellingRotor()
// Tell the voice over engine that this is static text so it doesn't
// say, "double tap to edit"
textView.accessibilityTraits = .staticText
}
textView.isScrollEnabled = false
textView.backgroundColor = nil
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.adjustsFontForContentSizeCategory = true
textView.delegate = self
return textView
}()
private var viewModel: ViewModel?
init() {
super.init(frame: .zero)
self.addAndPinSubview(textView)
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
func configure(with viewModel: ViewModel) throws {
switch viewModel.style {
case .html(let makeStyle):
textView.attributedText = try NSAttributedString(
htmlText: viewModel.text,
style: makeStyle()
)
case .plainText(let font, let textColor):
textView.text = viewModel.text
textView.font = font
textView.textColor = textColor
}
// Cache the viewModel only if an error was not thrown creating an
// attributed string
self.viewModel = viewModel
}
// MARK: UIView
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard let viewModel = viewModel,
case .html(let makeStyle) = viewModel.style
else {
return
}
// NOTE: `traitCollectionDidChange` is called off the main thread when the app backgrounds
DispatchQueue.main.async { [weak self] in
do {
// Recompute attributed text with updated font sizes
self?.textView.attributedText = try NSAttributedString(
htmlText: viewModel.text,
style: makeStyle()
)
} catch {
// Ignore errors thrown. This means the font size won't update,
// but the text should still display if an error wasn't already
// thrown from `configure`.
}
}
}
}
extension HTMLTextView: UITextViewDelegate {
func textView(
_ textView: UITextView,
shouldInteractWith url: URL,
in characterRange: NSRange
) -> Bool {
viewModel?.didOpenURL(url)
return false
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
// textView.isEditable must be true for links to be able to be opened on
// iOS 13, so always return false to disable edit-ability
return false
}
}
/// A UITextView without the misspelled words rotor
private class TextViewWithoutSpellingRotor: UITextView {
override var accessibilityCustomRotors: [UIAccessibilityCustomRotor]? {
get {
// Removes the misspelled word rotor from the accessibility rotors
return super.accessibilityCustomRotors?.filter { $0.systemRotorType != .misspelledWord }
}
set {
super.accessibilityCustomRotors = newValue
}
}
}
|
mit
|
2151722f127db706a6c18efd74b3fff3
| 31.20979 | 100 | 0.602475 | 5.192785 | false | false | false | false |
stripe/stripe-ios
|
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/OcrDDUtils.swift
|
1
|
6251
|
//
// OcrDDUtils.swift
// CardScan
//
// Created by xaen on 6/17/20.
//
import UIKit
struct OcrDDUtils {
static let offsetQuickRead: Float = 2.0
static let falsePositiveTolerance: Float = 1.2
static let minimumCardDigits = 12
static let numOfQuickReadDigits = 16
static let numOfQuickReadDigitsPerGroup = 4
static func isQuickRead(allBoxes: DetectedAllOcrBoxes) -> Bool {
if (allBoxes.allBoxes.isEmpty) || (allBoxes.allBoxes.count != numOfQuickReadDigits) {
return false
}
var boxCenters = [Float]()
var boxHeights = [Float]()
var aggregateDeviation: Float = 0
for idx in 0..<allBoxes.allBoxes.count {
boxCenters.append(Float((allBoxes.allBoxes[idx].rect.midY)))
boxHeights.append(abs(Float(allBoxes.allBoxes[idx].rect.height)))
}
let medianYCenter = boxCenters.sorted(by: <)[boxCenters.count / 2]
let medianHeight = boxHeights.sorted(by: <)[boxHeights.count / 2]
for idx in 0..<boxCenters.count {
aggregateDeviation += abs(medianYCenter - boxCenters[idx])
}
if aggregateDeviation > offsetQuickRead * medianHeight {
let quickReadGroups = allBoxes.allBoxes
.sorted(by: { return $0.rect.centerY() < $1.rect.centerY() })
.chunked(into: 4)
.map { $0.sorted(by: { return $0.rect.centerX() < $1.rect.centerX() }) }
guard let quickReadGroupFirstRowFirstDigit = quickReadGroups[0].first,
let quickReadGroupSecondRowFirstDigit = quickReadGroups[1].first,
let quickReadGroupFirstRowLastDigit = quickReadGroups[0].last,
let quickReadGroupSecondRowLastDigit = quickReadGroups[1].last
else {
return false
}
if quickReadGroupSecondRowFirstDigit.rect.centerX()
< quickReadGroupFirstRowLastDigit.rect.centerX()
&& quickReadGroupSecondRowLastDigit.rect.centerX()
> quickReadGroupFirstRowFirstDigit.rect.centerX()
{
return true
}
}
return false
}
static func processQuickRead(allBoxes: DetectedAllOcrBoxes) -> (String, [CGRect])? {
if allBoxes.allBoxes.count != numOfQuickReadDigits {
return nil
}
var _cardNumber: String = ""
var boxes: [CGRect] = []
let sortedBoxes = allBoxes.allBoxes.sorted(by: { (left, right) -> Bool in
let leftAverageY = (left.rect.minY / 2 + left.rect.maxY / 2)
let rightAverageY = (right.rect.minY / 2 + right.rect.maxY / 2)
return leftAverageY < rightAverageY
})
var start = 0
var end = numOfQuickReadDigitsPerGroup - 1 // since indices start with 0
for _ in 0..<sortedBoxes.count / numOfQuickReadDigitsPerGroup {
if let (partialNumber, partialBoxes) = OcrDDUtils.sortBoxesInRange(
boxes: sortedBoxes,
start: start,
end: end
) {
_cardNumber = _cardNumber + partialNumber
boxes += partialBoxes
start = start + numOfQuickReadDigitsPerGroup
end = end + numOfQuickReadDigitsPerGroup
} else {
return nil
}
}
if CreditCardUtils.isValidNumber(cardNumber: _cardNumber) {
return (_cardNumber, boxes)
}
return nil
}
static func sortBoxesInRange(
boxes: [DetectedSSDOcrBox],
start: Int,
end: Int
) -> (String, [CGRect])? {
if boxes.indices.contains(start) && boxes.indices.contains(end) {
var _groupNumber: String = ""
let groupSlice = boxes[start...end]
let group = Array(groupSlice)
let sortedGroup = group.sorted(by: { $0.rect.minX < $1.rect.minX })
var sortedBoxes: [CGRect] = []
for idx in 0..<sortedGroup.count {
_groupNumber = _groupNumber + String(sortedGroup[idx].label)
sortedBoxes.append(sortedGroup[idx].rect)
}
return (_groupNumber, sortedBoxes)
} else {
return nil
}
}
static func sortAndRemoveFalsePositives(allBoxes: DetectedAllOcrBoxes) -> (String, [CGRect])? {
if (allBoxes.allBoxes.isEmpty) || (allBoxes.allBoxes.count < minimumCardDigits) {
return nil
}
var leftCordinates = [Float]()
var topCordinates = [Float]()
var bottomCordinates = [Float]()
var sortedBoxes = [CGRect]()
for idx in 0..<allBoxes.allBoxes.count {
leftCordinates.append(Float(allBoxes.allBoxes[idx].rect.minX))
topCordinates.append(Float(allBoxes.allBoxes[idx].rect.minY))
bottomCordinates.append(Float(allBoxes.allBoxes[idx].rect.maxY))
}
let medianYmin = topCordinates.sorted(by: <)[topCordinates.count / 2]
let medianYmax = bottomCordinates.sorted(by: <)[bottomCordinates.count / 2]
let medianHeight = abs(medianYmax - medianYmin)
let medianCenter = (medianYmin + medianYmax) / 2
let sortedLeftCordinates = leftCordinates.enumerated().sorted(by: {
$0.element < $1.element
})
let indices = sortedLeftCordinates.map { $0.offset }
var _cardNumber: String = ""
indices.forEach { index in
if allBoxes.allBoxes.indices.contains(index) {
let box = allBoxes.allBoxes[index]
let boxCenter = abs(Float(box.rect.maxY) + Float(box.rect.minY)) / 2
let boxHeight = abs(Float(box.rect.maxY) - Float(box.rect.minY))
if abs(boxCenter - medianCenter) < medianHeight
&& boxHeight < falsePositiveTolerance * medianHeight
{
_cardNumber = _cardNumber + String(box.label)
sortedBoxes.append(box.rect)
}
}
}
if CreditCardUtils.isValidNumber(cardNumber: _cardNumber) {
return (_cardNumber, sortedBoxes)
}
return nil
}
}
|
mit
|
7d5e8c2b16f9cf1e596a85b1471aae1f
| 34.316384 | 99 | 0.580227 | 4.164557 | false | false | false | false |
romansorochak/ParallaxHeader
|
Pods/Device/Source/iOS/Device.swift
|
1
|
7833
|
//
// Device.swift
// Device
//
// Created by Lucas Ortis on 30/10/2015.
// Copyright © 2015 Ekhoo. All rights reserved.
//
import UIKit
open class Device {
static fileprivate func getVersionCode() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let versionCode: String = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!)!
return versionCode
}
static fileprivate func getVersion(code: String) -> Version {
switch code {
/*** iPhone ***/
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return .iPhone4
case "iPhone4,1", "iPhone4,2", "iPhone4,3": return .iPhone4S
case "iPhone5,1", "iPhone5,2": return .iPhone5
case "iPhone5,3", "iPhone5,4": return .iPhone5C
case "iPhone6,1", "iPhone6,2": return .iPhone5S
case "iPhone7,2": return .iPhone6
case "iPhone7,1": return .iPhone6Plus
case "iPhone8,1": return .iPhone6S
case "iPhone8,2": return .iPhone6SPlus
case "iPhone8,3", "iPhone8,4": return .iPhoneSE
case "iPhone9,1", "iPhone9,3": return .iPhone7
case "iPhone9,2", "iPhone9,4": return .iPhone7Plus
case "iPhone10,1", "iPhone10,4": return .iPhone8
case "iPhone10,2", "iPhone10,5": return .iPhone8Plus
case "iPhone10,3", "iPhone10,6": return .iPhoneX
case "iPhone11,2": return .iPhoneXS
case "iPhone11,4", "iPhone11,6": return .iPhoneXS_Max
case "iPhone11,8": return .iPhoneXR
case "iPhone12,1": return .iPhone11
case "iPhone12,3": return .iPhone11Pro
case "iPhone12,5": return .iPhone11Pro_Max
/*** iPad ***/
case "iPad1,1", "iPad1,2": return .iPad1
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2
case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3
case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4
case "iPad6,11", "iPad6,12": return .iPad5
case "iPad7,5", "iPad7,6": return .iPad6
case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir
case "iPad5,3", "iPad5,4": return .iPadAir2
case "iPad11,3", "iPad11,4": return .iPadAir3
case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini
case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2
case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3
case "iPad5,1", "iPad5,2": return .iPadMini4
/*** iPadPro ***/
case "iPad6,3", "iPad6,4": return .iPadPro9_7Inch
case "iPad6,7", "iPad6,8": return .iPadPro12_9Inch
case "iPad7,1", "iPad7,2": return .iPadPro12_9Inch2
case "iPad7,3", "iPad7,4": return .iPadPro10_5Inch
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return .iPadPro11_0Inch
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return .iPadPro12_9Inch3
/*** iPod ***/
case "iPod1,1": return .iPodTouch1Gen
case "iPod2,1": return .iPodTouch2Gen
case "iPod3,1": return .iPodTouch3Gen
case "iPod4,1": return .iPodTouch4Gen
case "iPod5,1": return .iPodTouch5Gen
case "iPod7,1": return .iPodTouch6Gen
/*** Simulator ***/
case "i386", "x86_64": return .simulator
default: return .unknown
}
}
static fileprivate func getType(code: String) -> Type {
let versionCode = getVersionCode()
if versionCode.contains("iPhone") {
return .iPhone
} else if versionCode.contains("iPad") {
return .iPad
} else if versionCode.contains("iPod") {
return .iPod
} else if versionCode == "i386" || versionCode == "x86_64" {
return .simulator
} else {
return .unknown
}
}
static public func version() -> Version {
return getVersion(code: getVersionCode())
}
static public func size() -> Size {
let w: Double = Double(UIScreen.main.bounds.width)
let h: Double = Double(UIScreen.main.bounds.height)
let screenHeight: Double = max(w, h)
switch screenHeight {
case 480:
return .screen3_5Inch
case 568:
return .screen4Inch
case 667:
return UIScreen.main.scale == 3.0 ? .screen5_5Inch : .screen4_7Inch
case 736:
return .screen5_5Inch
case 812:
return .screen5_8Inch
case 896:
switch version() {
case .iPhoneXS_Max:
return .screen6_5Inch
default:
return .screen6_1Inch
}
case 1024:
switch version() {
case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4:
return .screen7_9Inch
case .iPadPro10_5Inch:
return .screen10_5Inch
default:
return .screen9_7Inch
}
case 1112:
switch version() {
case .iPad7:
return .screen10_2Inch
default:
return .screen10_5Inch
}
case 1194:
return .screen11Inch
case 1366:
return .screen12_9Inch
default:
return .unknownSize
}
}
static public func type() -> Type {
return getType(code: getVersionCode())
}
@available(*, deprecated, message: "use == operator instead")
static public func isEqualToScreenSize(_ size: Size) -> Bool {
return size == self.size() ? true : false;
}
@available(*, deprecated, message: "use > operator instead")
static public func isLargerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue < self.size().rawValue ? true : false;
}
@available(*, deprecated, message: "use < operator instead")
static public func isSmallerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue > self.size().rawValue ? true : false;
}
static public func isRetina() -> Bool {
return UIScreen.main.scale > 1.0
}
static public func isPad() -> Bool {
return type() == .iPad
}
static public func isPhone() -> Bool {
return type() == .iPhone
}
static public func isPod() -> Bool {
return type() == .iPod
}
static public func isSimulator() -> Bool {
return type() == .simulator
}
}
|
mit
|
b454266ce786cedf3acca7964c780d8c
| 39.791667 | 177 | 0.467952 | 4.380313 | false | false | false | false |
YoungGary/DYTV
|
DouyuTV/DouyuTV/Class/First(首页)/Controller/RecommendViewController.swift
|
1
|
6178
|
//
// RecommendViewController.swift
// DouyuTV
// 首页推荐控制器
// Created by YOUNG on 2017/3/13.
// Copyright © 2017年 Young. All rights reserved.
//
import UIKit
let itemMargin : CGFloat = 10
let itemWidth : CGFloat = (kScreenWidth - 3 * itemMargin)/2
let itemHeight : CGFloat = itemWidth * 0.75
let prettyHeight :CGFloat = itemWidth / 0.75
let cellID = "cellID"
let headerID = "headerID"
let prettyID = "prettyID"
//cycle
let kCycleViewY = kScreenWidth * 3/8
//selectViewH
let kSelectViewH : CGFloat = 90
class RecommendViewController: BaseViewController ,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: 50)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.register(UINib(nibName: "VideoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellID)
collectionView.register(UINib(nibName: "PrettyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: prettyID)
collectionView.register( UINib(nibName: "HeaderReusablleView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID)
collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
return collectionView
}()
var viewModel : RecommendViewModel = RecommendViewModel()
lazy var cycleView : CycleView = {
let cycleView = CycleView.loadViewWithNib()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewY+kSelectViewH), width: kScreenWidth, height: kCycleViewY)
return cycleView
}()
lazy var selectView : SelectView = {
let selectView = SelectView.loadViewWithNib()
selectView.frame = CGRect(x: 0, y: -kSelectViewH, width: kScreenWidth, height: kSelectViewH)
return selectView
}()
override func viewDidLoad() {
super.viewDidLoad()
//界面
setupInterface()
//fetch data
fetchDataFromNet()
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewY+kSelectViewH, 0, 0, 0)
}
}
extension RecommendViewController{
override func setupInterface() -> () {
contentView = collectionView
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.addSubview(selectView)
super.setupInterface()
}
func fetchDataFromNet(){
viewModel.fetchData {
self.collectionView.reloadData()
self.finishAnimation()
}
viewModel.fetchCycleData {
self.cycleView.modelArr = self.viewModel.cycleArr
}
}
}
//MARK:UICollectionViewDataSource and delegate
extension RecommendViewController{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.groupArr.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = viewModel.groupArr[section]
return group.authors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let group = viewModel.groupArr[indexPath.section]
if group.tag_name == "颜值" {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: prettyID, for: indexPath) as! PrettyCollectionViewCell
cell.prettyModel = group.authors[indexPath.row]
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! VideoCollectionViewCell
cell.normalModel = group.authors[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID, for: indexPath) as? HeaderReusablleView
headerView?.headerModel = viewModel.groupArr[indexPath.section]
return headerView!
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let group = viewModel.groupArr[indexPath.section]
if group.tag_name == "颜值" {
return CGSize(width: itemWidth, height: prettyHeight)
}else{
return CGSize(width: itemWidth, height: itemHeight)
}
}
}
extension RecommendViewController : UIScrollViewDelegate{
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if velocity.y > 0 {//hide
navigationController?.setNavigationBarHidden(true, animated: true)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "hideTtileVIEW"), object: nil)
}else{
navigationController?.setNavigationBarHidden(false, animated: true)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showTtileVIEW"), object: nil)
}
}
}
|
mit
|
1d250388f6facf47f1363fdd2678708e
| 29.59204 | 189 | 0.66401 | 5.625801 | false | false | false | false |
Donny8028/Swift-TinyFeatures
|
SnapChat Menu & Camera/SnapChat Menu & Camera/PickerViewController.swift
|
1
|
3731
|
//
// PickerViewController.swift
// SnapChat Menu & Camera
//
// Created by 賢瑭 何 on 2016/5/13.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
import AVFoundation
class PickerViewController: UIViewController {
var avCaptureDevice: AVCaptureDevice?
var session: AVCaptureSession?
var preViewlayer: AVCaptureVideoPreviewLayer?
var output: AVCaptureStillImageOutput?
var input: AVCaptureDeviceInput?
var cameraView = UIView()
var imageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(cameraView)
cameraView.frame = view.frame
// Do any additional setup after loading the view.
avCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
input = try AVCaptureDeviceInput(device: avCaptureDevice)
}
catch let e as NSError{
print("\(e.localizedDescription)")
input = nil
}
output = AVCaptureStillImageOutput()
output?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSessionPreset1920x1080
guard let _ = session?.canAddInput(input) else{
print("can't add input")
return
}
guard let _ = session?.canAddOutput(output) else {
print("can't add output")
return
}
session?.addInput(input)
session?.addOutput(output)
preViewlayer = AVCaptureVideoPreviewLayer(session: session)
preViewlayer?.videoGravity = AVLayerVideoGravityResize
preViewlayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(preViewlayer!)
session?.startRunning()
}
func fetchPhoto() {
imageView = UIImageView()
cameraView.addSubview(imageView!)
let connection = output?.connectionWithMediaType(AVMediaTypeVideo)
output?.captureStillImageAsynchronouslyFromConnection(connection){ (sampleBuffer, error) in
if sampleBuffer != nil && error == nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let image = UIImage(data: imageData)
self.imageView?.image = image
self.imageView?.frame = self.cameraView.frame
self.imageView!.hidden = false
}else{
print("\(error.localizedDescription)")
}
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
imageView?.hidden = true
didTakePhoto = false
}else{
didTakePhoto = true
fetchPhoto()
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
session?.stopRunning()
}
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
view.addGestureRecognizer(tap)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
preViewlayer?.frame = cameraView.bounds
}
func tap(gesture: UITapGestureRecognizer) {
if gesture.numberOfTapsRequired == 1 {
didPressTakeAnother()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
62d779931fa2febaaf69674b1f311a99
| 30.542373 | 106 | 0.623858 | 5.734977 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/NewVersion/Tabbar/ZSTabBarController.swift
|
1
|
3881
|
//
// ZSTabBarController.swift
// zhuishushenqi
//
// Created by caony on 2019/6/18.
// Copyright © 2019年 QS. All rights reserved.
//
import UIKit
class ZSTabBarController: UITabBarController,UITabBarControllerDelegate {
var lastSelectedIndex:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
setupSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
private func setupSubviews() {
let homeItem = UITabBarItem(title: "书架", image: UIImage(named: "tab_bookshelf")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_bookshelf_sel")?.withRenderingMode(.alwaysOriginal))
let channelItem = UITabBarItem(title: "书城", image: UIImage(named: "tab_bookstore")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_bookstore_sel")?.withRenderingMode(.alwaysOriginal))
let dynamicItem = UITabBarItem(title: "社区", image: UIImage(named: "tab_bbs")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_bbs_sel")?.withRenderingMode(.alwaysOriginal))
let vipItem = UITabBarItem(title: "发现", image: UIImage(named: "tab_discover")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_discover_sel")?.withRenderingMode(.alwaysOriginal))
let mineItem = UITabBarItem(title: "我的", image: UIImage(named: "tab_profile")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_profile_sel")?.withRenderingMode(.alwaysOriginal))
let homeVC = ZSBookShelfViewController()
let homeNav = UINavigationController(rootViewController: homeVC)
homeNav.tabBarItem = homeItem
let channelVC = ZSBookStoreViewController()
let channelNav = UINavigationController(rootViewController: channelVC)
channelNav.tabBarItem = channelItem
let dynamicVC = ZSCommunityViewController()
let dynamicNav = UINavigationController(rootViewController: dynamicVC)
dynamicNav.tabBarItem = dynamicItem
let vipVC = ZSDiscoverViewController()
let vipNav = UINavigationController(rootViewController: vipVC)
vipNav.tabBarItem = vipItem
let mineVC = ZSMineViewController()
let mineNav = UINavigationController(rootViewController: mineVC)
mineNav.tabBarItem = mineItem
viewControllers = [homeNav, channelNav, dynamicNav, vipNav, mineNav]
for (_, item) in tabBar.items!.enumerated() {
let normalAttributes = [NSAttributedString.Key.foregroundColor:UIColor(red: 0.48, green: 0.48, blue: 0.48, alpha: 1.0)]
let selectedAttributes = [NSAttributedString.Key.foregroundColor:UIColor.init(hexString: "#A70B0B")]
item.setTitleTextAttributes(normalAttributes, for: .normal)
item.setTitleTextAttributes(selectedAttributes as [NSAttributedString.Key : Any], for: .selected)
}
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
guard let baseNav = viewController as? UINavigationController else {
return
}
guard let _ = baseNav.topViewController as? BaseViewController else {
return
}
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
lastSelectedIndex = selectedIndex
if let index = tabBar.items?.firstIndex(of: item) {
guard let navController = viewControllers?[index] as? UINavigationController else {
return
}
guard let _ = navController.topViewController as? BaseViewController else {
return
}
}
}
}
|
mit
|
8eaac9acc82c045fcfcd5381569d5b97
| 43.860465 | 215 | 0.675998 | 5.178523 | false | false | false | false |
ello/ello-ios
|
Sources/Controllers/RoleAdmin/RoleAdminGenerator.swift
|
1
|
1955
|
////
/// RoleAdminGenerator.swift
//
import PromiseKit
class RoleAdminGenerator {
enum Error: Swift.Error {
case missingArgs
}
func loadRoles(user: User) -> Promise<[CategoryUser]> {
let (promise, seal) = Promise<[CategoryUser]>.pending()
API().userDetail(token: .id(user.id))
.execute()
.done { user in
seal.fulfill(user.categoryRoles ?? [])
}
.catch(seal.reject)
return promise
}
func delete(categoryUser: CategoryUser) -> Guarantee<Void> {
let (promise, fulfill) = Guarantee<Void>.pending()
let endpoint: ElloAPI = .deleteCategoryUser(categoryUser.id)
ElloProvider.shared.request(endpoint)
.ensure {
fulfill(Void())
}
.ignoreErrors()
return promise
}
func add(categoryId: String, userId: String, role: CategoryUser.Role) -> Promise<CategoryUser> {
let (promise, seal) = Promise<CategoryUser>.pending()
let endpoint: ElloAPI = .createCategoryUser(
categoryId: categoryId,
userId: userId,
role: role.rawValue
)
ElloProvider.shared.request(endpoint)
.done { jsonable, config in
seal.fulfill(jsonable as! CategoryUser)
}
.catch(seal.reject)
return promise
}
func edit(categoryId: String, userId: String, role: CategoryUser.Role) -> Promise<CategoryUser>
{
let (promise, seal) = Promise<CategoryUser>.pending()
let endpoint: ElloAPI = .editCategoryUser(
categoryId: categoryId,
userId: userId,
role: role.rawValue
)
ElloProvider.shared.request(endpoint)
.done { jsonable, config in
seal.fulfill(jsonable as! CategoryUser)
}
.catch(seal.reject)
return promise
}
}
|
mit
|
d82d96b58a4b95b5b9b6c420f891987f
| 26.535211 | 100 | 0.56624 | 4.6 | false | false | false | false |
amoriello/trust-line-ios
|
Trustline/BleManagementHelper.swift
|
1
|
3157
|
//
// BleManagement.swift
// Trustline
//
// Created by matt on 20/10/2015.
// Copyright © 2015 amoriello.hutti. All rights reserved.
//
import Foundation
class BleManagement {
typealias Handler = (token: Token?, error: NSError?) -> (Void)
// Discovers and pair to a new token
class func pairWithNewToken(bleManager :BleManager, handler: Handler) {
findIsolatedToken(bleManager, onFoundToken: connectAndPair, handler: handler);
}
class func findAndConnectToken(bleManager: BleManager, handler: Handler) {
findIsolatedToken(bleManager, onFoundToken: connect, handler: handler)
}
class func connectToPairedToken(bleManager :BleManager, pairedTokens : Set<CDPairedToken>, handler :Handler) {
findIsolatedToken(bleManager, pairedTokens: pairedTokens, onFoundToken: connect, handler: handler)
}
// MARK: - Implementation details for pairing with new token
private typealias FoundIsolatedTokenHandler = (token: Token, handler: Handler) -> (Void)
private class func findIsolatedToken(bleManager :BleManager, pairedTokens :Set<CDPairedToken>? = nil, onFoundToken: FoundIsolatedTokenHandler, handler: Handler) {
showMessage("Searching Token", hideOnTap: false, showAnnimation: true)
bleManager.discoverTokens(pairedTokens) { (tokens, error) in
if error != nil {
async { handler(token: nil, error: error) }
return
}
if (tokens.count == 0) {
async { handler(token: nil, error: createError("No token found", description: "Try to be closer to your token", code: 1)) }
return
}
if (tokens.count > 1) {
async { handler(token: nil, error: createError("Too many tokens found", description: "\(tokens.count) found, isolate the one you don't want", code: 1)) }
return
}
showMessage("Token found", hideOnTap: false, showAnnimation: true)
let token = tokens[0];
onFoundToken(token: token, handler: handler)
}
}
// Connect to a token
private class func connect(token: Token, handler: Handler) {
showMessage("Connecting...", hideOnTap: false, showAnnimation: true)
token.connect { (error) -> (Void) in
if error != nil {
async { handler(token: nil, error: error) }
return
}
showMessage("Connected!", hideOnTap: false, showAnnimation: true)
async { handler(token: token, error: error) }
}
}
// Connect and pair to a token
private class func connectAndPair(token: Token, handler: Handler) {
showMessage("Connecting...", hideOnTap: false, showAnnimation: true)
token.connect { (error) -> (Void) in
if error != nil {
async { handler(token: nil, error: error) }
return
}
showMessage("Connected!", hideOnTap: false, showAnnimation: true)
showMessage("Pairing...", hideOnTap: false, showAnnimation: true)
token.pair { error in
async { handler(token: token, error: error) }
}
}
}
private class func async(handler: () -> (Void)) {
dispatch_async(dispatch_get_main_queue(), handler)
}
}
|
mit
|
3ab15999b70d50fb6f57bc029421a144
| 29.941176 | 164 | 0.650507 | 4.13089 | false | false | false | false |
danielmartin/swift
|
test/SILGen/conditionally_unreachable.swift
|
4
|
1614
|
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib -primary-file %s | %FileCheck %s -check-prefix=RAW
// RUN: %target-swift-emit-sil -enable-sil-ownership -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s
// RUN: %target-swift-emit-sil -enable-sil-ownership -O -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s
// RUN: %target-swift-emit-sil -enable-sil-ownership -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s
// RUN: %target-swift-emit-sil -enable-sil-ownership -O -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s
import Swift
@_silgen_name("foo") func foo()
func condUnreachable() {
if Int32(Builtin.assert_configuration()) == 0 {
foo()
} else {
Builtin.conditionallyUnreachable()
}
}
// RAW-LABEL: sil hidden [ossa] @$s25conditionally_unreachable15condUnreachableyyF
// RAW: cond_br {{%.*}}, [[YEA:bb[0-9]+]], [[NAY:bb[0-9]+]]
// RAW: [[YEA]]:
// RAW: function_ref @foo
// RAW: [[NAY]]:
// RAW: builtin "conditionallyUnreachable"
// DEBUG-LABEL: sil hidden @$s25conditionally_unreachable15condUnreachableyyF
// DEBUG-NOT: cond_br
// DEBUG: function_ref @foo
// DEBUG-NOT: {{ unreachable}}
// DEBUG: return
// RELEASE-LABEL: sil hidden @$s25conditionally_unreachable15condUnreachableyyF
// RELEASE-NOT: cond_br
// RELEASE-NOT: function_ref @foo
// RELEASE-NOT: return
// RELEASE-NOT: builtin
// RELEASE: {{ unreachable}}
|
apache-2.0
|
afb4ddd96aff55961731def67b33ef77
| 42.621622 | 147 | 0.671004 | 3.376569 | false | true | false | false |
wqhiOS/WeiBo
|
WeiBo/WeiBo/Classes/Model/Common/User/UserAccountTool.swift
|
1
|
1808
|
//
// UserAccountTool.swift
// WeiBo
//
// Created by wuqh on 2017/6/16.
// Copyright © 2017年 吴启晗. All rights reserved.
//
import UIKit
class UserAccountTool {
// MARK: - 单例
static let shareInstance: UserAccountTool = UserAccountTool()
// MARK: - 存储属性
var account: UserAccount?
// MARK: - 计算属性
static var accountPath : String {
let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
print((accountPath as NSString).appendingPathComponent("account.plist"))
return (accountPath as NSString).appendingPathComponent("account.plist")
}
var isLogin: Bool {
if account == nil {
return false
}
guard let expiresDate = account?.expires_date else {
return false
}
return expiresDate.compare( Date()) == ComparisonResult.orderedDescending
}
// MARK: - 重写init函数
init () {
// 1.从沙河中读取归档的信息
account = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccountTool.accountPath) as? UserAccount
}
/// 保存userAccount
///
/// - Parameter userAccount: 账户信息
class func saveUserAccount(userAccount: UserAccount) {
NSKeyedArchiver.archiveRootObject(userAccount, toFile: UserAccountTool.accountPath)
shareInstance.account = userAccount
}
/// 注销 (删除userAccount)
///
/// - Parameter userAccount: 账户信息
class func deleteUserAccount(userAccount: UserAccount) {
if FileManager.default.fileExists(atPath: UserAccountTool.accountPath) {
try? FileManager.default.removeItem(atPath: UserAccountTool.accountPath)
}
}
}
|
mit
|
89dc4e9c7f30499d8cb58434f886e64d
| 27.616667 | 111 | 0.645312 | 4.83662 | false | false | false | false |
Kawoou/KWDrawerController
|
DrawerController/UIViewController+DrawerController.swift
|
1
|
1998
|
/*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
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
extension UIViewController {
private struct AssociatedKeys {
static var drawerController = "drawerController"
}
public internal(set) var drawerController: DrawerController? {
get {
guard let controller = objc_getAssociatedObject(self, &AssociatedKeys.drawerController) as? DrawerController else {
var parentController = parent
while let parent = parentController {
if let drawerController = parent.drawerController {
return drawerController
}
parentController = parent.parent
}
return nil
}
return controller
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.drawerController, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
}
|
mit
|
c4c61fc249735893a0eb31ecad61fd69
| 37.423077 | 127 | 0.695195 | 5.356568 | false | false | false | false |
dulingkang/DemoCollect
|
DemoCollect/DemoCollect/SubClasses/PriceChoose.swift
|
1
|
9187
|
//
// PriceChoose.swift
// DemoCollect
//
// Created by dulingkang on 2018/4/26.
// Copyright © 2018年 com.shawn. All rights reserved.
//
import UIKit
import AVKit
class PriceChoose: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let key = generateKey()
let urlStr = "https://bbxzb.babaxiong.com/dalu.mp4?_upt=" + key
let url = URL(string: urlStr)
let vc = AVPlayerViewController()
vc.player = AVPlayer(url: url!)
vc.view.frame = self.view.frame
vc.player?.play()
self.present(vc, animated: true) {
}
}
func generateKey() -> String {
let str = "https://bbxzb.babaxiong.com/dalu.mp4"
//double v13; // d0
//signed __int64 v14; // x26
//v14 = (signed __int64)v13 + 900;
//NSString *str = [NSString stringWithFormat:@"%ld", v14];
let date = Date().timeIntervalSince1970
let d = NSInteger(date) + 900
let str2 = "sjdf723k&" + "\(d)&" + "/dalu.mp4"
let v10 = str2.md5
print(v10, v10.lengthOfBytes(using: .utf8))
let start = v10.index(v10.startIndex, offsetBy: 12)
let end = v10.index(v10.endIndex, offsetBy: -(v10.lengthOfBytes(using: .utf8) - 20))
let range = start..<end
let mySubstring = v10[range] // play
print(mySubstring)
let last = mySubstring + "\(d)"
print(last)
return last
}
}
extension String {
public var md5: String {
if let data = self.data(using: .utf8, allowLossyConversion: true) {
let message = data.withUnsafeBytes { bytes -> [UInt8] in
return Array(UnsafeBufferPointer(start: bytes, count: data.count))
}
let MD5Calculator = MD5(message)
let MD5Data = MD5Calculator.calculate()
var MD5String = String()
for c in MD5Data {
MD5String += String(format: "%02x", c)
}
return MD5String
} else {
return self
}
}
}
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] {
let totalBytes = length ?? (MemoryLayout<T>.size * 8)
let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
valuePointer.pointee = value
let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in
var bytes = [UInt8](repeating: 0, count: totalBytes)
for j in 0..<min(MemoryLayout<T>.size, totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
}
return bytes
}
#if swift(>=4.1)
valuePointer.deinitialize(count: 1)
valuePointer.deallocate()
#else
valuePointer.deinitialize()
valuePointer.deallocate(capacity: 1)
#endif
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
func appendBytes(_ arrayOfBytes: [UInt8]) {
append(arrayOfBytes, length: arrayOfBytes.count)
}
}
protocol HashProtocol {
var message: Array<UInt8> { get }
/** Common part for hash calculation. Prepare header data. */
func prepare(_ len: Int) -> Array<UInt8>
}
extension HashProtocol {
func prepare(_ len: Int) -> Array<UInt8> {
var tmpMessage = message
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
tmpMessage += Array<UInt8>(repeating: 0, count: counter)
return tmpMessage
}
}
func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> {
var result = Array<UInt32>()
result.reserveCapacity(16)
for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) {
let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24
let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16
let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8
let d3 = UInt32(slice[idx])
let val: UInt32 = d0 | d1 | d2 | d3
result.append(val)
}
return result
}
struct BytesIterator: IteratorProtocol {
let chunkSize: Int
let data: [UInt8]
init(chunkSize: Int, data: [UInt8]) {
self.chunkSize = chunkSize
self.data = data
}
var offset = 0
mutating func next() -> ArraySlice<UInt8>? {
let end = min(chunkSize, data.count - offset)
let result = data[offset..<offset + end]
offset += result.count
return result.count > 0 ? result : nil
}
}
struct BytesSequence: Sequence {
let chunkSize: Int
let data: [UInt8]
func makeIterator() -> BytesIterator {
return BytesIterator(chunkSize: chunkSize, data: data)
}
}
func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 {
return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
}
class MD5: HashProtocol {
static let size = 16 // 128 / 8
let message: [UInt8]
init (_ message: [UInt8]) {
self.message = message
}
/** specifies the per-round shift amounts */
private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> [UInt8] {
var tmpMessage = prepare(64)
tmpMessage.reserveCapacity(tmpMessage.count + 4)
// hash values
var hh = hashes
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.count * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage += lengthBytes.reversed()
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = toUInt32Array(chunk)
assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A: UInt32 = hh[0]
var B: UInt32 = hh[1]
var C: UInt32 = hh[2]
var D: UInt32 = hh[3]
var dTemp: UInt32 = 0
// Main loop
for j in 0 ..< sines.count {
var g = 0
var F: UInt32 = 0
switch j {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
hh.forEach {
let itemLE = $0.littleEndian
let r1 = UInt8(itemLE & 0xff)
let r2 = UInt8((itemLE >> 8) & 0xff)
let r3 = UInt8((itemLE >> 16) & 0xff)
let r4 = UInt8((itemLE >> 24) & 0xff)
result += [r1, r2, r3, r4]
}
return result
}
}
|
mit
|
42b1ffe163406b3c3905d1017f5d6d2f
| 28.229299 | 113 | 0.566136 | 3.348413 | false | false | false | false |
HongxiangShe/DYZB
|
DY/DY/Class/Tools/Common.swift
|
1
|
601
|
//
// Common.swift
// DY
//
// Created by 佘红响 on 16/12/7.
// Copyright © 2016年 佘红响. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20 // 状态栏高度
let kNavigationBarH : CGFloat = 44 // 导航栏高度
let kTabBarH : CGFloat = 49 // tabBar的高度
let kTopBarH : CGFloat = kStatusBarH + kNavigationBarH // 状态栏高度 + 导航栏高度
let kScreenWidth : CGFloat = UIScreen.main.bounds.size.width
let kScreenHeight : CGFloat = UIScreen.main.bounds.size.height
|
mit
|
5ac53cb48fe443efe6155ffa1feb39da
| 30.764706 | 76 | 0.592593 | 3.941606 | false | false | false | false |
Azero123/JW-Broadcasting
|
JW Broadcasting/StreamingViewController.swift
|
1
|
19229
|
//
// StreamingViewController.swift
// JW Broadcasting
//
// Created by Austin Zelenka on 9/15/15.
// Copyright © 2015 Austin Zelenka. All rights reserved.
//
/*
External references:
func dictionaryOfPath(path: String) -> NSDictionary? in AppDelegate
let base in AppDelegate
let version in AppDelegate
var languageCode in AppDelegate
This view controller represents the Streaming page. I opened reviewed the resources for http://tv.jw.org and tried to mimic the functionality of requesting a list of the next video files coming up playing them one at a time.
The initial "playlist" is fetched using http://mediator.jw.org (base) on version "v1" using the language code (check rootController for information on language and language codes). Then the file location is "Streaming" and the website has a paramater sent called utcOffset with a typical value of -480.
The final url typically comes out as such:
http://mediator.jw.org/v1/schedules/E/Streaming?utcOffset=-480
This url contains all the information for every channel for hours worth of time in a JSON format with a format of:
category = {
description = String
key = "Streaming"
name = "Streaming"
type = "container"
tags = [
"RokuCategorySelectionPosterScreen" (Unkown string for Roku???)
"JWLExclude" (Exclude from the JW Library app???)
]
images = {} (Probably would follow the same format as in VOD if there were any images)
parentCategory = null (Streaming does not have a parent category)
subcategories = [
%subcategory%,
%subcategory%,
...
]
}
%subcategory% represents a Streaming channel (Children, Family, From our Studio, etc.) and follows this format:
%subcategory% = {
position = {
index = Int (The index in media that we will play)
time = Float (The time progressed through the video)
}
media = [
{
files = [
{
progressiveDownloadURL = String (String of URL for mp4 file)
}
...
] (files related to the video or audio file the later down the list the higher the resolution)
}
The key information we need here is where we are currently at and what videos to play.
Firstly we need to create a AVPlayerLayer we do this in startStream() on view did load after we ensure we have a relatively new schedule for the streams.
func startStream()
The startStream method sets up the AVPlayer in the AVPlayerLayer (check AVKit documentation by apple for information on these classes).
Lastly the notification for videos ending is configured to:
playerItemDidReachEnd(notification:NSNotification)
The "playlist" is refreshed every time a video ends by the notification method:
func playerItemDidReachEnd(notification:NSNotification)
Which calls func updateStream()
LATER IMPROVEMENT
Later instead of updating the files every time we need to start the stream we will have code that checks if the current file contains the video to be played at this time, then request a new file upon video completion however not change the time index or video url unless needed.
Also next up videos will be added the the AVPlayers queue so that it will preload them.
Lastly add code that when under poor connection drops the video quality down and monitors the for if the video gets off time (possible modifying the .rate slightly of the AVPlayer to catch up or slow down)
Possibly implement some form of HTTP sitching
POSSIBLE REQUESTS
Information for brothers in bethel on this page
Using stitching techniques we can have separate Audio, Video, and caption text. The users can enable/disable captions and the video would not have to be stored several times for different languages. (However downloaded videos may still require the current method of dubbing and captioning so maybe not?)
*/
import Foundation
import AVKit
class StreamingViewController : UIViewController {
var currentURL:String?
var playlist=[]
var _streamID:Int=0
var streamID:Int {
/*
The channel is being changed (probably from the HomeController to select the proper channel)
*/
set (newValue){
_streamID=newValue
if (thisControllerIsVisible){ // Only update the stream if this page is already visible so that we don't modify variables before initialization
updateStream()
previousLanguageCode=languageCode // Keep in mind what language we were last in
previousStreamId=streamID // Keep in mind the previous channel
}
}
get {
return _streamID
}
}
@IBOutlet weak var activityIndicator: UIActivityIndicatorView! // The spinning wheel
override func viewDidLoad() {
super.viewDidLoad()
let streamingScheduleURL=base+"/"+version+"/schedules/"+languageCode+"/Streaming?utcOffset=0"
/*
Show the spinning wheel to the user so the user knows that we are downloading data
*/
self.activityIndicator.transform = CGAffineTransformMakeScale(2.0, 2.0)
self.activityIndicator.hidesWhenStopped=true
self.activityIndicator.startAnimating()
self.view.userInteractionEnabled=true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dictionaryOfPath(streamingScheduleURL, usingCache: false) //Download streaming schedule
dispatch_async(dispatch_get_main_queue()) {
if (self.view.hidden==false){ //Only display if view is visible (This was an ios 9.0 issue and the if statement could possibly be removed
self.startStream()
self.update()
}
}
}
}
var _player:AVQueuePlayer?
var player:AVQueuePlayer? {
set (newValue){
_player=newValue
//updateStream()
}
get {
return _player
}
}
var playerLayer:AVPlayerLayer?
func startStream(){
//creastes the AVPlayer applying necissary changes and then calls updateStream() to update the video to the schedule
player = AVQueuePlayer()//Creates the player for the layer
playerLayer=AVPlayerLayer(player: player)//Creates the layer
playerLayer!.frame=UIScreen.mainScreen().bounds//Sets the video to be the size of the screen
player!.actionAtItemEnd = AVPlayerActionAtItemEnd.None;
updateStream()//Matches to the current video and to the stream index
}
var indexInPlaylist=0
func playerItemDidReachEnd(notification:NSNotification){
/*
Current code for moving to the next stream video.
*/
indexInPlaylist++ //Next video index
self.player?.advanceToNextItem()
self.performSelector("updateStream", withObject: nil, afterDelay: 1)//updateStream() //Makes sure we are on the right video and at the righr time (give or take 10 seconds)
}
var thisControllerIsVisible=false
@IBOutlet var focusButton: UIButton!
var initialAppear=true
var previousLanguageCode=languageCode
var previousStreamId = -1
override func viewWillAppear(animated: Bool) {
thisControllerIsVisible=true
//if (initialAppear){
if ((player) != nil || previousLanguageCode != languageCode || previousStreamId != streamID){ //If we have initialized the player and any major data has changed then we need to refresh the content
updateStream()
}
previousLanguageCode=languageCode//Remember what language we are in
previousStreamId=streamID//Remember what channel we are on
self.view.hidden=false
}
override func viewDidAppear(animated: Bool) {
//updateStream()
}
override func viewWillDisappear(animated: Bool) {
//Hide and pause the video when we leave the Streaming page
self.view.hidden=true
player?.pause()
}
override func viewDidDisappear(animated: Bool) {
//Remeove any data we do not need store when streaming is off
thisControllerIsVisible=false
player?.pause()
player?.replaceCurrentItemWithPlayerItem(nil)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//The view size changed so let's correct the player size
playerLayer?.position=CGPointMake(0, 0)
playerLayer!.frame=self.view.frame
}
func updateStream(){
activityIndicator.startAnimating() //This process normally doesn't take a while but if it does let the user know the app is loading content
let streamingScheduleURL=base+"/"+version+"/schedules/"+languageCode+"/Streaming?utcOffset=-480" //The Schedule url for all the streams
if ((self.player?.currentItem) != nil){
//self.player?.currentItem?.removeObserver(self, forKeyPath: "status", context: nil)
}
//fetchDataUsingCache(streamingScheduleURL, downloaded: {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
//let streamMeta=dictionaryOfPath(streamingScheduleURL, usingCache: false)
dispatch_async(dispatch_get_main_queue()) {
print("[Channels] \(self.streamID)")
fetchDataUsingCache(streamingScheduleURL, downloaded: nil)
let subcategory=unfold("\(streamingScheduleURL)|category|subcategories|\(self.streamID)")//streamMeta?.objectForKey("category")?.objectForKey("subcategories")!.objectAtIndex(self.streamID)
//Code for getting current index
var i=(unfold("\(streamingScheduleURL)|category|subcategories|\(self.streamID)|position|index") as! NSNumber).integerValue //Get the current index from tv.jw.org
self.indexInPlaylist=i //Getting the index was successful now use it
var timeIndex=subcategory!.objectForKey("position")?.objectForKey("time")?.floatValue
if (self.player != nil){
do {
let storedPath=cacheDirectory!+"/"+(NSURL(string: streamingScheduleURL)?.path!.stringByReplacingOccurrencesOfString("/", withString: "-"))! // the desired stored file path
print("streaming stored path:\(storedPath)")
let dateDataWasRecieved=try NSFileManager.defaultManager().attributesOfItemAtPath(storedPath)[NSFileModificationDate] as! NSDate
print("We have had this file since:\(dateDataWasRecieved.timeIntervalSinceNow)")
timeIndex=timeIndex!-Float(dateDataWasRecieved.timeIntervalSinceNow)
}
catch {
print("[ERROR] problem discovering the date streaming schedule was recieved")
}
//The date that we got the file last, let's hope that we don't have any issues here
}
while (true) {
let supposedCurrentVideoDuration=unfold("\(streamingScheduleURL)|category|subcategories|\(self.streamID)|media|\(i)|duration")
if ((supposedCurrentVideoDuration) == nil){
print("[ERROR] broke because current video duration could not be determined")
fetchDataUsingCache(streamingScheduleURL, downloaded: {
self.updateStream()
}, usingCache: false)
return
}
let supposedCurrentVideoDurationInt=(supposedCurrentVideoDuration as! NSNumber).integerValue
if (timeIndex>Float(supposedCurrentVideoDurationInt)){
timeIndex=timeIndex!-Float(supposedCurrentVideoDurationInt)
i++
}
else {
break
}
}
/*
Check for new videos to add to queue.
This loops through all the upcoming videos in the stream comparing them with what we previously had.
If the videos do not match up it removes the video from the queue and replaces it with the new one.
If we do not have any video in that place it just adds it to the queue.
*/
for ; i<(unfold("\(streamingScheduleURL)|category|subcategories|\(self.streamID)|media|count") as! NSNumber).integerValue ; i++ {
let videoURL=unfold("\(streamingScheduleURL)|category|subcategories|\(self.streamID)|media|\(i)|files|\(StreamingLowestQuality ? "first": "last")|progressiveDownloadURL") as? String
if (self.player?.items().count > i){
//The video index is already taken so check it
if ((self.player?.items()[i].asset.isKindOfClass(AVURLAsset.self)) == true){
//Make sure the url is available
if ((self.player?.items()[i-1].asset as! AVURLAsset).URL.absoluteString != videoURL){
//Okay so we have a differen't video than what we previously had so remove it and add the new video
print("[Stream] Replace video \(i-1) \((self.player?.items()[i-1].asset as! AVURLAsset).URL.absoluteString) \(videoURL)")
/*self.player?.removeItem((self.player?.items()[i-1])!)//remove
let playerItem=AVPlayerItem(URL: NSURL(string: videoURL!)!)//make new video
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)//Let us know when the video finishes playing to go to the next one
self.player?.insertItem(playerItem, afterItem: self.player?.items()[i-2])//Insert video to it's proper place
*/
}
}
}
else {
//The does not exist yet so just add the new video
if (self.player != nil && videoURL != nil){
print("[Stream] add video")
let playerItem=AVPlayerItem(URL: NSURL(string: videoURL!)!)//make new video
//AVPlayerItemDidPlayToEndTimeNotification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)//Let us know when the video finishes playing to go to the next one
self.player?.insertItem(playerItem, afterItem: nil)//Insert video to it's proper place
}
}
}
if (self.player != nil){
if ((self.player?.currentTime().value)!-CMTimeMake(Int64(timeIndex!), 1).value < abs(10)){
print("[Channels] too far behind")
self.player!.seekToTime(CMTimeMake(Int64(timeIndex!), 1))
}
else {
print("[Channels] close enough")
}
}
}
}
//player?.setRate(1.5, time: kCMTimeInvalid, atHostTime: CMTimeMake(Int64(timeIndex!), 1))
/*might try using set rate to speed the video up until it catches up to the current time that way users can watch the video uninterrupted. Currently having some bugs with this however*/
}
var advancedLabel:UILabel?
func update(){
if (StreamingAdvancedMode){
if (advancedLabel == nil){
advancedLabel=UILabel(frame: CGRect(x: 10, y: self.view.frame.height-50, width: self.view.bounds.width, height: 40))
advancedLabel?.font=UIFont.systemFontOfSize(30)
advancedLabel?.shadowColor=UIColor.blackColor()
advancedLabel?.textColor=UIColor.whiteColor()
self.view.superview!.addSubview(advancedLabel!)
player?.rate=1.0
}
}
if ((self.player) != nil && player?.currentItem != nil && player?.currentItem?.status == AVPlayerItemStatus.ReadyToPlay){
advancedLabel?.text=" bitrate \(player?.rate) \(floor((player?.currentTime().seconds)!))/\(floor((player?.currentItem?.duration.seconds)!)) \(player?.currentItem?.asset)"
if (self.player!.currentItem!.status == AVPlayerItemStatus.ReadyToPlay) {
activityIndicator.stopAnimating()
if (self.view.hidden==false){
self.view.layer.addSublayer(playerLayer!)
}
if (thisControllerIsVisible){
player?.play()
}
}
}
self.performSelector("update", withObject: nil, afterDelay: 0.25)
}
}
|
mit
|
1c888eb506b6c6ff984b8b1d4d1a377f
| 42.504525 | 303 | 0.56865 | 5.760336 | false | false | false | false |
Mazy-ma/DemoBySwift
|
GPUImage_AddFilterToCamera/GPUImage_AddFilterToCamera/ViewController.swift
|
1
|
7778
|
//
// ViewController.swift
// GPUImage_AddFilterToCamera
//
// Created by Mazy on 2017/4/22.
// Copyright © 2017年 Mazy. All rights reserved.
//
/*
初始化相机
初始化滤镜(GPUImage提供了120多种滤镜的效果,可以自己替换)
初始化GPUImageView
将初始化过的相机加到目标滤镜上
将滤镜加在目标GPUImage上
GPUImage加在控制器视图上
相机开始捕捉画面
将相机捕捉的画面存在手机的相册中
*/
/*
注:现在iOS访问用户的相机和相册都要事先在info.plist文件中提前布置请求权限。是否允许访问相册:Privacy - Photo Library Usage Description;是否允许访问相机:Privacy - Camera Usage Description。
*/
import UIKit
import GPUImage
import Photos
let kWidth = UIScreen.main.bounds.size.width
let kHeight = UIScreen.main.bounds.size.height
class ViewController: UIViewController {
// 步骤一:初始化相机,第一个参数表示相册的尺寸,第二个参数表示前后摄像头
let camera: GPUImageStillCamera = GPUImageStillCamera(sessionPreset: AVCaptureSessionPreset1280x720, cameraPosition: AVCaptureDevicePosition.front)
// 设置图像图层
let imageView = GPUImageView(frame: CGRect(origin: CGPoint.zero, size: UIScreen.main.bounds.size))
// 设置当前选中的按钮
var selectedBtn: UIButton?
// 控制属性的
let slider = UISlider()
// 保存当前滤镜
var currentFilter: GPUImageFilter?
// 磨皮滤镜(美颜)
let bilateralFilter = GPUImageBilateralFilter()
// 哈哈镜效果
let stretchDistortionFilter = GPUImageStretchDistortionFilter()
// 伽马线滤镜
let gammaFilter = GPUImageGammaFilter()
// 边缘检测
let xYDerivativeFilter = GPUImageXYDerivativeFilter()
// 怀旧
let sepiaFilter = GPUImageSepiaFilter()
// 反色
let invertFilter = GPUImageColorInvertFilter()
// 饱和度
let saturationFilter = GPUImageSaturationFilter()
// 美白滤镜
let brightnessFilter = GPUImageBrightnessFilter()
// 滤镜数组,保存所有的滤镜到一个数组,便于后面的切换
var filtersArray: [AnyObject] {
return [bilateralFilter,stretchDistortionFilter,brightnessFilter,gammaFilter,xYDerivativeFilter,sepiaFilter,invertFilter,saturationFilter]
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置相机方向为竖屏
camera.outputImageOrientation = .portrait
// 取出第一个滤镜,并添加到相机中
let firstFilter = filtersArray.first as! GPUImageFilter
currentFilter = firstFilter
camera.addTarget(firstFilter)
// 将滤镜添加到图像图层
bilateralFilter.addTarget(imageView)
// 添加相机图层,相机图层需要强引用
view.insertSubview(imageView, at: 0)
// 开始图像获取
camera.startCapture()
/*
//滤镜组
let groupFilter = GPUImageFilterGroup()
// 将磨皮加美白加入到滤镜组
groupFilter.addTarget(bilateralFilter)
groupFilter.addTarget(brightnessFilter)
// 设置滤镜组链
bilateralFilter.addTarget(brightnessFilter)
groupFilter.initialFilters = [bilateralFilter]
groupFilter.terminalFilter = brightnessFilter
*/
// MARK: - 设置界面
setupUI()
}
}
// MARK: - 给相机加滤镜
extension ViewController {
fileprivate func setupUI() {
let titleArray = ["美颜","哈哈镜","亮度","伽马线","边缘检测","怀旧","反色","饱和度"]
for (i, value) in titleArray.enumerated() {
let button = UIButton(type: .custom)
button.frame = CGRect(x: Int(kWidth-90), y: 40+40*i, width: 80, height: 30)
button.layer.cornerRadius = 5
button.setTitle(value, for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .lightGray
button.tag = 100 + i
button.addTarget(self, action: #selector(filterStyleIsClicked), for: .touchUpInside)
view.addSubview(button)
if i == 0 {
selectedBtn = button
button.backgroundColor = .orange
}
}
// 照相的按钮
let catchBtn = UIButton(type: .custom)
catchBtn.setBackgroundImage(UIImage(named: "catch"), for: .normal)
catchBtn.frame = CGRect(x: (kWidth-60)/2, y: kHeight-80, width: 60, height: 60)
catchBtn.addTarget(self, action: #selector(catchAction), for: .touchUpInside)
view.addSubview(catchBtn)
// 设置slider
slider.frame = CGRect(x: (kWidth-300)/2, y: kHeight-130, width: 300, height: 30)
slider.value = 0.5
slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
view.addSubview(slider)
// 照相的按钮
let switchBtn = UIButton(type: .custom)
switchBtn.setBackgroundImage(UIImage(named: "switch"), for: .normal)
switchBtn.frame = CGRect(x: (kWidth-60), y: kHeight-70, width: 40, height: 40)
switchBtn.addTarget(self, action: #selector(switchAction), for: .touchUpInside)
view.addSubview(switchBtn)
}
/// 点击滤镜切换按钮,切换滤镜
@objc func filterStyleIsClicked(sender: UIButton) {
selectedBtn?.backgroundColor = .lightGray
sender.backgroundColor = .orange
switch(sender.tag-100) {
case 4,5,6:
slider.isHidden = true
break
default:
slider.isHidden = false
break
}
let filter = filtersArray[sender.tag-100] as! GPUImageFilter
camera.removeAllTargets()
camera.addTarget(filter)
filter.addTarget(imageView)
currentFilter = filter
selectedBtn = sender
}
/// 拍照并保存图片到相册
@objc func catchAction() {
camera.capturePhotoAsPNGProcessedUp(toFilter: currentFilter) { (pngData, error) in
guard let data = pngData,
let image = UIImage(data: data) else {
return
}
PHPhotoLibrary.shared().performChanges({
_ = PHAssetChangeRequest.creationRequestForAsset(from: image)
}, completionHandler: { (success, error) in
print("success=\(success) error\(error)")
if success {
print("图片保存成功")
}
})
}
}
/// slider值改变控制滤镜的属性
@objc func sliderValueChanged(sender:UISlider) {
if let currentFilter = currentFilter as? GPUImageGammaFilter {
currentFilter.gamma = CGFloat(sender.value*3)
} else if let currentFilter = currentFilter as?GPUImageStretchDistortionFilter {
currentFilter.center = CGPoint(x: Double(sender.value), y: 0.5)
} else if let currentFilter = currentFilter as? GPUImageBilateralFilter {
currentFilter.distanceNormalizationFactor = CGFloat(sender.value*10)
} else if let currentFilter = currentFilter as? GPUImageBrightnessFilter {
currentFilter.brightness = CGFloat(sender.value)
} else if let currentFilter = currentFilter as? GPUImageSaturationFilter {
currentFilter.saturation = CGFloat(sender.value*2)
}
}
/// 切换摄像头
@objc func switchAction() {
camera.rotateCamera()
}
}
|
apache-2.0
|
d7c2d359d6b2bf4a0f9833438d3e8e46
| 29.84 | 151 | 0.620695 | 4.251838 | false | false | false | false |
TG908/iOS
|
TUM Campus App/CafeteriaMenuManager.swift
|
1
|
2600
|
//
// CafeteriaMenuManager.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/6/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class CafeteriaMenuManager: Manager {
static var cafeteriaMenus = [DataElement]()
var manager: TumDataManager?
required init(mainManager: TumDataManager) {
manager = mainManager
}
func fetchData(_ handler: @escaping ([DataElement]) -> ()) {
if CafeteriaMenuManager.cafeteriaMenus.isEmpty {
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
Alamofire.request(getURL(), method: .get, parameters: nil,
headers: ["X-DEVICE-ID": uuid]).responseJSON() { (response) in
if let value = response.result.value {
let json = JSON(value)
if let cafeteriasJsonArray = json["mensa_menu"].array {
for item in cafeteriasJsonArray {
self.addMenu(item)
}
if let beilagenJsonArray = json["mensa_beilagen"].array {
for item in beilagenJsonArray {
self.addMenu(item)
}
}
handler(CafeteriaMenuManager.cafeteriaMenus)
}
}
}
}
}
}
func addMenu(_ item: JSON) {
if let cafeteria = item["mensa_id"].string, let date = item["date"].string, let typeShort = item["type_short"].string, let typeLong = item["type_long"].string, let name = item["name"].string, let mensa = self.manager?.getCafeteriaForID(cafeteria) {
let id = item["id"].string ?? ""
let typeNR = item["type_nr"].string ?? ""
let idNumber = Int(id) ?? 0
let nr = Int(typeNR) ?? Int.max
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"
let dateAsDate = dateformatter.date(from: date) ?? Date()
let newMenu = CafeteriaMenu(id: idNumber, date: dateAsDate, typeShort: typeShort, typeLong: typeLong, typeNr: nr, name: name)
mensa.addMenu(newMenu)
CafeteriaMenuManager.cafeteriaMenus.append(newMenu)
}
}
func getURL() -> String {
return "http://lu32kap.typo3.lrz.de/mensaapp/exportDB.php?mensa_id=all"
}
}
|
gpl-3.0
|
e016f1f6b7082234cb866ad2cf0987c4
| 38.984615 | 256 | 0.533282 | 4.442735 | false | false | false | false |
Darktt/ScrollBanner
|
SrcollViewDemo/ViewController.swift
|
1
|
6807
|
//
// ViewController.swift
// SrcollViewDemo
//
// Created by EdenLi on 2016/2/4.
// Copyright © 2016年 Darktt. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate
{
@IBOutlet var scrollView: UIScrollView?
@IBOutlet var leftSubScrollView: UIScrollView?
@IBOutlet var rightSubScrollView: UIScrollView?
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let screenRect: CGRect = UIScreen.mainScreen().bounds
var leftViews = Array<UIView>()
var rightViews = Array<UIView>()
var views = Array<UIView>()
for index in 1...5 {
var backgroundColor: UIColor = self.colorForIndex(index - 1)
// Setup left view
let leftView = UIView(frame: CGRect.zero, backgrouneColor: backgroundColor)
leftViews.append(leftView)
backgroundColor = self.colorForIndex(index)
// Setup center view
let view = UIView(frame: CGRect.zero, backgrouneColor: backgroundColor)
views.append(view)
backgroundColor = self.colorForIndex(index + 1)
// Setup right view
let rightView = UIView(frame: CGRect.zero, backgrouneColor: backgroundColor)
rightViews.append(rightView)
}
func SetupScrollViewParameterWithScrollView(_scrollView: UIScrollView, forSubviews views: Array<UIView>)
{
_scrollView.pagingEnabled = true
_scrollView.showsHorizontalScrollIndicator = false
_scrollView.showsVerticalScrollIndicator = false
_scrollView.clipsToBounds = true
_scrollView.delegate = self
_scrollView.addSubviews(views, scrollOrientation: [.Horizontal])
}
if let leftSubScrollView = self.leftSubScrollView {
SetupScrollViewParameterWithScrollView(leftSubScrollView, forSubviews: leftViews)
}
if let scrollView = self.scrollView {
SetupScrollViewParameterWithScrollView(scrollView, forSubviews: views)
}
if let rightSubScrollView = self.rightSubScrollView {
SetupScrollViewParameterWithScrollView(rightSubScrollView, forSubviews: rightViews)
}
}
override func viewDidLayoutSubviews()
{
var offsetX: CGFloat = 0.0
let width: CGFloat = CGRectGetWidth(self.scrollView!.bounds)
let height: CGFloat = CGRectGetHeight(self.scrollView!.bounds)
let leftViews: Array<UIView> = self.leftSubScrollView!.subviews
let midViews: Array<UIView> = self.scrollView!.subviews
let rightViews: Array<UIView> = self.rightSubScrollView!.subviews
for index in 0 ..< leftViews.count {
let frame = CGRect(x: offsetX, width: width, height: height)
let leftView = leftViews[index]
leftView.frame = frame
let midView = midViews[index]
midView.frame = frame
let rightView = rightViews[index]
rightView.frame = frame
offsetX += width
}
// Update content size
if let lastView = midViews.last {
let contentSize = CGSize(width: CGRectGetMaxX(lastView.frame))
self.leftSubScrollView?.contentSize = contentSize
self.scrollView?.contentSize = contentSize
self.rightSubScrollView?.contentSize = contentSize
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return .LightContent
}
override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation
{
return .Fade
}
override func prefersStatusBarHidden() -> Bool
{
return false
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Other Methods -
func colorForIndex(index: Int) -> UIColor
{
let color: UIColor
switch index {
case -4, 1, 6:
color = UIColor.greenColor()
case -3, 2, 7:
color = UIColor.redColor()
case -2, 3, 8:
color = UIColor.orangeColor()
case -1, 4, 9:
color = UIColor.purpleColor()
case 0, 5, 10:
color = UIColor.blueColor()
default:
color = UIColor.clearColor()
}
return color
}
func getOtherScrollViews(scrollView: UIScrollView) -> (UIScrollView, UIScrollView)
{
var scrollViews = (UIScrollView(), UIScrollView())
switch scrollView
{
case self.leftSubScrollView!:
scrollViews = (self.scrollView!, self.rightSubScrollView!)
case self.scrollView!:
scrollViews = (self.leftSubScrollView!, self.rightSubScrollView!)
case self.rightSubScrollView!:
scrollViews = (self.leftSubScrollView!, self.scrollView!)
default:
break
}
return scrollViews;
}
// MARK: - UIScrollViewDelegate -
func scrollViewWillBeginDragging(scrollView: UIScrollView)
{
let scrollViews: (UIScrollView, UIScrollView) = self.getOtherScrollViews(scrollView)
scrollViews.0.userInteractionEnabled = false
scrollViews.1.userInteractionEnabled = false
print("**** \(__FUNCTION__) ****")
print("Given scrollView: \(scrollView)\n")
print("Other scrollViews: .0 \(scrollViews.0), .1 \(scrollViews.1)\n")
}
func scrollViewDidScroll(scrollView: UIScrollView)
{
let scrollViews: (UIScrollView, UIScrollView) = self.getOtherScrollViews(scrollView)
scrollViews.0.contentOffset = scrollView.contentOffset
scrollViews.1.contentOffset = scrollView.contentOffset
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool)
{
let scrollViews: (UIScrollView, UIScrollView) = self.getOtherScrollViews(scrollView)
scrollViews.0.userInteractionEnabled = true
scrollViews.1.userInteractionEnabled = true
print("**** \(__FUNCTION__) ****")
print("Given scrollView: \(scrollView)\n")
print("Other scrollViews: .0 \(scrollViews.0), .1 \(scrollViews.1)\n")
}
}
|
apache-2.0
|
fc53918a1caf9514b6047e9002243eab
| 31.246445 | 112 | 0.593474 | 5.549755 | false | false | false | false |
chipivk/SwiftPages
|
SwiftPages/SwiftPages.swift
|
1
|
12341
|
//
// SwiftPages.swift
// SwiftPages
//
// Created by Gabriel Alvarado on 6/27/15.
// Copyright (c) 2015 Gabriel Alvarado. All rights reserved.
//
import UIKit
public class SwiftPages: UIView, UIScrollViewDelegate {
//Items variables
private var containerView: UIView!
private var scrollView: UIScrollView!
private var topBar: UIView!
private var animatedBar: UIView!
private var viewControllerIDs: [String] = []
private var buttonTitles: [String] = []
private var buttonImages: [UIImage] = []
private var pageViews: [UIViewController?] = []
//Container view position variables
private var xOrigin: CGFloat = 0
private var yOrigin: CGFloat = 64
private var distanceToBottom: CGFloat = 0
//Color variables
private var animatedBarColor = UIColor(red: 28/255, green: 95/255, blue: 185/255, alpha: 1)
private var topBarBackground = UIColor.whiteColor()
private var buttonsTextColor = UIColor.grayColor()
private var containerViewBackground = UIColor.whiteColor()
//Item size variables
private var topBarHeight: CGFloat = 52
private var animatedBarHeight: CGFloat = 3
//Bar item variables
private var aeroEffectInTopBar: Bool = false //This gives the top bap a blurred effect, also overlayes the it over the VC's
private var buttonsWithImages: Bool = false
private var barShadow: Bool = true
private var buttonsTextFontAndSize: UIFont = UIFont(name: "HelveticaNeue-Light", size: 20)!
// MARK: - Positions Of The Container View API -
public func setOriginX (origin : CGFloat) { xOrigin = origin }
public func setOriginY (origin : CGFloat) { yOrigin = origin }
public func setDistanceToBottom (distance : CGFloat) { distanceToBottom = distance }
// MARK: - API's -
public func setAnimatedBarColor (color : UIColor) { animatedBarColor = color }
public func setTopBarBackground (color : UIColor) { topBarBackground = color }
public func setButtonsTextColor (color : UIColor) { buttonsTextColor = color }
public func setContainerViewBackground (color : UIColor) { containerViewBackground = color }
public func setTopBarHeight (pointSize : CGFloat) { topBarHeight = pointSize}
public func setAnimatedBarHeight (pointSize : CGFloat) { animatedBarHeight = pointSize}
public func setButtonsTextFontAndSize (fontAndSize : UIFont) { buttonsTextFontAndSize = fontAndSize}
public func enableAeroEffectInTopBar (boolValue : Bool) { aeroEffectInTopBar = boolValue}
public func enableButtonsWithImages (boolValue : Bool) { buttonsWithImages = boolValue}
public func enableBarShadow (boolValue : Bool) { barShadow = boolValue}
override public func drawRect(rect: CGRect)
{
// MARK: - Size Of The Container View -
var pagesContainerHeight = self.frame.height - yOrigin - distanceToBottom
var pagesContainerWidth = self.frame.width
//Set the containerView, every item is constructed relative to this view
containerView = UIView(frame: CGRectMake(xOrigin, yOrigin, pagesContainerWidth, pagesContainerHeight))
containerView.backgroundColor = containerViewBackground
self.addSubview(containerView)
//Set the scrollview
if (aeroEffectInTopBar) {
scrollView = UIScrollView(frame: CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height))
} else {
scrollView = UIScrollView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, containerView.frame.size.height - topBarHeight))
}
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.delegate = self
scrollView.backgroundColor = UIColor.clearColor()
containerView.addSubview(scrollView)
//Set the top bar
topBar = UIView(frame: CGRectMake(0, 0, containerView.frame.size.width, topBarHeight))
topBar.backgroundColor = topBarBackground
if (aeroEffectInTopBar) {
if #available(iOS 8.0, *) {
//Create the blurred visual effect
//You can choose between ExtraLight, Light and Dark
topBar.backgroundColor = UIColor.clearColor()
let blurEffect: UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = topBar.bounds
blurView.translatesAutoresizingMaskIntoConstraints = false
topBar.addSubview(blurView)
} else {
// Fallback on earlier versions
}
}
containerView.addSubview(topBar)
//Set the top bar buttons
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
//Check to see if the top bar will be created with images ot text
if (!buttonsWithImages) {
for item in buttonTitles
{
var barButton: UIButton!
barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight))
barButton.backgroundColor = UIColor.clearColor()
barButton.titleLabel!.font = buttonsTextFontAndSize
barButton.setTitle(buttonTitles[buttonNumber], forState: UIControlState.Normal)
barButton.setTitleColor(buttonsTextColor, forState: UIControlState.Normal)
barButton.tag = buttonNumber
barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
topBar.addSubview(barButton)
buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition
buttonNumber++
}
} else {
for item in buttonImages
{
var barButton: UIButton!
barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight))
barButton.backgroundColor = UIColor.clearColor()
barButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
barButton.setImage(item, forState: .Normal)
barButton.tag = buttonNumber
barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
topBar.addSubview(barButton)
buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition
buttonNumber++
}
}
//Set up the animated UIView
animatedBar = UIView(frame: CGRectMake(0, topBarHeight - animatedBarHeight + 1, (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.8, animatedBarHeight))
animatedBar.center.x = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count * 2)
animatedBar.backgroundColor = animatedBarColor
containerView.addSubview(animatedBar)
//Add the bar shadow (set to true or false with the barShadow var)
if (barShadow) {
var shadowView = UIView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, 4))
var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = shadowView.bounds
gradient.colors = [UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 0.28).CGColor, UIColor.clearColor().CGColor]
shadowView.layer.insertSublayer(gradient, atIndex: 0)
containerView.addSubview(shadowView)
}
let pageCount = viewControllerIDs.count
//Fill the array containing the VC instances with nil objects as placeholders
for _ in 0..<pageCount {
pageViews.append(nil)
}
//Defining the content size of the scrollview
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageCount),
height: pagesScrollViewSize.height)
//Load the pages to show initially
loadVisiblePages()
}
// MARK: - Initialization Functions -
public func initializeWithVCIDsArrayAndButtonTitlesArray (VCIDsArray: [String], buttonTitlesArray: [String])
{
//Important - Titles Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonTitlesArray.count {
viewControllerIDs = VCIDsArray
buttonTitles = buttonTitlesArray
buttonsWithImages = false
} else {
print("Initilization failed, the VC ID array count does not match the button titles array count.")
}
}
public func initializeWithVCIDsArrayAndButtonImagesArray (VCIDsArray: [String], buttonImagesArray: [UIImage])
{
//Important - Images Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonImagesArray.count {
viewControllerIDs = VCIDsArray
buttonImages = buttonImagesArray
buttonsWithImages = true
} else {
print("Initilization failed, the VC ID array count does not match the button images array count.")
}
}
public func loadPage(page: Int)
{
if page < 0 || page >= viewControllerIDs.count {
// If it's outside the range of what you have to display, then do nothing
return
}
//Use optional binding to check if the view has already been loaded
if let pageView = pageViews[page]
{
// Do nothing. The view is already loaded.
} else
{
print("Loading Page \(page)")
//The pageView instance is nil, create the page
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
//Create the variable that will hold the VC being load
var newPageView: UIViewController
//Look for the VC by its identifier in the storyboard and add it to the scrollview
newPageView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(viewControllerIDs[page]) as! UIViewController
newPageView.view.frame = frame
scrollView.addSubview(newPageView.view)
//Replace the nil in the pageViews array with the VC just created
pageViews[page] = newPageView
}
}
public func loadVisiblePages()
{
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
// Work out which pages you want to load
let firstPage = page - 1
let lastPage = page + 1
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
}
public func barButtonAction(sender: UIButton?)
{
var index: Int = sender!.tag
let pagesScrollViewSize = scrollView.frame.size
[scrollView .setContentOffset(CGPointMake(pagesScrollViewSize.width * (CGFloat)(index), 0), animated: true)]
}
public func scrollViewDidScroll(scrollView: UIScrollView)
{
// Load the pages that are now on screen
loadVisiblePages()
//The calculations for the animated bar's movements
//The offset addition is based on the width of the animated bar (button width times 0.8)
var offsetAddition = (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.1
animatedBar.frame = CGRectMake((offsetAddition + (scrollView.contentOffset.x/(CGFloat)(viewControllerIDs.count))), animatedBar.frame.origin.y, animatedBar.frame.size.width, animatedBar.frame.size.height);
}
}
|
mit
|
7857cdf9f987be8ad08bafd209f67f9d
| 45.573585 | 212 | 0.655701 | 5.196211 | false | false | false | false |
atl009/WordPress-iOS
|
WordPress/Classes/Models/ManagedAccountSettings.swift
|
2
|
3774
|
import Foundation
import CoreData
import WordPressKit
// MARK: - Reflects the user's Account Settings, as stored in Core Data.
//
class ManagedAccountSettings: NSManagedObject {
// MARK: - NSManagedObject
override class var entityName: String {
return "AccountSettings"
}
func updateWith(_ accountSettings: AccountSettings) {
firstName = accountSettings.firstName
lastName = accountSettings.lastName
displayName = accountSettings.displayName
aboutMe = accountSettings.aboutMe
username = accountSettings.username
email = accountSettings.email
emailPendingAddress = accountSettings.emailPendingAddress
emailPendingChange = accountSettings.emailPendingChange
primarySiteID = NSNumber(value: accountSettings.primarySiteID)
webAddress = accountSettings.webAddress
language = accountSettings.language
}
/// Applies a change to the account settings
/// To change a setting, you create a change and apply it to the AccountSettings object.
/// This method will return a new change object to apply if you want to revert the changes
/// (for instance, if they failed to save)
///
/// - Returns: the change object needed to revert this change
///
func applyChange(_ change: AccountSettingsChange) -> AccountSettingsChange {
let reverse = reverseChange(change)
switch change {
case .firstName(let value):
self.firstName = value
case .lastName(let value):
self.lastName = value
case .displayName(let value):
self.displayName = value
case .aboutMe(let value):
self.aboutMe = value
case .email(let value):
self.emailPendingAddress = value
self.emailPendingChange = true
case .emailRevertPendingChange:
self.emailPendingAddress = nil
self.emailPendingChange = false
case .primarySite(let value):
self.primarySiteID = NSNumber(value: value)
case .webAddress(let value):
self.webAddress = value
case .language(let value):
self.language = value
}
return reverse
}
fileprivate func reverseChange(_ change: AccountSettingsChange) -> AccountSettingsChange {
switch change {
case .firstName:
return .firstName(self.firstName)
case .lastName:
return .lastName(self.lastName)
case .displayName:
return .displayName(self.displayName)
case .aboutMe:
return .aboutMe(self.aboutMe)
case .email:
return .emailRevertPendingChange
case .emailRevertPendingChange:
return .email(self.emailPendingAddress ?? String())
case .primarySite:
return .primarySite(self.primarySiteID.intValue)
case .webAddress:
return .webAddress(self.webAddress)
case .language:
return .language(self.language)
}
}
}
extension AccountSettings {
init(managed: ManagedAccountSettings) {
firstName = managed.firstName
lastName = managed.lastName
displayName = managed.displayName
aboutMe = managed.aboutMe
username = managed.username
email = managed.email
emailPendingAddress = managed.emailPendingAddress
emailPendingChange = managed.emailPendingChange
primarySiteID = managed.primarySiteID.intValue
webAddress = managed.webAddress
language = managed.language
}
var emailForDisplay: String {
let pendingEmail = emailPendingAddress?.nonEmptyString() ?? email
return emailPendingChange ? pendingEmail : email
}
}
|
gpl-2.0
|
d8bddae7c95ba06efdaa3023a2690df0
| 33.309091 | 94 | 0.652358 | 5.330508 | false | false | false | false |
BoutFitness/Concept2-SDK
|
Pod/Classes/Models/RowingAdditionalWorkoutSummaryData.swift
|
1
|
2793
|
//
// RowingAdditionalWorkoutSummaryData.swift
// Pods
//
// Created by Jesse Curry on 10/27/15.
//
//
struct RowingAdditionalWorkoutSummaryData: CharacteristicModel, CustomDebugStringConvertible {
let DataLength = 20
/*
Data bytes packed as follows:
Log Entry Date Lo,
Log Entry Date Hi,
Log Entry Time Lo,
Log Entry Time Hi,
Split/Interval Type,
Split/Interval Size Lo, (meters or seconds)
Split/Interval Size Hi,
Split/Interval Count,
Total Calories Lo,
Total Calories Hi,
Watts Lo,
Watts Hi,
Total Rest Distance Lo (1 m lsb),
Total Rest Distance Mid,
Total Rest Distance High
Interval Rest Time Lo (seconds),
Interval Rest Time Hi,
Avg Calories Lo, (cals/hr)
Avg Calories Hi
*/
var logEntryDate:C2Date
var logEntryTime:C2Time
var intervalType:IntervalType?
var intervalSize:C2IntervalSize
var intervalCount:C2IntervalCount
var totalCalories:C2CalorieCount
var watts:C2Power
var totalRestDistance:C2Distance
var intervalRestTime:C2TimeInterval
var averageCalories:C2CalorieCount
init(fromData data: Data) {
var arr = [UInt8](repeating: 0, count: DataLength)
(data as NSData).getBytes(&arr, length: DataLength)
logEntryDate = 0 // TODO: find date/time format
logEntryTime = 0
intervalType = IntervalType(rawValue: Int(arr[4]))
intervalSize = C2IntervalSize(sizeWithLow: UInt16(arr[5]), high: UInt16(arr[6]))
intervalCount = C2IntervalCount(arr[7])
totalCalories = C2CalorieCount(calorieCountWithLow: UInt16(arr[8]), high: UInt16(arr[9]))
watts = C2Power(powerWithLow: UInt16(arr[10]), high: UInt16(arr[11]))
totalRestDistance = C2Distance(restDistanceWithLow: UInt32(arr[12]), mid: UInt32(arr[13]), high: UInt32(arr[14]))
intervalRestTime = C2TimeInterval(restTimeWithLow: UInt16(arr[15]), high: UInt16(arr[16]))
averageCalories = C2CalorieCount(calorieCountWithLow: UInt16(arr[17]), high: UInt16(arr[18]))
}
// MARK: PerformanceMonitor
func updatePerformanceMonitor(performanceMonitor:PerformanceMonitor) {
// performanceMonitor.logEntryDate.value = logEntryDate
// performanceMonitor.logEntryTime.value = logEntryTime
performanceMonitor.intervalType.value = intervalType
performanceMonitor.intervalSize.value = intervalSize
performanceMonitor.intervalCount.value = intervalCount
performanceMonitor.totalCalories.value = totalCalories
performanceMonitor.watts.value = watts
performanceMonitor.totalRestDistance.value = totalRestDistance
performanceMonitor.intervalRestTime.value = intervalRestTime
performanceMonitor.averageCalories.value = averageCalories
}
// MARK: -
var debugDescription:String {
return "[RowingAdditionalWorkoutSummaryData]"
}
}
|
mit
|
4b0b3c76dd77083f0826fe9191ac1374
| 33.9125 | 117 | 0.736842 | 4.053701 | false | false | false | false |
Henawey/DevTest
|
BonialCodingTest/HomeScreenSceneRouter.swift
|
1
|
2097
|
//
// HomeScreenSceneRouter.swift
// BonialCodingTest
//
// Created by Ahmed Henawey on 10/21/16.
// Copyright (c) 2016 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol HomeScreenSceneRouterInput
{
func navigateToSomewhere()
}
class HomeScreenSceneRouter: HomeScreenSceneRouterInput
{
weak var viewController: HomeScreenSceneViewController!
// MARK: Navigation
func navigateToSomewhere()
{
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: Communication
func passDataToNextScene(segue: UIStoryboardSegue)
{
// NOTE: Teach the router which scenes it can communicate with
// if segue.identifier == "ShowSomewhereScene" {
// passDataToSomewhereScene(segue)
// }
}
func passDataToSomewhereScene(segue: UIStoryboardSegue)
{
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
|
unlicense
|
1eb71631095fbf6a33f45ee506e80d26
| 32.822581 | 110 | 0.745827 | 5.229426 | false | false | false | false |
JoeLago/MHGDB-iOS
|
MHGDB/Common/Categories/NSAttributedString+Swift.swift
|
1
|
1567
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import UIKit
extension NSMutableAttributedString {
func append(string: String) {
append(NSAttributedString(string: string))
}
func append(int: Int) {
append(NSAttributedString(string: "\(int)"))
}
func append(image: UIImage?) {
let attachment = NSTextAttachment()
attachment.image = image
append(NSAttributedString(attachment: attachment))
}
func append(image: UIImage?, rect: CGRect) {
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = rect
append(NSAttributedString(attachment: attachment))
}
// TODO: Potentially want to pass in frame here
func appendImage(named: String) {
let image = UIImage(named: named)
if (image == nil) {
Log(error: "Attributed string image not found: '\(named)'")
}
append(image: image, rect: CGRect(x: 2, y: -3, width: 15, height: 15))
}
}
extension NSMutableAttributedString {
convenience init(damage: Int, element: Element?, elementDamage: Int?, affinity: Int? = nil) {
self.init()
append(string: "\(damage)")
if let elementDamage = elementDamage, elementDamage > 0 {
appendImage(named: (element?.rawValue ?? "") + ".png")
append(string: " \(elementDamage)")
}
if let affinity = affinity, affinity != 0 {
append(string: " \(affinity > 0 ? "+" : "")\(affinity)%")
}
}
}
|
mit
|
62868755e97d150a62e7796720128da8
| 28.566038 | 97 | 0.591576 | 4.477143 | false | false | false | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Sources/Water.swift
|
2
|
1371
|
//
// Water.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import SceneKit
public final class Water: Item, LocationConstructible, NodeConstructible {
// MARK: Static
static let template: SCNNode = {
let resourcePath = "\(WorldConfiguration.resourcesDir)barrier/zon_barrier_water_1x1"
return loadTemplate(named: resourcePath, fileExtension: "scn")
}()
// MARK: Item
public static let identifier: WorldNodeIdentifier = .water
public weak var world: GridWorld?
public let node: NodeWrapper
public var worldIndex = -1
public var isStackable: Bool {
return true
}
public init() {
node = NodeWrapper(identifier: .water)
}
init?(node: SCNNode) {
// Support maps exported with blocks named "Obstacle".
guard node.identifier == .water
|| node.identifierComponents.first == "Obstacle" else { return nil }
self.node = NodeWrapper(node)
}
public func loadGeometry() {
guard scnNode.childNodes.isEmpty else { return }
scnNode.addChildNode(Water.template.clone())
}
}
import PlaygroundSupport
extension Water: MessageConstructor {
// MARK: MessageConstructor
var message: PlaygroundValue {
return .array(baseMessage)
}
}
|
mit
|
ccaead8cee3f3a5b2c217e941971f19d
| 22.237288 | 92 | 0.62655 | 4.600671 | false | false | false | false |
jkolb/Asheron
|
Sources/Asheron/Setup.swift
|
1
|
5920
|
/*
The MIT License (MIT)
Copyright (c) 2020 Justin Kolb
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.
*/
public final class Setup : Identifiable {
public struct Flags : OptionSet, Packable {
public static let hasParentIndex = Flags(rawValue: 1 << 0)
public static let hasDefaultScale = Flags(rawValue: 1 << 1)
public static let allowFreeHeading = Flags(rawValue: 1 << 2)
public static let hasCollisionBSP = Flags(rawValue: 1 << 3)
public let rawValue: UInt32
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
public var id: Identifier
public var parts: [Identifier]
public var parentIndex: [UInt32]
public var defaultScale: [Vector3]
public var allowFreeHeading: Bool
public var hasCollisionBSP: Bool
public var holdingLocations: [UInt32:LocationType]
public var connectionPoints: [UInt32:LocationType]
public var placementFrames: [UInt32:PlacementType]
public var cylSphere: [CylSphere]
public var sphere: [Sphere]
public var height: Float32
public var radius: Float32
public var stepDownHeight: Float32
public var stepUpHeight: Float32
public var sortingSphere: Sphere
public var selectionSphere: Sphere
public var lights: [UInt32:LightInfo]
public var defaultAnimId: Identifier
public var defaultScriptId: Identifier
public var defaultMTable: Identifier
public var defaultSTable: Identifier
public var defaultPhsTable: Identifier
public init(from dataStream: DataStream, id: Identifier) {
let diskId = Identifier(from: dataStream)
precondition(diskId == id)
self.id = id
let flags = Flags(from: dataStream)
self.allowFreeHeading = flags.contains(.allowFreeHeading)
self.hasCollisionBSP = flags.contains(.hasCollisionBSP)
let numParts = Int32(from: dataStream)
self.parts = [Identifier](from: dataStream, count: numericCast(numParts))
self.parentIndex = flags.contains(.hasParentIndex) ? [UInt32](from: dataStream, count: numericCast(numParts)) : []
self.defaultScale = flags.contains(.hasDefaultScale) ? [Vector3](from: dataStream, count: numericCast(numParts)) : []
self.holdingLocations = [UInt32:LocationType](from: dataStream)
self.connectionPoints = [UInt32:LocationType](from: dataStream)
self.placementFrames = [UInt32:PlacementType](from: dataStream, valueCount: numericCast(numParts))
self.cylSphere = [CylSphere](from: dataStream)
self.sphere = [Sphere](from: dataStream)
self.height = Float32(from: dataStream)
self.radius = Float32(from: dataStream)
self.stepDownHeight = Float32(from: dataStream)
self.stepUpHeight = Float32(from: dataStream)
self.sortingSphere = Sphere(from: dataStream)
self.selectionSphere = Sphere(from: dataStream)
self.lights = [UInt32:LightInfo](from: dataStream)
self.defaultAnimId = Identifier(from: dataStream)
self.defaultScriptId = Identifier(from: dataStream)
self.defaultMTable = Identifier(from: dataStream)
self.defaultSTable = Identifier(from: dataStream)
self.defaultPhsTable = Identifier(from: dataStream)
}
}
public struct AnimFrame {
public var frame: [Frame]
public var hooks: [AnimHook]
public init(from dataStream: DataStream, count: Int) {
self.frame = [Frame](from: dataStream, count: count)
self.hooks = [AnimHook](from: dataStream)
}
}
public struct LocationType : Packable {
public var partId: UInt32
public var frame: Frame
public init(from dataStream: DataStream) {
self.partId = UInt32(from: dataStream)
self.frame = Frame(from: dataStream)
}
@inlinable public func encode(to dataStream: DataStream) {
fatalError("Not implemented")
}
}
public struct PlacementType : CountPackable {
public var animFrame: AnimFrame
public init(from dataStream: DataStream, count: Int) {
self.animFrame = AnimFrame(from: dataStream, count: count)
}
}
public enum LightType : Int32 {
case invalid = -1
case point = 0
case distant = 1
case spot = 2
}
public struct LightInfo : Packable {
public var type: LightType
public var offset: Frame
public var color: ARGB8888 // RGBColor
public var intensity: Float32
public var falloff: Float32
public var coneAngle: Float32
public init(from dataStream: DataStream) {
self.type = .invalid
self.offset = Frame(from: dataStream)
self.color = ARGB8888(from: dataStream)
self.intensity = Float32(from: dataStream)
self.falloff = Float32(from: dataStream)
self.coneAngle = Float32(from: dataStream)
}
@inlinable public func encode(to dataStream: DataStream) {
fatalError("Not implemented")
}
}
|
mit
|
094689adbaedfb23d5e15be85cca3cd7
| 37.947368 | 125 | 0.701689 | 4.346549 | false | false | false | false |
Off-Piste/Trolley.io
|
Trolley/Core/Root/Currency/Currency.swift
|
2
|
12971
|
//
// Currency.swift
// Pods
//
// Created by Harry Wright on 31.03.17.
//
//
import Foundation
public enum Currency {
case AED
case AFN
case ALL
case AMD
case ANG
case AOA
case ARS
case AUD
case AWG
case AZN
case BAM
case BBD
case BDT
case BGN
case BHD
case BIF
case BMD
case BND
case BOB
case BRL
case BSD
case BWP
case BYR
case BZD
case CAD
case CHF
case CLP
case CNY
case COP
case CRC
case CUP
case CVE
case CZK
case DJF
case DKK
case DOP
case DZD
case EGP
case ERN
case ETB
case EUR
case FJD
case FKP
case GBP
case GEL
case GHS
case GIP
case GMD
case GNF
case GTQ
case GYD
case HKD
case HNL
case HRK
case HUF
case IDR
case ILS
case INR
case IQD
case IRR
case ISK
case JMD
case JOD
case JPY
case KES
case KGS
case KHR
case KMF
case KPW
case KRW
case KWD
case KYD
case KZT
case LAK
case LBP
case LKR
case LRD
case LYD
case MAD
case MDL
case MGA
case MKD
case MMK
case MNT
case MOP
case MRO
case MUR
case MVR
case MWK
case MXN
case MYR
case MZN
case NGN
case NIO
case NOK
case NPR
case NZD
case OMR
case PEN
case PGK
case PHP
case PKR
case PLN
case PYG
case QAR
case RON
case RSD
case RUB
case RWF
case SAR
case SBD
case SCR
case SDG
case SEK
case SGD
case SHP
case SLL
case SOS
case SRD
case SSP
case STD
case SYP
case SZL
case THB
case TJS
case TMT
case TND
case TOP
case TRY
case TTD
case TWD
case TZS
case UAH
case UGX
case USD
case UYU
case UZS
case VEF
case VND
case VUV
case WST
case XAF
case XCD
case XOF
case XPF
case YER
case ZAR
case ZMW
case ZWL
}
public extension Currency {
init(localeIdentifier: String) {
switch localeIdentifier {
case "AED": self = .AED
case "AFN": self = .AFN
case "ALL": self = .ALL
case "AMD": self = .AMD
case "ANG": self = .ANG
case "AOA": self = .AOA
case "ARS": self = .ARS
case "AUD": self = .AUD
case "AWG": self = .AWG
case "AZN": self = .AZN
case "BAM": self = .BAM
case "BBD": self = .BBD
case "BDT": self = .BDT
case "BGN": self = .BGN
case "BHD": self = .BHD
case "BIF": self = .BIF
case "BMD": self = .BMD
case "BND": self = .BND
case "BOB": self = .BOB
case "BRL": self = .BRL
case "BSD": self = .BSD
case "BWP": self = .BWP
case "BYR": self = .BYR
case "BZD": self = .BZD
case "CAD": self = .CAD
case "CHF": self = .CHF
case "CLP": self = .CLP
case "CNY": self = .CNY
case "COP": self = .COP
case "CRC": self = .CRC
case "CUP": self = .CUP
case "CVE": self = .CVE
case "CZK": self = .CZK
case "DJF": self = .DJF
case "DKK": self = .DKK
case "DOP": self = .DOP
case "DZD": self = .DZD
case "EGP": self = .EGP
case "ERN": self = .ERN
case "ETB": self = .ETB
case "EUR": self = .EUR
case "FJD": self = .FJD
case "FKP": self = .FKP
case "GBP": self = .GBP
case "GEL": self = .GEL
case "GHS": self = .GHS
case "GIP": self = .GIP
case "GMD": self = .GMD
case "GNF": self = .GNF
case "GTQ": self = .GTQ
case "GYD": self = .GYD
case "HKD": self = .HKD
case "HNL": self = .HNL
case "HRK": self = .HRK
case "HUF": self = .HUF
case "IDR": self = .IDR
case "ILS": self = .ILS
case "INR": self = .INR
case "IQD": self = .IQD
case "IRR": self = .IRR
case "ISK": self = .ISK
case "JMD": self = .JMD
case "JOD": self = .JOD
case "JPY": self = .JPY
case "KES": self = .KES
case "KGS": self = .KGS
case "KHR": self = .KHR
case "KMF": self = .KMF
case "KPW": self = .KPW
case "KRW": self = .KRW
case "KWD": self = .KWD
case "KYD": self = .KYD
case "KZT": self = .KZT
case "LAK": self = .LAK
case "LBP": self = .LBP
case "LKR": self = .LKR
case "LRD": self = .LRD
case "LYD": self = .LYD
case "MAD": self = .MAD
case "MDL": self = .MDL
case "MGA": self = .MGA
case "MKD": self = .MKD
case "MMK": self = .MMK
case "MNT": self = .MNT
case "MOP": self = .MOP
case "MRO": self = .MRO
case "MUR": self = .MUR
case "MVR": self = .MVR
case "MWK": self = .MWK
case "MXN": self = .MXN
case "MYR": self = .MYR
case "MZN": self = .MZN
case "NGN": self = .NGN
case "NIO": self = .NIO
case "NOK": self = .NOK
case "NPR": self = .NPR
case "NZD": self = .NZD
case "OMR": self = .OMR
case "PEN": self = .PEN
case "PGK": self = .PGK
case "PHP": self = .PHP
case "PKR": self = .PKR
case "PLN": self = .PLN
case "PYG": self = .PYG
case "QAR": self = .QAR
case "RON": self = .RON
case "RSD": self = .RSD
case "RUB": self = .RUB
case "RWF": self = .RWF
case "SAR": self = .SAR
case "SBD": self = .SBD
case "SCR": self = .SCR
case "SDG": self = .SDG
case "SEK": self = .SEK
case "SGD": self = .SGD
case "SHP": self = .SHP
case "SLL": self = .SLL
case "SOS": self = .SOS
case "SRD": self = .SRD
case "SSP": self = .SSP
case "STD": self = .STD
case "SYP": self = .SYP
case "SZL": self = .SZL
case "THB": self = .THB
case "TJS": self = .TJS
case "TMT": self = .TMT
case "TND": self = .TND
case "TOP": self = .TOP
case "TRY": self = .TRY
case "TTD": self = .TTD
case "TWD": self = .TWD
case "TZS": self = .TZS
case "UAH": self = .UAH
case "UGX": self = .UGX
case "USD": self = .USD
case "UYU": self = .UYU
case "UZS": self = .UZS
case "VEF": self = .VEF
case "VND": self = .VND
case "VUV": self = .VUV
case "WST": self = .WST
case "XAF": self = .XAF
case "XCD": self = .XCD
case "XOF": self = .XOF
case "XPF": self = .XPF
case "YER": self = .YER
case "ZAR": self = .ZAR
case "ZMW": self = .ZMW
case "ZWL": self = .ZWL
default: self = .GBP
}
}
public var description: String{
get{
switch self {
case .AED: return "AED"
case .AFN: return "AFN"
case .ALL: return "ALL"
case .AMD: return "AMD"
case .ANG: return "ANG"
case .AOA: return "AOA"
case .ARS: return "ARS"
case .AUD: return "AUD"
case .AWG: return "AWG"
case .AZN: return "AZN"
case .BAM: return "BAM"
case .BBD: return "BBD"
case .BDT: return "BDT"
case .BGN: return "BGN"
case .BHD: return "BHD"
case .BIF: return "BIF"
case .BMD: return "BMD"
case .BND: return "BND"
case .BOB: return "BOB"
case .BRL: return "BRL"
case .BSD: return "BSD"
case .BWP: return "BWP"
case .BYR: return "BYR"
case .BZD: return "BZD"
case .CAD: return "CAD"
case .CHF: return "CHF"
case .CLP: return "CLP"
case .CNY: return "CNY"
case .COP: return "COP"
case .CRC: return "CRC"
case .CUP: return "CUP"
case .CVE: return "CVE"
case .CZK: return "CZK"
case .DJF: return "DJF"
case .DKK: return "DKK"
case .DOP: return "DOP"
case .DZD: return "DZD"
case .EGP: return "EGP"
case .ERN: return "ERN"
case .ETB: return "ETB"
case .EUR: return "EUR"
case .FJD: return "FJD"
case .FKP: return "FKP"
case .GBP: return "GBP"
case .GEL: return "GEL"
case .GHS: return "GHS"
case .GIP: return "GIP"
case .GMD: return "GMD"
case .GNF: return "GNF"
case .GTQ: return "GTQ"
case .GYD: return "GYD"
case .HKD: return "HKD"
case .HNL: return "HNL"
case .HRK: return "HRK"
case .HUF: return "HUF"
case .IDR: return "IDR"
case .ILS: return "ILS"
case .INR: return "INR"
case .IQD: return "IQD"
case .IRR: return "IRR"
case .ISK: return "ISK"
case .JMD: return "JMD"
case .JOD: return "JOD"
case .JPY: return "JPY"
case .KES: return "KES"
case .KGS: return "KGS"
case .KHR: return "KHR"
case .KMF: return "KMF"
case .KPW: return "KPW"
case .KRW: return "KRW"
case .KWD: return "KWD"
case .KYD: return "KYD"
case .KZT: return "KZT"
case .LAK: return "LAK"
case .LBP: return "LBP"
case .LKR: return "LKR"
case .LRD: return "LRD"
case .LYD: return "LYD"
case .MAD: return "MAD"
case .MDL: return "MDL"
case .MGA: return "MGA"
case .MKD: return "MKD"
case .MMK: return "MMK"
case .MNT: return "MNT"
case .MOP: return "MOP"
case .MRO: return "MRO"
case .MUR: return "MUR"
case .MVR: return "MVR"
case .MWK: return "MWK"
case .MXN: return "MXN"
case .MYR: return "MYR"
case .MZN: return "MZN"
case .NGN: return "NGN"
case .NIO: return "NIO"
case .NOK: return "NOK"
case .NPR: return "NPR"
case .NZD: return "NZD"
case .OMR: return "OMR"
case .PEN: return "PEN"
case .PGK: return "PGK"
case .PHP: return "PHP"
case .PKR: return "PKR"
case .PLN: return "PLN"
case .PYG: return "PYG"
case .QAR: return "QAR"
case .RON: return "RON"
case .RSD: return "RSD"
case .RUB: return "RUB"
case .RWF: return "RWF"
case .SAR: return "SAR"
case .SBD: return "SBD"
case .SCR: return "SCR"
case .SDG: return "SDG"
case .SEK: return "SEK"
case .SGD: return "SGD"
case .SHP: return "SHP"
case .SLL: return "SLL"
case .SOS: return "SOS"
case .SRD: return "SRD"
case .SSP: return "SSP"
case .STD: return "STD"
case .SYP: return "SYP"
case .SZL: return "SZL"
case .THB: return "THB"
case .TJS: return "TJS"
case .TMT: return "TMT"
case .TND: return "TND"
case .TOP: return "TOP"
case .TRY: return "TRY"
case .TTD: return "TTD"
case .TWD: return "TWD"
case .TZS: return "TZS"
case .UAH: return "UAH"
case .UGX: return "UGX"
case .USD: return "USD"
case .UYU: return "UYU"
case .UZS: return "UZS"
case .VEF: return "VEF"
case .VND: return "VND"
case .VUV: return "VUV"
case .WST: return "WST"
case .XAF: return "XAF"
case .XCD: return "XCD"
case .XOF: return "XOF"
case .XPF: return "XPF"
case .YER: return "YER"
case .ZAR: return "ZAR"
case .ZMW: return "ZMW"
case .ZWL: return "ZWL"
}
}
}
/// <#Description#>
public var code: String {
return self.description
}
/// <#Description#>
public var conversionRate: NSDecimalNumber {
return CurrencyConverter.shared.decimalRate
}
/// <#Description#>
///
/// - Parameter value: <#value description#>
/// - Returns: <#return value description#>
public func convert(value: NSDecimalNumber) -> NSDecimalNumber {
return CurrencyConverter.shared.convert(value: value)
}
}
|
mit
|
500cc04be294272dd599b5251a40d1fe
| 25.20404 | 68 | 0.464421 | 3.321639 | false | false | false | false |
stripe/stripe-ios
|
StripeUICore/StripeUICore/Source/Elements/Section/SectionView.swift
|
1
|
2196
|
//
// SectionView.swift
// StripeUICore
//
// Created by Yuki Tokuhiro on 6/4/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
typealias SectionViewModel = SectionElement.ViewModel
/// For internal SDK use only
@objc(STP_Internal_SectionView)
final class SectionView: UIView {
// MARK: - Views
lazy var errorOrSubLabel: UILabel = {
return ElementsUI.makeErrorLabel(theme: viewModel.theme)
}()
let containerView: SectionContainerView
lazy var titleLabel: UILabel = {
return ElementsUI.makeSectionTitleLabel(theme: viewModel.theme)
}()
let viewModel: SectionViewModel
// MARK: - Initializers
init(viewModel: SectionViewModel) {
self.viewModel = viewModel
self.containerView = SectionContainerView(views: viewModel.views, theme: viewModel.theme)
super.init(frame: .zero)
let stack = UIStackView(arrangedSubviews: [titleLabel, containerView, errorOrSubLabel])
stack.axis = .vertical
stack.spacing = 4
addAndPinSubview(stack)
update(with: viewModel)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private methods
func update(with viewModel: SectionViewModel) {
isHidden = viewModel.views.filter({ !$0.isHidden }).isEmpty
guard !isHidden else {
return
}
containerView.updateUI(newViews: viewModel.views)
titleLabel.text = viewModel.title
titleLabel.isHidden = viewModel.title == nil
if let errorText = viewModel.errorText, !errorText.isEmpty {
errorOrSubLabel.text = viewModel.errorText
errorOrSubLabel.isHidden = false
errorOrSubLabel.textColor = viewModel.theme.colors.danger
} else if let subLabel = viewModel.subLabel {
errorOrSubLabel.text = subLabel
errorOrSubLabel.isHidden = false
errorOrSubLabel.textColor = viewModel.theme.colors.secondaryText
} else {
errorOrSubLabel.text = nil
errorOrSubLabel.isHidden = true
}
}
}
|
mit
|
bb0298c937e3217ba4380c2cc167bd4d
| 29.486111 | 97 | 0.652847 | 4.630802 | false | false | false | false |
KeithPiTsui/Pavers
|
Pavers/Sources/UI/Styles/lenses/CAShapeLayerLenses.swift
|
1
|
4333
|
import PaversFRP
import UIKit
public protocol CAShapeLayerProtocol: CALayerProtocol {
/* The path defining the shape to be rendered. If the path extends
* outside the layer bounds it will not automatically be clipped to the
* layer, only if the normal layer masking rules cause that. Upon
* assignment the path is copied. Defaults to null. Animatable.
* (Note that although the path property is animatable, no implicit
* animation will be created when the property is changed.) */
var path: CGPath? {get set}
/* The color to fill the path, or nil for no fill. Defaults to opaque
* black. Animatable. */
var fillColor: CGColor? {get set}
/* The fill rule used when filling the path. Options are `non-zero' and
* `even-odd'. Defaults to `non-zero'. */
var fillRule: CAShapeLayerFillRule {get set}
/* The color to fill the path's stroked outline, or nil for no stroking.
* Defaults to nil. Animatable. */
var strokeColor: CGColor? {get set}
/* These values define the subregion of the path used to draw the
* stroked outline. The values must be in the range [0,1] with zero
* representing the start of the path and one the end. Values in
* between zero and one are interpolated linearly along the path
* length. strokeStart defaults to zero and strokeEnd to one. Both are
* animatable. */
var strokeStart: CGFloat {get set}
var strokeEnd: CGFloat {get set}
/* The line width used when stroking the path. Defaults to one.
* Animatable. */
var lineWidth: CGFloat {get set}
/* The miter limit used when stroking the path. Defaults to ten.
* Animatable. */
var miterLimit: CGFloat {get set}
/* The cap style used when stroking the path. Options are `butt', `round'
* and `square'. Defaults to `butt'. */
var lineCap: CAShapeLayerLineCap {get set}
/* The join style used when stroking the path. Options are `miter', `round'
* and `bevel'. Defaults to `miter'. */
var lineJoin: CAShapeLayerLineJoin {get set}
/* The phase of the dashing pattern applied when creating the stroke.
* Defaults to zero. Animatable. */
var lineDashPhase: CGFloat {get set}
/* The dash pattern (an array of NSNumbers) applied when creating the
* stroked version of the path. Defaults to nil. */
var lineDashPattern: [NSNumber]? {get set}
}
extension CAShapeLayer: CAShapeLayerProtocol {}
extension LensHolder where Object: CAShapeLayerProtocol {
public var path: Lens<Object, CGPath?> {
return Lens(
view: { $0.path },
set: { $1.path = $0; return $1 }
)
}
public var fillColor: Lens<Object, CGColor?> {
return Lens(
view: { $0.fillColor },
set: { $1.fillColor = $0; return $1 }
)
}
public var fillRule: Lens<Object, CAShapeLayerFillRule> {
return Lens(
view: { $0.fillRule },
set: { $1.fillRule = $0; return $1 }
)
}
public var strokeColor: Lens<Object, CGColor?> {
return Lens(
view: { $0.strokeColor },
set: { $1.strokeColor = $0; return $1 }
)
}
public var strokeStart: Lens<Object, CGFloat> {
return Lens(
view: { $0.strokeStart },
set: { $1.strokeStart = $0; return $1 }
)
}
public var strokeEnd: Lens<Object, CGFloat> {
return Lens(
view: { $0.strokeEnd },
set: { $1.strokeEnd = $0; return $1 }
)
}
public var lineWidth: Lens<Object, CGFloat> {
return Lens(
view: { $0.lineWidth },
set: { $1.lineWidth = $0; return $1 }
)
}
public var miterLimit: Lens<Object, CGFloat> {
return Lens(
view: { $0.miterLimit },
set: { $1.miterLimit = $0; return $1 }
)
}
public var lineCap: Lens<Object, CAShapeLayerLineCap> {
return Lens(
view: { $0.lineCap },
set: { $1.lineCap = $0; return $1 }
)
}
public var lineJoin: Lens<Object, CAShapeLayerLineJoin> {
return Lens(
view: { $0.lineJoin },
set: { $1.lineJoin = $0; return $1 }
)
}
public var lineDashPhase: Lens<Object, CGFloat> {
return Lens(
view: { $0.lineDashPhase },
set: { $1.lineDashPhase = $0; return $1 }
)
}
public var lineDashPattern: Lens<Object, [NSNumber]?> {
return Lens(
view: { $0.lineDashPattern },
set: { $1.lineDashPattern = $0; return $1 }
)
}
}
|
mit
|
20a153fb5d2213041d77562eaad9aac7
| 22.421622 | 77 | 0.636511 | 3.907124 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
TableView1/TableView1/ViewController.swift
|
2
|
1673
|
//
// ViewController.swift
// TableView1
//
// Created by bingoogol on 14-6-15.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
var bj:NSArray!
var gd:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
bj = ["东城","西城","宣武","崇文"]
gd = ["广州","佛山","深圳"]
}
// 分组,Section表示表格的组数
func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 2
}
// 每个分组中显示的数据量
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return bj.count
} else {
return gd.count
}
}
// 每个分组中显示的数据内容
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = UITableViewCell(style: UITableViewCellStyle.Default,reuseIdentifier: nil)
if indexPath.section == 0 {
cell.textLabel.text = bj[indexPath.row] as String
} else {
cell.textLabel.text = gd[indexPath.row] as String
}
return cell
}
// 分组的标题
func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
return section == 0 ? "北京":"广东"
}
//
func tableView(tableView: UITableView!, titleForFooterInSection section: Int) -> String! {
return section == 0 ? "北京有烤鸭":"广东有黄飞鸿"
}
}
|
apache-2.0
|
8dca8d708fde900156b3c6a4be847259
| 25.964912 | 112 | 0.594665 | 4.17663 | false | false | false | false |
eric1202/LZJ_Coin
|
LZJ_Coin/LZJ_Coin/Section/JuBi/JuBiCoin.swift
|
1
|
1732
|
//
// JuBiCoin.swift
// LZJ_Coin
//
// Created by Heyz on 2017/5/23.
// Copyright © 2017年 LZJ. All rights reserved.
//
import UIKit
import Alamofire
class JuBiCoin: NSObject {
enum CoinType : String{
case IFC = "ifc"
case EOS = "eos"
case XRP = "xrp"
case NEO = "neo"
}
var highPrice = 0.0
var lowPrice = 0.0
var buyPrice = 0.0
var sellPrice = 0.0
var lastPrice = 0.0
var vol = 0.0
class func getTicker(type:CoinType,completion:@escaping ((_ result:JuBiCoin?,_ error:NSError?)->())) -> () {
let url = String.init(format: "https://www.okex.com/api/v1/ticker.do?symbol=%@_usdt", type.rawValue)
Alamofire.request(url).responseJSON { (res) in
if let err = res.error{
completion(nil,err as NSError)
}else{
if let result : Dictionary = res.value as? Dictionary<String,AnyObject>{
let coin = JuBiCoin.init()
coin.highPrice = Double(result["ticker"]!["high"]! as! String)!
coin.lowPrice = Double(result["ticker"]!["low"]! as! String)!
coin.buyPrice = Double(result["ticker"]!["buy"]! as! String)!
coin.sellPrice = Double(result["ticker"]!["sell"]! as! String)!
coin.lastPrice = Double(result["ticker"]!["last"]! as! String)!
coin.vol = Double(result["ticker"]!["vol"]! as! String)!
completion(coin,nil)
}
else {
completion(nil,NSError.init(domain: "NoneData", code: 1001, userInfo: [NSLocalizedDescriptionKey : "NoneData"]))
}
}
}
}
}
|
mit
|
cf679c92c9da0bd9b4afaae5c91d3959
| 32.25 | 132 | 0.528629 | 3.902935 | false | false | false | false |
diegosanchezr/Chatto
|
ChattoAdditions/Source/Chat Items/PhotoMessages/PhotoMessageViewModel.swift
|
1
|
3537
|
/*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
public enum TransferDirection {
case Upload
case Download
}
public enum TransferStatus {
case Idle
case Transfering
case Failed
case Success
}
public protocol PhotoMessageViewModelProtocol: DecoratedMessageViewModelProtocol {
var transferDirection: Observable<TransferDirection> { get set }
var transferProgress: Observable<Double> { get set} // in [0,1]
var transferStatus: Observable<TransferStatus> { get set }
var image: Observable<UIImage?> { get set }
var imageSize: CGSize { get }
func willBeShown() // Optional
func wasHidden() // Optional
}
public extension PhotoMessageViewModelProtocol {
func willBeShown() {}
func wasHidden() {}
}
public class PhotoMessageViewModel: PhotoMessageViewModelProtocol {
public var photoMessage: PhotoMessageModelProtocol
public var transferStatus: Observable<TransferStatus> = Observable(.Idle)
public var transferProgress: Observable<Double> = Observable(0)
public var transferDirection: Observable<TransferDirection> = Observable(.Download)
public var image: Observable<UIImage?>
public var imageSize: CGSize {
return self.photoMessage.imageSize
}
public let messageViewModel: MessageViewModelProtocol
public var showsFailedIcon: Bool {
return self.messageViewModel.showsFailedIcon || self.transferStatus.value == .Failed
}
public init(photoMessage: PhotoMessageModelProtocol, messageViewModel: MessageViewModelProtocol) {
self.photoMessage = photoMessage
self.image = Observable(photoMessage.image)
self.messageViewModel = messageViewModel
}
public func willBeShown() {
// Need to declare empty. Otherwise subclass code won't execute (as of Xcode 7.2)
}
public func wasHidden() {
// Need to declare empty. Otherwise subclass code won't execute (as of Xcode 7.2)
}
}
public class PhotoMessageViewModelDefaultBuilder: ViewModelBuilderProtocol {
public init() { }
let messageViewModelBuilder = MessageViewModelDefaultBuilder()
public func createViewModel(model: PhotoMessageModel) -> PhotoMessageViewModel {
let messageViewModel = self.messageViewModelBuilder.createMessageViewModel(model)
let photoMessageViewModel = PhotoMessageViewModel(photoMessage: model, messageViewModel: messageViewModel)
return photoMessageViewModel
}
}
|
mit
|
5f06a38f6f30f0da0b95fdd04434de73
| 37.032258 | 114 | 0.754877 | 4.98169 | false | false | false | false |
brentsimmons/Evergreen
|
Mac/Preferences/ExtensionPoints/ExtensionPointEnableBasicWindowController.swift
|
1
|
3529
|
//
// ExtensionPointEnableBasicWindowController.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Cocoa
import AuthenticationServices
import OAuthSwift
import Secrets
class ExtensionPointEnableWindowController: NSWindowController {
@IBOutlet weak var imageView: NSImageView!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var descriptionLabel: NSTextField!
private weak var hostWindow: NSWindow?
private let callbackURL = URL(string: "vincodennw://")!
private var oauth: OAuthSwift?
var extensionPointType: ExtensionPoint.Type?
convenience init() {
self.init(windowNibName: NSNib.Name("ExtensionPointEnableBasic"))
}
override func windowDidLoad() {
super.windowDidLoad()
guard let extensionPointType = extensionPointType else { return }
imageView.image = extensionPointType.templateImage
titleLabel.stringValue = extensionPointType.title
descriptionLabel.attributedStringValue = extensionPointType.description
}
// MARK: API
func runSheetOnWindow(_ hostWindow: NSWindow) {
self.hostWindow = hostWindow
hostWindow.beginSheet(window!)
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
}
@IBAction func enable(_ sender: Any) {
guard let extensionPointType = extensionPointType else { return }
if let oauth1 = extensionPointType as? OAuth1SwiftProvider.Type {
enableOauth1(oauth1)
} else {
ExtensionPointManager.shared.activateExtensionPoint(extensionPointType)
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
}
}
}
extension ExtensionPointEnableWindowController: OAuthSwiftURLHandlerType {
public func handle(_ url: URL) {
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackURL.scheme, completionHandler: { (url, error) in
if let callbackedURL = url {
OAuth1Swift.handle(url: callbackedURL)
}
guard let error = error else { return }
self.oauth?.cancel()
self.oauth = nil
if case ASWebAuthenticationSessionError.canceledLogin = error {
print("Login cancelled.")
} else {
NSApplication.shared.presentError(error)
}
})
session.presentationContextProvider = self
if !session.start() {
print("Session failed to start!!!")
}
}
}
extension ExtensionPointEnableWindowController: ASWebAuthenticationPresentationContextProviding {
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return hostWindow!
}
}
private extension ExtensionPointEnableWindowController {
func enableOauth1(_ provider: OAuth1SwiftProvider.Type) {
let oauth1 = provider.oauth1Swift
self.oauth = oauth1
oauth1.authorizeURLHandler = self
oauth1.authorize(withCallbackURL: callbackURL) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let tokenSuccess):
// let token = tokenSuccess.credential.oauthToken
// let secret = tokenSuccess.credential.oauthTokenSecret
let screenName = tokenSuccess.parameters["screen_name"] as? String ?? ""
print("******************* \(screenName)")
self.hostWindow!.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
case .failure(let oauthSwiftError):
NSApplication.shared.presentError(oauthSwiftError)
}
self.oauth?.cancel()
self.oauth = nil
}
}
}
|
mit
|
5d386bfaa006df731ce5295ecfcb04d3
| 25.526316 | 128 | 0.742347 | 4.131148 | false | false | false | false |
Arty-Maly/Volna
|
Volna/RadioStation.swift
|
1
|
7943
|
//
// RadioStation+CoreDataClass.swift
// Volna
//
// Created by Artem Malyshev on 1/16/17.
// Copyright © 2017 Artem Malyshev. All rights reserved.
//
import Foundation
import CoreData
@objc(RadioStation)
public class RadioStation: NSManagedObject {
class func saveStation(stationInfo: [String: String], inManagedContext context: NSManagedObjectContext) -> RadioStation? {
var radioStation: RadioStation?
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "name = %@", stationInfo["name"]!)
if let station = (try? context.fetch(request))?.first as? RadioStation {
radioStation = station
} else if let station = NSEntityDescription.insertNewObject(forEntityName: "RadioStation", into: context) as? RadioStation {
station.position = Int16(stationInfo["position"]!)!
radioStation = station
}
radioStation?.name = stationInfo["name"]!
radioStation?.url = stationInfo["url"]!
radioStation?.image = stationInfo["image"]!
do {
try context.save()
} catch let error {
print(error)
}
return radioStation
}
class func getStationCountBySearchText(inManagedContext context: NSManagedObjectContext, searchText: String) -> Int {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "name CONTAINS[cd] %@", searchText)
do {
let count = try context.count(for: request)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
}
class func getStationsBySearchText(inManagedContext context: NSManagedObjectContext, searchText: String) -> [RadioStation] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "name CONTAINS[cd] %@", searchText)
if let stations = (try? context.fetch(request)) as? [RadioStation] {
return stations
} else {
fatalError()
}
}
class func getStationCount(inManagedContext context: NSManagedObjectContext) -> Int {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
do {
let count = try context.count(for: request)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
}
class func getStationByPosition(position: Int, inManagedContext context: NSManagedObjectContext) -> RadioStation {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "position = %ld", position)
guard let station = (try? context.fetch(request))?.first else { return findMissingStation(context, missingPosition: position, predicate: "position") }
return station as! RadioStation
}
private class func findMissingStation(_ context: NSManagedObjectContext, missingPosition position: Int, predicate: String) -> RadioStation {
Logger.logDuplicatStationsHappened(position, predicate: predicate)
var positions: [Int16]
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
guard let localStations = (try? context.fetch(request)) as? Array<RadioStation> else {
print("error retrieving stations")
fatalError("error retrieving stations")
}
if predicate == "position" {
positions = localStations.map { return $0.position }
} else {
positions = localStations.filter { $0.favouritePosition != nil }.map { return $0.favouritePosition! }
}
let duplicates = Array(Set(positions.filter({ i in positions.filter({ $0 == i }).count > 1})))
guard duplicates.count > 0, let duplicate = duplicates.first else {
Logger.logCouldNotFindDuplicates(position, array: duplicates, predicate: predicate)
fatalError()
}
request.predicate = NSPredicate(format: "\(predicate) = %ld", duplicate)
let station = (try? context.fetch(request))?.last as! RadioStation
station.position = Int16(position)
do {
try context.save()
} catch let error {
fatalError("error saving missing station \(error)")
}
return station
}
class func getStationByFavouritePositionInRange(range: CountableClosedRange<Int>, inManagedContext context: NSManagedObjectContext) -> [RadioStation] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "favouritePosition >= %ld AND favouritePosition <= %ld", range.lowerBound, range.upperBound)
let stations = (try? context.fetch(request)) as! [RadioStation]
return stations
}
class func getStationByPositionInRange(range: CountableClosedRange<Int>, inManagedContext context: NSManagedObjectContext) -> [RadioStation] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "position >= %ld AND position <= %ld", range.lowerBound, range.upperBound)
let stations = (try? context.fetch(request)) as! [RadioStation]
return stations
}
func toHash() -> [String: String] {
let dict = [ "name": self.name as String,
"url" : self.url as String,
"image": self.image as String
]
return dict
}
class func getFavouritesCount(inManagedContext context: NSManagedObjectContext) -> Int {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "favourite == %@", NSNumber(value: true))
do {
let count = try context.count(for: request)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
}
class func getFavouriteStationByPosition(position: Int, inManagedContext: NSManagedObjectContext) -> RadioStation {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "favouritePosition = %ld", position)
guard let station = (try? inManagedContext.fetch(request))?.first else { return findMissingStation(inManagedContext, missingPosition: position, predicate: "favouritePosition") }
return station as! RadioStation
}
func toggleFavourite(context: NSManagedObjectContext) {
if self.favourite {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RadioStation")
request.predicate = NSPredicate(format: "favouritePosition > %ld", self.favouritePosition!)
let stations = (try? context.fetch(request)) as! [RadioStation]
for station in stations {
station.favouritePosition = station.favouritePosition! - 1
}
self.favouritePosition = nil
} else {
self.favouritePosition = Int16(RadioStation.getFavouritesCount(inManagedContext: context))
}
self.favourite = !self.favourite
do {
try context.save()
} catch let error {
print(error)
}
}
func update(attributes: [String: String]) {
self.image = attributes["image"]!
self.name = attributes["name"]!
self.position = Int16(attributes["position"]!)!
self.url = attributes["url"]!
}
}
|
gpl-3.0
|
a862053581bcd443de98d037e2a4c55a
| 43.870056 | 185 | 0.64417 | 5.020228 | false | false | false | false |
LFL2018/swiftSmpleCode
|
playground_Code/08.The construction and destruction.playground/Contents.swift
|
1
|
2564
|
//16年 05.30 下班回来
import UIKit
///////////////////////// Class /////////////////////////
//: 构造和析构 swift 构造器无返回值(保证每个对象第一次使用前完成正确的初始化)
class DraginLi {
var name :String
var age : Int
var gender : String
// 定义指定初始化
init(name:String,age:Int,gender:String){
self.name = name
self.age = age
self.gender = gender
}
//: 2.0-3.0版本写法 类的便利构造器 : convenience 含有这个关键词则负责创建对象
convenience init(name:String){
self.init(name:name,age: 0,gender: "")
}
//: 3.0 开始,可以不加convenience 便利构造器可以返回nil,节省内存开销
// init?(name:String) {
// if name.isEmpty {
// return nil
// }
// self.init()
// }
}
//let dragonLi = DraginLi() 默认是无参数的构造器
let dragonLi = DraginLi(name: "LFL", age: 23, gender: "学士")
//提示:类后面() 定位其中,按esc ,会提示对应构造器,方便书写
///////////////////////// struct /////////////////////////
struct size {
var width:Double
var height:Double
}
//
let s = size(width: 10, height: 10) // struct 默认提供构造器!
//构造器代理:减少代码重复
struct size1 {
var width:Double
var height:Double
init(width:Double,height:Double){
self.height = height
self.width = width
}
// 下面再提供单个,就是构造器代理代理
init(width:Double){
self.init(width:width,height: 0)
}
}
//
let s1 = size1(width: 10) // struct 默认提供构造器!
s1.height // 也会被初始化0
// 继承
class DragonLiSon: DraginLi {
var player :String = "test"
init (){
super.init(name: "dragon", age: 22, gender: "学士")
// 不可以调用父类的便利构造器
}
// 重写,先调取父类.后面才可以自定义
override init(name:String,age:Int,gender:String){
super.init(name: name, age: age, gender: gender)
self.age = 10
}
// 析构
deinit{
print("deinit")
}
}
//let name1 = DragonLiSon(name: "test") // 没有无参数的构造器
// 一但子类提供了他显示的指定构造器,就不会继承父类的其他构造器.可以测试得知
// init 前面加上required 子类必须实现这个指定构造器
//析构函数:类似于初始化init, 只可以class ,类中只可以一个
//调用:先调用子类,再调用父类
let kkkkk = DragonLiSon(name: "hhhh")
|
mit
|
f8aa555c0f3f3d12e79d5cf01de9a742
| 19.081633 | 59 | 0.572154 | 2.852174 | false | false | false | false |
proxyco/RxBluetoothKit
|
Tests/Utilities.swift
|
1
|
4601
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Polidea
//
// 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 Quick
import Nimble
import RxTests
import RxSwift
import CoreBluetooth
import RxBluetoothKit
//Helps
final class Box<T> {
let value: T
init(value: T) {
self.value = value
}
}
func expectError<ErrorType : Equatable, Element>(event: Event<Element>, errorType: ErrorType, file: String = #file, line: UInt = #line) {
expect(event.isStopEvent, file: file, line: line).to(beTrue())
expect(event.error, file: file, line: line).toNot(beNil())
expect(event.error is ErrorType, file: file, line: line).to(beTrue())
expect(event.error as? ErrorType, file: file, line: line).to(equal(errorType))
}
extension TestScheduler {
func scheduleObservable<Element>(time: ObservableScheduleTimes = ObservableScheduleTimes(), create: () -> Observable<Element>) -> ScheduledObservable<Element> {
var source : Observable<Element>? = nil
var subscription : Disposable? = nil
let observer = createObserver(Element)
self.scheduleAbsoluteVirtual((), time: time.createTime) {
source = create()
return NopDisposable.instance
}
self.scheduleAbsoluteVirtual((), time: time.subscribeTime) {
subscription = source!.subscribe(observer)
return NopDisposable.instance
}
self.scheduleAbsoluteVirtual((), time: time.disposeTime) {
subscription!.dispose()
return NopDisposable.instance
}
return ScheduledObservable(observer: observer, time: time)
}
}
struct ScheduledObservable<Element> {
let observer : TestableObserver<Element>
let time : ObservableScheduleTimes
var createTime : Int {
return time.createTime
}
var subscribeTime : Int {
return time.subscribeTime
}
var disposeTime : Int {
return time.disposeTime
}
var events : [Recorded<Event<Element>>] {
return observer.events
}
}
struct ObservableScheduleTimes {
let createTime : Int
let subscribeTime : Int
let disposeTime : Int
init(createTime: Int, subscribeTime: Int, disposeTime: Int) {
self.createTime = createTime
self.subscribeTime = subscribeTime
self.disposeTime = disposeTime
}
init() {
self.createTime = TestScheduler.Defaults.created
self.subscribeTime = TestScheduler.Defaults.subscribed
self.disposeTime = TestScheduler.Defaults.disposed
}
}
extension ObservableScheduleTimes {
var before : ObservableScheduleTimes {
return ObservableScheduleTimes(createTime: createTime - 1,
subscribeTime: subscribeTime - 1,
disposeTime: disposeTime - 1)
}
var after : ObservableScheduleTimes {
return ObservableScheduleTimes(createTime: createTime + 1,
subscribeTime: subscribeTime + 1,
disposeTime: disposeTime + 1)
}
}
extension BluetoothError {
static var invalidStateErrors : [(BluetoothState, BluetoothError)] {
return [(.PoweredOff, .BluetoothPoweredOff),
(.Resetting, .BluetoothResetting),
(.Unauthorized, .BluetoothUnauthorized),
(.Unknown, .BluetoothInUnknownState),
(.Unsupported, .BluetoothUnsupported)]
}
}
|
mit
|
f5f48cdedf56f06d0b2f2dfb4717ced1
| 33.593985 | 164 | 0.658118 | 4.868783 | false | false | false | false |
ryanbooker/SwiftCheck
|
SwiftCheck/Gen.swift
|
1
|
14224
|
//
// Gen.swift
// SwiftCheck
//
// Created by Robert Widmann on 7/31/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// `Gen` represents a generator for random arbitrary values of type `A`.
///
/// `Gen` wraps a function that, when given a random number generator and a
/// size, can be used to control the distribution of resultant values. A
/// generator relies on its size to help control aspects like the length of
/// generated arrays and the magnitude of integral values.
public struct Gen<A> {
/// The function underlying the receiver.
///
/// +--- An RNG
/// | +--- The size of generated values.
/// | |
/// v v
let unGen : (StdGen, Int) -> A
/// Generates a value.
///
/// This property exists as a convenience mostly to test generators. In
/// practice, you should never use this property because it hinders the
/// replay functionality and the robustness of tests in general.
public var generate : A {
let r = newStdGen()
return unGen(r, 30)
}
/// Generates some example values.
///
/// This property exists as a convenience mostly to test generators. In
/// practice, you should never use this property because it hinders the
/// replay functionality and the robustness of tests in general.
public var sample : [A] {
return sequence((2...20).map { self.resize($0) }).generate
}
/// Constructs a Generator that selects a random value from the given
/// collection and produces only that value.
///
/// The input collection is required to be non-empty.
public static func fromElementsOf<S : Indexable where S.Index : protocol<Comparable, RandomType>>(xs : S) -> Gen<S._Element> {
return Gen.fromElementsIn(xs.startIndex...xs.endIndex.advancedBy(-1)).map { i in
return xs[i]
}
}
/// Constructs a Generator that selects a random value from the given
/// interval and produces only that value.
///
/// The input interval is required to be non-empty.
public static func fromElementsIn<S : IntervalType where S.Bound : RandomType>(xs : S) -> Gen<S.Bound> {
assert(!xs.isEmpty, "Gen.fromElementsOf used with empty interval")
return choose((xs.start, xs.end))
}
/// Constructs a Generator that uses a given array to produce smaller arrays
/// composed of its initial segments. The size of each initial segment
/// increases with the receiver's size parameter.
///
/// The input array is required to be non-empty.
public static func fromInitialSegmentsOf<S>(xs : [S]) -> Gen<[S]> {
assert(!xs.isEmpty, "Gen.fromInitialSegmentsOf used with empty list")
return Gen<[S]>.sized { n in
let ss = xs[xs.startIndex..<max(xs.startIndex.successor(), size(xs.endIndex, n))]
return Gen<[S]>.pure([S](ss))
}
}
/// Constructs a Generator that produces permutations of a given array.
public static func fromShufflingElementsOf<S>(xs : [S]) -> Gen<[S]> {
return choose((Int.min + 1, Int.max)).proliferateSized(xs.count).flatMap { ns in
return Gen<[S]>.pure(Swift.zip(ns, xs).sort({ l, r in l.0 < r.0 }).map { $0.1 })
}
}
/// Constructs a generator that depends on a size parameter.
public static func sized(f : Int -> Gen<A>) -> Gen<A> {
return Gen(unGen: { r, n in
return f(n).unGen(r, n)
})
}
/// Constructs a random element in the range of two `RandomType`s.
///
/// When using this function, it is necessary to explicitly specialize the
/// generic parameter `A`. For example:
///
/// Gen<UInt32>.choose((32, 255)) >>- (Gen<Character>.pure • Character.init • UnicodeScalar.init)
public static func choose<A : RandomType>(rng : (A, A)) -> Gen<A> {
return Gen<A>(unGen: { s, _ in
return A.randomInRange(rng, gen: s).0
})
}
/// Constructs a Generator that randomly selects and uses a particular
/// generator from the given sequence of Generators.
///
/// If control over the distribution of generators is needed, see
/// `Gen.frequency` or `Gen.weighted`.
public static func oneOf<S : CollectionType where S.Generator.Element == Gen<A>, S.Index : protocol<RandomType, BidirectionalIndexType>>(gs : S) -> Gen<A> {
assert(gs.count != 0, "oneOf used with empty list")
return choose((gs.indices.startIndex, gs.indices.endIndex.predecessor())) >>- { x in
return gs[x]
}
}
/// Given a sequence of Generators and weights associated with them, this
/// function randomly selects and uses a Generator.
///
/// Only use this function when you need to assign uneven "weights" to each
/// generator. If all generators need to have an equal chance of being
/// selected, use `Gen.oneOf`.
public static func frequency<S : SequenceType where S.Generator.Element == (Int, Gen<A>)>(xs : S) -> Gen<A> {
let xs: [(Int, Gen<A>)] = Array(xs)
assert(xs.count != 0, "frequency used with empty list")
return choose((1, xs.map({ $0.0 }).reduce(0, combine: +))).flatMap { l in
return pick(l, xs)
}
}
/// Given a list of values and weights associated with them, this function
/// randomly selects and uses a Generator wrapping one of the values.
///
/// This function operates in exactly the same manner as `Gen.frequency`,
/// `Gen.fromElementsOf`, and `Gen.fromElementsIn` but for any type rather
/// than only Generators. It can help in cases where your `Gen.from*` call
/// contains only `Gen.pure` calls by allowing you to remove every
/// `Gen.pure` in favor of a direct list of values.
public static func weighted<S : SequenceType where S.Generator.Element == (Int, A)>(xs : S) -> Gen<A> {
return frequency(xs.map { ($0, Gen.pure($1)) })
}
/// Zips together 2 generators of type `A` and `B` into a generator of pairs.
public static func zip<A, B>(gen1 : Gen<A>, _ gen2 : Gen<B>) -> Gen<(A, B)> {
return gen1.flatMap { l in
return gen2.flatMap { r in
return Gen<(A, B)>.pure((l, r))
}
}
}
}
// MARK: Generator Modifiers
extension Gen {
/// Shakes up the receiver's internal Random Number Generator with a seed.
public func variant<S : IntegerType>(seed : S) -> Gen<A> {
return Gen(unGen: { rng, n in
return self.unGen(vary(seed, rng), n)
})
}
/// Modifies a Generator to always use a given size.
public func resize(n : Int) -> Gen<A> {
return Gen(unGen: { r, _ in
return self.unGen(r, n)
})
}
/// Modifiers a Generator's size parameter by transforming it with the given
/// function.
public func scale(f : Int -> Int) -> Gen<A> {
return Gen.sized { n in
return self.resize(f(n))
}
}
/// Modifies a Generator such that it only returns values that satisfy a
/// predicate. When the predicate fails the test case is treated as though
/// it never occured.
///
/// Because the Generator will spin until it reaches a non-failing case,
/// executing a condition that fails more often than it succeeds may result
/// in a space leak. At that point, it is better to use `suchThatOptional`
/// or `.invert` the test case.
public func suchThat(p : A -> Bool) -> Gen<A> {
return self.suchThatOptional(p).flatMap { mx in
switch mx {
case .Some(let x):
return Gen.pure(x)
case .None:
return Gen.sized { n in
return self.suchThat(p).resize(n.successor())
}
}
}
}
/// Modifies a Generator such that it attempts to generate values that
/// satisfy a predicate. All attempts are encoded in the form of an
/// `Optional` where values satisfying the predicate are wrapped in `.Some`
/// and failing values are `.None`.
public func suchThatOptional(p : A -> Bool) -> Gen<Optional<A>> {
return Gen<Optional<A>>.sized { n in
return attemptBoundedTry(self, 0, max(n, 1), p)
}
}
/// Modifies a Generator such that it produces arrays with a length
/// determined by the receiver's size parameter.
public var proliferate : Gen<[A]> {
return Gen<[A]>.sized { n in
return Gen.choose((0, n)) >>- self.proliferateSized
}
}
/// Modifies a Generator such that it produces non-empty arrays with a
/// length determined by the receiver's size parameter.
public var proliferateNonEmpty : Gen<[A]> {
return Gen<[A]>.sized { n in
return Gen.choose((1, max(1, n))) >>- self.proliferateSized
}
}
/// Modifies a Generator such that it only produces arrays of a given length.
public func proliferateSized(k : Int) -> Gen<[A]> {
return sequence(Array<Gen<A>>(count: k, repeatedValue: self))
}
}
// MARK: Instances
extension Gen /*: Functor*/ {
/// Returns a new generator that applies a given function to any outputs the
/// receiver creates.
public func map<B>(f : A -> B) -> Gen<B> {
return f <^> self
}
}
/// Fmap | Returns a new generator that applies a given function to any outputs
/// the given generator creates.
///
/// This function is most useful for converting between generators of inter-
/// related types. For example, you might have a Generator of `Character`
/// values that you then `.proliferate` into an `Array` of `Character`s. You
/// can then use `fmap` to convert that generator of `Array`s to a generator of
/// `String`s.
public func <^> <A, B>(f : A -> B, g : Gen<A>) -> Gen<B> {
return Gen(unGen: { r, n in
return f(g.unGen(r, n))
})
}
extension Gen /*: Applicative*/ {
/// Lifts a value into a generator that will only generate that value.
public static func pure(a : A) -> Gen<A> {
return Gen(unGen: { _ in
return a
})
}
/// Given a generator of functions, applies any generated function to any
/// outputs the receiver creates.
public func ap<B>(fn : Gen<A -> B>) -> Gen<B> {
return fn <*> self
}
}
/// Ap | Returns a Generator that uses the first given Generator to produce
/// functions and the second given Generator to produce values that it applies
/// to those functions. It can be used in conjunction with <^> to simplify the
/// application of "combining" functions to a large amount of sub-generators.
/// For example:
///
/// struct Foo { let b : Int; let c : Int; let d : Int }
///
/// let genFoo = curry(Foo.init) <^> Int.arbitrary <*> Int.arbitrary <*> Int.arbitrary
///
/// This combinator acts like `zip`, but instead of creating pairs it creates
/// values after applying the zipped function to the zipped value.
///
/// Promotes function application to a Generator of functions applied to a
/// Generator of values.
public func <*> <A, B>(fn : Gen<A -> B>, g : Gen<A>) -> Gen<B> {
return fn >>- { x1 in
return g >>- { x2 in
return Gen.pure(x1(x2))
}
}
}
extension Gen /*: Monad*/ {
/// Applies the function to any generated values to yield a new generator.
/// This generator is then given a new random seed and returned.
///
/// `flatMap` allows for the creation of Generators that depend on other
/// generators. One might, for example, use a Generator of integers to
/// control the length of a Generator of strings, or use it to choose a
/// random index into a Generator of arrays.
public func flatMap<B>(fn : A -> Gen<B>) -> Gen<B> {
return self >>- fn
}
}
/// Applies the function to any generated values to yield a new generator. This
/// generator is then given a new random seed and returned.
///
/// `flatMap` allows for the creation of Generators that depend on other
/// generators. One might, for example, use a Generator of integers to control
/// the length of a Generator of strings, or use it to choose a random index
/// into a Generator of arrays.
public func >>- <A, B>(m : Gen<A>, fn : A -> Gen<B>) -> Gen<B> {
return Gen(unGen: { r, n in
let (r1, r2) = r.split
let m2 = fn(m.unGen(r1, n))
return m2.unGen(r2, n)
})
}
/// Creates and returns a Generator of arrays of values drawn from each
/// generator in the given array.
///
/// The array that is created is guaranteed to use each of the given Generators
/// in the order they were given to the function exactly once. Thus all arrays
/// generated are of the same rank as the array that was given.
public func sequence<A>(ms : [Gen<A>]) -> Gen<[A]> {
return ms.reduce(Gen<[A]>.pure([]), combine: { y, x in
return x.flatMap { x1 in
return y.flatMap { xs in
return Gen<[A]>.pure([x1] + xs)
}
}
})
}
/// Flattens a generator of generators by one level.
public func join<A>(rs : Gen<Gen<A>>) -> Gen<A> {
return rs.flatMap { x in
return x
}
}
/// Lifts a function from some A to some R to a function from generators of A to
/// generators of R.
public func liftM<A, R>(f : A -> R, _ m1 : Gen<A>) -> Gen<R> {
return m1.flatMap{ x1 in
return Gen.pure(f(x1))
}
}
/// Promotes a rose of generators to a generator of rose values.
public func promote<A>(x : Rose<Gen<A>>) -> Gen<Rose<A>> {
return delay().flatMap { (let eval : Gen<A> -> A) in
return Gen<Rose<A>>.pure(liftM(eval, x))
}
}
/// Promotes a function returning generators to a generator of functions.
public func promote<A, B>(m : A -> Gen<B>) -> Gen<A -> B> {
return delay().flatMap { (let eval : Gen<B> -> B) in
return Gen<A -> B>.pure({ x in eval(m(x)) })
}
}
internal func delay<A>() -> Gen<Gen<A> -> A> {
return Gen(unGen: { r, n in
return { g in
return g.unGen(r, n)
}
})
}
// MARK: - Implementation Details
import func Darwin.log
private func vary<S : IntegerType>(k : S, _ rng : StdGen) -> StdGen {
let s = rng.split
let gen = ((k % 2) == 0) ? s.0 : s.1
return (k == (k / 2)) ? gen : vary(k / 2, rng)
}
private func attemptBoundedTry<A>(gen: Gen<A>, _ k : Int, _ bound : Int, _ pred : A -> Bool) -> Gen<Optional<A>> {
if bound == 0 {
return Gen.pure(.None)
}
return gen.resize(2 * k + bound).flatMap { (let x : A) -> Gen<Optional<A>> in
if pred(x) {
return Gen.pure(.Some(x))
}
return attemptBoundedTry(gen, k.successor(), bound - 1, pred)
}
}
private func size<S : IntegerType>(k : S, _ m : Int) -> Int {
let n = Double(m)
return Int((log(n + 1)) * Double(k.toIntMax()) / log(100))
}
private func selectOne<A>(xs : [A]) -> [(A, [A])] {
if xs.isEmpty {
return []
}
let y = xs.first!
let ys = Array(xs[1..<xs.endIndex])
let rec : [(A, Array<A>)] = selectOne(ys).map({ t in (t.0, [y] + t.1) })
return [(y, ys)] + rec
}
private func pick<A>(n : Int, _ lst : [(Int, Gen<A>)]) -> Gen<A> {
let (k, x) = lst[0]
let tl = Array<(Int, Gen<A>)>(lst[1..<lst.count])
if n <= k {
return x
}
return pick(n - k, tl)
}
|
mit
|
3e94b169c365f4325592e376160da598
| 33.019139 | 157 | 0.653376 | 3.271974 | false | false | false | false |
Foild/StatefulViewController
|
StatefulViewController/StatefulViewController.swift
|
1
|
5837
|
//
// StatefulViewController.swift
// StatefulViewController
//
// Created by Alexander Schuch on 30/07/14.
// Copyright (c) 2014 Alexander Schuch. All rights reserved.
//
import UIKit
/// Represents all possible states of this view controller
public enum StatefulViewControllerState: String {
case Content = "content"
case Loading = "loading"
case Error = "error"
case Empty = "empty"
}
/// Delegate protocol
@objc public protocol StatefulViewControllerDelegate {
/// Return true if content is available in your controller.
///
/// - returns: true if there is content available in your controller.
///
func hasContent() -> Bool
/// This method is called if an error occured, but `hasContent` returned true.
/// You would typically display an unobstrusive error message that is easily dismissable
/// for the user to continue browsing content.
///
/// - parameter error: The error that occured
///
optional func handleErrorWhenContentAvailable(error: NSError)
}
///
/// A view controller subclass that presents placeholder views based on content, loading, error or empty states.
///
public class StatefulViewController: UIViewController {
lazy private var stateMachine: ViewStateMachine = ViewStateMachine(view: self.view)
var viewIndex: Int = 0 {
didSet {
stateMachine.viewIndex = viewIndex
}
}
/// The current state of the view controller.
/// All states other than `Content` imply that there is a placeholder view shown.
public var currentState: StatefulViewControllerState {
switch stateMachine.currentState {
case .None: return .Content
case .View(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
public var lastState: StatefulViewControllerState {
switch stateMachine.lastState {
case .None: return .Content
case .View(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
// MARK: Views
/// The loading view is shown when the `startLoading` method gets called
public var loadingView: UIView! {
didSet { setPlaceholderView(loadingView, forState: .Loading) }
}
/// The error view is shown when the `endLoading` method returns an error
public var errorView: UIView! {
didSet { setPlaceholderView(errorView, forState: .Error) }
}
/// The empty view is shown when the `hasContent` method returns false
public var emptyView: UIView! {
didSet { setPlaceholderView(emptyView, forState: .Empty) }
}
// MARK: UIViewController
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Make sure to stay in the correct state when transitioning
let isLoading = (lastState == .Loading)
let error: NSError? = (lastState == .Error) ? NSError(domain: "", code: 0, userInfo: nil) : nil
transitionViewStates(isLoading, error: error, animated: false)
}
// MARK: Start and stop loading
/// Transitions the controller to the loading state and shows
/// the loading view if there is no content shown already.
///
/// - parameter animated: true if the switch to the placeholder view should be animated, false otherwise
///
public func startLoading(animated: Bool = false, completion: (() -> ())? = nil) {
transitionViewStates(true, animated: animated, completion: completion)
}
/// Ends the controller's loading state.
/// If an error occured, the error view is shown.
/// If the `hasContent` method returns false after calling this method, the empty view is shown.
///
/// - parameter animated: true if the switch to the placeholder view should be animated, false otherwise
/// - parameter error: An error that might have occured whilst loading
///
public func endLoading(animated: Bool = true, error: NSError? = nil, completion: (() -> ())? = nil) {
transitionViewStates(false, animated: animated, error: error, completion: completion)
}
// MARK: Update view states
/// Transitions the view to the appropriate state based on the `loading` and `error`
/// input parameters and shows/hides corresponding placeholder views.
///
/// - parameter loading: true if the controller is currently loading
/// - parameter error: An error that might have occured whilst loading
/// - parameter animated: true if the switch to the placeholder view should be animated, false otherwise
///
public func transitionViewStates(loading: Bool = false, error: NSError? = nil, animated: Bool = true, completion: (() -> ())? = nil) {
let hasContent = (self as? StatefulViewControllerDelegate)?.hasContent() ?? true
// Update view for content (i.e. hide all placeholder views)
if hasContent {
if let e = error {
// show unobstrusive error
(self as? StatefulViewControllerDelegate)?.handleErrorWhenContentAvailable?(e)
}
self.stateMachine.transitionToState(.None, animated: animated, completion: completion)
return
}
// Update view for placeholder
var newState: StatefulViewControllerState = .Empty
if loading {
newState = .Loading
} else if let e = error {
newState = .Error
}
self.stateMachine.transitionToState(.View(newState.rawValue), animated: animated, completion: completion)
}
// MARK: Helper
private func setPlaceholderView(view: UIView, forState state: StatefulViewControllerState) {
stateMachine[state.rawValue] = view
}
}
|
mit
|
870c3928c2b2cd4bd24eefcd83688426
| 37.150327 | 138 | 0.658557 | 5.036238 | false | false | false | false |
bhajian/raspi-remote
|
raspi-remote/FirstViewController.swift
|
1
|
6994
|
//
// FirstViewController.swift
// raspi-remote
//
// Created by behnam hajian on 2016-07-13.
// Copyright © 2016 behnam hajian. All rights reserved.
//
import UIKit
import TextToSpeechV1
import AVFoundation
import SpeechToTextV1
import Foundation
class FirstViewController: UIViewController {
var player: AVAudioPlayer?
var captureSession: AVCaptureSession?
var recorder: AVAudioRecorder!
@IBOutlet weak var transcribedLabel: UILabel!
var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var baseServiceUrl = "http://behnam.mybluemix.net/"
override func viewDidLoad() {
super.viewDidLoad()
let document = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let fileName = "speechToTextRecording.wav"
let filePath = NSURL(fileURLWithPath: document + "/" + fileName)
let session = AVAudioSession.sharedInstance()
var settings = [String: AnyObject] ()
settings[AVSampleRateKey] = NSNumber(float: 44100.0)
settings[AVNumberOfChannelsKey] = NSNumber(int: 1)
do{
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
recorder = try AVAudioRecorder(URL: filePath, settings: settings)
} catch{
}
guard let recorder = recorder else {
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func listenTouchDown(sender: UIButton) {
if (!recorder.recording) {
do {
let session = AVAudioSession.sharedInstance()
try session.setActive(true)
recorder.record()
sender.alpha = 1
} catch {
}
} else {
do {
recorder.stop()
sender.alpha = 0.5
let session = AVAudioSession.sharedInstance()
try session.setActive(false)
let username = "87bb86cb-61a5-4742-afec-26a7f23c592e"
let password = "FxxzwmJ5Dgrj"
let speechToText = SpeechToText(username: username, password: password)
let settings = TranscriptionSettings(contentType: .WAV)
let failure = { (error: NSError) in print(error) }
speechToText.transcribe(recorder.url, settings: settings, failure: failure){
result in if let transcription = result.last?.alternatives.last?.transcript{
self.transcribedLabel.text = transcription
let command = transcription.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString
if(command == "forward"){
self.forwardTouchInside(sender)
}
if(command == "backward"){
self.backwardTouchInside(sender)
}
if(command == "turn left"){
self.leftTouchInside(sender)
}
if(command == "turn right"){
self.rightTouchInside(sender)
}
if(command == "stop"){
self.stopTouchInside(sender)
}
if(command == "camera up"){
self.stopTouchInside(sender)
}
if(command == "camera down"){
self.stopTouchInside(sender)
}
if(command == "camera laft"){
self.stopTouchInside(sender)
}
if(command == "camera right"){
self.stopTouchInside(sender)
}
}
}
} catch {}
}
}
private func makeGetRequest(request: NSURLRequest){
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let data = data {
let response = NSString(data: data, encoding: NSUTF8StringEncoding)
print(response)
}
}
task.resume()
}
@IBAction func forwardTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/goForward")!)
makeGetRequest(request);
}
@IBAction func backwardTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/goBackward")!)
makeGetRequest(request);
}
@IBAction func rightTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/turnRight/coarse")!)
makeGetRequest(request);
}
@IBAction func leftTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/turnLeft/coarse")!)
makeGetRequest(request);
}
@IBAction func directionStreightTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/home")!)
makeGetRequest(request);
}
@IBAction func stopTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/stop")!)
makeGetRequest(request);
}
@IBAction func speedValueChanged(sender: UISlider) {
let selectedValue = Int(sender.value)
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/setSpeed/" + String(selectedValue))!)
makeGetRequest(request);
}
@IBAction func cameraUpTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/up")!)
makeGetRequest(request);
}
@IBAction func cameraDownTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/down")!)
makeGetRequest(request);
}
@IBAction func cameraRightTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/right")!)
makeGetRequest(request);
}
@IBAction func cameraLeftTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/left")!)
makeGetRequest(request);
}
@IBAction func cameraHomeTouchInside(sender: AnyObject) {
let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/home")!)
makeGetRequest(request);
}
}
|
mit
|
36c337d51098190fb5ab2477e70f6a6f
| 35.233161 | 140 | 0.566567 | 5.305766 | false | false | false | false |
bhajian/raspi-remote
|
Carthage/Checkouts/ios-sdk/Source/SpeechToTextV1/Models/WordTimestamp.swift
|
1
|
1538
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** The timestamp of a word in a Speech to Text transcription. */
public struct WordTimestamp: JSONDecodable {
/// A particular word from the transcription.
public let word: String
/// The start time, in seconds, of the given word in the audio input.
public let startTime: Double
/// The end time, in seconds, of the given word in the audio input.
public let endTime: Double
/// Used internally to initialize a `WordTimestamp` model from JSON.
public init(json: JSON) throws {
let array = try json.array()
word = try array[Index.Word.rawValue].string()
startTime = try array[Index.StartTime.rawValue].double()
endTime = try array[Index.EndTime.rawValue].double()
}
/// The index of each element in the JSON array.
private enum Index: Int {
case Word = 0
case StartTime = 1
case EndTime = 2
}
}
|
mit
|
80d4b226c2984c91b6472d891118cf42
| 32.434783 | 75 | 0.689857 | 4.381766 | false | false | false | false |
AlesTsurko/DNMKit
|
DNM_iOS/DNM_iOS/BezierCurveStyleWidthVariable.swift
|
1
|
4428
|
//
// BezierCurveStyleWidthVariable.swift
// DNMView
//
// Created by James Bean on 11/6/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class BezierCurveStyleWidthVariable: BezierCurveStyler {
public var widthAtBeginning: CGFloat = 2
public var widthAtEnd: CGFloat = 2
public var exponent: CGFloat = 1
public init(
styledBezierCurve: StyledBezierCurve,
widthAtBeginning: CGFloat,
widthAtEnd: CGFloat,
exponent: CGFloat = 1
)
{
super.init(styledBezierCurve: styledBezierCurve)
self.widthAtBeginning = widthAtBeginning
self.widthAtEnd = widthAtEnd
self.exponent = exponent
addWidths()
}
public required init(styledBezierCurve: StyledBezierCurve) {
super.init(styledBezierCurve: styledBezierCurve)
addWidths()
}
private func addWidths() {
switch exponent {
case 1: addWidthsLinear()
case _ where exponent > 1: addWidthsExponential()
case _ where exponent < 1: addWidthsLogarithmic()
default: break
}
}
private func addWidthsExponential() {
// make switch statement?
if widthAtBeginning > widthAtEnd { addWidthsExponentialDecrease() }
else if widthAtBeginning < widthAtEnd { addWidthsExponentialIncrease() }
else { addWidthsLinear() }
}
private func addWidthsExponentialIncrease() {
let newPath: BezierPath = BezierPath()
let c = carrierCurve
// upper curve
let upper_left = CGPoint(x: c.p1.x, y: c.p1.y - 0.5 * widthAtBeginning)
let upper_right = CGPoint(x: c.p2.x, y: c.p2.y - 0.5 * widthAtEnd)
let upper_cp = CGPoint(x: c.p2.x, y: c.p2.y - 0.5 * widthAtBeginning)
let upperCurve = BezierCurveQuadratic(
point1: upper_left, controlPoint: upper_cp, point2: upper_right
)
newPath.addCurve(upperCurve)
let lower_right = CGPoint(x: c.p2.x, y: c.p2.y + 0.5 * widthAtEnd)
let lower_left = CGPoint(x: c.p1.x, y: c.p1.y + 0.5 * widthAtBeginning)
let lower_cp = CGPoint(x: c.p2.x, y: c.p2.y + 0.5 * widthAtBeginning)
let lowerCurve = BezierCurveQuadratic(
point1: lower_right, controlPoint: lower_cp, point2: lower_left
)
newPath.addCurve(lowerCurve)
bezierPath = newPath
}
private func addWidthsExponentialDecrease() {
let newPath: BezierPath = BezierPath()
let c = carrierCurve
// upper curve
let upper_left = CGPoint(x: c.p1.x, y: c.p1.y - 0.5 * widthAtBeginning)
let upper_right = CGPoint(x: c.p2.x, y: c.p2.y - 0.5 * widthAtEnd)
let upper_cp = CGPoint(x: c.p1.x, y: c.p1.y - 0.5 * widthAtEnd)
let upperCurve = BezierCurveQuadratic(
point1: upper_left, controlPoint: upper_cp, point2: upper_right
)
newPath.addCurve(upperCurve)
let lower_right = CGPoint(x: c.p2.x, y: c.p2.y + 0.5 * widthAtEnd)
let lower_left = CGPoint(x: c.p1.x, y: c.p1.y + 0.5 * widthAtBeginning)
let lower_cp = CGPoint(x: c.p1.x, y: c.p1.y + 0.5 * widthAtEnd)
let lowerCurve = BezierCurveQuadratic(
point1: lower_right, controlPoint: lower_cp, point2: lower_left
)
newPath.addCurve(lowerCurve)
bezierPath = newPath }
private func addWidthsLogarithmic() {
// TODO
addWidthsLinear()
}
private func addWidthsLinear() {
let newPath: BezierPath = BezierPath()
let c = carrierCurve
// upper curve: currently linear
let left_upper = CGPoint(x: c.p1.x, y: c.p1.y - 0.5 * widthAtBeginning)
let right_upper = CGPoint(x: c.p2.x, y: c.p2.y - 0.5 * widthAtEnd)
let upperCurve = BezierCurveLinear(point1: left_upper, point2: right_upper)
newPath.addCurve(upperCurve)
// lower curve: currently linear
let right_lower = CGPoint(x: c.p2.x, y: c.p2.y + 0.5 * widthAtEnd)
let left_lower = CGPoint(x: c.p1.x, y: c.p1.y + 0.5 * widthAtBeginning)
let lowerCurve = BezierCurveLinear(point1: right_lower, point2: left_lower)
newPath.addCurve(lowerCurve)
bezierPath = newPath
}
}
|
gpl-2.0
|
885af906d78dbb967b2e8b1c60d253b3
| 32.801527 | 83 | 0.596341 | 3.786997 | false | false | false | false |
genadyo/Lyft
|
Lyft/Classes/LyftRides.swift
|
1
|
15373
|
//
// LyftRides.swift
// SFParties
//
// Created by Genady Okrain on 5/10/16.
// Copyright © 2016 Okrain. All rights reserved.
//
// Examples:
//
// Lyft.requestRide(requestRideQuery: RequestRideQuery(originLat: 34.305658, originLng: -118.8893667, originAddress: "123 Main St, Anytown, CA", destinationLat: 36.9442175, destinationLng: -123.8679133, destinationAddress: "123 Main St, Anytown, CA", rideType: .Lyft)) { result, response, error in
//
// }
//
// Lyft.requestRideDetails(rideId: "123456789") { result, response, error in
//
// }
//
// Lyft.cancelRide(rideId: "123456789") { result, response, error in
//
// }
//
// Lyft.rateAndTipRide(rideId: "123456789", rateAndTipQuery: RateAndTipQuery(rating: 5, tipAmount: 100, tipCurrency: "USA", feedback: "great ride!") { result, response, error in
//
// }
//
// Lyft.requestRideReceipt(rideId: "123456789") { result, response, error in
//
// }
//
// Lyft.requestRidesHistory(ridesHistoryQuery: RidesHistoryQuery(startTime: "2015-12-01T21:04:22Z", endTime: "2015-12-04T21:04:22Z", limit: "10")) { result, response, error in
//
// }
import Foundation
public extension Lyft {
static func requestRide(requestRideQuery: RequestRideQuery, completionHandler: ((_ result: Ride?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.POST, path: "/rides", params: [
"origin": ["lat": "\(requestRideQuery.origin.lat)", "lng": "\(requestRideQuery.origin.lng)", "address": "\(requestRideQuery.origin.address)"] as AnyObject,
"destination": ["lat": "\(requestRideQuery.destination.lat)", "lng": "\(requestRideQuery.destination.lng)", "address": "\(requestRideQuery.destination.address)"] as AnyObject,
"ride_type": requestRideQuery.rideType.rawValue as AnyObject,
"primetime_confirmation_token": requestRideQuery.primetimeConfirmationToken as AnyObject]
) { response, error in
if let response = response {
if let passenger = response["passenger"] as? [String: AnyObject],
let passengerFirstName = passenger["first_name"] as? String,
let origin = response["origin"] as? [String: AnyObject],
let originAddress = origin["address"] as? String,
let originLat = origin["lat"] as? Float,
let originLng = origin["lng"] as? Float,
let destination = response["destination"] as? [String: AnyObject],
let destinationAddress = destination["address"] as? String,
let destinationLat = destination["lat"] as? Float,
let destinationLng = destination["lng"] as? Float,
let s = response["status"] as? String,
let status = StatusType(rawValue: s),
let rideId = response["ride_id"] as? String {
let origin = Address(lat: originLat, lng: originLng, address: originAddress)
let destination = Address(lat: destinationLat, lng: destinationLng, address: destinationAddress)
let passenger = Passenger(firstName: passengerFirstName)
let ride = Ride(rideId: rideId, status: status, origin: origin, destination: destination, passenger: passenger)
completionHandler?(ride, response, nil)
return
}
}
completionHandler?(nil, response, error)
}
}
static func requestRideDetails(rideId: String, completionHandler: ((_ result: Ride?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.GET, path: "/rides/\(rideId)", params: nil) { response, error in
if let response = response {
if let passenger = response["passenger"] as? [String: AnyObject],
let firstName = passenger["first_name"] as? String,
let origin = response["origin"] as? [String: AnyObject],
let originAddress = origin["address"] as? String,
let originLat = origin["lat"] as? Float,
let originLng = origin["lng"] as? Float,
let destination = response["destination"] as? [String: AnyObject],
let destinationAddress = destination["address"] as? String,
let destinationLat = destination["lat"] as? Float,
let destinationLng = destination["lng"] as? Float,
let s = response["status"] as? String,
let status = StatusType(rawValue: s),
let rideId = response["ride_id"] as? String {
let origin = Address(lat: originLat, lng: originLng, address: originAddress)
let destination = Address(lat: destinationLat, lng: destinationLng, address: destinationAddress)
let passenger = Passenger(firstName: firstName)
let ride = Ride(rideId: rideId, status: status, origin: origin, destination: destination, passenger: passenger)
completionHandler?(ride, response, nil)
return
}
}
completionHandler?(nil, response, error)
}
}
static func cancelRide(rideId: String, cancelConfirmationToken: String? = nil, completionHandler: ((_ result: CancelConfirmationToken?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.POST, path: "/rides/\(rideId)/cancel", params: (cancelConfirmationToken != nil) ? (["cancel_confirmation_token": cancelConfirmationToken!] as AnyObject) as? [String : AnyObject] : nil) { response, error in
if let response = response {
if let amount = response["amount"] as? Int,
let currency = response["currency"] as? String,
let token = response["token"] as? String,
let tokenDuration = response["token_duration"] as? Int {
completionHandler?(CancelConfirmationToken(amount: amount, currency: currency, token: token, tokenDuration: tokenDuration), response, nil)
return
}
}
completionHandler?(nil, response, error)
}
}
static func rateAndTipRide(rideId: String, rateAndTipQuery: RateAndTipQuery, completionHandler: ((_ result: AnyObject?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.PUT, path: "/rides/\(rideId)/rating", params: [
"rating": rateAndTipQuery.rating as AnyObject,
"tip": ["amount": rateAndTipQuery.tip.amount, "currency": rateAndTipQuery.tip.currency] as AnyObject,
"feedback": rateAndTipQuery.feedback as AnyObject])
{ response, error in
completionHandler?(nil, response, error)
}
}
static func requestRideReceipt(rideId: String, completionHandler: ((_ result: RideReceipt?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.GET, path: "/rides/\(rideId)/receipt", params: nil) { response, error in
if let response = response {
if let rideId = response["ride_id"] as? String,
let price = response["price"] as? [String: AnyObject],
let priceAmount = price["amount"] as? Int,
let priceCurrency = price["currency"] as? String,
let priceDescription = price["description"] as? String,
let lineItems = response["line_items"] as? [AnyObject],
let charges = response["charges"] as? [AnyObject],
let requestedAt = response["requested_at"] as? String {
var l = [LineItem]()
for lineItem in lineItems {
if let amount = lineItem["amount"] as? Int, let currency = lineItem["currency"] as? String, let type = lineItem["type"] as? String {
l.append(LineItem(amount: amount, currency: currency, type: type))
}
}
var c = [Charge]()
for charge in charges {
if let amount = charge["amount"] as? Int, let currency = charge["currency"] as? String, let paymentMethod = charge["payment_method"] as? String {
c.append(Charge(amount: amount, currency: currency, paymentMethod: paymentMethod))
}
}
let price = Price(amount: priceAmount, currency: priceCurrency, description: priceDescription)
completionHandler?(RideReceipt(rideId: rideId, price: price, lineItems: l, charge: c, requestedAt: requestedAt), response, nil)
return
}
}
completionHandler?(nil, response, error)
}
}
static func requestRidesHistory(ridesHistoryQuery: RidesHistoryQuery, completionHandler: ((_ result: [RideHistory]?, _ response: [String: AnyObject]?, _ error: NSError?) -> ())?) {
request(.GET, path: "/rides", params: ["start_time": ridesHistoryQuery.startTime as AnyObject, "end_time": ridesHistoryQuery.endTime as AnyObject, "limit": ridesHistoryQuery.limit as AnyObject])
{ response, error in
var ridesHistory = [RideHistory]()
if let response = response, let rideHistory = response["ride_history"] as? [AnyObject] {
for r in rideHistory {
if let rideId = r["ride_id"] as? String,
let s = r["status"] as? String,
let status = StatusType(rawValue: s),
let rType = r["ride_type"] as? String,
let rideType = RideType(rawValue: rType),
let passenger = r["passenger"] as? [String: AnyObject],
let passengerFirstName = passenger["first_name"] as? String,
let driver = r["driver"] as? [String: AnyObject],
let driverFirstName = driver["first_name"] as? String,
let driverPhoneNumber = driver["phone_number"] as? String,
let driverRating = driver["rating"] as? Float,
let driverImageURL = driver["image_url"] as? String,
let vehicle = r["vehicle"] as? [String: AnyObject],
let vehicleMake = vehicle["make"] as? String,
let vehicleModel = vehicle["model"] as? String,
let vehicleLicensePlate = vehicle["license_plate"] as? String,
let vehicleCode = vehicle["color"] as? String,
let vehicleImageURL = vehicle["image_url"] as? String,
let origin = r["origin"] as? [String: AnyObject],
let originLat = origin["lat"] as? Float,
let originLng = origin["lng"] as? Float,
let originAddress = origin["address"] as? String,
let originETASeconds = origin["eta_seconds"] as? Int,
let destination = r["destination"] as? [String: AnyObject],
let destinationLat = destination["lat"] as? Float,
let destinationLng = destination["lng"] as? Float,
let destinationAddress = destination["address"] as? String,
let destinationETASeconds = destination["eta_seconds"] as? Int,
let pickup = r["pickup"] as? [String: AnyObject],
let pickupLat = pickup["lat"] as? Float,
let pickupLng = pickup["lng"] as? Float,
let pickupAddress = pickup["address"] as? String,
let pickupTime = pickup["time"] as? String,
let dropoff = r["dropoff"] as? [String: AnyObject],
let dropoffLat = dropoff["lat"] as? Float,
let dropoffLng = dropoff["lng"] as? Float,
let dropoffAddress = dropoff["address"] as? String,
let dropoffTime = dropoff["time"] as? String,
let location = r["location"] as? [String: AnyObject],
let locationLat = location["lat"] as? Float,
let locationLng = location["lng"] as? Float,
let locationAddress = location["address"] as? String,
let primetimePercentage = r["primetime_percentage"] as? String,
let price = r["price"] as? [String: AnyObject],
let priceAmount = price["amount"] as? Int,
let priceCurrency = price["currency"] as? String,
let priceDescription = price["description"] as? String,
let lineItems = r["line_items"] as? [AnyObject],
let ETASeconds = r["eta_seconds"] as? Int,
let requestedAt = r["requested_at"] as? String {
let passenger = Passenger(firstName: passengerFirstName)
let driver = Driver(firstName: driverFirstName, phoneNumber: driverPhoneNumber, rating: driverRating, imageURL: driverImageURL)
let vehicle = Vehicle(make: vehicleMake, model: vehicleModel, licensePlate: vehicleLicensePlate, color: vehicleCode, imageURL: vehicleImageURL)
let origin = Address(lat: originLat, lng: originLng, address: originAddress, ETASeconds: originETASeconds)
let destination = Address(lat: destinationLat, lng: destinationLng, address: destinationAddress, ETASeconds: destinationETASeconds)
let pickup = Address(lat: pickupLat, lng: pickupLng, address: pickupAddress, time: pickupTime)
let dropoff = Address(lat: dropoffLat, lng: dropoffLng, address: dropoffAddress, time: dropoffTime)
let location = Address(lat: locationLat, lng: locationLng, address: locationAddress)
let price = Price(amount: priceAmount, currency: priceCurrency, description: priceDescription)
var l = [LineItem]()
for lineItem in lineItems {
if let amount = lineItem["amount"] as? Int, let currency = lineItem["currency"] as? String, let type = lineItem["type"] as? String {
l.append(LineItem(amount: amount, currency: currency, type: type))
}
}
let rideHistory = RideHistory(rideId: rideId, status: status, rideType: rideType, passenger: passenger, driver: driver, vehicle: vehicle, origin: origin, destination: destination, pickup: pickup, dropoff: dropoff, location: location, primetimePercentage: primetimePercentage, price: price, lineItems: l, ETAseconds: ETASeconds, requestedAt: requestedAt)
ridesHistory.append(rideHistory)
}
}
}
completionHandler?(ridesHistory, response, error)
}
}
}
|
mit
|
e14387b255db448ba53369f383a53407
| 64.412766 | 377 | 0.565964 | 4.762082 | false | false | false | false |
anas10/Monumap
|
Monumap/Network/Serialization/Observable+JSONSerializable.swift
|
1
|
1974
|
//
// Observable+JSONSerializable.swift
// Monumap
//
// Created by Anas Ait Ali on 19/03/2017.
// Copyright © 2017 Anas Ait Ali. All rights reserved.
//
import Foundation
import Moya
import RxSwift
extension Observable {
typealias JSONDictionary = [String: Any]
// Get given JSONified data, pass back objects
func mapToObject<B: JSONSerializable>(_ classType: B.Type, key: String? = nil) -> Observable<B> {
return self.map { json in
guard let dict = json as? JSONDictionary else {
throw JSONSerializationError.invalidJSON
}
if let key = key {
if let value = dict[key] {
guard let jsonDict = value as? JSONDictionary else {
throw JSONSerializationError.invalidJSON
}
return try B(json: jsonDict)
} else { throw JSONSerializationError.missing(key) }
}
return try B(json: dict)
}
}
// Get given JSONified data, pass back objects as an array
func mapToObjectArray<B: JSONSerializable>(_ classType: B.Type, key: String? = nil) -> Observable<[B]> {
return self.map { json in
if let key = key {
guard let dict = json as? JSONDictionary else {
throw JSONSerializationError.invalidJSON
}
if let value = dict[key] {
return try self.jsonToObjectArray(B.self, json: value)
} else { throw JSONSerializationError.missing(key) }
}
return try self.jsonToObjectArray(B.self, json: json)
}
}
fileprivate func jsonToObjectArray<T, B: JSONSerializable>(_ classType: B.Type, json: T) throws -> [B] {
guard let array = json as? [JSONDictionary] else {
throw JSONSerializationError.invalidJSON
}
return try array.map { try B(json: $0) }
}
}
|
apache-2.0
|
e1204b090a53732046a765cc34f2d395
| 29.828125 | 108 | 0.571718 | 4.754217 | false | false | false | false |
Kinglioney/DouYuTV
|
DouYuTV/DouYuTV/Classes/Main/View/CollectionBaseCell.swift
|
1
|
1164
|
//
// CollectionBaseCell.swift
// DouYuTV
//
// Created by apple on 2017/7/19.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionBaseCell: UICollectionViewCell {
//MARK:- 控件属性
@IBOutlet weak var icoImageView: UIImageView!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var onlineBtn: UIButton!
//MARK:- 定义模型属性
var anchor : AnchoModel? {
didSet{
//0、校验模型是否有值
guard let anchor = anchor else {return}
//1、取出在线人数显示
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online))万在线"
}else{
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
//2、昵称的显示
nickNameLabel.text = anchor.nickname
//3、设置封面图片
guard let imageURL = URL(string: anchor.vertical_src) else{return}
icoImageView.kf.setImage(with: imageURL)
}
}
}
|
mit
|
49bbad54e1150251cb64f677821958ba
| 24.452381 | 79 | 0.571562 | 4.310484 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/Workspace/DefaultPluginScriptRunner.swift
|
2
|
31518
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Foundation
import PackageGraph
import PackageModel
import SPMBuildCore
import TSCBasic
import struct TSCUtility.SerializedDiagnostics
import struct TSCUtility.Triple
/// A plugin script runner that compiles the plugin source files as an executable binary for the host platform, and invokes it as a subprocess.
public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable {
private let fileSystem: FileSystem
private let cacheDir: AbsolutePath
private let toolchain: UserToolchain
private let enableSandbox: Bool
private let cancellator: Cancellator
private let verboseOutput: Bool
private let sdkRootCache = ThreadSafeBox<AbsolutePath>()
public init(fileSystem: FileSystem, cacheDir: AbsolutePath, toolchain: UserToolchain, enableSandbox: Bool = true, verboseOutput: Bool = false) {
self.fileSystem = fileSystem
self.cacheDir = cacheDir
self.toolchain = toolchain
self.enableSandbox = enableSandbox
self.cancellator = Cancellator(observabilityScope: .none)
self.verboseOutput = verboseOutput
}
/// Starts evaluating a plugin by compiling it and running it as a subprocess. The name is used as the basename for the executable and auxiliary files. The tools version controls the availability of APIs in PackagePlugin, and should be set to the tools version of the package that defines the plugin (not the package containing the target to which it is being applied). This function returns immediately and then repeated calls the output handler on the given callback queue as plain-text output is received from the plugin, and then eventually calls the completion handler on the given callback queue once the plugin is done.
public func runPluginScript(
sourceFiles: [AbsolutePath],
pluginName: String,
initialMessage: Data,
toolsVersion: ToolsVersion,
workingDirectory: AbsolutePath,
writableDirectories: [AbsolutePath],
readOnlyDirectories: [AbsolutePath],
fileSystem: FileSystem,
observabilityScope: ObservabilityScope,
callbackQueue: DispatchQueue,
delegate: PluginScriptCompilerDelegate & PluginScriptRunnerDelegate,
completion: @escaping (Result<Int32, Error>) -> Void
) {
// If needed, compile the plugin script to an executable (asynchronously). Compilation is skipped if the plugin hasn't changed since it was last compiled.
self.compilePluginScript(
sourceFiles: sourceFiles,
pluginName: pluginName,
toolsVersion: toolsVersion,
observabilityScope: observabilityScope,
callbackQueue: DispatchQueue.sharedConcurrent,
delegate: delegate,
completion: {
dispatchPrecondition(condition: .onQueue(DispatchQueue.sharedConcurrent))
switch $0 {
case .success(let result):
if result.succeeded {
// Compilation succeeded, so run the executable. We are already running on an asynchronous queue.
self.invoke(
compiledExec: result.executableFile,
workingDirectory: workingDirectory,
writableDirectories: writableDirectories,
readOnlyDirectories: readOnlyDirectories,
initialMessage: initialMessage,
observabilityScope: observabilityScope,
callbackQueue: callbackQueue,
delegate: delegate,
completion: completion)
}
else {
// Compilation failed, so throw an error.
callbackQueue.async { completion(.failure(DefaultPluginScriptRunnerError.compilationFailed(result))) }
}
case .failure(let error):
// Compilation failed, so just call the callback block on the appropriate queue.
callbackQueue.async { completion(.failure(error)) }
}
}
)
}
public var hostTriple: Triple {
return self.toolchain.triple
}
/// Starts compiling a plugin script asynchronously and when done, calls the completion handler on the callback queue with the results (including the path of the compiled plugin executable and with any emitted diagnostics, etc). Existing compilation results that are still valid are reused, if possible. This function itself returns immediately after starting the compile. Note that the completion handler only receives a `.failure` result if the compiler couldn't be invoked at all; a non-zero exit code from the compiler still returns `.success` with a full compilation result that notes the error in the diagnostics (in other words, a `.failure` result only means "failure to invoke the compiler").
public func compilePluginScript(
sourceFiles: [AbsolutePath],
pluginName: String,
toolsVersion: ToolsVersion,
observabilityScope: ObservabilityScope,
callbackQueue: DispatchQueue,
delegate: PluginScriptCompilerDelegate,
completion: @escaping (Result<PluginCompilationResult, Error>) -> Void
) {
// Determine the path of the executable and other produced files.
let execName = pluginName.spm_mangledToC99ExtendedIdentifier()
#if os(Windows)
let execSuffix = ".exe"
#else
let execSuffix = ""
#endif
let execFilePath = self.cacheDir.appending(component: execName + execSuffix)
let diagFilePath = self.cacheDir.appending(component: execName + ".dia")
observabilityScope.emit(debug: "Compiling plugin to executable at \(execFilePath)")
// Construct the command line for compiling the plugin script(s).
// FIXME: Much of this is similar to what the ManifestLoader is doing. This should be consolidated.
// We use the toolchain's Swift compiler for compiling the plugin.
var commandLine = [self.toolchain.swiftCompilerPathForManifests.pathString]
observabilityScope.emit(debug: "Using compiler \(self.toolchain.swiftCompilerPathForManifests.pathString)")
// Get access to the path containing the PackagePlugin module and library.
let pluginLibraryPath = self.toolchain.swiftPMLibrariesLocation.pluginLibraryPath
// if runtimePath is set to "PackageFrameworks" that means we could be developing SwiftPM in Xcode
// which produces a framework for dynamic package products.
if pluginLibraryPath.extension == "framework" {
commandLine += [
"-F", pluginLibraryPath.parentDirectory.pathString,
"-framework", "PackagePlugin",
"-Xlinker", "-rpath", "-Xlinker", pluginLibraryPath.parentDirectory.pathString,
]
} else {
commandLine += [
"-L", pluginLibraryPath.pathString,
"-lPackagePlugin",
]
#if !os(Windows)
// -rpath argument is not supported on Windows,
// so we add runtimePath to PATH when executing the manifest instead
commandLine += ["-Xlinker", "-rpath", "-Xlinker", pluginLibraryPath.pathString]
#endif
}
#if os(macOS)
// On macOS earlier than 12, add an rpath to the directory that contains the concurrency fallback library.
if #available(macOS 12.0, *) {
// Nothing is needed; the system has everything we need.
}
else {
// Add an `-rpath` so the Swift 5.5 fallback libraries can be found.
let swiftSupportLibPath = self.toolchain.swiftCompilerPathForManifests.parentDirectory.parentDirectory.appending(components: "lib", "swift-5.5", "macosx")
commandLine += ["-Xlinker", "-rpath", "-Xlinker", swiftSupportLibPath.pathString]
}
#endif
// Use the same minimum deployment target as the PackageDescription library (with a fallback of 10.15).
#if os(macOS)
let version = self.toolchain.swiftPMLibrariesLocation.pluginLibraryMinimumDeploymentTarget.versionString
commandLine += ["-target", self.hostTriple.tripleString(forPlatformVersion: version)]
#endif
// Add any extra flags required as indicated by the ManifestLoader.
commandLine += self.toolchain.swiftCompilerFlags
commandLine.append("-g")
// Add the Swift language version implied by the package tools version.
commandLine += ["-swift-version", toolsVersion.swiftLanguageVersion.rawValue]
// Add the PackageDescription version specified by the package tools version, which controls what PackagePlugin API is seen.
commandLine += ["-package-description-version", toolsVersion.description]
// if runtimePath is set to "PackageFrameworks" that means we could be developing SwiftPM in Xcode
// which produces a framework for dynamic package products.
if pluginLibraryPath.extension == "framework" {
commandLine += ["-I", pluginLibraryPath.parentDirectory.parentDirectory.pathString]
} else {
commandLine += ["-I", pluginLibraryPath.pathString]
}
#if os(macOS)
if let sdkRoot = self.toolchain.sdkRootPath ?? self.sdkRoot() {
commandLine += ["-sdk", sdkRoot.pathString]
}
#endif
// Honor any module cache override that's set in the environment.
let moduleCachePath = ProcessEnv.vars["SWIFTPM_MODULECACHE_OVERRIDE"] ?? ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"]
if let moduleCachePath = moduleCachePath {
commandLine += ["-module-cache-path", moduleCachePath]
}
// Parse the plugin as a library so that `@main` is supported even though there might be only a single source file.
commandLine += ["-parse-as-library"]
// Ask the compiler to create a diagnostics file (we'll put it next to the executable).
commandLine += ["-Xfrontend", "-serialize-diagnostics-path", "-Xfrontend", diagFilePath.pathString]
// Add all the source files that comprise the plugin scripts.
commandLine += sourceFiles.map { $0.pathString }
// Finally add the output path of the compiled executable.
commandLine += ["-o", execFilePath.pathString]
if (verboseOutput) {
commandLine.append("-v")
}
// Pass through the compilation environment.
let environment = toolchain.swiftCompilerEnvironment
// First try to create the output directory.
do {
observabilityScope.emit(debug: "Plugin compilation output directory '\(execFilePath.parentDirectory)'")
try FileManager.default.createDirectory(at: execFilePath.parentDirectory.asURL, withIntermediateDirectories: true, attributes: nil)
}
catch {
// Bail out right away if we didn't even get this far.
return callbackQueue.async {
completion(.failure(DefaultPluginScriptRunnerError.compilationPreparationFailed(error: error)))
}
}
// Hash the compiler inputs to decide whether we really need to recompile.
let compilerInputHash: String?
do {
// Include the full compiler arguments and environment, and the contents of the source files.
let stream = BufferedOutputByteStream()
stream <<< commandLine
for (key, value) in toolchain.swiftCompilerEnvironment.sorted(by: { $0.key < $1.key }) {
stream <<< "\(key)=\(value)\n"
}
for sourceFile in sourceFiles {
try stream <<< fileSystem.readFileContents(sourceFile).contents
}
compilerInputHash = stream.bytes.sha256Checksum
observabilityScope.emit(debug: "Computed hash of plugin compilation inputs: \(compilerInputHash!)")
}
catch {
// We couldn't compute the hash. We warn about it but proceed with the compilation (a cache miss).
observabilityScope.emit(debug: "Couldn't compute hash of plugin compilation inputs (\(error))")
compilerInputHash = .none
}
/// Persisted information about the last time the compiler was invoked.
struct PersistedCompilationState: Codable {
var commandLine: [String]
var environment: [String:String]
var inputHash: String?
var output: String
var result: Result
enum Result: Equatable, Codable {
case exit(code: Int32)
case abnormal(exception: UInt32)
case signal(number: Int32)
init(_ processExitStatus: ProcessResult.ExitStatus) {
switch processExitStatus {
case .terminated(let code):
self = .exit(code: code)
#if os(Windows)
case .abnormal(let exception):
self = .abnormal(exception: exception)
#else
case .signalled(let signal):
self = .signal(number: signal)
#endif
}
}
}
var succeeded: Bool {
return result == .exit(code: 0)
}
}
// Check if we already have a compiled executable and a persisted state (we only recompile if things have changed).
let stateFilePath = self.cacheDir.appending(component: execName + "-state" + ".json")
var compilationState: PersistedCompilationState? = .none
if fileSystem.exists(execFilePath) && fileSystem.exists(stateFilePath) {
do {
// Try to load the previous compilation state.
let previousState = try JSONDecoder.makeWithDefaults().decode(
path: stateFilePath,
fileSystem: fileSystem,
as: PersistedCompilationState.self)
// If it succeeded last time and the compiler inputs are the same, we don't need to recompile.
if previousState.succeeded && previousState.inputHash == compilerInputHash {
compilationState = previousState
}
}
catch {
// We couldn't read the compilation state file even though it existed. We warn about it but proceed with recompiling.
observabilityScope.emit(debug: "Couldn't read previous compilation state (\(error))")
}
}
// If we still have a compilation state, it means the executable is still valid and we don't need to do anything.
if let compilationState = compilationState {
// Just call the completion handler with the persisted results.
let result = PluginCompilationResult(
succeeded: compilationState.succeeded,
commandLine: commandLine,
executableFile: execFilePath,
diagnosticsFile: diagFilePath,
compilerOutput: compilationState.output,
cached: true)
delegate.skippedCompilingPlugin(cachedResult: result)
return callbackQueue.async {
completion(.success(result))
}
}
// Otherwise we need to recompile. We start by telling the delegate.
delegate.willCompilePlugin(commandLine: commandLine, environment: environment)
// Clean up any old files to avoid confusion if the compiler can't be invoked.
do {
try fileSystem.removeFileTree(execFilePath)
try fileSystem.removeFileTree(diagFilePath)
try fileSystem.removeFileTree(stateFilePath)
}
catch {
observabilityScope.emit(debug: "Couldn't clean up before invoking compiler (\(error))")
}
// Now invoke the compiler asynchronously.
TSCBasic.Process.popen(arguments: commandLine, environment: environment, queue: callbackQueue) {
// We are now on our caller's requested callback queue, so we just call the completion handler directly.
dispatchPrecondition(condition: .onQueue(callbackQueue))
completion($0.tryMap { process in
// Emit the compiler output as observable info.
let compilerOutput = ((try? process.utf8Output()) ?? "") + ((try? process.utf8stderrOutput()) ?? "")
if !compilerOutput.isEmpty {
observabilityScope.emit(info: compilerOutput)
}
// Save the persisted compilation state for possible reuse next time.
let compilationState = PersistedCompilationState(
commandLine: commandLine,
environment: toolchain.swiftCompilerEnvironment,
inputHash: compilerInputHash,
output: compilerOutput,
result: .init(process.exitStatus))
do {
try JSONEncoder.makeWithDefaults().encode(path: stateFilePath, fileSystem: self.fileSystem, compilationState)
}
catch {
// We couldn't write out the `.state` file. We warn about it but proceed.
observabilityScope.emit(debug: "Couldn't save plugin compilation state (\(error))")
}
// Construct a PluginCompilationResult for both the successful and unsuccessful cases (to convey diagnostics, etc).
let result = PluginCompilationResult(
succeeded: compilationState.succeeded,
commandLine: commandLine,
executableFile: execFilePath,
diagnosticsFile: diagFilePath,
compilerOutput: compilerOutput,
cached: false)
// Tell the delegate that we're done compiling the plugin, passing it the result.
delegate.didCompilePlugin(result: result)
// Also return the result to the caller.
return result
})
}
}
/// Returns path to the sdk, if possible.
// FIXME: This is copied from ManifestLoader. This should be consolidated when ManifestLoader is cleaned up.
private func sdkRoot() -> AbsolutePath? {
if let sdkRoot = self.sdkRootCache.get() {
return sdkRoot
}
var sdkRootPath: AbsolutePath?
// Find SDKROOT on macOS using xcrun.
#if os(macOS)
let foundPath = try? TSCBasic.Process.checkNonZeroExit(
args: "/usr/bin/xcrun", "--sdk", "macosx", "--show-sdk-path"
)
guard let sdkRoot = foundPath?.spm_chomp(), !sdkRoot.isEmpty else {
return nil
}
if let path = try? AbsolutePath(validating: sdkRoot) {
sdkRootPath = path
self.sdkRootCache.put(path)
}
#endif
return sdkRootPath
}
/// Private function that invokes a compiled plugin executable and communicates with it until it finishes.
fileprivate func invoke(
compiledExec: AbsolutePath,
workingDirectory: AbsolutePath,
writableDirectories: [AbsolutePath],
readOnlyDirectories: [AbsolutePath],
initialMessage: Data,
observabilityScope: ObservabilityScope,
callbackQueue: DispatchQueue,
delegate: PluginScriptRunnerDelegate,
completion: @escaping (Result<Int32, Error>) -> Void
) {
#if os(iOS) || os(watchOS) || os(tvOS)
callbackQueue.async {
completion(.failure(DefaultPluginScriptRunnerError.pluginUnavailable(reason: "subprocess invocations are unavailable on this platform")))
}
#else
// Construct the command line. Currently we just invoke the executable built from the plugin without any parameters.
var command = [compiledExec.pathString]
// Optionally wrap the command in a sandbox, which places some limits on what it can do. In particular, it blocks network access and restricts the paths to which the plugin can make file system changes. It does allow writing to temporary directories.
if self.enableSandbox {
do {
command = try Sandbox.apply(command: command, strictness: .writableTemporaryDirectory, writableDirectories: writableDirectories + [self.cacheDir], readOnlyDirectories: readOnlyDirectories)
} catch {
return callbackQueue.async {
completion(.failure(error))
}
}
}
// Create and configure a Process. We set the working directory to the cache directory, so that relative paths end up there.
let process = Process()
process.executableURL = URL(fileURLWithPath: command[0])
process.arguments = Array(command.dropFirst())
process.environment = ProcessInfo.processInfo.environment
#if os(Windows)
let pluginLibraryPath = self.toolchain.swiftPMLibrariesLocation.pluginLibraryPath.pathString
var env = ProcessInfo.processInfo.environment
if let Path = env["Path"] {
env["Path"] = "\(pluginLibraryPath);\(Path)"
} else {
env["Path"] = pluginLibraryPath
}
process.environment = env
#endif
process.currentDirectoryURL = workingDirectory.asURL
// Set up a pipe for sending structured messages to the plugin on its stdin.
let stdinPipe = Pipe()
let outputHandle = stdinPipe.fileHandleForWriting
let outputQueue = DispatchQueue(label: "plugin-send-queue")
process.standardInput = stdinPipe
// Set up a pipe for receiving messages from the plugin on its stdout.
let stdoutPipe = Pipe()
let stdoutLock = NSLock()
stdoutPipe.fileHandleForReading.readabilityHandler = { fileHandle in
// Receive the next message and pass it on to the delegate.
stdoutLock.withLock {
do {
while let message = try fileHandle.readPluginMessage() {
// FIXME: We should handle errors here.
callbackQueue.async {
do {
try delegate.handleMessage(data: message, responder: { data in
outputQueue.async {
do {
try outputHandle.writePluginMessage(data)
}
catch {
print("error while trying to send message to plugin: \(error)")
}
}
})
}
catch {
print("error while trying to handle message from plugin: \(error)")
}
}
}
}
catch {
print("error while trying to read message from plugin: \(error)")
}
}
}
process.standardOutput = stdoutPipe
// Set up a pipe for receiving free-form text output from the plugin on its stderr.
let stderrPipe = Pipe()
let stderrLock = NSLock()
var stderrData = Data()
let stderrHandler = { (data: Data) in
// Pass on any available data to the delegate.
if data.isEmpty { return }
stderrData.append(contentsOf: data)
callbackQueue.async { delegate.handleOutput(data: data) }
}
stderrPipe.fileHandleForReading.readabilityHandler = { fileHandle in
// Read and pass on any available free-form text output from the plugin.
// We need the lock since we could run concurrently with the termination handler.
stderrLock.withLock { stderrHandler(fileHandle.availableData) }
}
process.standardError = stderrPipe
// Add it to the list of currently running plugin processes, so it can be cancelled if the host is interrupted.
guard let cancellationKey = self.cancellator.register(process) else {
return callbackQueue.async {
completion(.failure(CancellationError()))
}
}
// Set up a handler to deal with the exit of the plugin process.
process.terminationHandler = { process in
// Remove the process from the list of currently running ones.
self.cancellator.deregister(cancellationKey)
// Close the output handle through which we talked to the plugin.
try? outputHandle.close()
// Read and pass on any remaining free-form text output from the plugin.
// We need the lock since we could run concurrently with the readability handler.
stderrLock.withLock {
try? stderrPipe.fileHandleForReading.readToEnd().map{ stderrHandler($0) }
}
// Read and pass on any remaining messages from the plugin.
let handle = stdoutPipe.fileHandleForReading
if let handler = handle.readabilityHandler {
handler(handle)
}
// Call the completion block with a result that depends on how the process ended.
callbackQueue.async {
completion(Result {
// We throw an error if the plugin ended with a signal.
if process.terminationReason == .uncaughtSignal {
throw DefaultPluginScriptRunnerError.invocationEndedBySignal(
signal: process.terminationStatus,
command: command,
output: String(decoding: stderrData, as: UTF8.self))
}
// Otherwise return the termination satatus.
return process.terminationStatus
})
}
}
// Start the plugin process.
do {
try process.run()
}
catch {
callbackQueue.async {
completion(.failure(DefaultPluginScriptRunnerError.invocationFailed(error: error, command: command)))
}
}
/// Send the initial message to the plugin.
outputQueue.async {
try? outputHandle.writePluginMessage(initialMessage)
}
#endif
}
public func cancel(deadline: DispatchTime) throws {
try self.cancellator.cancel(deadline: deadline)
}
}
/// An error encountered by the default plugin runner.
public enum DefaultPluginScriptRunnerError: Error, CustomStringConvertible {
/// The plugin is not available for some reason.
case pluginUnavailable(reason: String)
/// An error occurred while preparing to compile the plugin script.
case compilationPreparationFailed(error: Error)
/// An error occurred while compiling the plugin script (e.g. syntax error).
/// The diagnostics are available in the plugin compilation result.
case compilationFailed(PluginCompilationResult)
/// The plugin invocation couldn't be started.
case invocationFailed(error: Error, command: [String])
/// The plugin invocation ended by a signal.
case invocationEndedBySignal(signal: Int32, command: [String], output: String)
/// The plugin invocation ended with a non-zero exit code.
case invocationEndedWithNonZeroExitCode(exitCode: Int32, command: [String], output: String)
/// There was an error communicating with the plugin.
case pluginCommunicationError(message: String, command: [String], output: String)
public var description: String {
func makeContextString(_ command: [String], _ output: String) -> String {
return "<command: \(command.map{ $0.spm_shellEscaped() }.joined(separator: " "))>, <output:\n\(output.spm_shellEscaped())>"
}
switch self {
case .pluginUnavailable(let reason):
return "plugin is unavailable: \(reason)"
case .compilationPreparationFailed(let error):
return "plugin compilation preparation failed: \(error)"
case .compilationFailed(let result):
return "plugin compilation failed: \(result)"
case .invocationFailed(let error, let command):
return "plugin invocation failed: \(error) \(makeContextString(command, ""))"
case .invocationEndedBySignal(let signal, let command, let output):
return "plugin process ended by an uncaught signal: \(signal) \(makeContextString(command, output))"
case .invocationEndedWithNonZeroExitCode(let exitCode, let command, let output):
return "plugin process ended with a non-zero exit code: \(exitCode) \(makeContextString(command, output))"
case .pluginCommunicationError(let message, let command, let output):
return "plugin communication error: \(message) \(makeContextString(command, output))"
}
}
}
fileprivate extension FileHandle {
func writePluginMessage(_ message: Data) throws {
// Write the header (a 64-bit length field in little endian byte order).
var length = UInt64(littleEndian: UInt64(message.count))
let header = Swift.withUnsafeBytes(of: &length) { Data($0) }
assert(header.count == 8)
try self.write(contentsOf: header)
// Write the payload.
try self.write(contentsOf: message)
}
func readPluginMessage() throws -> Data? {
// Read the header (a 64-bit length field in little endian byte order).
guard let header = try self.read(upToCount: 8) else { return nil }
guard header.count == 8 else {
throw PluginMessageError.truncatedHeader
}
let length = header.withUnsafeBytes{ $0.load(as: UInt64.self).littleEndian }
guard length >= 2 else {
throw PluginMessageError.invalidPayloadSize
}
// Read and return the message.
guard let message = try self.read(upToCount: Int(length)), message.count == length else {
throw PluginMessageError.truncatedPayload
}
return message
}
enum PluginMessageError: Swift.Error {
case truncatedHeader
case invalidPayloadSize
case truncatedPayload
}
}
|
apache-2.0
|
8d2d062914cce9ef18fc3d80e27cb073
| 46.972603 | 708 | 0.615521 | 5.536273 | false | false | false | false |
Alamofire/AlamofireImage
|
Example/Source/ImageViewController.swift
|
1
|
2315
|
//
// ImageViewController.swift
//
// Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import AlamofireImage
import Foundation
import UIKit
class ImageViewController: UIViewController {
var gravatar: Gravatar!
var imageView: UIImageView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setUpInstanceProperties()
setUpImageView()
}
// MARK: - Private - Setup Methods
private func setUpInstanceProperties() {
title = gravatar.email
edgesForExtendedLayout = UIRectEdge()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
}
private func setUpImageView() {
imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
let URL = gravatar.url(size: view.bounds.size.width)
imageView.af_setImage(withURL: URL,
placeholderImage: nil,
filter: CircleFilter(),
imageTransition: .flipFromBottom(0.5))
view.addSubview(imageView)
imageView.frame = view.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
|
mit
|
947d7e1cae091da7a9d31408b0ba5219
| 34.075758 | 81 | 0.687257 | 4.822917 | false | false | false | false |
ZamzamInc/ZamzamKit
|
Sources/ZamzamCore/Extensions/Color.swift
|
1
|
2245
|
//
// PlatformColor.swift
// ZamzamCore
//
// Created by Basem Emara on 2/20/16.
// Copyright © 2016 Zamzam Inc. All rights reserved.
//
#if os(macOS)
import AppKit.NSColor
public typealias PlatformColor = NSColor
#elseif canImport(UIKit)
import UIKit.UIColor
public typealias PlatformColor = UIColor
#endif
public extension PlatformColor {
/// A random color.
static var random: PlatformColor {
PlatformColor(rgb: (
.random(in: 0...255),
.random(in: 0...255),
.random(in: 0...255)
))
}
}
public extension PlatformColor {
/// An additional convenience initializer function that allows to init a color object using a hex color value.
///
/// For hex code `#990000`, initialize using `0x990000`.
///
/// UIColor(hex: 0x990000)
///
/// - Parameters:
/// - hex: RGB UInt color hex value.
/// - alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0.
convenience init(hex: UInt32, alpha: Double = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: CGFloat(alpha)
)
}
/// An additional convenience initializer function that allows to init a color object using integers.
///
/// UIColor(rgb: (66, 134, 244))
///
/// - Parameters:
/// - rgb: A tuple of integers representing the RGB colors.
/// - alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0.
convenience init(rgb: (Int, Int, Int), alpha: Double = 1.0) {
self.init(
red: CGFloat(rgb.0) / 255.0,
green: CGFloat(rgb.1) / 255.0,
blue: CGFloat(rgb.2) / 255.0,
alpha: CGFloat(alpha)
)
}
}
#if os(macOS)
public extension NSColor {
/// The primary color to use for text labels.
///
/// Unified with iOS color name.
static let label = NSColor.labelColor
/// The color to use for the window background.
///
/// Unified with iOS color name.
static let systemBackground = NSColor.windowBackgroundColor
}
#endif
|
mit
|
db4e4a8a1fb2db5a2a04cf8d08d181f0
| 28.526316 | 114 | 0.597148 | 3.816327 | false | false | false | false |
apple/swift
|
test/Concurrency/global_actor_inference.swift
|
4
|
22808
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path %t/other_global_actor_inference.swiftmodule -module-name other_global_actor_inference -warn-concurrency %S/Inputs/other_global_actor_inference.swift
// RUN: %target-typecheck-verify-swift -I %t -disable-availability-checking
// REQUIRES: concurrency
import other_global_actor_inference
actor SomeActor { }
@globalActor
struct SomeGlobalActor {
static let shared = SomeActor()
}
@globalActor
struct OtherGlobalActor {
static let shared = SomeActor()
}
@globalActor
struct GenericGlobalActor<T> {
static var shared: SomeActor { SomeActor() }
}
// ----------------------------------------------------------------------
// Check that MainActor exists
// ----------------------------------------------------------------------
@MainActor protocol Aluminium {
func method()
}
@MainActor class Copper {}
@MainActor func iron() {}
struct Carbon {
@IntWrapper var atomicWeight: Int
func getWeight() -> Int {
return atomicWeight
}
}
// ----------------------------------------------------------------------
// Check that @MainActor(blah) doesn't work
// ----------------------------------------------------------------------
// expected-error@+1{{global actor attribute 'MainActor' argument can only be '(unsafe)'}}
@MainActor(blah) func brokenMainActorAttr() { }
// ----------------------------------------------------------------------
// Global actor inference for protocols
// ----------------------------------------------------------------------
@SomeGlobalActor
protocol P1 {
func method()
}
protocol P2 {
@SomeGlobalActor func method1()
func method2()
}
class C1: P1 {
func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
@OtherGlobalActor func testMethod() {
method() // expected-error {{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = method
}
}
class C2: P2 {
func method1() { } // expected-note {{calls to instance method 'method1()' from outside of its actor context are implicitly asynchronous}}
func method2() { }
@OtherGlobalActor func testMethod() {
method1() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method1()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = method1
method2() // okay
}
}
struct AllInP1: P1 {
func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
func other() { } // expected-note {{calls to instance method 'other()' from outside of its actor context are implicitly asynchronous}}
}
func testAllInP1(ap1: AllInP1) { // expected-note 2 {{add '@SomeGlobalActor' to make global function 'testAllInP1(ap1:)' part of global actor 'SomeGlobalActor'}}
ap1.method() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous nonisolated context}}
ap1.other() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'other()' in a synchronous nonisolated context}}
}
struct NotAllInP1 {
func other() { }
}
extension NotAllInP1: P1 {
func method() { } // expected-note{{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
}
func testNotAllInP1(nap1: NotAllInP1) { // expected-note{{add '@SomeGlobalActor' to make global function 'testNotAllInP1(nap1:)' part of global actor 'SomeGlobalActor'}}
nap1.method() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous nonisolated context}}
nap1.other() // okay
}
// Make sure we don't infer 'nonisolated' for stored properties.
@MainActor
protocol Interface {
nonisolated var baz: Int { get } // expected-note{{'baz' declared here}}
}
@MainActor
class Object: Interface {
var baz: Int = 42 // expected-warning{{main actor-isolated property 'baz' cannot be used to satisfy nonisolated protocol requirement}}
}
// ----------------------------------------------------------------------
// Global actor inference for classes and extensions
// ----------------------------------------------------------------------
@SomeGlobalActor class C3 {
func method1() { } // expected-note {{calls to instance method 'method1()' from outside of its actor context are implicitly asynchronous}}
}
extension C3 {
func method2() { } // expected-note {{calls to instance method 'method2()' from outside of its actor context are implicitly asynchronous}}
}
class C4: C3 {
func method3() { } // expected-note {{calls to instance method 'method3()' from outside of its actor context are implicitly asynchronous}}
}
extension C4 {
func method4() { } // expected-note {{calls to instance method 'method4()' from outside of its actor context are implicitly asynchronous}}
}
class C5 {
func method1() { }
}
@SomeGlobalActor extension C5 {
func method2() { } // expected-note {{calls to instance method 'method2()' from outside of its actor context are implicitly asynchronous}}
}
@OtherGlobalActor func testGlobalActorInference(c3: C3, c4: C4, c5: C5) {
// Propagation via class annotation
c3.method1() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method1()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
c3.method2() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method2()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c3.method1
_ = c3.method2
// Propagation via subclassing
c4.method3() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method3()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
c4.method4() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method4()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c4.method3
_ = c4.method4
// Propagation in an extension.
c5.method1() // OK: no propagation
c5.method2() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method2()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c5.method1 // OK
_ = c5.method2
}
protocol P3 {
@OtherGlobalActor func method1()
func method2()
}
class C6: P2, P3 {
func method1() { }
func method2() { }
func testMethod() {
method1() // okay: no inference
method2() // okay: no inference
let _ = method1 // okay: no inference
let _ = method2 // okay: no inference
}
}
// ----------------------------------------------------------------------
// Global actor checking for overrides
// ----------------------------------------------------------------------
actor GenericSuper<T> {
@GenericGlobalActor<T> func method() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method2() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method3() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method4() { }
@GenericGlobalActor<T> func method5() { }
}
actor GenericSub<T> : GenericSuper<[T]> { // expected-error{{actor types do not support inheritance}}
override func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
// expected-error@-1{{instance method overrides a 'final' instance method}}
@GenericGlobalActor<T> override func method2() { } // expected-error{{instance method overrides a 'final' instance method}}
nonisolated override func method3() { } // expected-error{{instance method overrides a 'final' instance method}}
@OtherGlobalActor func testMethod() {
method() // expected-error{{actor-isolated instance method 'method()' can not be referenced from global actor 'OtherGlobalActor'}}
_ = method // expected-error{{actor-isolated instance method 'method()' can not be partially applied}}
}
}
// ----------------------------------------------------------------------
// Global actor inference for superclasses
// ----------------------------------------------------------------------
struct Container<T> {
@GenericGlobalActor<T> class Superclass { }
@GenericGlobalActor<[T]> class Superclass2 { }
}
struct OtherContainer<U> {
// NOT Okay to change the global actor in a subclass.
@GenericGlobalActor<[U]> class Subclass1 : Container<[U]>.Superclass { }
@GenericGlobalActor<U> class Subclass2 : Container<[U]>.Superclass { }
// expected-error@-1{{global actor 'GenericGlobalActor<U>'-isolated class 'Subclass2' has different actor isolation from global actor 'GenericGlobalActor<T>'-isolated superclass 'Superclass'}}
// Ensure that substitutions work properly when inheriting.
class Subclass3<V> : Container<(U, V)>.Superclass2 {
func method() { }
@OtherGlobalActor func testMethod() async {
await method()
let _ = method
}
}
}
class SuperclassWithGlobalActors {
@GenericGlobalActor<Int> func f() { }
@GenericGlobalActor<Int> func g() { } // expected-note{{overridden declaration is here}}
func h() { }
func i() { }
func j() { }
}
@GenericGlobalActor<String> // it's okay to add a global actor to nonisolated
class SubclassWithGlobalActors : SuperclassWithGlobalActors {
override func f() { } // okay: inferred to @GenericGlobalActor<Int>
@GenericGlobalActor<String> override func g() { } // expected-error{{global actor 'GenericGlobalActor<String>'-isolated instance method 'g()' has different actor isolation from global actor 'GenericGlobalActor<Int>'-isolated overridden declaration}}
override func h() { } // okay: inferred to unspecified
func onGenericGlobalActorString() { }
@GenericGlobalActor<Int> func onGenericGlobalActorInt() { }
}
// ----------------------------------------------------------------------
// Global actor inference for unspecified contexts
// ----------------------------------------------------------------------
// expected-note@+1 {{calls to global function 'foo()' from outside of its actor context are implicitly asynchronous}}
@SomeGlobalActor func foo() { sibling() }
@SomeGlobalActor func sibling() { foo() }
func bar() async {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }}
foo() // expected-note{{calls to global function 'foo()' from outside of its actor context are implicitly asynchronous}}
}
// expected-note@+1 {{add '@SomeGlobalActor' to make global function 'barSync()' part of global actor 'SomeGlobalActor'}} {{1-1=@SomeGlobalActor }}
func barSync() {
foo() // expected-error {{call to global actor 'SomeGlobalActor'-isolated global function 'foo()' in a synchronous nonisolated context}}
}
// ----------------------------------------------------------------------
// Property observers
// ----------------------------------------------------------------------
@OtherGlobalActor
struct Observed {
var thing: Int = 0 { // expected-note {{property declared here}}
didSet {}
willSet {}
}
}
func checkObserved(_ o: Observed) { // expected-note {{add '@OtherGlobalActor' to make global function 'checkObserved' part of global actor 'OtherGlobalActor'}}
_ = o.thing // expected-error {{global actor 'OtherGlobalActor'-isolated property 'thing' can not be referenced from a non-isolated context}}
}
// ----------------------------------------------------------------------
// Property wrappers
// ----------------------------------------------------------------------
@propertyWrapper
@OtherGlobalActor
struct WrapperOnActor<Wrapped: Sendable> {
private var stored: Wrapped
nonisolated init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@MainActor var wrappedValue: Wrapped {
get { }
set { }
}
@SomeGlobalActor var projectedValue: Wrapped {
get { }
set { }
}
}
@MainActor
@propertyWrapper
public struct WrapperOnMainActor<Wrapped> {
// Make sure inference of @MainActor on wrappedValue doesn't crash.
public var wrappedValue: Wrapped
public var accessCount: Int
nonisolated public init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
public struct WrapperOnMainActor2<Wrapped> {
@MainActor public var wrappedValue: Wrapped
public init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
actor WrapperActor<Wrapped: Sendable> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
nonisolated var wrappedValue: Wrapped {
get { }
set { }
}
nonisolated var projectedValue: Wrapped {
get { }
set { }
}
}
struct HasWrapperOnActor {
@WrapperOnActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
// expected-note@+1 3{{to make instance method 'testErrors()'}}
func testErrors() {
_ = synced // expected-error{{main actor-isolated property 'synced' can not be referenced from a non-isolated context}}
_ = $synced // expected-error{{global actor 'SomeGlobalActor'-isolated property '$synced' can not be referenced from a non-isolated context}}
_ = _synced // expected-error{{global actor 'OtherGlobalActor'-isolated property '_synced' can not be referenced from a non-isolated context}}
}
@MainActor mutating func testOnMain() {
_ = synced
synced = 17
}
@WrapperActor var actorSynced: Int = 0
func testActorSynced() {
_ = actorSynced
_ = $actorSynced
_ = _actorSynced
}
}
@propertyWrapper
actor WrapperActorBad1<Wrapped> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
var wrappedValue: Wrapped { // expected-error{{'wrappedValue' property in property wrapper type 'WrapperActorBad1' cannot be isolated to the actor instance; consider 'nonisolated'}}}}
get { storage }
set { storage = newValue }
}
}
@propertyWrapper
actor WrapperActorBad2<Wrapped: Sendable> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
nonisolated var wrappedValue: Wrapped {
get { }
set { }
}
var projectedValue: Wrapped { // expected-error{{'projectedValue' property in property wrapper type 'WrapperActorBad2' cannot be isolated to the actor instance; consider 'nonisolated'}}
get { }
set { }
}
}
@propertyWrapper
struct WrapperWithMainActorDefaultInit {
var wrappedValue: Int { fatalError() }
@MainActor init() {} // expected-note 2 {{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}}
}
actor ActorWithWrapper {
@WrapperOnActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
@WrapperWithMainActorDefaultInit var property: Int // expected-error {{call to main actor-isolated initializer 'init()' in a synchronous actor-isolated context}}
func f() {
_ = synced // expected-error{{main actor-isolated property 'synced' can not be referenced on a different actor instance}}
_ = $synced // expected-error{{global actor 'SomeGlobalActor'-isolated property '$synced' can not be referenced on a different actor instance}}
_ = _synced // expected-error{{global actor 'OtherGlobalActor'-isolated property '_synced' can not be referenced on a different actor instance}}
@WrapperWithMainActorDefaultInit var value: Int // expected-error {{call to main actor-isolated initializer 'init()' in a synchronous actor-isolated context}}
}
}
@propertyWrapper
struct WrapperOnSomeGlobalActor<Wrapped: Sendable> {
private var stored: Wrapped
nonisolated init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@SomeGlobalActor var wrappedValue: Wrapped {
get { stored }
set { stored = newValue }
}
}
struct InferredFromPropertyWrapper {
@WrapperOnSomeGlobalActor var value = 17
func test() -> Int { // expected-note{{calls to instance method 'test()' from outside of its actor context are implicitly asynchronous}}
value
}
}
func testInferredFromWrapper(x: InferredFromPropertyWrapper) { // expected-note{{add '@SomeGlobalActor' to make global function 'testInferredFromWrapper(x:)' part of global actor 'SomeGlobalActor'}}
_ = x.test() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'test()' in a synchronous nonisolated context}}
}
@propertyWrapper
struct SimplePropertyWrapper {
var wrappedValue: Int { .zero }
var projectedValue: Int { .max }
}
@MainActor
class WrappedContainsNonisolatedAttr {
@SimplePropertyWrapper nonisolated var value
// expected-error@-1 {{'nonisolated' is not supported on properties with property wrappers}}
// expected-note@-2 2{{property declared here}}
nonisolated func test() {
_ = value // expected-error {{main actor-isolated property 'value' can not be referenced from a non-isolated context}}
_ = $value // expected-error {{main actor-isolated property '$value' can not be referenced from a non-isolated context}}
}
}
// ----------------------------------------------------------------------
// Unsafe global actors
// ----------------------------------------------------------------------
protocol UGA {
@SomeGlobalActor(unsafe) func req() // expected-note{{calls to instance method 'req()' from outside of its actor context are implicitly asynchronous}}
}
struct StructUGA1: UGA {
@SomeGlobalActor func req() { }
}
struct StructUGA2: UGA {
nonisolated func req() { }
}
@SomeGlobalActor
struct StructUGA3: UGA {
func req() {
sibling()
}
}
@GenericGlobalActor<String>
func testUGA<T: UGA>(_ value: T) {
value.req() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'req()' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}}
}
class UGAClass {
@SomeGlobalActor(unsafe) func method() { }
}
class UGASubclass1: UGAClass {
@SomeGlobalActor override func method() { }
}
class UGASubclass2: UGAClass {
override func method() { }
}
@propertyWrapper
@OtherGlobalActor(unsafe)
struct WrapperOnUnsafeActor<Wrapped> {
private var stored: Wrapped
init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@MainActor(unsafe) var wrappedValue: Wrapped {
get { }
set { }
}
@SomeGlobalActor(unsafe) var projectedValue: Wrapped {
get { }
set { }
}
}
struct HasWrapperOnUnsafeActor {
@WrapperOnUnsafeActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
func testUnsafeOkay() {
_ = synced
_ = $synced
_ = _synced
}
nonisolated func testErrors() {
_ = synced // expected-error{{main actor-isolated property 'synced' can not be referenced from a non-isolated context}}
_ = $synced // expected-error{{global actor 'SomeGlobalActor'-isolated property '$synced' can not be referenced from a non-isolated context}}
_ = _synced // expected-error{{global actor 'OtherGlobalActor'-isolated property '_synced' can not be referenced from a non-isolated context}}
}
@MainActor mutating func testOnMain() {
_ = synced
synced = 17
}
}
// ----------------------------------------------------------------------
// Nonisolated closures
// ----------------------------------------------------------------------
@SomeGlobalActor func getGlobal7() -> Int { 7 }
func acceptClosure<T>(_: () -> T) { }
@SomeGlobalActor func someGlobalActorFunc() async {
acceptClosure { getGlobal7() } // okay
}
// ----------------------------------------------------------------------
// Main actor that predates concurrency
// ----------------------------------------------------------------------
@preconcurrency func takesUnsafeMainActor(fn: @MainActor () -> Void) { }
@MainActor func onlyOnMainActor() { }
func useUnsafeMainActor() {
takesUnsafeMainActor {
onlyOnMainActor() // okay due to parameter attribute
}
}
// ----------------------------------------------------------------------
// @IBAction implies @MainActor(unsafe)
// ----------------------------------------------------------------------
class SomeWidgetThing {
@IBAction func onTouch(_ object: AnyObject) {
onlyOnMainActor() // okay
}
}
// ----------------------------------------------------------------------
// @_inheritActorContext
// ----------------------------------------------------------------------
func acceptAsyncSendableClosure<T>(_: @Sendable () async -> T) { }
func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable () async -> T) { }
@MainActor func testCallFromMainActor() {
acceptAsyncSendableClosure {
onlyOnMainActor() // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1 {{calls to global function 'onlyOnMainActor()' from outside of its actor context are implicitly asynchronous}}
}
acceptAsyncSendableClosure {
await onlyOnMainActor() // okay
}
acceptAsyncSendableClosureInheriting {
onlyOnMainActor() // okay
}
acceptAsyncSendableClosureInheriting {
await onlyOnMainActor() // expected-warning{{no 'async' operations occur within 'await' expression}}
}
}
// defer bodies inherit global actor-ness
@MainActor
var statefulThingy: Bool = false // expected-note {{var declared here}}
@MainActor
func useFooInADefer() -> String { // expected-note {{calls to global function 'useFooInADefer()' from outside of its actor context are implicitly asynchronous}}
defer {
statefulThingy = true
}
return "hello"
}
// ----------------------------------------------------------------------
// Dynamic replacement
// ----------------------------------------------------------------------
@_dynamicReplacement(for: dynamicOnMainActor)
func replacesDynamicOnMainActor() {
onlyOnMainActor()
}
// ----------------------------------------------------------------------
// Global-actor isolation of stored property initializer expressions
// ----------------------------------------------------------------------
class Cutter {
@MainActor var x = useFooInADefer()
@MainActor var y = { () -> Bool in
var z = statefulThingy
return z
}()
}
@SomeGlobalActor
class Butter {
var a = useFooInADefer() // expected-error {{call to main actor-isolated global function 'useFooInADefer()' in a synchronous global actor 'SomeGlobalActor'-isolated context}}
nonisolated let b = statefulThingy // expected-error {{main actor-isolated var 'statefulThingy' can not be referenced from a non-isolated context}}
var c: Int = {
return getGlobal7()
}()
lazy var d: Int = getGlobal7()
static var e: Int = getGlobal7()
}
|
apache-2.0
|
3632554f0fbdfa4bb4741f1fb91550a0
| 33.349398 | 251 | 0.644116 | 4.58084 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/Commands/PackageTools/ResetCommands.swift
|
2
|
1810
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import CoreCommands
extension SwiftPackageTool {
struct Clean: SwiftCommand {
static let configuration = CommandConfiguration(
abstract: "Delete build artifacts")
@OptionGroup(_hiddenFromHelp: true)
var globalOptions: GlobalOptions
func run(_ swiftTool: SwiftTool) throws {
try swiftTool.getActiveWorkspace().clean(observabilityScope: swiftTool.observabilityScope)
}
}
struct PurgeCache: SwiftCommand {
static let configuration = CommandConfiguration(
abstract: "Purge the global repository cache.")
@OptionGroup(_hiddenFromHelp: true)
var globalOptions: GlobalOptions
func run(_ swiftTool: SwiftTool) throws {
try swiftTool.getActiveWorkspace().purgeCache(observabilityScope: swiftTool.observabilityScope)
}
}
struct Reset: SwiftCommand {
static let configuration = CommandConfiguration(
abstract: "Reset the complete cache/build directory")
@OptionGroup(_hiddenFromHelp: true)
var globalOptions: GlobalOptions
func run(_ swiftTool: SwiftTool) throws {
try swiftTool.getActiveWorkspace().reset(observabilityScope: swiftTool.observabilityScope)
}
}
}
|
apache-2.0
|
34652cadef19fb167d332275b26fe532
| 33.807692 | 107 | 0.632044 | 5.552147 | false | true | false | false |
remypanicker/firefox-ios
|
Client/Frontend/Home/RemoteTabsPanel.swift
|
9
|
21581
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Account
import Shared
import SnapKit
import Storage
import Sync
import XCGLogger
private let log = Logger.browserLogger
private struct RemoteTabsPanelUX {
static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight!
static let RowHeight = SiteTableViewControllerUX.RowHeight
static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8)
static let EmptyStateTitleFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize, weight: UIFontWeightMedium)
static let EmptyStateTitleTextColor = UIColor.darkGrayColor()
static let EmptyStateInstructionsFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize - 1, weight: UIFontWeightLight)
static let EmptyStateInstructionsTextColor = UIColor.grayColor()
static let EmptyStateInstructionsWidth = 226
static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape
static let EmptyStateSignInButtonColor = UIColor(red:0.3, green:0.62, blue:1, alpha:1)
static let EmptyStateSignInButtonTitleFont = UIFont.systemFontOfSize(16)
static let EmptyStateSignInButtonTitleColor = UIColor.whiteColor()
static let EmptyStateSignInButtonCornerRadius: CGFloat = 4
static let EmptyStateSignInButtonHeight = 44
static let EmptyStateSignInButtonWidth = 200
static let EmptyStateCreateAccountButtonFont = UIFont.systemFontOfSize(12)
// Temporary placeholder for strings removed in Bug 1193456.
private let CreateAccountString = NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j")
}
private let RemoteClientIdentifier = "RemoteClient"
private let RemoteTabIdentifier = "RemoteTab"
class RemoteTabsPanel: UITableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationPrivateDataCleared, object: nil)
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier)
tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier)
tableView.rowHeight = RemoteTabsPanelUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.delegate = nil
tableView.dataSource = nil
refreshControl = UIRefreshControl()
view.backgroundColor = UIConstants.PanelBackgroundColor
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataCleared, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refreshControl?.addTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged)
refreshTabs()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
refreshControl?.removeTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataCleared:
refreshTabs()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
var tableViewDelegate: RemoteTabsPanelDataSource? {
didSet {
self.tableView.delegate = tableViewDelegate
self.tableView.dataSource = tableViewDelegate
}
}
func refreshTabs() {
tableView.scrollEnabled = false
tableView.allowsSelection = false
tableView.tableFooterView = UIView(frame: CGRectZero)
// Short circuit if the user is not logged in
if !profile.hasAccount() {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NotLoggedIn)
self.endRefreshing()
return
}
self.profile.getCachedClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.updateDelegateClientAndTabData(clientAndTabs)
}
// Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync
let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
if NSDate.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds && !(self.refreshControl?.refreshing ?? false) {
self.startRefreshing()
self.profile.getClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime)
self.updateDelegateClientAndTabData(clientAndTabs)
}
self.endRefreshing()
}
} else {
// If we failed before and didn't sync, show the failure delegate
if let _ = result.failureValue {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .FailedToSync)
}
self.endRefreshing()
}
}
}
private func startRefreshing() {
if let refreshControl = self.refreshControl {
let height = -refreshControl.bounds.size.height
self.tableView.setContentOffset(CGPointMake(0, height), animated: true)
refreshControl.beginRefreshing()
}
}
func endRefreshing() {
if self.refreshControl?.refreshing ?? false {
self.refreshControl?.endRefreshing()
}
self.tableView.scrollEnabled = true
self.tableView.reloadData()
}
func updateDelegateClientAndTabData(clientAndTabs: [ClientAndTabs]) {
if clientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoClients)
} else {
let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 }
if nonEmptyClientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoTabs)
} else {
self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: self, clientAndTabs: nonEmptyClientAndTabs)
self.tableView.allowsSelection = true
}
}
}
@objc private func SELrefreshTabs() {
refreshTabs()
}
}
enum RemoteTabsError {
case NotLoggedIn
case NoClients
case NoTabs
case FailedToSync
func localizedString() -> String {
switch self {
case NotLoggedIn:
return "" // This does not have a localized string because we have a whole specific screen for it.
case NoClients:
return NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", comment: "Error message in the remote tabs panel")
case NoTabs:
return NSLocalizedString("You don't have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel")
case FailedToSync:
return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel")
}
}
}
protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate {
}
class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
private var clientAndTabs: [ClientAndTabs]
init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) {
self.homePanel = homePanel
self.clientAndTabs = clientAndTabs
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.clientAndTabs.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clientAndTabs[section].tabs.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RemoteTabsPanelUX.HeaderHeight
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let clientTabs = self.clientAndTabs[section]
let client = clientTabs.client
let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView
view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight)
view.textLabel?.text = client.name
view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor
/*
* A note on timestamps.
* We have access to two timestamps here: the timestamp of the remote client record,
* and the set of timestamps of the client's tabs.
* Neither is "last synced". The client record timestamp changes whenever the remote
* client uploads its record (i.e., infrequently), but also whenever another device
* sends a command to that client -- which can be much later than when that client
* last synced.
* The client's tabs haven't necessarily changed, but it can still have synced.
* Ideally, we should save and use the modified time of the tabs record itself.
* This will be the real time that the other client uploaded tabs.
*/
let timestamp = clientTabs.approximateLastSyncTime()
let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.")
view.detailTextLabel?.text = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString())
let image: UIImage?
if client.type == "desktop" {
image = UIImage(named: "deviceTypeDesktop")
image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list")
} else {
image = UIImage(named: "deviceTypeMobile")
image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list")
}
view.imageView.image = image
view.mergeAccessibilityLabels()
return view
}
private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab {
return clientAndTabs[indexPath.section].tabs[indexPath.item]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell
let tab = tabAtIndexPath(indexPath)
cell.setLines(tab.title, detailText: tab.URL.absoluteString)
// TODO: Bug 1144765 - Populate image with cached favicons.
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let tab = tabAtIndexPath(indexPath)
if let homePanel = self.homePanel {
// It's not a bookmark, so let's call it Typed (which means History, too).
homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed)
}
}
}
// MARK: -
class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
var error: RemoteTabsError
var notLoggedCell: UITableViewCell?
init(homePanel: HomePanel, error: RemoteTabsError) {
self.homePanel = homePanel
self.error = error
self.notLoggedCell = nil
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let cell = self.notLoggedCell {
cell.updateConstraints()
}
return tableView.bounds.height
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Making the footer height as small as possible because it will disable button tappability if too high.
return 1
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch error {
case .NotLoggedIn:
let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel)
self.notLoggedCell = cell
return cell
default:
let cell = RemoteTabsErrorCell(error: self.error)
self.notLoggedCell = nil
return cell
}
}
}
// MARK: -
class RemoteTabsErrorCell: UITableViewCell {
static let Identifier = "RemoteTabsErrorCell"
init(error: RemoteTabsError) {
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0)
let containerView = UIView()
contentView.addSubview(containerView)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
containerView.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(containerView)
make.centerX.equalTo(containerView)
}
let instructionsLabel = UILabel()
instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont
instructionsLabel.text = error.localizedString()
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
containerView.addSubview(instructionsLabel)
instructionsLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(containerView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
containerView.snp_makeConstraints { make in
// Let the container wrap around the content
make.top.equalTo(imageView.snp_top)
make.left.bottom.right.equalTo(instructionsLabel)
// And then center it in the overlay view that sits on top of the UITableView
make.center.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: -
class RemoteTabsNotLoggedInCell: UITableViewCell {
static let Identifier = "RemoteTabsNotLoggedInCell"
var homePanel: HomePanel?
var instructionsLabel: UILabel
var signInButton: UIButton
var titleLabel: UILabel
init(homePanel: HomePanel?) {
let titleLabel = UILabel()
let instructionsLabel = UILabel()
let signInButton = UIButton()
self.instructionsLabel = instructionsLabel
self.signInButton = signInButton
self.titleLabel = titleLabel
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
self.homePanel = homePanel
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
contentView.addSubview(imageView)
titleLabel.font = RemoteTabsPanelUX.EmptyStateTitleFont
titleLabel.text = NSLocalizedString("Welcome to Sync", comment: "See http://mzl.la/1Qtkf0j")
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor
contentView.addSubview(titleLabel)
instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont
instructionsLabel.text = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "See http://mzl.la/1Qtkf0j")
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
contentView.addSubview(instructionsLabel)
signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor
signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal)
signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, forState: .Normal)
signInButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateSignInButtonTitleFont
signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: "SELsignIn", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(signInButton)
imageView.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(instructionsLabel)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(contentView.snp_centerY).offset(-180).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(contentView.snp_top).offset(50).priorityHigh()
}
titleLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(imageView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func SELsignIn() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel)
}
}
override func updateConstraints() {
if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) && !(DeviceInfo.deviceModel().rangeOfString("iPad") != nil) {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.left.lessThanOrEqualTo(contentView.snp_left).offset(80).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.right.lessThanOrEqualTo(contentView.snp_centerX).offset(-10).priorityHigh()
}
signInButton.snp_remakeConstraints { make in
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
make.centerY.equalTo(titleLabel.snp_centerY)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.right.greaterThanOrEqualTo(contentView.snp_right).offset(-80).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.left.greaterThanOrEqualTo(contentView.snp_centerX).offset(10).priorityHigh()
}
} else {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(contentView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
signInButton.snp_remakeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
}
}
super.updateConstraints()
}
}
|
mpl-2.0
|
006247d51ba58ff8222127c9d4428d45
| 41.904573 | 178 | 0.692878 | 5.329958 | false | false | false | false |
GoogleCloudPlatform/firebase-ios-samples
|
PlayChat/AppDelegate.swift
|
1
|
8274
|
/**
# Copyright Google LLC. 2016
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
**/
import Firebase
import GoogleSignIn
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate,
UITableViewDelegate,
UITextFieldDelegate {
let IBX: String = "inbox"
let CHS: String = "channels"
let REQLOG: String = "requestLogger"
var chanArray: [String] = []
var maxMessages: UInt = 20
var window: UIWindow?
var storyboard: UIStoryboard?
var navigationController: UINavigationController?
var tabBarController: UITabBarController?
var msgViewController: MessageViewController?
var user: GIDGoogleUser!
var inbox: String?
var ref: DatabaseReference!
var msgs: [Message] = []
var channelViewDict: [String: UITableView] = [: ]
var fbLog: FirebaseLogger?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
chanArray = dictionary["Channels"]!.components(separatedBy: ",")
maxMessages = dictionary["MaxMessages"]! as! UInt
} else {
print("Couldn't read 'Info.plist' file")
}
storyboard = UIStoryboard(name: "Main", bundle: nil)
navigationController = storyboard!.instantiateInitialViewController()
as? UINavigationController
tabBarController = self.storyboard!
.instantiateViewController(withIdentifier: "TabBarController")
as? UITabBarController
msgViewController = MessageViewController(maxMessages: maxMessages)
tabBarController?.delegate = msgViewController
tabBarController?.viewControllers = [buildChannelView(chanArray[0])]
for i in 1...chanArray.count - 1 {
tabBarController?.viewControllers?.append(buildChannelView(chanArray[i]))
}
FirebaseApp.configure()
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
return true
}
func buildChannelView(_ title: String) -> UIViewController {
let channelView = UIViewController()
let fontBold: UIFont = UIFont(name: "HelveticaNeue-Bold", size: 14)!
channelView.tabBarItem.title = title
channelView.tabBarItem.setTitleTextAttributes(
[
NSAttributedStringKey.foregroundColor: UIColor.gray,
NSAttributedStringKey.font: fontBold
], for: .normal)
channelView.tabBarItem.setTitleTextAttributes(
[
NSAttributedStringKey.foregroundColor: UIColor.black,
NSAttributedStringKey.font: fontBold
], for: .selected)
let tableView: UITableView = UITableView()
let height = channelView.view.frame.height
let width = channelView.view.frame.width
print(height)
print(width)
tableView.frame = CGRect(x: 0, y: 20, width: width, height: height - 110)
tableView.rowHeight = 50
tableView.estimatedRowHeight = 40
tableView.delegate = self
tableView.dataSource = msgViewController
tableView.register(
MessageCell.self,
forCellReuseIdentifier: NSStringFromClass(MessageCell.self))
tableView.translatesAutoresizingMaskIntoConstraints = true
channelView.view.addSubview(tableView)
msgViewController!.channelViewDict[title] = tableView
let signOutButton: UIButton = UIButton(
frame: CGRect(x: 5, y: height - 80, width: 55, height: 20))
signOutButton.setTitle(" << ", for: UIControlState())
signOutButton.titleLabel?.textColor = UIColor.cyan
signOutButton.addTarget(self, action: #selector(AppDelegate.signOut(_: )), for: .touchUpInside)
channelView.view.addSubview(signOutButton)
let textField: UITextField = UITextField(
frame: CGRect(x: 60, y: height - 80, width: 300, height: 20))
textField.attributedPlaceholder = NSAttributedString(
string: "Enter your message",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightGray])
textField.isUserInteractionEnabled = true
textField.textColor = UIColor.white
textField.backgroundColor = UIColor.black
textField.becomeFirstResponder()
textField.delegate = self
channelView.view.addSubview(textField)
return channelView
}
func application(
_ application: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey: Any]
) -> Bool {
return GIDSignIn.sharedInstance().handle(
url,
sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: [: ]
)
}
func sign(_ signIn: GIDSignIn, didSignInFor user: GIDGoogleUser, withError error: Error?) {
if let error = error {
print("signIn error : \(error.localizedDescription)")
return
}
if self.user == nil {
self.user = user
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if error != nil {
return
}
print("Signed-in to Firebase as \(String(describing: authResult!.user.displayName))")
let nav = UINavigationController(
rootViewController: self.tabBarController!)
self.window?.rootViewController?.present( nav, animated: true, completion: nil)
self.ref = Database.database().reference()
self.inbox = "client-" + String(abs(self.user.userID.hash))
self.msgViewController!.inbox = self.inbox
self.msgViewController!.ref = self.ref
self.requestLogger()
}
}
}
func sign(_ signIn: GIDSignIn, didDisconnectWith user: GIDGoogleUser, withError error: Error) {
// Perform any operations when the user disconnects from the app.
}
@objc func signOut(_ sender: UIButton) {
fbLog!.log(inbox, message: "Signed out")
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
let signInController = self.storyboard!
.instantiateViewController(withIdentifier: "Signin") as UIViewController
let nav = UINavigationController(rootViewController: signInController)
window?.rootViewController?.present(nav, animated: false, completion: nil)
window?.rootViewController?.dismiss(animated: false, completion: nil)
} catch let error as NSError {
print ("Error signing out: %@", error)
}
user = nil
}
// [START requestLogger]
func requestLogger() {
ref.child(IBX + "/" + inbox!).removeValue()
ref.child(IBX + "/" + inbox!)
.observe(.value, with: { snapshot in
print(self.inbox!)
if snapshot.exists() {
self.fbLog = FirebaseLogger(ref: self.ref, path: self.IBX + "/"
+ String(describing: snapshot.value!) + "/logs")
self.ref.child(self.IBX + "/" + self.inbox!).removeAllObservers()
self.msgViewController!.fbLog = self.fbLog
self.fbLog!.log(self.inbox, message: "Signed in")
}
})
ref.child(REQLOG).childByAutoId().setValue(inbox)
}
// [END requestLogger]
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if msgs.count == Int(maxMessages) {
msgs.removeFirst()
}
let channel = tabBarController!.selectedViewController!
.tabBarItem.title! as String
let msg: Message = Message(text: textField.text!, displayName: user.profile.name)
let entry = ref.child(CHS).child(channel).childByAutoId()
entry.setValue(msg.toDictionary())
textField.text = ""
return true
}
}
|
apache-2.0
|
366124b3681d2d2f3ab9dc959cb3f7ba
| 35.773333 | 99 | 0.69664 | 4.779896 | false | false | false | false |
KanChen2015/DRCCamera
|
DRCCamera/DRCCamera/ImageHandler.swift
|
1
|
6613
|
//
// ImageHandler.swift
// DRCCamera
//
// Created by Kan Chen on 9/28/15.
// Copyright © 2015 Kan Chen. All rights reserved.
//
import Foundation
import UIKit
class ImageHandler {
class func scaleAndRotateImage(image : UIImage) -> UIImage{
let kMaxResolution:CGFloat = 8000
let imageRef = image.CGImage!
let width:CGFloat = CGFloat(CGImageGetWidth(imageRef))
let height:CGFloat = CGFloat(CGImageGetHeight(imageRef))
var transform = CGAffineTransformIdentity
var bounds = CGRectMake(0, 0, CGFloat(width), CGFloat(height))
if width > kMaxResolution || height > kMaxResolution {
let ratio: CGFloat = width / height
if ratio > 1 {
bounds.size.width = kMaxResolution
bounds.size.height = bounds.size.width / ratio
} else {
bounds.size.height = kMaxResolution
bounds.size.width = bounds.size.height * ratio
}
}
let scaleRatio = bounds.size.width / width
let imageSize: CGSize = CGSizeMake(width, height)
var boundHeight: CGFloat
let orient = image.imageOrientation
switch orient{
case UIImageOrientation.Up: //EXIF = 1
transform = CGAffineTransformIdentity
break
case .UpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0)
transform = CGAffineTransformScale(transform, -1.0, 1.0)
break
case .Down: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
break
case .DownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height)
transform = CGAffineTransformScale(transform, 1.0, -1.0)
case .LeftMirrored: //EXIF 5
boundHeight = bounds.size.height
bounds.size.height = bounds.size.width
bounds.size.width = boundHeight
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width)
transform = CGAffineTransformScale(transform, -1.0, 1.0)
transform = CGAffineTransformRotate(transform, CGFloat(3.0 * M_PI / 2.0))
break
case .Left: // EXIF = 6
boundHeight = bounds.size.height
bounds.size.height = bounds.size.width
bounds.size.width = boundHeight
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width)
transform = CGAffineTransformRotate(transform, CGFloat(3.0 * M_PI / 2.0))
break
case .RightMirrored: //EXIF = 7
boundHeight = bounds.size.height
bounds.size.height = bounds.size.width
bounds.size.width = boundHeight
transform = CGAffineTransformMakeScale(-1.0, 1.0)
transform = CGAffineTransformRotate(transform, CGFloat( M_PI / 2.0))
break
case .Right: //EXIF = 8
boundHeight = bounds.size.height
bounds.size.height = bounds.size.width
bounds.size.width = boundHeight
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI / 2.0))
break
}
UIGraphicsBeginImageContext(bounds.size)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
if orient == UIImageOrientation.Right || orient == UIImageOrientation.Left{
CGContextScaleCTM(context, -scaleRatio, scaleRatio)
CGContextTranslateCTM(context, -height, 0)
}else{
CGContextScaleCTM(context, scaleRatio, -scaleRatio)
CGContextTranslateCTM(context, 0, -height)
}
CGContextConcatCTM(context, transform)
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imageRef)
let imageCopy: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageCopy
}
class func getImageCorrectedPerspectiv(image: CIImage , feature f: CIRectangleFeature) -> UIImage{
let correctImage = image.imageByApplyingFilter("CIPerspectiveCorrection", withInputParameters: [
"inputTopLeft": CIVector(CGPoint: f.topLeft),
"inputTopRight": CIVector(CGPoint: f.topRight),
"inputBottomLeft": CIVector(CGPoint: f.bottomLeft),
"inputBottomRight": CIVector(CGPoint: f.bottomRight)])
let context = CIContext(options: nil)
let correctRef = context.createCGImage(correctImage, fromRect: correctImage.extent)
let correctUIImage = UIImage(CGImage: correctRef)
return correctUIImage
}
}
extension UIImage{
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let radiansToDegrees: (CGFloat) -> CGFloat = {
return $0 * (180.0 / CGFloat(M_PI))
}
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
|
mit
|
468ee470f204005305c66a5b8d096795
| 40.85443 | 115 | 0.624773 | 5.125581 | false | false | false | false |
IamAlchemist/DemoAnimatedPath
|
AnimatedPath/ViewController.swift
|
2
|
5887
|
//
// ViewController.swift
// AnimatedPath
//
// Created by Wizard Li on 12/28/15.
// Copyright © 2015 morgenworks. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let animationLayer = CALayer()
let penLayer = CALayer()
var pathLayer : CAShapeLayer? = nil
func setupPenLayer() {
let penImage = UIImage(named: "pen")
penLayer.frame = CGRect(x: 0, y: 0, width: penImage!.size.width, height: penImage!.size.height)
penLayer.contents = penImage?.CGImage
penLayer.anchorPoint = CGPointZero
penLayer.hidden = true
}
func setupTextLayer() {
penLayer.removeFromSuperlayer()
self.pathLayer?.removeFromSuperlayer()
let letters = CGPathCreateMutable()
let font = CTFontCreateWithName("Helvetica-Bold" as NSString, 72, nil)
let attrs = [NSFontAttributeName : font]
let attrString = NSAttributedString(string: "Hello!", attributes: attrs)
let line = CTLineCreateWithAttributedString(attrString)
let runArray = ((CTLineGetGlyphRuns(line) as [AnyObject]) as! [CTRunRef])
for index in 0..<CFArrayGetCount(runArray)
{
let run = runArray[index]
for runGlyphIndex in 0..<CTRunGetGlyphCount(run)
{
let thisGlyphRange = CFRangeMake(runGlyphIndex, 1)
var glyph = CGGlyph()
var position = CGPoint()
CTRunGetGlyphs(run, thisGlyphRange, &glyph)
CTRunGetPositions(run, thisGlyphRange, &position)
let letter = CTFontCreatePathForGlyph(font, glyph, nil)
var t = CGAffineTransformMakeTranslation(position.x, position.y);
CGPathAddPath(letters, &t, letter)
}
}
let path = UIBezierPath()
path.moveToPoint(CGPointZero)
path.appendPath(UIBezierPath(CGPath: letters))
let pathLayer = CAShapeLayer()
pathLayer.frame = animationLayer.bounds
pathLayer.bounds = CGPathGetBoundingBox(path.CGPath)
pathLayer.geometryFlipped = true
pathLayer.path = path.CGPath
pathLayer.strokeColor = UIColor.blackColor().CGColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 2
pathLayer.lineJoin = kCALineJoinBevel
self.pathLayer = pathLayer
animationLayer.addSublayer(pathLayer)
pathLayer.addSublayer(penLayer)
}
func setupDrawingLayer() {
penLayer.removeFromSuperlayer()
self.pathLayer?.removeFromSuperlayer()
let pathRect = CGRectInset(animationLayer.bounds, 100, 100)
let bottomLeft = CGPoint(x: CGRectGetMinX(pathRect), y: CGRectGetMinY(pathRect))
let topLeft = CGPoint(x: CGRectGetMinX(pathRect), y: CGRectGetMinY(pathRect) + CGRectGetHeight(pathRect) * 2.0/3.0)
let bottomRight = CGPoint(x: CGRectGetMaxX(pathRect), y: CGRectGetMinY(pathRect))
let topRight = CGPoint(x: CGRectGetMaxX(pathRect), y: CGRectGetMinY(pathRect) + CGRectGetHeight(pathRect) * 2.0/3.0)
let rootTip = CGPoint(x: CGRectGetMidX(pathRect), y: CGRectGetMaxY(pathRect))
let path = UIBezierPath()
path.moveToPoint(bottomLeft)
path.addLineToPoint(topLeft)
path.addLineToPoint(rootTip)
path.addLineToPoint(topRight)
path.addLineToPoint(topLeft)
path.addLineToPoint(bottomRight)
path.addLineToPoint(topRight)
path.addLineToPoint(bottomLeft)
path.addLineToPoint(bottomRight)
let pathLayer = CAShapeLayer()
pathLayer.frame = animationLayer.bounds
pathLayer.bounds = pathRect
pathLayer.geometryFlipped = true
pathLayer.path = path.CGPath
pathLayer.strokeColor = UIColor.blackColor().CGColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 10
pathLayer.lineJoin = kCALineJoinBevel
self.pathLayer = pathLayer
animationLayer.addSublayer(pathLayer)
pathLayer.addSublayer(penLayer)
}
func startAnimation() {
penLayer.removeAllAnimations()
pathLayer?.removeAllAnimations()
penLayer.hidden = false
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd");
pathAnimation.duration = 10
pathAnimation.fromValue = NSNumber(float: 0)
pathAnimation.toValue = NSNumber(float: 1)
pathLayer?.addAnimation(pathAnimation, forKey: "strokeEnd")
let penAnimation = CAKeyframeAnimation(keyPath: "position")
penAnimation.duration = 10
penAnimation.path = pathLayer?.path
penAnimation.calculationMode = kCAAnimationPaced
penAnimation.delegate = self
penAnimation.fillMode = kCAFillModeForwards
penLayer.addAnimation(penAnimation, forKey: "position")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if flag {
penLayer.hidden = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
animationLayer.frame = CGRect(x: 20, y: 64, width: CGRectGetWidth(view.bounds)-40, height: CGRectGetHeight(view.bounds)-84)
view.layer.addSublayer(animationLayer)
setupPenLayer()
setupTextLayer()
startAnimation()
}
@IBAction func segmentChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
setupDrawingLayer()
startAnimation()
case 1:
setupTextLayer()
startAnimation()
default:
break
}
}
}
|
mit
|
57c6a65b6255d6fcc11ec50b2ebaac0b
| 33.023121 | 131 | 0.619436 | 5.269472 | false | false | false | false |
quran/quran-ios
|
Tests/BatchDownloaderTests/NetworkManagerTests.swift
|
1
|
1726
|
//
// NetworkManagerTests.swift
//
//
// Created by Mohamed Afifi on 2022-02-05.
//
@testable import BatchDownloader
import XCTest
class NetworkManagerTests: XCTestCase {
private var networkManager: NetworkManager!
private var session: NetworkSessionFake!
private let baseURL = URL(validURL: "http://example.com")
override func setUpWithError() throws {
session = NetworkSessionFake(queue: .main, delegate: nil)
networkManager = NetworkManager(session: session, baseURL: baseURL)
}
func testRequestCompletedSuccessfully() throws {
let promise = networkManager.request("v1/products", parameters: [("sort", "newest")])
let body = "product1"
let response = URLResponse()
let task = try XCTUnwrap(session.dataTasks.first)
XCTAssertEqual(task.originalRequest?.url?.absoluteString, "http://example.com/v1/products?sort=newest")
session.dataTasks.first?.completionHandler?(body.data(using: .utf8), response, nil)
let result = try wait(for: promise)
XCTAssertEqual(String(data: result, encoding: .utf8), body)
}
func testRequestFailure() throws {
let promise = networkManager.request("v1/products", parameters: [("sort", "newest")])
let task = try XCTUnwrap(session.dataTasks.first)
XCTAssertEqual(task.originalRequest?.url?.absoluteString, "http://example.com/v1/products?sort=newest")
session.dataTasks.first?.completionHandler?(nil, nil, FileSystemError(error: CocoaError(.coderReadCorrupt)))
assert(
try wait(for: promise),
throws: NetworkError.unknown(FileSystemError.unknown(CocoaError(.fileWriteOutOfSpace))) as NSError
)
}
}
|
apache-2.0
|
ad1783a44cbb6afbd3381753d1f7a7fc
| 34.958333 | 116 | 0.690035 | 4.578249 | false | true | false | false |
itssofluffy/NanoMessage
|
examples/pull.swift
|
1
|
2583
|
/*
pull.swift
Copyright (c) 2016, 2017 Stephen Whittle 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 NanoMessage
import ISFLibrary
var urlToUse = "tcp://*:5555"
switch (CommandLine.arguments.count) {
case 1:
break
case 2:
urlToUse = CommandLine.arguments[1]
default:
fatalError("usage: pull [url]")
}
guard let url = URL(string: urlToUse) else {
fatalError("url is not valid")
}
do {
let node = try PullSocket()
print(node)
let endPoint: EndPoint = try node.createEndPoint(url: url, type: .Bind, name: "receive end-point")
print(endPoint)
let timeout = TimeInterval(seconds: 10)
let pollTimeout = TimeInterval(milliseconds: 250)
while (true) {
do {
let received = try node.receiveMessage(timeout: timeout)
print(received)
} catch NanoMessageError.ReceiveTimedOut {
break
} catch {
throw error
}
let socket = try node.pollSocket(timeout: pollTimeout)
if (!socket.messageIsWaiting) {
break
}
}
print("messages: \(node.messagesReceived!)")
print("bytes : \(node.bytesReceived!)")
if (try node.removeEndPoint(endPoint)) {
print("end-point removed")
}
} catch let error as NanoMessageError {
print(error, to: &errorStream)
} catch {
print("an unexpected error '\(error)' has occured in the library libNanoMessage.", to: &errorStream)
}
exit(EXIT_SUCCESS)
|
mit
|
2bb733531a76925666526db81e5a4a06
| 29.75 | 104 | 0.680991 | 4.507853 | false | false | false | false |
guoc/spi
|
SPiKeyboard/TastyImitationKeyboard/DefaultKeyboard.swift
|
1
|
4986
|
//
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
func defaultKeyboard() -> Keyboard {
let defaultKeyboard = Keyboard()
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
let keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
let backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
let keyModeChangeNumbers = Key(.modeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
let keyboardChange = Key(.keyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
let settings = Key(.settings)
defaultKeyboard.addKey(settings, row: 3, page: 0)
let space = Key(.space)
// space.uppercaseKeyCap = "space" // Commented by guoc
space.uppercaseKeyCap = "空格" // Added by guoc
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
let returnKey = Key(.return)
// returnKey.uppercaseKeyCap = "return" // Commented by guoc
returnKey.uppercaseKeyCap = "⏎" // Added by guoc
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
defaultKeyboard.addKey(returnKey, row: 3, page: 0)
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
// for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] {
let row = cornerBracketEnabled ? ["-", "/", ":", ";", "(", ")", "$", "@", "「", "」"] : ["-", "/", ":", ";", "(", ")", "$", "@", "“", "”"]
for key in row {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
let keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
// for key in [".", ",", "?", "!", "'"] {
for key in ["。", ",", "、", "?", "!", "."] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 1)
let keyModeChangeLetters = Key(.modeChange)
keyModeChangeLetters.uppercaseKeyCap = "ABC"
keyModeChangeLetters.toMode = 0
defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 1)
defaultKeyboard.addKey(Key(settings), row: 3, page: 1)
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
// for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
for key in ["【", "】", "{", "}", "#", "%", "^", "*", "+", "="] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
// for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] {
for key in ["_", "—", "\\", "|", "~", "《", "》", "£", "&", "·"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
// for key in [".", ",", "?", "!", "'"] {
for key in ["…", ",", "、", "?", "!", "'"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 2)
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 2)
defaultKeyboard.addKey(Key(settings), row: 3, page: 2)
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
return defaultKeyboard
}
|
bsd-3-clause
|
e97e34fd4493bbd5424f56b3ae17f698
| 34.637681 | 140 | 0.561814 | 3.558611 | false | false | false | false |
Goro-Otsubo/GPaperTrans
|
GPaperTrans/GRootViewController.swift
|
1
|
5331
|
//
// GRootViewController.swift
// GPaperTrans
//
// Created by Goro Otsubo on 2014/11/14.
// Copyright (c) 2014 Goro Otsubo. All rights reserved.
//
import UIKit
// Controller for top basement view
// show top picture
class GRootViewController: UIViewController {
let imageNode:ASImageNode = ASImageNode() // image view for top half
var colViewCtrl:GCollectionViewController? // collectionViewController for bottom half view
var asyncFlag:Bool = true
required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.colViewCtrl = nil
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("storyboards are incompatible with truth and beauty")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
let viewHeight = CGRectGetHeight(self.view.frame)
let viewWidth = CGRectGetWidth(self.view.frame)
let cellSizeRatio:CGFloat = 0.5
let cellHeight = viewHeight * cellSizeRatio //height of cell
// image node for top half
imageNode.frame = CGRectMake(0,0,viewWidth,viewHeight-cellHeight)
imageNode.backgroundColor = UIColor.darkGrayColor()
self.fetchImage(viewWidth, y:viewHeight-cellHeight)
self.view.addSubview(imageNode.view)
let backLabel = UILabel(frame: CGRectMake(0,0,150,40))
backLabel.textColor = UIColor.whiteColor()
backLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
backLabel.text = "Go Back"
self.view.addSubview(backLabel)
let tapRecog = UITapGestureRecognizer()
tapRecog.addTarget(self, action: "tapped:")
self.view.addGestureRecognizer(tapRecog)
let gradLayer = CAGradientLayer()
gradLayer.frame = imageNode.frame;
gradLayer.colors = [
UIColor(white:0.0 , alpha: 0.4).CGColor,
UIColor(white:0.0 , alpha: 0.0).CGColor,
UIColor(white:0.0 , alpha: 0.0).CGColor,
UIColor(white:0.0, alpha: 0.4).CGColor,
UIColor(white:0.0, alpha: 0.6).CGColor
]
gradLayer.startPoint = CGPointMake(0.5,0);
gradLayer.endPoint = CGPointMake(0.5,1.0);
gradLayer.locations = [0.0,0.2,0.93,0.98,1.0]
imageNode.layer.addSublayer(gradLayer)
let shortLayout = UICollectionViewFlowLayout()
shortLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
shortLayout.itemSize = CGSizeMake(viewWidth*cellSizeRatio,cellHeight)
shortLayout.sectionInset = UIEdgeInsetsMake(viewHeight - cellHeight, 0, 0, 0)
shortLayout.minimumInteritemSpacing = 0
shortLayout.minimumLineSpacing = 3
let tallLayout = UICollectionViewFlowLayout()
tallLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
tallLayout.itemSize = CGSizeMake(viewWidth,viewHeight)
tallLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
tallLayout.minimumInteritemSpacing = 0
tallLayout.minimumLineSpacing = 0
self.colViewCtrl = GCollectionViewController(collectionViewLayout: shortLayout)
colViewCtrl?.asyncNodeFlag = asyncFlag
colViewCtrl!.view.frame = self.view.frame
colViewCtrl!.tallLayout = tallLayout
colViewCtrl!.shortLayout = shortLayout
self.view.addSubview(colViewCtrl!.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Just for Demo
//fetch image and display in upper half part of screen
func fetchImage(x:CGFloat, y:CGFloat){
let url = NSURL(string:"http://lorempixel.com/\(Int(x))/\(Int(y))/")
SDWebImageDownloader.sharedDownloader().downloadImageWithURL(url,
options: SDWebImageDownloaderOptions.IgnoreCachedResponse,
progress: nil,
completed: {[weak self] (image, data, error, finished) in
if let wSelf = self {
// do what you want with the image/self
if let imageData = image {
if(wSelf.imageNode.nodeLoaded){
dispatch_sync(dispatch_get_main_queue()) {
// once the node's view is loaded, the node should only be used on the main thread
wSelf.imageNode.image = imageData
}
}
else{
wSelf.imageNode.image = imageData
}
}
}
})
}
// call back function to close this controller
func tapped(sender:UITapGestureRecognizer){
let tappedPos = sender.locationInView(sender.view)
if CGRectContainsPoint(CGRectMake(0,0,150,100), tappedPos) {
dismissViewControllerAnimated(true, completion: nil)
}
}
}
|
mit
|
3d858b62f352c941a32d7d041c0d8185
| 35.265306 | 114 | 0.612831 | 5.000938 | false | false | false | false |
IngmarStein/swift
|
stdlib/public/core/ArrayCast.swift
|
4
|
3158
|
//===--- ArrayCast.swift - Casts and conversions for Array ----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Because NSArray is effectively an [AnyObject], casting [T] -> [U]
// is an integral part of the bridging process and these two issues
// are handled together.
//
//===----------------------------------------------------------------------===//
@_silgen_name("_swift_arrayDownCastIndirect")
public func _arrayDownCastIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Array<SourceValue>>,
_ target: UnsafeMutablePointer<Array<TargetValue>>) {
target.initialize(to: _arrayForceCast(source.pointee))
}
/// Implements `source as! [TargetElement]`.
///
/// - Note: When SourceElement and TargetElement are both bridged verbatim, type
/// checking is deferred until elements are actually accessed.
public func _arrayForceCast<SourceElement, TargetElement>(
_ source: Array<SourceElement>
) -> Array<TargetElement> {
#if _runtime(_ObjC)
if _isClassOrObjCExistential(SourceElement.self)
&& _isClassOrObjCExistential(TargetElement.self) {
let src = source._buffer
if let native = src.requestNativeBuffer() {
if native.storesOnlyElementsOfType(TargetElement.self) {
// A native buffer that is known to store only elements of the
// TargetElement can be used directly
return Array(_buffer: src.cast(toBufferOf: TargetElement.self))
}
// Other native buffers must use deferred element type checking
return Array(_buffer:
src.downcast(toBufferWithDeferredTypeCheckOf: TargetElement.self))
}
return Array(_immutableCocoaArray: source._buffer._asCocoaArray())
}
#endif
return source.map { $0 as! TargetElement }
}
internal struct _UnwrappingFailed : Error {}
extension Optional {
internal func unwrappedOrError() throws -> Wrapped {
if let x = self { return x }
throw _UnwrappingFailed()
}
}
@_silgen_name("_swift_arrayDownCastConditionalIndirect")
public func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Array<SourceValue>>,
_ target: UnsafeMutablePointer<Array<TargetValue>>
) -> Bool {
if let result: Array<TargetValue> = _arrayConditionalCast(source.pointee) {
target.initialize(to: result)
return true
}
return false
}
/// Implements `source as? [TargetElement]`: convert each element of
/// `source` to a `TargetElement` and return the resulting array, or
/// return `nil` if any element fails to convert.
///
/// - Complexity: O(n), because each element must be checked.
public func _arrayConditionalCast<SourceElement, TargetElement>(
_ source: [SourceElement]
) -> [TargetElement]? {
return try? source.map { try ($0 as? TargetElement).unwrappedOrError() }
}
|
apache-2.0
|
0e8d93a2e0c3e34b61cf759acc66056b
| 37.048193 | 80 | 0.684611 | 4.422969 | false | false | false | false |
gurenupet/hah-auth-ios-swift
|
hah-auth-ios-swift/hah-auth-ios-swift/Libs/JHTAlertController/JHTAlertAnimation.swift
|
2
|
3333
|
//
// JHTAlertAnimation.swift
// JHTAlertController
//
// Created by Jessel, Jeremiah on 11/15/16.
// Copyright © 2016 Jacuzzi Hot Tubs, LLC. All rights reserved.
//
import UIKit
public class JHTAlertAnimation : NSObject, UIViewControllerAnimatedTransitioning {
/// Lets the animation transition know if the alert is presenting or dismissing
let isPresenting: Bool
/// The initialization of the JHTAlertAnimation
///
/// - Parameter isPresenting: a Bool that determines if the alert is presenting or dismissing
init(isPresenting: Bool) {
self.isPresenting = isPresenting
}
// MARK: Transition Animations
/// The duration of the animation.
///
/// - Parameter transitionContext: the context of the animation
/// - Returns: a time interval that differes if the alert is presenting or dismissing
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return isPresenting ? 0.2 : 0.2
}
/// Calls the appropriate animatation
///
/// - Parameter transitionContext: the context of the animation
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresenting {
self.presentAnimateTransition(transitionContext)
} else {
self.dismissAnimateTransition(transitionContext)
}
}
/// Presents the alert animation
///
/// - Parameter transitionContext: the context for the animation
func presentAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
guard let alertController = transitionContext.viewController(forKey: .to) as? JHTAlertController else {
return
}
let containerView = transitionContext.containerView
containerView.addSubview(alertController.view)
containerView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
containerView.alpha = 0
alertController.view.alpha = 0.0
alertController.view.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
UIView.animate(withDuration:self.transitionDuration(using: transitionContext), animations: {
alertController.view.alpha = 1.0
containerView.alpha = 1.0
alertController.view.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}, completion: { _ in
UIView.animate(withDuration: 0.2, animations: {
alertController.view.transform = CGAffineTransform.identity
}, completion: { _ in
transitionContext.completeTransition(true)
})
})
}
/// The dismiss animation for the alert
///
/// - Parameter transitionContext: the context for the animation
func dismissAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
let alertController = transitionContext.viewController(forKey: .from) as! JHTAlertController
let containerView = transitionContext.containerView
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
alertController.view.alpha = 0.0
containerView.alpha = 0.0
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
}
|
mit
|
1d53986762b7b01f615200b5d8c853ca
| 34.446809 | 115 | 0.690576 | 5.391586 | false | false | false | false |
giaunv/physicscup-swift-spritekit-iphone
|
physicscup/GameViewController.swift
|
1
|
2872
|
//
// GameViewController.swift
// physicscup
//
// Created by giaunv on 3/28/15.
// Copyright (c) 2015 366. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
var lastRotation = CGFloat(0);
@IBAction func rotated(sender: UIRotationGestureRecognizer) {
if(sender.state == UIGestureRecognizerState.Ended){
lastRotation = 0.0
return
}
var rotation = 0.0 - (sender.rotation - lastRotation)
var trans = CGAffineTransformMakeRotation(rotation)
let skView = self.view as SKView
if let skScene = skView.scene{
var newGravity = CGPointApplyAffineTransform(CGPointMake(skScene.physicsWorld.gravity.dx, skScene.physicsWorld.gravity.dy), trans)
skScene.physicsWorld.gravity = CGVectorMake(newGravity.x, newGravity.y)
}
lastRotation = sender.rotation
}
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
e2611a87bb4c4a5084b55c14ce31c1b7
| 31.636364 | 142 | 0.626045 | 5.408663 | false | false | false | false |
airspeedswift/swift
|
test/AutoDiff/Sema/derivative_attr_type_checking.swift
|
3
|
44678
|
// RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s
// Swift.AdditiveArithmetic:3:17: note: cannot yet register derivative default implementation for protocol requirements
import _Differentiation
// Dummy `Differentiable`-conforming type.
struct DummyTangentVector: Differentiable & AdditiveArithmetic {
static var zero: Self { Self() }
static func + (_: Self, _: Self) -> Self { Self() }
static func - (_: Self, _: Self) -> Self { Self() }
typealias TangentVector = Self
}
// Test top-level functions.
func id(_ x: Float) -> Float {
return x
}
@derivative(of: id)
func jvpId(x: Float) -> (value: Float, differential: (Float) -> (Float)) {
return (x, { $0 })
}
@derivative(of: id, wrt: x)
func vjpIdExplicitWrt(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
func generic<T: Differentiable>(_ x: T, _ y: T) -> T {
return x
}
@derivative(of: generic)
func jvpGeneric<T: Differentiable>(x: T, y: T) -> (
value: T, differential: (T.TangentVector, T.TangentVector) -> T.TangentVector
) {
return (x, { $0 + $1 })
}
@derivative(of: generic)
func vjpGenericExtraGenericRequirements<T: Differentiable & FloatingPoint>(
x: T, y: T
) -> (value: T, pullback: (T) -> (T, T)) where T == T.TangentVector {
return (x, { ($0, $0) })
}
// Test `wrt` parameter clauses.
func add(x: Float, y: Float) -> Float {
return x + y
}
@derivative(of: add, wrt: x) // ok
func vjpAddWrtX(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
@derivative(of: add, wrt: (x, y)) // ok
func vjpAddWrtXY(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// Test index-based `wrt` parameters.
func subtract(x: Float, y: Float) -> Float {
return x - y
}
@derivative(of: subtract, wrt: (0, y)) // ok
func vjpSubtractWrt0Y(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
@derivative(of: subtract, wrt: (1)) // ok
func vjpSubtractWrt1(x: Float, y: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x - y, { $0 })
}
// Test invalid original function.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test `@derivative` attribute where `value:` result does not conform to `Differentiable`.
// Invalid original function should be diagnosed first.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound2(_ x: Float) -> (value: Int, pullback: (Float) -> Float) {
fatalError()
}
// Test incorrect `@derivative` declaration type.
// expected-note @+2 {{'incorrectDerivativeType' defined here}}
// expected-note @+1 {{candidate global function does not have expected type '(Int) -> Int'}}
func incorrectDerivativeType(_ x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:' and second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func jvpResultIncorrect(x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectFirstLabel(x: Float) -> (Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectSecondLabel(x: Float) -> (value: Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{referenced declaration 'incorrectDerivativeType' could not be resolved}}
@derivative(of: incorrectDerivativeType)
func vjpResultNotDifferentiable(x: Int) -> (
value: Int, pullback: (Int) -> Int
) {
return (x, { $0 })
}
// expected-error @+2 {{function result's 'pullback' type does not match 'incorrectDerivativeType'}}
// expected-note @+3 {{'pullback' does not have expected type '(Float.TangentVector) -> Float.TangentVector' (aka '(Float) -> Float')}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectPullbackType(x: Float) -> (
value: Float, pullback: (Double) -> Double
) {
return (x, { $0 })
}
// Test invalid `wrt:` differentiation parameters.
func invalidWrtParam(_ x: Float, _ y: Float) -> Float {
return x
}
// expected-error @+1 {{unknown parameter name 'z'}}
@derivative(of: add, wrt: z)
func vjpUnknownParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (y, x))
func vjpParamOrderNotIncreasing(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: invalidWrtParam, wrt: self)
func vjpInvalidSelfParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{parameter index is larger than total number of parameters}}
@derivative(of: invalidWrtParam, wrt: 2)
func vjpSubtractWrt2(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, x))
func vjpSubtractWrt1x(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, 0))
func vjpSubtractWrt10(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
func noParameters() -> Float {
return 1
}
// expected-error @+1 {{'vjpNoParameters()' has no parameters to differentiate with respect to}}
@derivative(of: noParameters)
func vjpNoParameters() -> (value: Float, pullback: (Float) -> Float) {
return (1, { $0 })
}
func noDifferentiableParameters(x: Int) -> Float {
return 1
}
// expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
@derivative(of: noDifferentiableParameters)
func vjpNoDifferentiableParameters(x: Int) -> (
value: Float, pullback: (Float) -> Int
) {
return (1, { _ in 0 })
}
func functionParameter(_ fn: (Float) -> Float) -> Float {
return fn(1)
}
// expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '(Float) -> Float' does not conform to 'Differentiable'}}
@derivative(of: functionParameter, wrt: fn)
func vjpFunctionParameter(_ fn: (Float) -> Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (functionParameter(fn), { $0 })
}
// Test static methods.
protocol StaticMethod: Differentiable {
static func foo(_ x: Float) -> Float
static func generic<T: Differentiable>(_ x: T) -> T
}
extension StaticMethod {
static func foo(_ x: Float) -> Float { x }
static func generic<T: Differentiable>(_ x: T) -> T { x }
}
extension StaticMethod {
@derivative(of: foo)
static func jvpFoo(x: Float) -> (value: Float, differential: (Float) -> Float)
{
return (x, { $0 })
}
// Test qualified declaration name.
@derivative(of: StaticMethod.foo)
static func vjpFoo(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
@derivative(of: generic)
static func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: foo, wrt: (self, x))
static func vjpFooWrtSelf(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
}
// Test instance methods.
protocol InstanceMethod: Differentiable {
func foo(_ x: Self) -> Self
func generic<T: Differentiable>(_ x: T) -> Self
}
extension InstanceMethod {
// expected-note @+1 {{'foo' defined here}}
func foo(_ x: Self) -> Self { x }
// expected-note @+1 {{'generic' defined here}}
func generic<T: Differentiable>(_ x: T) -> Self { self }
}
extension InstanceMethod {
@derivative(of: foo)
func jvpFoo(x: Self) -> (
value: Self, differential: (TangentVector, TangentVector) -> (TangentVector)
) {
return (x, { $0 + $1 })
}
// Test qualified declaration name.
@derivative(of: InstanceMethod.foo, wrt: x)
func jvpFooWrtX(x: Self) -> (
value: Self, differential: (TangentVector) -> (TangentVector)
) {
return (x, { $0 })
}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> (TangentVector, T.TangentVector)
) {
return (self, { ($0, .zero) })
}
@derivative(of: generic, wrt: (self, x))
func jvpGenericWrt<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
// expected-error @+1 {{'self' parameter must come first in the parameter list}}
@derivative(of: generic, wrt: (x, self))
func jvpGenericWrtSelf<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
}
extension InstanceMethod {
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'foo'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)'}}
@derivative(of: foo)
func vjpFoo(x: Self) -> (
value: Self, pullback: (TangentVector) -> TangentVector
) {
return (x, { $0 })
}
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'generic'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, T.TangentVector)'}}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> T.TangentVector
) {
return (self, { _ in .zero })
}
}
// Test `@derivative` declaration with more constrained generic signature.
func req1<T>(_ x: T) -> T {
return x
}
@derivative(of: req1)
func vjpExtraConformanceConstraint<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
func req2<T, U>(_ x: T, _ y: U) -> T {
return x
}
@derivative(of: req2)
func vjpExtraConformanceConstraints<T: Differentiable, U: Differentiable>( _ x: T, _ y: U) -> (
value: T, pullback: (T) -> (T, U)
) where T == T.TangentVector, U == U.TangentVector, T: CustomStringConvertible {
return (x, { ($0, .zero) })
}
// Test `@derivative` declaration with extra same-type requirements.
func req3<T>(_ x: T) -> T {
return x
}
@derivative(of: req3)
func vjpSameTypeRequirementsGenericParametersAllConcrete<T>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) where T: Differentiable, T.TangentVector == Float {
return (x, { $0 })
}
struct Wrapper<T: Equatable>: Equatable {
var x: T
init(_ x: T) { self.x = x }
}
extension Wrapper: AdditiveArithmetic where T: AdditiveArithmetic {
static var zero: Self { .init(.zero) }
static func + (lhs: Self, rhs: Self) -> Self { .init(lhs.x + rhs.x) }
static func - (lhs: Self, rhs: Self) -> Self { .init(lhs.x - rhs.x) }
}
extension Wrapper: Differentiable where T: Differentiable, T == T.TangentVector {
typealias TangentVector = Wrapper<T.TangentVector>
}
extension Wrapper where T: Differentiable, T == T.TangentVector {
@derivative(of: init(_:))
static func vjpInit(_ x: T) -> (value: Self, pullback: (Wrapper<T>.TangentVector) -> (T)) {
fatalError()
}
}
// Test class methods.
class Super {
@differentiable
// expected-note @+1 {{candidate instance method is not defined in the current type context}}
func foo(_ x: Float) -> Float {
return x
}
@derivative(of: foo)
func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (foo(x), { v in v })
}
}
class Sub: Super {
// TODO(TF-649): Enable `@derivative` to override derivatives for original
// declaration defined in superclass.
// expected-error @+1 {{referenced declaration 'foo' could not be resolved}}
@derivative(of: foo)
override func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float)
{
return (foo(x), { v in v })
}
}
// Test non-`func` original declarations.
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Differentiable & AdditiveArithmetic
where T: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Struct<T.TangentVector>
mutating func move(along direction: TangentVector) {
x.move(along: direction.x)
}
}
class Class<T> {
var x: T
init(_ x: T) {
self.x = x
}
}
extension Class: Differentiable where T: Differentiable {}
// Test computed properties.
extension Struct {
var computedProperty: T {
get { x }
set { x = newValue }
_modify { yield &x }
}
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: computedProperty)
func vjpProperty() -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { v in .init(x: v) })
}
@derivative(of: computedProperty.get)
func jvpProperty() -> (value: T, differential: (TangentVector) -> T.TangentVector) {
fatalError()
}
@derivative(of: computedProperty.set)
mutating func vjpPropertySetter(_ newValue: T) -> (
value: (), pullback: (inout TangentVector) -> T.TangentVector
) {
fatalError()
}
// expected-error @+1 {{cannot register derivative for _modify accessor}}
@derivative(of: computedProperty._modify)
mutating func vjpPropertyModify(_ newValue: T) -> (
value: (), pullback: (inout TangentVector) -> T.TangentVector
) {
fatalError()
}
}
// Test initializers.
extension Struct {
init(_ x: Float) {}
init(_ x: T, y: Float) {}
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: init)
static func vjpInit(_ x: Float) -> (
value: Struct, pullback: (TangentVector) -> Float
) {
return (.init(x), { _ in .zero })
}
@derivative(of: init(_:y:))
static func vjpInit2(_ x: T, _ y: Float) -> (
value: Struct, pullback: (TangentVector) -> (T.TangentVector, Float)
) {
return (.init(x, y: y), { _ in (.zero, .zero) })
}
}
// Test subscripts.
extension Struct {
subscript() -> Float {
get { 1 }
set {}
}
subscript(float float: Float) -> Float {
get { 1 }
set {}
}
// expected-note @+1 {{candidate subscript does not have a setter}}
subscript<T: Differentiable>(x: T) -> T { x }
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: subscript.get)
func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript)
func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript().get)
func jvpSubscriptGetter() -> (value: Float, differential: (TangentVector) -> Float) {
return (1, { _ in .zero })
}
@derivative(of: subscript(float:).get, wrt: self)
func vjpSubscriptLabeledGetter(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript(float:), wrt: self)
func vjpSubscriptLabeled(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript(float:).get)
func jvpSubscriptLabeledGetter(float: Float) -> (value: Float, differential: (TangentVector, Float) -> Float) {
return (1, { (_,_) in 1})
}
@derivative(of: subscript(_:).get, wrt: self)
func vjpSubscriptGenericGetter<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript(_:), wrt: self)
func vjpSubscriptGeneric<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { _ in .zero })
}
@derivative(of: subscript.set)
mutating func vjpSubscriptSetter(_ newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> Float
) {
fatalError()
}
@derivative(of: subscript().set)
mutating func jvpSubscriptSetter(_ newValue: Float) -> (
value: (), differential: (inout TangentVector, Float) -> ()
) {
fatalError()
}
@derivative(of: subscript(float:).set)
mutating func vjpSubscriptLabeledSetter(float: Float, newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> (Float, Float)
) {
fatalError()
}
@derivative(of: subscript(float:).set)
mutating func jvpSubscriptLabeledSetter(float: Float, _ newValue: Float) -> (
value: (), differential: (inout TangentVector, Float, Float) -> Void
) {
fatalError()
}
// Error: original subscript has no setter.
// expected-error @+1 {{referenced declaration 'subscript(_:)' could not be resolved}}
@derivative(of: subscript(_:).set, wrt: self)
mutating func vjpSubscriptGeneric_NoSetter<T: Differentiable>(x: T) -> (
value: T, pullback: (T.TangentVector) -> TangentVector
) {
return (x, { _ in .zero })
}
}
extension Class {
subscript() -> Float {
get { 1 }
// expected-note @+1 {{'subscript()' declared here}}
set {}
}
}
extension Class where T: Differentiable {
@derivative(of: subscript.get)
func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript)
func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// FIXME(SR-13096): Enable derivative registration for class property/subscript setters.
// This requires changing derivative type calculation rules for functions with
// class-typed parameters. We need to assume that all functions taking
// class-typed operands may mutate those operands.
// expected-error @+1 {{cannot yet register derivative for class property or subscript setters}}
@derivative(of: subscript.set)
func vjpSubscriptSetter(_ newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> Float
) {
fatalError()
}
}
// Test duplicate `@derivative` attribute.
func duplicate(_ x: Float) -> Float { x }
// expected-note @+1 {{other attribute declared here}}
@derivative(of: duplicate)
func jvpDuplicate1(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// expected-error @+1 {{a derivative already exists for 'duplicate'}}
@derivative(of: duplicate)
func jvpDuplicate2(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// Test invalid original declaration kind.
// expected-note @+1 {{candidate var does not have a getter}}
var globalVariable: Float
// expected-error @+1 {{referenced declaration 'globalVariable' could not be resolved}}
@derivative(of: globalVariable)
func invalidOriginalDeclaration(x: Float) -> (
value: Float, differential: (Float) -> (Float)
) {
return (x, { $0 })
}
// Test ambiguous original declaration.
protocol P1 {}
protocol P2 {}
// expected-note @+1 {{candidate global function found here}}
func ambiguous<T: P1>(_ x: T) -> T { x }
// expected-note @+1 {{candidate global function found here}}
func ambiguous<T: P2>(_ x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'ambiguous' is ambiguous}}
@derivative(of: ambiguous)
func jvpAmbiguous<T: P1 & P2 & Differentiable>(x: T)
-> (value: T, differential: (T.TangentVector) -> (T.TangentVector))
{
return (x, { $0 })
}
// Test no valid original declaration.
// Original declarations are invalid because they have extra generic
// requirements unsatisfied by the `@derivative` function.
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: BinaryFloatingPoint>(x: T) -> T { x }
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: CustomStringConvertible>(x: T) -> T { x }
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: FloatingPoint>(x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'invalid' could not be resolved}}
@derivative(of: invalid)
func jvpInvalid<T: Differentiable>(x: T) -> (
value: T, differential: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
// Test invalid derivative type context: instance vs static method mismatch.
struct InvalidTypeContext<T: Differentiable> {
// expected-note @+1 {{candidate static method does not have type equal to or less constrained than '<T where T : Differentiable> (InvalidTypeContext<T>) -> (T) -> T'}}
static func staticMethod(_ x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'staticMethod' could not be resolved}}
@derivative(of: staticMethod)
func jvpStatic(_ x: T) -> (
value: T, differential: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
}
// Test stored property original declaration.
struct HasStoredProperty {
// expected-note @+1 {{'stored' declared here}}
var stored: Float
}
extension HasStoredProperty: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Self
}
extension HasStoredProperty {
// expected-error @+1 {{cannot register derivative for stored property 'stored'}}
@derivative(of: stored)
func vjpStored() -> (value: Float, pullback: (Float) -> TangentVector) {
return (stored, { _ in .zero })
}
}
// Test derivative registration for protocol requirements. Currently unsupported.
// TODO(TF-982): Lift this restriction and add proper support.
protocol ProtocolRequirementDerivative {
// expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}}
func requirement(_ x: Float) -> Float
}
extension ProtocolRequirementDerivative {
// expected-error @+1 {{referenced declaration 'requirement' could not be resolved}}
@derivative(of: requirement)
func vjpRequirement(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
}
// Test `inout` parameters.
func multipleSemanticResults(_ x: inout Float) -> Float {
return x
}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(x: inout Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (multipleSemanticResults(&x), { $0 })
}
struct InoutParameters: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
}
extension InoutParameters {
// expected-note @+1 4 {{'staticMethod(_:rhs:)' defined here}}
static func staticMethod(_ lhs: inout Self, rhs: Self) {}
// Test wrt `inout` parameter.
@derivative(of: staticMethod)
static func vjpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func vjpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod)
static func jvpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func jvpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` parameter.
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (inout TangentVector) -> TangentVector
) { fatalError() }
}
extension InoutParameters {
// expected-note @+1 4 {{'mutatingMethod' defined here}}
mutating func mutatingMethod(_ other: Self) {}
// Test wrt `inout` `self` parameter.
@derivative(of: mutatingMethod)
mutating func vjpWrtInout(_ other: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func vjpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod)
mutating func jvpWrtInout(_ other: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func jvpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` `self` parameter.
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInout(_ other: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInout(_ other: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
}
// Test no semantic results.
func noSemanticResults(_ x: Float) {}
// expected-error @+1 {{cannot differentiate void function 'noSemanticResults'}}
@derivative(of: noSemanticResults)
func vjpNoSemanticResults(_ x: Float) -> (value: Void, pullback: Void) {}
// Test multiple semantic results.
extension InoutParameters {
func multipleSemanticResults(_ x: inout Float) -> Float { x }
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(_ x: inout Float) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
func inoutVoid(_ x: Float, _ void: inout Void) -> Float {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: inoutVoid)
func vjpInoutVoidParameter(_ x: Float, _ void: inout Void) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
}
// Test original/derivative function `inout` parameter mismatches.
extension InoutParameters {
// expected-note @+1 {{candidate instance method does not have expected type '(InoutParameters) -> (inout Float) -> Void'}}
func inoutParameterMismatch(_ x: Float) {}
// expected-error @+1 {{referenced declaration 'inoutParameterMismatch' could not be resolved}}
@derivative(of: inoutParameterMismatch)
func vjpInoutParameterMismatch(_ x: inout Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
// expected-note @+1 {{candidate instance method does not have expected type '(inout InoutParameters) -> (Float) -> Void'}}
func mutatingMismatch(_ x: Float) {}
// expected-error @+1 {{referenced declaration 'mutatingMismatch' could not be resolved}}
@derivative(of: mutatingMismatch)
mutating func vjpMutatingMismatch(_ x: Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
}
// Test cross-file derivative registration.
extension FloatingPoint where Self: Differentiable {
@usableFromInline
@derivative(of: rounded)
func vjpRounded() -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector)
) {
fatalError()
}
}
extension Differentiable where Self: AdditiveArithmetic {
// expected-error @+1 {{referenced declaration '+' could not be resolved}}
@derivative(of: +)
static func vjpPlus(x: Self, y: Self) -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)
) {
return (x + y, { v in (v, v) })
}
}
extension AdditiveArithmetic
where Self: Differentiable, Self == Self.TangentVector {
// expected-error @+1 {{referenced declaration '+' could not be resolved}}
@derivative(of: +)
func vjpPlusInstanceMethod(x: Self, y: Self) -> (
value: Self, pullback: (Self) -> (Self, Self)
) {
return (x + y, { v in (v, v) })
}
}
// Test derivatives of default implementations.
protocol HasADefaultImplementation {
func req(_ x: Float) -> Float
}
extension HasADefaultImplementation {
func req(_ x: Float) -> Float { x }
// ok
@derivative(of: req)
func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// Test default derivatives of requirements.
protocol HasADefaultDerivative {
// expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}}
func req(_ x: Float) -> Float
}
extension HasADefaultDerivative {
// TODO(TF-982): Support default derivatives for protocol requirements.
// expected-error @+1 {{referenced declaration 'req' could not be resolved}}
@derivative(of: req)
func vjpReq(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// MARK: - Original function visibility = derivative function visibility
public func public_original_public_derivative(_ x: Float) -> Float { x }
@derivative(of: public_original_public_derivative)
public func _public_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_usablefrominline_derivative(_ x: Float) -> Float { x }
@usableFromInline
@derivative(of: public_original_usablefrominline_derivative)
func _public_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_internal_derivative(_ x: Float) -> Float { x }
@derivative(of: internal_original_internal_derivative)
func _internal_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_private_derivative(_ x: Float) -> Float { x }
@derivative(of: private_original_private_derivative)
private func _private_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_fileprivate_derivative(_ x: Float) -> Float { x }
@derivative(of: fileprivate_original_fileprivate_derivative)
fileprivate func _fileprivate_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_usablefrominline_derivative(_ x: Float) -> Float { x }
@usableFromInline
@derivative(of: internal_original_usablefrominline_derivative)
func _internal_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_inlinable_derivative(_ x: Float) -> Float { x }
@inlinable
@derivative(of: internal_original_inlinable_derivative)
func _internal_original_inlinable_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_alwaysemitintoclient_derivative(_ x: Float) -> Float { x }
@_alwaysEmitIntoClient
@derivative(of: internal_original_alwaysemitintoclient_derivative)
func _internal_original_alwaysemitintoclient_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility < derivative function visibility
@usableFromInline
func usablefrominline_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_usablefrominline_original_public_derivative' is public, but original function 'usablefrominline_original_public_derivative' is internal}}
@derivative(of: usablefrominline_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _usablefrominline_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_public_derivative' is public, but original function 'internal_original_public_derivative' is internal}}
@derivative(of: internal_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _internal_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_usablefrominline_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_usablefrominline_derivative' is internal, but original function 'private_original_usablefrominline_derivative' is private}}
@derivative(of: private_original_usablefrominline_derivative)
@usableFromInline
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-1=private }}
func _private_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_public_derivative' is public, but original function 'private_original_public_derivative' is private}}
@derivative(of: private_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-7=private}}
public func _private_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_internal_derivative' is internal, but original function 'private_original_internal_derivative' is private}}
@derivative(of: private_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}}
func _private_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_fileprivate_original_private_derivative' is private, but original function 'fileprivate_original_private_derivative' is fileprivate}}
@derivative(of: fileprivate_original_private_derivative)
// expected-note @+1 {{mark the derivative function as 'fileprivate' to match the original function}} {{1-8=fileprivate}}
private func _fileprivate_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_fileprivate_derivative' is fileprivate, but original function 'private_original_fileprivate_derivative' is private}}
@derivative(of: private_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-12=private}}
fileprivate func _private_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility > derivative function visibility
public func public_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_private_derivative' is fileprivate, but original function 'public_original_private_derivative' is public}}
@derivative(of: public_original_private_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
fileprivate func _public_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_internal_derivative' is internal, but original function 'public_original_internal_derivative' is public}}
@derivative(of: public_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
func _public_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_fileprivate_derivative' is fileprivate, but original function 'internal_original_fileprivate_derivative' is internal}}
@derivative(of: internal_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-12=internal}}
fileprivate func _internal_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test invalid reference to an accessor of a non-storage declaration.
// expected-note @+1 {{candidate global function does not have a getter}}
func function(_ x: Float) -> Float {
x
}
// expected-error @+1 {{referenced declaration 'function' could not be resolved}}
@derivative(of: function(_:).get)
func vjpFunction(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test ambiguity that exists when Type function name is the same
// as an accessor label.
extension Float {
// Original function name conflicts with an accessor name ("set").
func set() -> Float {
self
}
// Original function name does not conflict with an accessor name.
func method() -> Float {
self
}
// Test ambiguous parse.
// Expected:
// - Base type: `Float`
// - Declaration name: `set`
// - Accessor kind: <none>
// Actual:
// - Base type: <none>
// - Declaration name: `Float`
// - Accessor kind: `set`
// expected-error @+1 {{cannot find 'Float' in scope}}
@derivative(of: Float.set)
func jvpSet() -> (value: Float, differential: (Float) -> Float) {
fatalError()
}
@derivative(of: Float.method)
func jvpMethod() -> (value: Float, differential: (Float) -> Float) {
fatalError()
}
}
// Test original function with opaque result type.
// expected-note @+1 {{candidate global function does not have expected type '(Float) -> Float'}}
func opaqueResult(_ x: Float) -> some Differentiable { x }
// expected-error @+1 {{referenced declaration 'opaqueResult' could not be resolved}}
@derivative(of: opaqueResult)
func vjpOpaqueResult(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
|
apache-2.0
|
42da5631a741576825e91ae47537f5d9
| 37.317324 | 256 | 0.688728 | 3.865213 | false | false | false | false |
vinsalmont/Movie
|
Pods/BNRCoreDataStack/Sources/NSPersistentStoreCoordinator+AsyncHelpers.swift
|
2
|
1586
|
//
// NSPersistentStoreCoordinator+AsyncHelpers.swift
// CoreDataStack
//
// Created by Zachary Waldowski on 12/2/15.
// Copyright © 2015-2016 Big Nerd Ranch. All rights reserved.
//
import CoreData
extension NSPersistentStoreCoordinator {
/**
Synchronously exexcutes a given function on the coordinator's internal
queue.
- attention: This method may safely be called reentrantly.
- parameter body: The method body to perform on the reciever.
- returns: The value returned from the inner function.
- throws: Any error thrown by the inner function. This method should be
technically `rethrows`, but cannot be due to Swift limitations.
**/
public func performAndWaitOrThrow<Return>(_ body: () throws -> Return) rethrows -> Return {
func impl(execute work: () throws -> Return, recover: (Error) throws -> Void) rethrows -> Return {
var result: Return!
var error: Error?
// performAndWait is marked @escaping as of iOS 10.0.
// swiftlint:disable type_name
typealias Fn = (() -> Void) -> Void
let performAndWaitNoescape = unsafeBitCast(self.performAndWait, to: Fn.self)
performAndWaitNoescape {
do {
result = try work()
} catch let e {
error = e
}
}
if let error = error {
try recover(error)
}
return result
}
return try impl(execute: body, recover: { throw $0 })
}
}
|
apache-2.0
|
f819f61371a1c8625b64048579a81e06
| 32.020833 | 106 | 0.591798 | 5 | false | false | false | false |
MrZoidberg/metapp
|
metapp/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift
|
26
|
14823
|
//
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension Reactive where Base: UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bindTo(tableView.rx.items) { (tableView, row, element) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(row)"
return cell
}
.addDisposableTo(disposeBag)
*/
public func items<S: Sequence, O: ObservableType>
(_ source: O)
-> (_ cellFactory: @escaping (UITableView, Int, S.Iterator.Element) -> UITableViewCell)
-> Disposable
where O.E == S {
return { cellFactory in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.items(dataSource: dataSource)(source)
}
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bindTo(tableView.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = "\(element) @ row \(row)"
}
.addDisposableTo(disposeBag)
*/
public func items<S: Sequence, Cell: UITableViewCell, O : ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: O)
-> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
-> Disposable
where O.E == S {
return { source in
return { configureCell in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = IndexPath(item: i, section: 0)
let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
This method will retain the data source for as long as the subscription isn't disposed (result `Disposable`
being disposed).
In case `source` observable sequence terminates sucessfully, the data source will present latest element
until the subscription isn't disposed.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
Example
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
let items = Observable.just([
SectionModel(model: "First section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Second section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Third section", items: [
1.0,
2.0,
3.0
])
])
dataSource.configureCell = { (dataSource, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
items
.bindTo(tableView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
*/
public func items<
DataSource: RxTableViewDataSourceType & UITableViewDataSource,
O: ObservableType>
(dataSource: DataSource)
-> (_ source: O)
-> Disposable
where DataSource.Element == O.E {
return { source in
// This is called for sideeffects only, and to make sure delegate proxy is in place when
// data source is being bound.
// This is needed because theoretically the data source subscription itself might
// call `self.rx.delegate`. If that happens, it might cause weird side effects since
// setting data source will set delegate, and UITableView might get into a weird state.
// Therefore it's better to set delegate proxy first, just to be sure.
_ = self.delegate
// Strong reference is needed because data source is in use until result subscription is disposed
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = tableView else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
}
extension UITableView {
/**
Factory method that enables subclasses to implement their own `delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
/**
Factory method that enables subclasses to implement their own `rx.dataSource`.
- returns: Instance of delegate proxy that wraps `dataSource`.
*/
public func createRxDataSourceProxy() -> RxTableViewDataSourceProxy {
return RxTableViewDataSourceProxy(parentObject: self)
}
}
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var dataSource: DelegateProxy {
return RxTableViewDataSourceProxy.proxyForObject(base)
}
/**
Installs data source as forwarding delegate on `rx.dataSource`.
Data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setDataSource(_ dataSource: UITableViewDataSource)
-> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var itemSelected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
*/
public var itemDeselected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`.
*/
public var itemAccessoryButtonTapped: ControlEvent<IndexPath> {
let source: Observable<IndexPath> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemInserted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert
}
.map { a in
return (try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemDeleted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete
}
.map { a in
return try castOrThrow(IndexPath.self, a[2])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:)))
.map { a in
return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`.
*/
public var willDisplayCell: ControlEvent<WillDisplayCellEvent> {
let source: Observable<WillDisplayCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`.
*/
public var didEndDisplayingCell: ControlEvent<DidEndDisplayingCellEvent> {
let source: Observable<DidEndDisplayingCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelSelected(MyModel.self)
.map { ...
```
*/
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeselected(MyModel.self)
.map { ...
```
*/
public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
*/
public func model<T>(at indexPath: IndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.")
let element = try dataSource.model(at: indexPath)
return castOrFatalError(element)
}
}
#endif
#if os(tvOS)
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)))
.map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = a[1] as! UIFocusUpdateContext
let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2])
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif
|
mpl-2.0
|
c3863dd03b35f98ff257601681a5e8d9
| 36.241206 | 200 | 0.627918 | 5.354769 | false | false | false | false |
rtocd/NotificationObservers
|
NotificationObservers/Source/UIApplication/ApplicationAdaptor.swift
|
1
|
6572
|
//
// ApplicationAdaptor.swift
// NotificationObservers
//
// Created by rtocd on 11/26/17.
// Copyright © 2017 RTOCD. All rights reserved.
//
import Foundation
// You can find the userInfo keys here https://developer.apple.com/documentation/uikit/uiapplication/userinfo_dictionary_keys
extension Application {
public struct Adaptor: Adaptable {
public let notification: Notification
public var application: UIApplication? {
return self.notification.object as? UIApplication
}
public init(notification: Notification) {
self.notification = notification
}
}
public struct StatusBarFrameAdaptor: Adaptable {
public let notification: Notification
public var application: UIApplication? {
return self.notification.object as? UIApplication
}
public var statusBarFrame: CGRect? {
return (self.notification.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSValue)?.cgRectValue
}
public init(notification: Notification) {
self.notification = notification
}
}
public struct StatusBarOrientationAdaptor: Adaptable {
public let notification: Notification
public var application: UIApplication? {
return self.notification.object as? UIApplication
}
public var statusBarOrientation: UIInterfaceOrientation? {
if let value = (self.notification.userInfo?[UIApplicationStatusBarOrientationUserInfoKey] as? NSNumber)?.intValue {
return UIInterfaceOrientation(rawValue: value)
}
return nil
}
public init(notification: Notification) {
self.notification = notification
}
}
public struct ContentSizeCategoryDidChangeAdaptor: Adaptable {
public let notification: Notification
public var application: UIApplication? {
return self.notification.object as? UIApplication
}
public var categoryNewValue: UIContentSizeCategory? {
if let value = self.notification.userInfo?[UIContentSizeCategoryNewValueKey] as? UIContentSizeCategory {
return value
}
return nil
}
public init(notification: Notification) {
self.notification = notification
}
}
public struct DidFinishLaunchingAdaptor: Adaptable {
public let notification: Notification
public var application: UIApplication? {
return self.notification.object as? UIApplication
}
public var sourceApplication: String? {
if let value = self.notification.userInfo?[UIApplicationLaunchOptionsKey.sourceApplication] as? String {
return value
}
return nil
}
public var url: URL? {
if let value = self.notification.userInfo?[UIApplicationLaunchOptionsKey.url] as? URL {
return value
}
return nil
}
public var remoteNotification: NSDictionary? {
// Should I create an adaptor for this NSDicionary?
if let value = self.notification.userInfo?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
return value
}
return nil
}
/// Note: This was deprecated in iOS 10. You should use UNUserNotificationCenter if possible
public var localNotification: UILocalNotification? {
if let value = self.notification.userInfo?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification {
return value
}
return nil
}
public init(notification: Notification) {
self.notification = notification
}
}
}
// MARK: -
extension ApplicationNotification {
public static func makeObserver() -> NotificationObserver<Application.Adaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.WillChangeStatusBarFrame {
public static func makeObserver() -> NotificationObserver<Application.StatusBarFrameAdaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.DidChangeStatusBarFrame {
public static func makeObserver() -> NotificationObserver<Application.StatusBarFrameAdaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.WillChangeStatusBarOrientation {
public static func makeObserver() -> NotificationObserver<Application.StatusBarOrientationAdaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.DidChangeStatusBarOrientation {
public static func makeObserver() -> NotificationObserver<Application.StatusBarOrientationAdaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.ContentSizeCategoryDidChange {
public static func makeObserver() -> NotificationObserver<Application.ContentSizeCategoryDidChangeAdaptor> {
return NotificationObserver(name: self.name)
}
}
extension Application.DidFinishLaunching {
public static func makeObserver() -> NotificationObserver<Application.DidFinishLaunchingAdaptor> {
return NotificationObserver(name: self.name)
}
}
// MARK: -
// TODO: Finish console debugging
extension Application.Adaptor: CustomDebugStringConvertible {
public var debugDescription: String {
return "[application: \(String(describing: self.application)))]"
}
}
extension Application.StatusBarFrameAdaptor: CustomDebugStringConvertible {
public var debugDescription: String {
return "[application: \(String(describing: self.application)))]"
}
}
extension Application.StatusBarOrientationAdaptor: CustomDebugStringConvertible {
public var debugDescription: String {
return "[application: \(String(describing: self.application)))]"
}
}
extension Application.ContentSizeCategoryDidChangeAdaptor: CustomDebugStringConvertible {
public var debugDescription: String {
return "[application: \(String(describing: self.application)))]"
}
}
extension Application.DidFinishLaunchingAdaptor: CustomDebugStringConvertible {
public var debugDescription: String {
return "[application: \(String(describing: self.application)))]"
}
}
|
mit
|
e01efc514b4b887e51356f985579fe57
| 32.52551 | 129 | 0.668848 | 5.909173 | false | false | false | false |
imobilize/Molib
|
Pod/Classes/ViewControllers/DataSourceProvider.swift
|
1
|
9581
|
import Foundation
import CoreData
public protocol DataSourceProvider {
associatedtype DataSourceDelegate: DataSourceProviderDelegate
associatedtype ItemType
var delegate: DataSourceDelegate? { get set }
func isEmpty() -> Bool
func numberOfSections() -> Int
func numberOfRowsInSection(section: Int) -> Int
func itemAtIndexPath(indexPath: NSIndexPath) -> ItemType
mutating func deleteItemAtIndexPath(indexPath: NSIndexPath)
mutating func insertItem(item: ItemType, atIndexPath: NSIndexPath)
mutating func updateItem(item: ItemType, atIndexPath: NSIndexPath)
mutating func deleteAllInSection(section: Int)
func titleForHeaderAtSection(section: Int) -> String?
}
public protocol DataSourceProviderDelegate {
associatedtype ItemType
mutating func providerWillChangeContent()
mutating func providerDidEndChangeContent()
mutating func providerDidInsertSectionAtIndex(index: Int)
mutating func providerDidDeleteSectionAtIndex(index: Int)
mutating func providerDidInsertItemsAtIndexPaths(items: [ItemType], atIndexPaths: [NSIndexPath])
mutating func providerDidDeleteItemsAtIndexPaths(items: [ItemType], atIndexPaths: [NSIndexPath])
mutating func providerDidUpdateItemsAtIndexPaths(items: [ItemType], atIndexPaths: [NSIndexPath])
mutating func providerDidMoveItem(item: ItemType, atIndexPath: NSIndexPath, toIndexPath: NSIndexPath)
mutating func providerDidDeleteAllItemsInSection(section: Int)
}
public class ArrayDataSourceProvider<T, Delegate: DataSourceProviderDelegate where Delegate.ItemType == T>: DataSourceProvider {
public var delegate: Delegate?
private var arrayItems: [T]
private var objectChanges: Array<(DataSourceChangeType,[NSIndexPath], [T])>!
private var sectionChanges: Array<(DataSourceChangeType,Int)>!
public init() {
self.objectChanges = Array()
self.sectionChanges = Array()
arrayItems = [T]()
}
public func isEmpty() -> Bool {
return arrayItems.isEmpty
}
public func numberOfSections() -> Int {
return 1
}
public func numberOfRowsInSection(section: Int) -> Int {
return arrayItems.count
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> T {
return arrayItems[indexPath.row]
}
public func deleteItemAtIndexPath(indexPath: NSIndexPath) {
let item = arrayItems[indexPath.row]
arrayItems.removeAtIndex(indexPath.row)
delegate?.providerDidDeleteItemsAtIndexPaths([item], atIndexPaths: [indexPath])
}
public func insertItem(item: T, atIndexPath indexPath: NSIndexPath) {
arrayItems.insert(item, atIndex: indexPath.row)
delegate?.providerDidInsertItemsAtIndexPaths([item], atIndexPaths: [indexPath])
}
public func updateItem(item: T, atIndexPath indexPath: NSIndexPath) {
var newItems = [T](arrayItems)
newItems.removeAtIndex(indexPath.row)
newItems.insert(item, atIndex: indexPath.row)
self.arrayItems = newItems
delegate?.providerDidUpdateItemsAtIndexPaths([item], atIndexPaths: [indexPath])
}
public func deleteAllInSection(section: Int) {
arrayItems.removeAll()
delegate?.providerDidDeleteAllItemsInSection(0)
}
public func batchUpdates(updatesBlock: VoidCompletion) {
objc_sync_enter(self)
delegate?.providerWillChangeContent()
updatesBlock()
delegate?.providerDidEndChangeContent()
objc_sync_exit(self)
}
public func titleForHeaderAtSection(section: Int) -> String? {
return nil
}
public func itemsArray() -> [T] {
return arrayItems
}
}
public class FetchedResultsDataSourceProvider<ObjectType: NSManagedObject, Delegate: DataSourceProviderDelegate where Delegate.ItemType == ObjectType> : DataSourceProvider {
public var delegate: Delegate? { didSet {
fetchedResultsControllerDelegate = FetchedResultsControllerDelegate<ObjectType, Delegate>(delegate: delegate!)
fetchedResultsController.delegate = fetchedResultsControllerDelegate
}
}
let fetchedResultsController: NSFetchedResultsController
var fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<ObjectType, Delegate>?
public init(fetchedResultsController: NSFetchedResultsController) {
self.fetchedResultsController = fetchedResultsController
}
public func isEmpty() -> Bool {
var empty = true
if let count = self.fetchedResultsController.fetchedObjects?.count {
empty = (count == 0)
}
return empty
}
public func numberOfSections() -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
public func numberOfRowsInSection(section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> ObjectType {
return self.fetchedResultsController.objectAtIndexPath(indexPath) as! ObjectType
}
public func deleteItemAtIndexPath(indexPath: NSIndexPath) {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! ObjectType)
do {
try context.save()
} catch _ {
}
}
public func insertItem(item: ObjectType, atIndexPath: NSIndexPath) {
let context = self.fetchedResultsController.managedObjectContext
context.insertObject(item)
do {
try context.save()
} catch _ {
}
}
public func updateItem(item: ObjectType, atIndexPath: NSIndexPath) {
let context = self.fetchedResultsController.managedObjectContext
//MARK: TODO update the item here
do {
try context.save()
} catch _ {
}
}
public func deleteAllInSection(section: Int) {
let context = self.fetchedResultsController.managedObjectContext
let sectionInfo = self.fetchedResultsController.sections![section]
if let objects = sectionInfo.objects {
for object in objects {
context.deleteObject(object as! NSManagedObject)
}
}
}
public func titleForHeaderAtSection(section: Int) -> String? {
return self.fetchedResultsController.sections?[section].name
}
deinit {
print("FetchedResultsDataSourceProvider dying")
}
}
class FetchedResultsControllerDelegate<ObjectType: NSManagedObject, Delegate: DataSourceProviderDelegate where Delegate.ItemType == ObjectType>: NSObject, NSFetchedResultsControllerDelegate {
var delegate: Delegate
init(delegate: Delegate) {
self.delegate = delegate
}
// MARK: - Fetched results controller
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.delegate.providerWillChangeContent()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.delegate.providerDidInsertSectionAtIndex(sectionIndex)
case .Delete:
self.delegate.providerDidDeleteSectionAtIndex(sectionIndex)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
let obj = anObject as! ObjectType
switch type {
case .Insert:
self.delegate.providerDidInsertItemsAtIndexPaths([obj], atIndexPaths: [newIndexPath!])
case .Delete:
self.delegate.providerDidDeleteItemsAtIndexPaths([obj], atIndexPaths: [indexPath!])
case .Update:
self.delegate.providerDidUpdateItemsAtIndexPaths([obj], atIndexPaths: [indexPath!])
case .Move:
if let initiaIndexPath = indexPath, finalIndexPath = newIndexPath {
if initiaIndexPath != finalIndexPath {
self.delegate.providerDidMoveItem(anObject as! ObjectType, atIndexPath: indexPath!, toIndexPath: newIndexPath!)
}
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.delegate.providerDidEndChangeContent()
}
deinit {
print("FetchedResultsControllerDelegate dying")
}
}
|
apache-2.0
|
f4411aa0e341108253cbd90d21b6c9c1
| 26.932945 | 211 | 0.638347 | 6.274394 | false | false | false | false |
podverse/podverse-ios
|
Podverse/ClipsListContainerViewController.swift
|
1
|
12976
|
//
// ClipsListContainerViewController.swift
// Podverse
//
// Created by Creon Creonopoulos on 5/30/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
import SDWebImage
protocol ClipsListDelegate:class {
func didSelectClip(clip:MediaRef)
}
class ClipsListContainerViewController: UIViewController {
var clipsArray = [MediaRef]()
weak var delegate:ClipsListDelegate?
let pvMediaPlayer = PVMediaPlayer.shared
let reachability = PVReachability.shared
var filterTypeSelected: ClipFilter = .episode {
didSet {
self.resetClipQuery()
self.tableViewHeader.filterTitle = filterTypeSelected.text
UserDefaults.standard.set(filterTypeSelected.text, forKey: kClipsListFilterType)
}
}
var sortingTypeSelected: ClipSorting = .topWeek {
didSet {
self.resetClipQuery()
self.tableViewHeader.sortingTitle = sortingTypeSelected.text
UserDefaults.standard.set(sortingTypeSelected.text, forKey: kClipsListSortingType)
}
}
var clipQueryPage: Int = 0
var clipQueryIsLoading: Bool = false
var clipQueryEndOfResultsReached: Bool = false
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var activityView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableViewHeader: FiltersTableHeaderView!
@IBOutlet weak var clipQueryActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var clipQueryMessage: UILabel!
@IBOutlet weak var clipQueryStatusView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.hidesWhenStopped = true
self.tableViewHeader.delegate = self
self.tableViewHeader.setupViews(isBlackBg: true)
self.tableView.separatorColor = .darkGray
self.clipQueryActivityIndicator.hidesWhenStopped = true
self.clipQueryMessage.isHidden = true
if let savedFilterType = UserDefaults.standard.value(forKey: kClipsListFilterType) as? String, let sFilterType = ClipFilter(rawValue: savedFilterType) {
self.filterTypeSelected = sFilterType
} else {
self.filterTypeSelected = .episode
}
if let savedSortingType = UserDefaults.standard.value(forKey: kClipsListSortingType) as? String, let episodesSortingType = ClipSorting(rawValue: savedSortingType) {
self.sortingTypeSelected = episodesSortingType
} else {
self.sortingTypeSelected = .topWeek
}
retrieveClips()
}
func resetClipQuery() {
self.clipsArray.removeAll()
self.clipQueryPage = 0
self.clipQueryIsLoading = true
self.clipQueryEndOfResultsReached = false
self.clipQueryMessage.isHidden = true
}
@objc func retrieveClips() {
if !pvMediaPlayer.isDataAvailable {
return
}
guard checkForConnectivity() else {
loadNoInternetMessage()
return
}
self.hideNoDataView()
if self.clipQueryPage == 0 {
showActivityIndicator()
}
self.clipQueryPage += 1
if self.filterTypeSelected == .episode, let item = pvMediaPlayer.nowPlayingItem, let mediaUrl = item.episodeMediaUrl {
MediaRef.retrieveMediaRefsFromServer(episodeMediaUrl: mediaUrl, sortingTypeRequestParam: self.sortingTypeSelected.requestParam, page: self.clipQueryPage) { (mediaRefs) -> Void in
self.reloadClipData(mediaRefs)
}
} else if self.filterTypeSelected == .podcast, let item = pvMediaPlayer.nowPlayingItem, let feedUrl = item.podcastFeedUrl {
MediaRef.retrieveMediaRefsFromServer(podcastFeedUrls: [feedUrl], sortingTypeRequestParam: self.sortingTypeSelected.requestParam, page: self.clipQueryPage) { (mediaRefs) -> Void in
self.reloadClipData(mediaRefs)
}
} else if self.filterTypeSelected == .subscribed {
let subscribedPodcastFeedUrls = Podcast.retrieveSubscribedUrls()
if subscribedPodcastFeedUrls.count < 1 {
self.reloadClipData()
return
}
MediaRef.retrieveMediaRefsFromServer(episodeMediaUrl: nil, podcastFeedUrls: subscribedPodcastFeedUrls, sortingTypeRequestParam: self.sortingTypeSelected.requestParam, page: self.clipQueryPage) { (mediaRefs) -> Void in
self.reloadClipData(mediaRefs)
}
} else {
MediaRef.retrieveMediaRefsFromServer(sortingTypeRequestParam: self.sortingTypeSelected.requestParam, page: self.clipQueryPage) { (mediaRefs) -> Void in
self.reloadClipData(mediaRefs)
}
}
}
func reloadClipData(_ mediaRefs: [MediaRef]? = nil) {
hideActivityIndicator()
self.clipQueryIsLoading = false
self.clipQueryActivityIndicator.stopAnimating()
guard checkForResults(results: mediaRefs) || checkForResults(results: self.clipsArray), let mediaRefs = mediaRefs else {
loadNoClipsMessage()
return
}
guard checkForResults(results: mediaRefs) else {
self.clipQueryEndOfResultsReached = true
self.clipQueryMessage.isHidden = false
return
}
for mediaRef in mediaRefs {
self.clipsArray.append(mediaRef)
}
self.tableView.isHidden = false
self.tableView.reloadData()
}
func loadNoDataView(message: String, buttonTitle: String?, buttonPressed: Selector?) {
if let noDataView = self.view.subviews.first(where: { $0.tag == kNoDataViewTag}) {
if let messageView = noDataView.subviews.first(where: {$0 is UILabel}), let messageLabel = messageView as? UILabel {
messageLabel.text = message
}
if let buttonView = noDataView.subviews.first(where: {$0 is UIButton}), let button = buttonView as? UIButton {
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(.blue, for: .normal)
}
}
else {
self.addNoDataViewWithMessage(message, buttonTitle: buttonTitle, buttonImage: nil, retryPressed: buttonPressed, isBlackBg: true)
}
showNoDataView()
}
func loadNoInternetMessage() {
loadNoDataView(message: Strings.Errors.noClipsInternet, buttonTitle: "Retry", buttonPressed: #selector(ClipsListContainerViewController.retrieveClips))
}
func loadNoClipsMessage() {
loadNoDataView(message: Strings.Errors.noClipsAvailable, buttonTitle: nil, buttonPressed: nil)
}
func showActivityIndicator() {
self.activityIndicator.startAnimating()
self.activityView.isHidden = false
self.tableView.isHidden = true
}
func hideActivityIndicator() {
self.activityIndicator.stopAnimating()
self.activityView.isHidden = true
}
}
extension ClipsListContainerViewController:UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return clipsArray.count
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let clip = clipsArray[indexPath.row]
if filterTypeSelected == .episode {
let cell = tableView.dequeueReusableCell(withIdentifier: "clipEpisodeCell", for: indexPath) as! ClipEpisodeTableViewCell
cell.clipTitle?.text = clip.title
if let time = clip.readableStartAndEndTime() {
cell.time?.text = time
}
return cell
} else if filterTypeSelected == .podcast {
let cell = tableView.dequeueReusableCell(withIdentifier: "clipPodcastCell", for: indexPath) as! ClipPodcastTableViewCell
cell.episodeTitle?.text = clip.episodeTitle
cell.clipTitle?.text = clip.title
if let episodePubDate = clip.episodePubDate {
cell.episodePubDate?.text = episodePubDate.toShortFormatString()
}
if let time = clip.readableStartAndEndTime() {
cell.time?.text = time
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "clipCell", for: indexPath) as! ClipTableViewCell
cell.podcastTitle?.text = clip.podcastTitle
cell.episodeTitle?.text = clip.episodeTitle
cell.clipTitle?.text = clip.title
cell.podcastImage.image = Podcast.retrievePodcastImage(podcastImageURLString: clip.podcastImageUrl, feedURLString: clip.podcastFeedUrl, completion: { image in
cell.podcastImage.image = image
})
if let episodePubDate = clip.episodePubDate {
cell.episodePubDate?.text = episodePubDate.toShortFormatString()
}
if let time = clip.readableStartAndEndTime() {
cell.time?.text = time
}
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
self.delegate?.didSelectClip(clip: self.clipsArray[indexPath.row])
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Bottom Refresh
if scrollView == self.tableView {
if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height) && !self.clipQueryIsLoading && !self.clipQueryEndOfResultsReached {
self.clipQueryIsLoading = true
self.clipQueryActivityIndicator.startAnimating()
self.retrieveClips()
}
}
}
}
extension ClipsListContainerViewController: FilterSelectionProtocol {
func filterButtonTapped() {
let alert = UIAlertController(title: "Clips From", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: ClipFilter.episode.text, style: .default, handler: { action in
self.filterTypeSelected = .episode
self.retrieveClips()
}))
alert.addAction(UIAlertAction(title: ClipFilter.podcast.text, style: .default, handler: { action in
self.filterTypeSelected = .podcast
self.retrieveClips()
}))
alert.addAction(UIAlertAction(title: ClipFilter.subscribed.text, style: .default, handler: { action in
self.filterTypeSelected = .subscribed
self.retrieveClips()
}))
alert.addAction(UIAlertAction(title: ClipFilter.allPodcasts.text, style: .default, handler: { action in
self.filterTypeSelected = .allPodcasts
self.retrieveClips()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func sortingButtonTapped() {
self.tableViewHeader.showSortByMenu(vc: self)
}
func sortByRecent() {
self.sortingTypeSelected = .recent
self.retrieveClips()
}
func sortByTop() {
self.tableViewHeader.showSortByTimeRangeMenu(vc: self)
}
func sortByTopWithTimeRange(timeRange: SortingTimeRange) {
if timeRange == .day {
self.sortingTypeSelected = .topDay
} else if timeRange == .week {
self.sortingTypeSelected = .topWeek
} else if timeRange == .month {
self.sortingTypeSelected = .topMonth
} else if timeRange == .year {
self.sortingTypeSelected = .topYear
} else if timeRange == .allTime {
self.sortingTypeSelected = .topAllTime
}
self.retrieveClips()
}
}
|
agpl-3.0
|
98044c20e1bebeb51e5bac46ee80d20e
| 34.941828 | 229 | 0.618497 | 5.276535 | false | false | false | false |
russbishop/swift
|
test/SILGen/switch_abstraction.swift
|
1
|
1531
|
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s | FileCheck %s
struct A {}
enum Optionable<T> {
case Summn(T)
case Nuttn
}
// CHECK-LABEL: sil hidden @_TF18switch_abstraction18enum_reabstractionFT1xGOS_10OptionableFVS_1AS1__1aS1__T_ : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> ()
// CHECK: switch_enum {{%.*}} : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt.1: [[DEST:bb[0-9]+]]
// CHECK: [[DEST]]([[ORIG:%.*]] : $@callee_owned (@in A) -> @out A):
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTR
// CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]([[ORIG]])
func enum_reabstraction(x x: Optionable<(A) -> A>, a: A) {
switch x {
case .Summn(var f):
f(a)
case .Nuttn:
()
}
}
enum Wacky<A, B> {
case Foo(A)
case Bar((B) -> A)
}
// CHECK-LABEL: sil hidden @_TF18switch_abstraction45enum_addr_only_to_loadable_with_reabstraction{{.*}} : $@convention(thin) <T> (@in Wacky<T, A>, A) -> @out T {
// CHECK: switch_enum_addr [[ENUM:%.*]] : $*Wacky<T, A>, {{.*}} case #Wacky.Bar!enumelt.1: [[DEST:bb[0-9]+]]
// CHECK: [[DEST]]:
// CHECK: [[ORIG_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM]] : $*Wacky<T, A>, #Wacky.Bar
// CHECK: [[ORIG:%.*]] = load [[ORIG_ADDR]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTR
// CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]<T>([[ORIG]])
func enum_addr_only_to_loadable_with_reabstraction<T>(x x: Wacky<T, A>, a: A)
-> T
{
switch x {
case .Foo(var b):
return b
case .Bar(var f):
return f(a)
}
}
|
apache-2.0
|
12029f21bb09a68e4c1f746a5c28207f
| 33.022222 | 169 | 0.582626 | 2.814338 | false | false | false | false |
JGiola/swift-package-manager
|
Sources/Build/BuildPlan.swift
|
1
|
42807
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import Basic
import Utility
import PackageModel
import PackageGraph
import PackageLoading
import func POSIX.getenv
public struct BuildParameters {
/// Mode for the indexing-while-building feature.
public enum IndexStoreMode: Equatable {
/// Index store should be enabled.
case on
/// Index store should be disabled.
case off
/// Index store should be enabled in debug configuration.
case auto
}
// FIXME: Error handling.
//
/// Path to the module cache directory to use for SwiftPM's own tests.
public static let swiftpmTestCache = resolveSymlinks(try! determineTempDirectory()).appending(component: "org.swift.swiftpm.tests-3")
/// Returns the directory to be used for module cache.
fileprivate var moduleCache: AbsolutePath {
let base: AbsolutePath
// FIXME: We use this hack to let swiftpm's functional test use shared
// cache so it doesn't become painfully slow.
if getenv("IS_SWIFTPM_TEST") != nil {
base = BuildParameters.swiftpmTestCache
} else {
base = buildPath
}
return base.appending(component: "ModuleCache")
}
/// The path to the data directory.
public let dataPath: AbsolutePath
/// The build configuration.
public let configuration: BuildConfiguration
/// The path to the build directory (inside the data directory).
public var buildPath: AbsolutePath {
return dataPath.appending(component: configuration.dirname)
}
/// The path to the index store directory.
public var indexStore: AbsolutePath {
assert(indexStoreMode != .off, "index store is disabled")
return buildPath.appending(components: "index", "store")
}
/// The path to the code coverage directory.
public var codeCovPath: AbsolutePath {
return buildPath.appending(component: "codecov")
}
/// The path to the code coverage profdata file.
public var codeCovDataFile: AbsolutePath {
return codeCovPath.appending(component: "default.profdata")
}
/// The toolchain.
public let toolchain: Toolchain
/// Destination triple.
public let triple: Triple
/// Extra build flags.
public let flags: BuildFlags
/// Extra flags to pass to Swift compiler.
public var swiftCompilerFlags: [String] {
var flags = self.flags.cCompilerFlags.flatMap({ ["-Xcc", $0] })
flags += self.flags.swiftCompilerFlags
flags += verbosity.ccArgs
return flags
}
/// Extra flags to pass to linker.
public var linkerFlags: [String] {
// Arguments that can be passed directly to the Swift compiler and
// doesn't require -Xlinker prefix.
//
// We do this to avoid sending flags like linker search path at the end
// of the search list.
let directSwiftLinkerArgs = ["-L"]
var flags: [String] = []
var it = self.flags.linkerFlags.makeIterator()
while let flag = it.next() {
if directSwiftLinkerArgs.contains(flag) {
// `-L <value>` variant.
flags.append(flag)
guard let nextFlag = it.next() else {
// We expected a flag but don't have one.
continue
}
flags.append(nextFlag)
} else if directSwiftLinkerArgs.contains(where: { flag.hasPrefix($0) }) {
// `-L<value>` variant.
flags.append(flag)
} else {
flags += ["-Xlinker", flag]
}
}
return flags
}
/// The tools version to use.
public let toolsVersion: ToolsVersion
/// If should link the Swift stdlib statically.
public let shouldLinkStaticSwiftStdlib: Bool
/// Which compiler sanitizers should be enabled
public let sanitizers: EnabledSanitizers
/// If should enable llbuild manifest caching.
public let shouldEnableManifestCaching: Bool
/// The mode to use for indexing-while-building feature.
public let indexStoreMode: IndexStoreMode
/// Whether to enable code coverage.
public let enableCodeCoverage: Bool
/// Checks if stdout stream is tty.
fileprivate let isTTY: Bool = {
guard let stream = stdoutStream.stream as? LocalFileOutputByteStream else {
return false
}
return TerminalController.isTTY(stream)
}()
public var regenerateManifestToken: AbsolutePath {
return dataPath.appending(components: "..", "regenerate-token")
}
public var llbuildManifest: AbsolutePath {
return dataPath.appending(components: "..", configuration.dirname + ".yaml")
}
public init(
dataPath: AbsolutePath,
configuration: BuildConfiguration,
toolchain: Toolchain,
destinationTriple: Triple = Triple.hostTriple,
flags: BuildFlags,
toolsVersion: ToolsVersion = ToolsVersion.currentToolsVersion,
shouldLinkStaticSwiftStdlib: Bool = false,
shouldEnableManifestCaching: Bool = false,
sanitizers: EnabledSanitizers = EnabledSanitizers(),
enableCodeCoverage: Bool = false,
indexStoreMode: IndexStoreMode = .auto
) {
self.dataPath = dataPath
self.configuration = configuration
self.toolchain = toolchain
self.triple = destinationTriple
self.flags = flags
self.toolsVersion = toolsVersion
self.shouldLinkStaticSwiftStdlib = shouldLinkStaticSwiftStdlib
self.shouldEnableManifestCaching = shouldEnableManifestCaching
self.sanitizers = sanitizers
self.enableCodeCoverage = enableCodeCoverage
self.indexStoreMode = indexStoreMode
}
/// Returns the compiler arguments for the index store, if enabled.
fileprivate var indexStoreArguments: [String] {
let addIndexStoreArguments: Bool
switch indexStoreMode {
case .on:
addIndexStoreArguments = true
case .off:
addIndexStoreArguments = false
case .auto:
addIndexStoreArguments = configuration == .debug
}
if addIndexStoreArguments {
return ["-index-store-path", indexStore.asString]
}
return []
}
/// Computes the target triple arguments for a given resolved target.
fileprivate func targetTripleArgs(for target: ResolvedTarget) -> [String] {
var args = ["-target"]
// Compute the triple string for Darwin platform using the platform version.
if triple.isDarwin() {
guard let macOSSupportedPlatform = target.underlyingTarget.getSupportedPlatform(for: .macOS) else {
fatalError("the target \(target) doesn't support building for macOS")
}
args += [triple.tripleString(forPlatformVersion: macOSSupportedPlatform.version.versionString)]
} else {
args += [triple.tripleString]
}
return args
}
/// The current platform we're building for.
var currentPlatform: PackageModel.Platform {
if self.triple.isDarwin() {
return .macOS
} else {
return .linux
}
}
/// Returns the scoped view of build settings for a given target.
fileprivate func createScope(for target: ResolvedTarget) -> BuildSettings.Scope {
return BuildSettings.Scope(target.underlyingTarget.buildSettings, boundCondition: (currentPlatform, configuration))
}
}
/// A target description which can either be for a Swift or Clang target.
public enum TargetBuildDescription {
/// Swift target description.
case swift(SwiftTargetBuildDescription)
/// Clang target description.
case clang(ClangTargetBuildDescription)
/// The objects in this target.
var objects: [AbsolutePath] {
switch self {
case .swift(let target):
return target.objects
case .clang(let target):
return target.objects
}
}
}
/// Target description for a Clang target i.e. C language family target.
public final class ClangTargetBuildDescription {
/// The target described by this target.
public let target: ResolvedTarget
/// The underlying clang target.
public var clangTarget: ClangTarget {
return target.underlyingTarget as! ClangTarget
}
/// The build parameters.
let buildParameters: BuildParameters
/// The modulemap file for this target, if any.
private(set) var moduleMap: AbsolutePath?
/// Path to the temporary directory for this target.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".build")
}
/// The objects in this target.
var objects: [AbsolutePath] {
return compilePaths().map({ $0.object })
}
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The filesystem to operate on.
let fileSystem: FileSystem
/// If this target is a test target.
public var isTestTarget: Bool {
return target.type == .test
}
/// Create a new target description with target and build parameters.
init(target: ResolvedTarget, buildParameters: BuildParameters, fileSystem: FileSystem = localFileSystem) throws {
assert(target.underlyingTarget is ClangTarget, "underlying target type mismatch \(target)")
self.fileSystem = fileSystem
self.target = target
self.buildParameters = buildParameters
// Try computing modulemap path for a C library.
if target.type == .library {
self.moduleMap = try computeModulemapPath()
}
}
/// An array of tuple containing filename, source, object and dependency path for each of the source in this target.
public func compilePaths()
-> [(filename: RelativePath, source: AbsolutePath, object: AbsolutePath, deps: AbsolutePath)]
{
return target.sources.relativePaths.map({ source in
let path = target.sources.root.appending(source)
let object = tempsPath.appending(RelativePath(source.asString + ".o"))
let deps = tempsPath.appending(RelativePath(source.asString + ".d"))
return (source, path, object, deps)
})
}
/// Builds up basic compilation arguments for this target.
public func basicArguments() -> [String] {
var args = [String]()
// Only enable ARC on macOS.
if buildParameters.triple.isDarwin() {
args += ["-fobjc-arc"]
}
args += buildParameters.targetTripleArgs(for: target)
args += buildParameters.toolchain.extraCCFlags
args += optimizationArguments
args += activeCompilationConditions
args += ["-fblocks"]
// Enable index store, if appropriate.
//
// This feature is not widely available in OSS clang. So, we only enable
// index store for Apple's clang or if explicitly asked to.
if Process.env.keys.contains("SWIFTPM_ENABLE_CLANG_INDEX_STORE") {
args += buildParameters.indexStoreArguments
} else if buildParameters.triple.isDarwin(), (try? buildParameters.toolchain._isClangCompilerVendorApple()) == true {
args += buildParameters.indexStoreArguments
}
if !buildParameters.triple.isWindows() {
// Using modules currently conflicts with the Windows SDKs.
args += ["-fmodules", "-fmodule-name=" + target.c99name]
}
args += ["-I", clangTarget.includeDir.asString]
args += additionalFlags
if !buildParameters.triple.isWindows() {
args += moduleCacheArgs
}
args += buildParameters.sanitizers.compileCFlags()
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xcc and -Xcxx below) should follow generated arguments to allow user overrides
args += buildParameters.flags.cCompilerFlags
// Add extra C++ flags if this target contains C++ files.
if clangTarget.isCXX {
args += self.buildParameters.flags.cxxCompilerFlags
}
return args
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
let scope = buildParameters.createScope(for: target)
var flags: [String] = []
// C defines.
let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)
flags += cDefines.map({ "-D" + $0 })
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.map({
"-I" + target.sources.root.appending(RelativePath($0)).asString
})
// Frameworks.
let frameworks = scope.evaluate(.LINK_FRAMEWORKS)
flags += frameworks.flatMap({ ["-framework", $0] })
// Other C flags.
flags += scope.evaluate(.OTHER_CFLAGS)
// Other CXX flags.
flags += scope.evaluate(.OTHER_CPLUSPLUSFLAGS)
return flags
}
/// Optimization arguments according to the build configuration.
private var optimizationArguments: [String] {
switch buildParameters.configuration {
case .debug:
if buildParameters.triple.isWindows() {
return ["-g", "-gcodeview", "-O0"]
} else {
return ["-g", "-O0"]
}
case .release:
return ["-O2"]
}
}
/// A list of compilation conditions to enable for conditional compilation expressions.
private var activeCompilationConditions: [String] {
var compilationConditions = ["-DSWIFT_PACKAGE=1"]
switch buildParameters.configuration {
case .debug:
compilationConditions += ["-DDEBUG=1"]
case .release:
break
}
return compilationConditions
}
/// Helper function to compute the modulemap path.
///
/// This function either returns path to user provided modulemap or tries to automatically generates it.
private func computeModulemapPath() throws -> AbsolutePath {
// If user provided the modulemap, we're done.
if fileSystem.isFile(clangTarget.moduleMapPath) {
return clangTarget.moduleMapPath
} else {
// Otherwise try to generate one.
var moduleMapGenerator = ModuleMapGenerator(for: clangTarget, fileSystem: fileSystem)
// FIXME: We should probably only warn if we're unable to generate the modulemap
// because the clang target is still a valid, it just can't be imported from Swift targets.
try moduleMapGenerator.generateModuleMap(inDir: tempsPath)
return tempsPath.appending(component: moduleMapFilename)
}
}
/// Module cache arguments.
private var moduleCacheArgs: [String] {
return ["-fmodules-cache-path=" + buildParameters.moduleCache.asString]
}
}
/// Target description for a Swift target.
public final class SwiftTargetBuildDescription {
/// The target described by this target.
public let target: ResolvedTarget
/// The build parameters.
let buildParameters: BuildParameters
/// Path to the temporary directory for this target.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".build")
}
/// The objects in this target.
var objects: [AbsolutePath] {
return target.sources.relativePaths.map({ tempsPath.appending(RelativePath($0.asString + ".o")) })
}
/// The path to the swiftmodule file after compilation.
var moduleOutputPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".swiftmodule")
}
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The swift version for this target.
var swiftVersion: SwiftLanguageVersion {
return (target.underlyingTarget as! SwiftTarget).swiftVersion
}
/// If this target is a test target.
public let isTestTarget: Bool
/// Create a new target description with target and build parameters.
init(target: ResolvedTarget, buildParameters: BuildParameters, isTestTarget: Bool? = nil) {
assert(target.underlyingTarget is SwiftTarget, "underlying target type mismatch \(target)")
self.target = target
self.buildParameters = buildParameters
// Unless mentioned explicitly, use the target type to determine if this is a test target.
self.isTestTarget = isTestTarget ?? (target.type == .test)
}
/// The arguments needed to compile this target.
public func compileArguments() -> [String] {
var args = [String]()
args += buildParameters.targetTripleArgs(for: target)
args += ["-swift-version", swiftVersion.rawValue]
// Enable batch mode in debug mode.
//
// Technically, it should be enabled whenever WMO is off but we
// don't currently make that distinction in SwiftPM
switch buildParameters.configuration {
case .debug:
args += ["-enable-batch-mode"]
case .release: break
}
args += buildParameters.indexStoreArguments
args += buildParameters.toolchain.extraSwiftCFlags
args += optimizationArguments
args += ["-j\(SwiftCompilerTool.numThreads)"]
args += activeCompilationConditions
args += additionalFlags
args += moduleCacheArgs
args += buildParameters.sanitizers.compileSwiftFlags()
// Add arguments needed for code coverage if it is enabled.
if buildParameters.enableCodeCoverage {
args += ["-profile-coverage-mapping", "-profile-generate"]
}
// Add arguments to colorize output if stdout is tty
if buildParameters.isTTY {
args += ["-Xfrontend", "-color-diagnostics"]
}
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xswiftc) should follow generated arguments to allow user overrides
args += buildParameters.swiftCompilerFlags
return args
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
let scope = buildParameters.createScope(for: target)
var flags: [String] = []
// Swift defines.
let swiftDefines = scope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS)
flags += swiftDefines.map({ "-D" + $0 })
// Frameworks.
let frameworks = scope.evaluate(.LINK_FRAMEWORKS)
flags += frameworks.flatMap({ ["-framework", $0] })
// Other Swift flags.
flags += scope.evaluate(.OTHER_SWIFT_FLAGS)
// Add C flags by prefixing them with -Xcc.
//
// C defines.
let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)
flags += cDefines.flatMap({ ["-Xcc", "-D" + $0] })
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.flatMap({ path -> [String] in
let path = target.sources.root.appending(RelativePath(path)).asString
return ["-Xcc", "-I" + path]
})
// Other C flags.
flags += scope.evaluate(.OTHER_CFLAGS).flatMap({ ["-Xcc", $0] })
return flags
}
/// A list of compilation conditions to enable for conditional compilation expressions.
private var activeCompilationConditions: [String] {
var compilationConditions = ["-DSWIFT_PACKAGE"]
switch buildParameters.configuration {
case .debug:
compilationConditions += ["-DDEBUG"]
case .release:
break
}
return compilationConditions
}
/// Optimization arguments according to the build configuration.
private var optimizationArguments: [String] {
switch buildParameters.configuration {
case .debug:
return ["-Onone", "-g", "-enable-testing"]
case .release:
return ["-O"]
}
}
/// Module cache arguments.
private var moduleCacheArgs: [String] {
return ["-module-cache-path", buildParameters.moduleCache.asString]
}
}
/// The build description for a product.
public final class ProductBuildDescription {
/// The reference to the product.
public let product: ResolvedProduct
/// The build parameters.
let buildParameters: BuildParameters
/// The path to the product binary produced.
public var binary: AbsolutePath {
return buildParameters.buildPath.appending(outname)
}
/// The output name of the product.
public var outname: RelativePath {
let name = product.name
switch product.type {
case .executable:
if buildParameters.triple.isWindows() {
return RelativePath("\(name).exe")
} else {
return RelativePath(name)
}
case .library(.static):
return RelativePath("lib\(name).a")
case .library(.dynamic):
return RelativePath("lib\(name).\(self.buildParameters.toolchain.dynamicLibraryExtension)")
case .library(.automatic):
fatalError()
case .test:
let base = "\(name).xctest"
if buildParameters.triple.isDarwin() {
return RelativePath("\(base)/Contents/MacOS/\(name)")
} else {
return RelativePath(base)
}
}
}
/// The objects in this product.
///
// Computed during build planning.
fileprivate(set) var objects = SortedArray<AbsolutePath>()
/// The dynamic libraries this product needs to link with.
// Computed during build planning.
fileprivate(set) var dylibs: [ProductBuildDescription] = []
/// Any additional flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The list of targets that are going to be linked statically in this product.
fileprivate var staticTargets: [ResolvedTarget] = []
/// Path to the temporary directory for this product.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: product.name + ".product")
}
/// Path to the link filelist file.
var linkFileListPath: AbsolutePath {
return tempsPath.appending(component: "Objects.LinkFileList")
}
/// Create a build description for a product.
init(product: ResolvedProduct, buildParameters: BuildParameters) {
assert(product.type != .library(.automatic), "Automatic type libraries should not be described.")
self.product = product
self.buildParameters = buildParameters
}
/// Strips the arguments which should *never* be passed to Swift compiler
/// when we're linking the product.
///
/// We might want to get rid of this method once Swift driver can strip the
/// flags itself, <rdar://problem/31215562>.
private func stripInvalidArguments(_ args: [String]) -> [String] {
let invalidArguments: Set<String> = ["-wmo", "-whole-module-optimization"]
return args.filter({ !invalidArguments.contains($0) })
}
/// The arguments to link and create this product.
public func linkArguments() -> [String] {
var args = [buildParameters.toolchain.swiftCompiler.asString]
args += buildParameters.toolchain.extraSwiftCFlags
args += buildParameters.sanitizers.linkSwiftFlags()
args += additionalFlags
if buildParameters.configuration == .debug {
if buildParameters.triple.isWindows() {
args += ["-Xlinker","-debug"]
} else {
args += ["-g"]
}
}
args += ["-L", buildParameters.buildPath.asString]
args += ["-o", binary.asString]
args += ["-module-name", product.name.spm_mangledToC99ExtendedIdentifier()]
args += dylibs.map({ "-l" + $0.product.name })
// Add arguements needed for code coverage if it is enabled.
if buildParameters.enableCodeCoverage {
args += ["-profile-coverage-mapping", "-profile-generate"]
}
switch product.type {
case .library(.automatic):
fatalError()
case .library(.static):
// No arguments for static libraries.
return []
case .test:
// Test products are bundle on macOS, executable on linux.
if buildParameters.triple.isDarwin() {
args += ["-Xlinker", "-bundle"]
} else {
args += ["-emit-executable"]
}
case .library(.dynamic):
args += ["-emit-library"]
case .executable:
// Link the Swift stdlib statically if requested.
if buildParameters.shouldLinkStaticSwiftStdlib {
// FIXME: This does not work for linux yet (SR-648).
#if os(macOS)
args += ["-static-stdlib"]
#endif
}
args += ["-emit-executable"]
}
// On linux, set rpath such that dynamic libraries are looked up
// adjacent to the product. This happens by default on macOS.
if buildParameters.triple.isLinux() {
args += ["-Xlinker", "-rpath=$ORIGIN"]
}
args += ["@" + linkFileListPath.asString]
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xlinker and -Xswiftc) should follow generated arguments to allow user overrides
args += buildParameters.linkerFlags
args += stripInvalidArguments(buildParameters.swiftCompilerFlags)
return args
}
/// Writes link filelist to the filesystem.
func writeLinkFilelist(_ fs: FileSystem) throws {
let stream = BufferedOutputByteStream()
for object in objects {
stream <<< object.asString.spm_shellEscaped() <<< "\n"
}
try fs.createDirectory(linkFileListPath.parentDirectory, recursive: true)
try fs.writeFileContents(linkFileListPath, bytes: stream.bytes)
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
var flags: [String] = []
// Linked libraries.
let libraries = OrderedSet(staticTargets.reduce([]) {
$0 + buildParameters.createScope(for: $1).evaluate(.LINK_LIBRARIES)
})
flags += libraries.map({ "-l" + $0 })
// Linked frameworks.
let frameworks = OrderedSet(staticTargets.reduce([]) {
$0 + buildParameters.createScope(for: $1).evaluate(.LINK_FRAMEWORKS)
})
flags += frameworks.flatMap({ ["-framework", $0] })
// Other linker flags.
for target in staticTargets {
let scope = buildParameters.createScope(for: target)
flags += scope.evaluate(.OTHER_LDFLAGS)
}
return flags
}
}
/// A build plan for a package graph.
public class BuildPlan {
public enum Error: Swift.Error, CustomStringConvertible, Equatable {
/// The linux main file is missing.
case missingLinuxMain
/// There is no buildable target in the graph.
case noBuildableTarget
public var description: String {
switch self {
case .missingLinuxMain:
return "missing LinuxMain.swift file in the Tests directory"
case .noBuildableTarget:
return "the package does not contain a buildable target"
}
}
}
/// The build parameters.
public let buildParameters: BuildParameters
/// The package graph.
public let graph: PackageGraph
/// The target build description map.
public let targetMap: [ResolvedTarget: TargetBuildDescription]
/// The product build description map.
public let productMap: [ResolvedProduct: ProductBuildDescription]
/// The build targets.
public var targets: AnySequence<TargetBuildDescription> {
return AnySequence(targetMap.values)
}
/// The products in this plan.
public var buildProducts: AnySequence<ProductBuildDescription> {
return AnySequence(productMap.values)
}
/// The filesystem to operate on.
let fileSystem: FileSystem
/// Diagnostics Engine to emit diagnostics
let diagnostics: DiagnosticsEngine
/// Create a build plan with build parameters and a package graph.
public init(
buildParameters: BuildParameters,
graph: PackageGraph,
diagnostics: DiagnosticsEngine,
fileSystem: FileSystem = localFileSystem
) throws {
self.buildParameters = buildParameters
self.graph = graph
self.diagnostics = diagnostics
self.fileSystem = fileSystem
// Create build target description for each target which we need to plan.
var targetMap = [ResolvedTarget: TargetBuildDescription]()
for target in graph.allTargets {
switch target.underlyingTarget {
case is SwiftTarget:
targetMap[target] = .swift(SwiftTargetBuildDescription(target: target, buildParameters: buildParameters))
case is ClangTarget:
targetMap[target] = try .clang(ClangTargetBuildDescription(
target: target,
buildParameters: buildParameters,
fileSystem: fileSystem))
case is SystemLibraryTarget:
break
default:
fatalError("unhandled \(target.underlyingTarget)")
}
}
/// Ensure we have at least one buildable target.
guard !targetMap.isEmpty else {
throw Error.noBuildableTarget
}
if buildParameters.triple.isLinux() {
// FIXME: Create a target for LinuxMain file on linux.
// This will go away once it is possible to auto detect tests.
let testProducts = graph.allProducts.filter({ $0.type == .test })
for product in testProducts {
guard let linuxMainTarget = product.linuxMainTarget else {
throw Error.missingLinuxMain
}
let target = SwiftTargetBuildDescription(
target: linuxMainTarget, buildParameters: buildParameters, isTestTarget: true)
targetMap[linuxMainTarget] = .swift(target)
}
}
var productMap: [ResolvedProduct: ProductBuildDescription] = [:]
// Create product description for each product we have in the package graph except
// for automatic libraries because they don't produce any output.
for product in graph.allProducts where product.type != .library(.automatic) {
productMap[product] = ProductBuildDescription(
product: product, buildParameters: buildParameters)
}
self.productMap = productMap
self.targetMap = targetMap
// Finally plan these targets.
try plan()
}
/// Plan the targets and products.
private func plan() throws {
// Plan targets.
for buildTarget in targets {
switch buildTarget {
case .swift(let target):
try plan(swiftTarget: target)
case .clang(let target):
plan(clangTarget: target)
}
}
// Plan products.
for buildProduct in buildProducts {
try plan(buildProduct)
}
// FIXME: We need to find out if any product has a target on which it depends
// both static and dynamically and then issue a suitable diagnostic or auto
// handle that situation.
}
/// Plan a product.
private func plan(_ buildProduct: ProductBuildDescription) throws {
// Compute the product's dependency.
let dependencies = computeDependencies(of: buildProduct.product)
// Add flags for system targets.
for systemModule in dependencies.systemModules {
guard case let target as SystemLibraryTarget = systemModule.underlyingTarget else {
fatalError("This should not be possible.")
}
// Add pkgConfig libs arguments.
buildProduct.additionalFlags += pkgConfig(for: target).libs
}
// Link C++ if needed.
// Note: This will come from build settings in future.
for target in dependencies.staticTargets {
if case let target as ClangTarget = target.underlyingTarget, target.isCXX {
buildProduct.additionalFlags += self.buildParameters.toolchain.extraCPPFlags
break
}
}
buildProduct.staticTargets = dependencies.staticTargets
buildProduct.dylibs = dependencies.dylibs.map({ productMap[$0]! })
buildProduct.objects += dependencies.staticTargets.flatMap({ targetMap[$0]!.objects })
// Write the link filelist file.
//
// FIXME: We should write this as a custom llbuild task once we adopt it
// as a library.
try buildProduct.writeLinkFilelist(fileSystem)
}
/// Computes the dependencies of a product.
private func computeDependencies(
of product: ResolvedProduct
) -> (
dylibs: [ResolvedProduct],
staticTargets: [ResolvedTarget],
systemModules: [ResolvedTarget]
) {
// Sort the product targets in topological order.
let nodes = product.targets.map(ResolvedTarget.Dependency.target)
let allTargets = try! topologicalSort(nodes, successors: { dependency in
switch dependency {
// Include all the depenencies of a target.
case .target(let target):
return target.dependencies
// For a product dependency, we only include its content only if we
// need to statically link it.
case .product(let product):
switch product.type {
case .library(.automatic), .library(.static):
return product.targets.map(ResolvedTarget.Dependency.target)
case .library(.dynamic), .test, .executable:
return []
}
}
})
// Create empty arrays to collect our results.
var linkLibraries = [ResolvedProduct]()
var staticTargets = [ResolvedTarget]()
var systemModules = [ResolvedTarget]()
for dependency in allTargets {
switch dependency {
case .target(let target):
switch target.type {
// Include executable and tests only if they're top level contents
// of the product. Otherwise they are just build time dependency.
case .executable, .test:
if product.targets.contains(target) {
staticTargets.append(target)
}
// Library targets should always be included.
case .library:
staticTargets.append(target)
// Add system target targets to system targets array.
case .systemModule:
systemModules.append(target)
}
case .product(let product):
// Add the dynamic products to array of libraries to link.
if product.type == .library(.dynamic) {
linkLibraries.append(product)
}
}
}
if buildParameters.triple.isLinux() {
if product.type == .test {
product.linuxMainTarget.map({ staticTargets.append($0) })
}
}
return (linkLibraries, staticTargets, systemModules)
}
/// Plan a Clang target.
private func plan(clangTarget: ClangTargetBuildDescription) {
for dependency in clangTarget.target.recursiveDependencies() {
switch dependency.underlyingTarget {
case let target as ClangTarget where target.type == .library:
// Setup search paths for C dependencies:
clangTarget.additionalFlags += ["-I", target.includeDir.asString]
case let target as SystemLibraryTarget:
clangTarget.additionalFlags += ["-fmodule-map-file=\(target.moduleMapPath.asString)"]
clangTarget.additionalFlags += pkgConfig(for: target).cFlags
default: continue
}
}
}
/// Plan a Swift target.
private func plan(swiftTarget: SwiftTargetBuildDescription) throws {
// We need to iterate recursive dependencies because Swift compiler needs to see all the targets a target
// depends on.
for dependency in swiftTarget.target.recursiveDependencies() {
switch dependency.underlyingTarget {
case let underlyingTarget as ClangTarget where underlyingTarget.type == .library:
guard case let .clang(target)? = targetMap[dependency] else {
fatalError("unexpected clang target \(underlyingTarget)")
}
// Add the path to modulemap of the dependency. Currently we require that all Clang targets have a
// modulemap but we may want to remove that requirement since it is valid for a target to exist without
// one. However, in that case it will not be importable in Swift targets. We may want to emit a warning
// in that case from here.
guard let moduleMap = target.moduleMap else { break }
swiftTarget.additionalFlags += [
"-Xcc", "-fmodule-map-file=\(moduleMap.asString)",
"-I", target.clangTarget.includeDir.asString,
]
case let target as SystemLibraryTarget:
swiftTarget.additionalFlags += ["-Xcc", "-fmodule-map-file=\(target.moduleMapPath.asString)"]
swiftTarget.additionalFlags += pkgConfig(for: target).cFlags
default: break
}
}
}
/// Creates arguments required to launch the Swift REPL that will allow
/// importing the modules in the package graph.
public func createREPLArguments() -> [String] {
let buildPath = buildParameters.buildPath.asString
var arguments = ["-I" + buildPath, "-L" + buildPath]
// Link the special REPL product that contains all of the library targets.
let replProductName = graph.rootPackages[0].manifest.name + Product.replProductSuffix
arguments.append("-l" + replProductName)
// The graph should have the REPL product.
assert(graph.allProducts.first(where: { $0.name == replProductName }) != nil)
// Add the search path to the directory containing the modulemap file.
for target in targets {
switch target {
case .swift: break
case .clang(let targetDescription):
if let includeDir = targetDescription.moduleMap?.parentDirectory {
arguments += ["-I" + includeDir.asString]
}
}
}
// Add search paths from the system library targets.
for target in graph.reachableTargets {
if let systemLib = target.underlyingTarget as? SystemLibraryTarget {
arguments += self.pkgConfig(for: systemLib).cFlags
}
}
return arguments
}
/// Get pkgConfig arguments for a system library target.
private func pkgConfig(for target: SystemLibraryTarget) -> (cFlags: [String], libs: [String]) {
// If we already have these flags, we're done.
if let flags = pkgConfigCache[target] {
return flags
}
// Otherwise, get the result and cache it.
guard let result = pkgConfigArgs(for: target, diagnostics: diagnostics) else {
pkgConfigCache[target] = ([], [])
return pkgConfigCache[target]!
}
// If there is no pc file on system and we have an available provider, emit a warning.
if let provider = result.provider, result.couldNotFindConfigFile {
diagnostics.emit(data: PkgConfigHintDiagnostic(pkgConfigName: result.pkgConfigName, installText: provider.installText))
} else if let error = result.error {
diagnostics.emit(
data: PkgConfigGenericDiagnostic(error: "\(error)"),
location: PkgConfigDiagnosticLocation(pcFile: result.pkgConfigName, target: target.name))
}
pkgConfigCache[target] = (result.cFlags, result.libs)
return pkgConfigCache[target]!
}
/// Cache for pkgConfig flags.
private var pkgConfigCache = [SystemLibraryTarget: (cFlags: [String], libs: [String])]()
}
struct PkgConfigDiagnosticLocation: DiagnosticLocation {
let pcFile: String
let target: String
public var localizedDescription: String {
return "'\(target)' \(pcFile).pc"
}
}
public struct PkgConfigGenericDiagnostic: DiagnosticData {
public static let id = DiagnosticID(
type: PkgConfigGenericDiagnostic.self,
name: "org.swift.diags.pkg-config-generic",
defaultBehavior: .warning,
description: {
$0 <<< { $0.error }
}
)
let error: String
}
public struct PkgConfigHintDiagnostic: DiagnosticData {
public static let id = DiagnosticID(
type: PkgConfigHintDiagnostic.self,
name: "org.swift.diags.pkg-config-hint",
defaultBehavior: .warning,
description: {
$0 <<< "you may be able to install" <<< { $0.pkgConfigName } <<< "using your system-packager:\n"
$0 <<< { $0.installText }
}
)
let pkgConfigName: String
let installText: String
}
|
apache-2.0
|
899b407b754a8731fa50151bd28de72f
| 36.158854 | 137 | 0.62415 | 4.9944 | false | false | false | false |
AlbertXYZ/HDCP
|
HDCP/HDCP/HDShareView.swift
|
1
|
6299
|
//
// HDShareView.swift
// HDCP
//
// Created by 徐琰璋 on 16/1/20.
// Copyright © 2016年 batonsoft. All rights reserved.
//
import UIKit
private let HDShareButtonHeight = 60
private let resourceArray = [["title":"微信好友","image":"share_wxhy_icon"],
["title":"朋友圈","image":"share_wxc_icon"],
["title":"QQ","image":"share_qq_icon"],
["title":"QQ空间","image":"share_qqzone_icon"]]
public protocol HDShareViewDelegate:NSObjectProtocol {
func didShareWithType(_ type:Int);
}
open class HDShareView: UIView {
weak open var delegate:HDShareViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
createSubviews()
}
func createSubviews() {
for i in 0 ..< resourceArray.count {
if i == 3 {
let btn = HDShareButton()
btn.backgroundColor = UIColor.white
btn.setTitleColor(Constants.HDMainTextColor, for: UIControl.State.normal)
btn.tag = i + 1000;
btn.titleLabel?.textAlignment = NSTextAlignment.center
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.setTitle(resourceArray[i]["title"], for: UIControl.State())
btn.setImage(UIImage(named:resourceArray[i]["image"]!), for: UIControl.State())
btn.addTarget(self, action: #selector(tagBtnOnclick(_:)), for: UIControl.Event.touchUpInside)
self.addSubview(btn)
let space = (Constants.HDSCREENWITH-180)/6
btn.snp.makeConstraints( { (make) -> Void in
make.top.equalTo(self).offset(HDShareButtonHeight+20+20+15)
make.width.equalTo(HDShareButtonHeight)
make.height.equalTo(HDShareButtonHeight+20)
make.left.equalTo(space)
})
/**
* 判断QQ是否安装
*/
if !QQApiInterface.isQQInstalled() {
btn.isEnabled = false
}
}else{
let btn = HDShareButton()
btn.backgroundColor = UIColor.white
btn.setTitleColor(Constants.HDMainTextColor, for: UIControl.State.normal)
btn.tag = i + 1000;
btn.titleLabel?.textAlignment = NSTextAlignment.center
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.setTitle(resourceArray[i]["title"], for: UIControl.State())
btn.setImage(UIImage(named:resourceArray[i]["image"]!), for: UIControl.State())
btn.addTarget(self, action: #selector(tagBtnOnclick(_:)), for: UIControl.Event.touchUpInside)
self.addSubview(btn)
let space = (Constants.HDSCREENWITH-CGFloat(3*HDShareButtonHeight))/6
btn.snp.makeConstraints( { (make) -> Void in
make.top.equalTo(self).offset(20)
make.width.equalTo(HDShareButtonHeight)
make.height.equalTo(HDShareButtonHeight+20)
make.left.equalTo(space+CGFloat(i*HDShareButtonHeight)+CGFloat(i*2)*space)
})
if i == 0 || i == 1 {
/**
* 判断微信是否安装
*/
if !WXApi.isWXAppInstalled() {
btn.isEnabled = false
}
}else{
/**
* 判断QQ是否安装
*/
if !QQApiInterface.isQQInstalled() {
btn.isEnabled = false
}
}
}
}
let line = UILabel()
line.backgroundColor = CoreUtils.HDColor(227, g: 227, b: 229, a: 1.0)
self.addSubview(line)
line.snp.makeConstraints { (make) -> Void in
make.left.equalTo(self).offset(0)
make.bottom.equalTo(self.snp.bottom).offset(-44)
make.width.equalTo(Constants.HDSCREENWITH)
make.height.equalTo(1)
}
let cancelBtn = UIButton()
cancelBtn.backgroundColor = UIColor.white
cancelBtn.setTitleColor(Constants.HDMainTextColor, for: UIControl.State.normal)
cancelBtn.setTitle("取消", for: UIControl.State())
cancelBtn.tag = 4 + 1000;
cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
cancelBtn.addTarget(self, action: #selector(tagBtnOnclick(_:)), for: UIControl.Event.touchUpInside)
self.addSubview(cancelBtn)
cancelBtn.snp.makeConstraints { (make) -> Void in
make.left.equalTo(self).offset(0)
make.bottom.equalTo(self.snp.bottom).offset(0)
make.width.equalTo(Constants.HDSCREENWITH)
make.height.equalTo(44)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tagBtnOnclick(_ btn:UIButton){
if (self.delegate != nil) {
self.delegate?.didShareWithType(btn.tag - 1000)
}
}
}
class HDShareButton: UIButton {
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: contentRect.size.height*0.75, width: contentRect.size.width, height: contentRect.size.height*0.25);
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: 0,width: contentRect.size.width,height: contentRect.size.height*0.75);
}
}
|
mit
|
5d7a2710cd92f6664d4851b243cfc046
| 32.12766 | 130 | 0.505299 | 4.884706 | false | false | false | false |
ilyahal/VKMusic
|
VkPlaylist/GetOwnerAudio.swift
|
1
|
5332
|
//
// GetOwnerAudio.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/// Получение списка аудиозаписей владельца
class GetOwnerAudio: RequestManagerObject {
override func performRequest(parameters: [Argument : AnyObject], withCompletionHandler completion: (Bool) -> Void) {
super.performRequest(parameters, withCompletionHandler: completion)
// Отмена выполнения предыдущего запроса и удаление загруженной информации
cancel()
DataManager.sharedInstance.ownerMusic.clear()
let ownerID = parameters[.OwnerID]! as! Int
// Если нет подключения к интернету
if !Reachability.isConnectedToNetwork() {
state = .NotSearchedYet
error = .NetworkError
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
completion(false)
return
}
// Слушатель для уведомления об успешном завершении получения аудиозаписей
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerDidGetAudioForOwnerNotification, object: nil, queue: NSOperationQueue.mainQueue()) { notification in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
let result = notification.userInfo!["Audio"] as! [Track]
DataManager.sharedInstance.ownerMusic.saveNewArray(result)
self.state = DataManager.sharedInstance.ownerMusic.array.count == 0 ? .NoResults : .Results
self.error = .None
completion(true)
}
// Слушатель для получения уведомления об ошибке при подключении к интернету
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetAudioForOwnerNetworkErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
DataManager.sharedInstance.ownerMusic.clear()
self.state = .NotSearchedYet
self.error = .NetworkError
completion(false)
}
// Слушатель для получения уведомления об ошибке при доступе к аудиозаписям владельца
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetAudioForOwnerAccessErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
DataManager.sharedInstance.ownerMusic.clear()
self.state = .NotSearchedYet
self.error = .AccessError
completion(false)
}
// Слушатель для уведомления о других ошибках
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetAudioForOwnerErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
DataManager.sharedInstance.ownerMusic.clear()
self.state = .NotSearchedYet
self.error = .UnknownError
completion(false)
}
let request = VKAPIManager.audioGetWithOwnerID(ownerID)
state = .Loading
error = .None
RequestManager.sharedInstance.activeRequests[key] = request
}
}
|
mit
|
c471cd02e8b2214e0269e0b7ae9160ee
| 40.824561 | 176 | 0.661213 | 4.815152 | false | false | false | false |
whiteath/ReadFoundationSource
|
Foundation/NumberFormatter.swift
|
8
|
27771
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFNumberFormatterNoStyle = CFNumberFormatterStyle.noStyle
internal let kCFNumberFormatterDecimalStyle = CFNumberFormatterStyle.decimalStyle
internal let kCFNumberFormatterCurrencyStyle = CFNumberFormatterStyle.currencyStyle
internal let kCFNumberFormatterPercentStyle = CFNumberFormatterStyle.percentStyle
internal let kCFNumberFormatterScientificStyle = CFNumberFormatterStyle.scientificStyle
internal let kCFNumberFormatterSpellOutStyle = CFNumberFormatterStyle.spellOutStyle
internal let kCFNumberFormatterOrdinalStyle = CFNumberFormatterStyle.ordinalStyle
internal let kCFNumberFormatterCurrencyISOCodeStyle = CFNumberFormatterStyle.currencyISOCodeStyle
internal let kCFNumberFormatterCurrencyPluralStyle = CFNumberFormatterStyle.currencyPluralStyle
internal let kCFNumberFormatterCurrencyAccountingStyle = CFNumberFormatterStyle.currencyAccountingStyle
#endif
extension NumberFormatter {
public enum Style : UInt {
case none
case decimal
case currency
case percent
case scientific
case spellOut
case ordinal
case currencyISOCode
case currencyPlural
case currencyAccounting
}
public enum PadPosition : UInt {
case beforePrefix
case afterPrefix
case beforeSuffix
case afterSuffix
}
public enum RoundingMode : UInt {
case ceiling
case floor
case down
case up
case halfEven
case halfDown
case halfUp
}
}
open class NumberFormatter : Formatter {
typealias CFType = CFNumberFormatter
private var _currentCfFormatter: CFType?
private var _cfFormatter: CFType {
if let obj = _currentCfFormatter {
return obj
} else {
#if os(OSX) || os(iOS)
let numberStyle = CFNumberFormatterStyle(rawValue: CFIndex(self.numberStyle.rawValue))!
#else
let numberStyle = CFNumberFormatterStyle(self.numberStyle.rawValue)
#endif
let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)!
_setFormatterAttributes(obj)
if let format = _format {
CFNumberFormatterSetFormat(obj, format._cfObject)
}
_currentCfFormatter = obj
return obj
}
}
// this is for NSUnitFormatter
open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
// Report the used range of the string and an NSError, in addition to the usual stuff from Formatter
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func objectValue(_ string: String, range: inout NSRange) throws -> Any? { NSUnimplemented() }
open override func string(for obj: Any) -> String? {
//we need to allow Swift's numeric types here - Int, Double et al.
guard let number = _SwiftValue.store(obj) as? NSNumber else { return nil }
return string(from: number)
}
// Even though NumberFormatter responds to the usual Formatter methods,
// here are some convenience methods which are a little more obvious.
open func string(from number: NSNumber) -> String? {
return CFNumberFormatterCreateStringWithNumber(kCFAllocatorSystemDefault, _cfFormatter, number._cfObject)._swiftObject
}
open func number(from string: String) -> NSNumber? {
var range = CFRange(location: 0, length: string.length)
let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in
#if os(OSX) || os(iOS)
let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue
#else
let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly)
#endif
let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption)
return result?._nsObject
}
return number
}
open class func localizedString(from num: NSNumber, number nstyle: Style) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = nstyle
return numberFormatter.string(for: num)!
}
internal func _reset() {
_currentCfFormatter = nil
}
internal func _setFormatterAttributes(_ formatter: CFNumberFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyCode, value: _currencyCode?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterDecimalSeparator, value: _decimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator, value: _currencyDecimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterAlwaysShowDecimalSeparator, value: _alwaysShowsDecimalSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSeparator, value: _groupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseGroupingSeparator, value: _usesGroupingSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPercentSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterZeroSymbol, value: _zeroSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNaNSymbol, value: _notANumberSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInfinitySymbol, value: _positiveInfinitySymbol._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinusSign, value: _minusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPlusSign, value: _plusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencySymbol, value: _currencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterExponentSymbol, value: _exponentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinIntegerDigits, value: _minimumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxIntegerDigits, value: _maximumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinFractionDigits, value: _minimumFractionDigits._bridgeToObjectiveC()._cfObject)
if _minimumFractionDigits <= 0 {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxFractionDigits, value: _maximumFractionDigits._bridgeToObjectiveC()._cfObject)
}
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSize, value: _groupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterSecondaryGroupingSize, value: _secondaryGroupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingMode, value: _roundingMode.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingIncrement, value: _roundingIncrement?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterFormatWidth, value: _formatWidth._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingCharacter, value: _paddingCharacter?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingPosition, value: _paddingPosition.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMultiplier, value: _multiplier?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositivePrefix, value: _positivePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositiveSuffix, value: _positiveSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativePrefix, value: _negativePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativeSuffix, value: _negativeSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject)
if _usesSignificantDigits {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxSignificantDigits, value: _maximumSignificantDigits._bridgeToObjectiveC()._cfObject)
}
}
internal func _setFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFNumberFormatterSetProperty(formatter, attributeName, value)
}
}
// Attributes of a NumberFormatter
internal var _numberStyle: Style = .none
open var numberStyle: Style {
get {
return _numberStyle
}
set {
switch newValue {
case .none, .ordinal, .spellOut:
_usesSignificantDigits = false
case .currency, .currencyPlural, .currencyISOCode, .currencyAccounting:
_usesSignificantDigits = false
_usesGroupingSeparator = true
_minimumFractionDigits = 2
case .decimal:
_usesGroupingSeparator = true
_maximumFractionDigits = 3
_minimumIntegerDigits = 1
default:
_usesSignificantDigits = true
_usesGroupingSeparator = true
}
_reset()
_numberStyle = newValue
}
}
internal var _locale: Locale = Locale.current
/*@NSCopying*/ open var locale: Locale! {
get {
return _locale
}
set {
_reset()
_locale = newValue
}
}
internal var _generatesDecimalNumbers: Bool = false
open var generatesDecimalNumbers: Bool {
get {
return _generatesDecimalNumbers
}
set {
_reset()
_generatesDecimalNumbers = newValue
}
}
internal var _negativeFormat: String!
open var negativeFormat: String! {
get {
return _negativeFormat
}
set {
_reset()
_negativeFormat = newValue
}
}
internal var _textAttributesForNegativeValues: [String : Any]?
open var textAttributesForNegativeValues: [String : Any]? {
get {
return _textAttributesForNegativeValues
}
set {
_reset()
_textAttributesForNegativeValues = newValue
}
}
internal var _positiveFormat: String!
open var positiveFormat: String! {
get {
return _positiveFormat
}
set {
_reset()
_positiveFormat = newValue
}
}
internal var _textAttributesForPositiveValues: [String : Any]?
open var textAttributesForPositiveValues: [String : Any]? {
get {
return _textAttributesForPositiveValues
}
set {
_reset()
_textAttributesForPositiveValues = newValue
}
}
internal var _allowsFloats: Bool = true
open var allowsFloats: Bool {
get {
return _allowsFloats
}
set {
_reset()
_allowsFloats = newValue
}
}
internal var _decimalSeparator: String!
open var decimalSeparator: String! {
get {
return _decimalSeparator
}
set {
_reset()
_decimalSeparator = newValue
}
}
internal var _alwaysShowsDecimalSeparator: Bool = false
open var alwaysShowsDecimalSeparator: Bool {
get {
return _alwaysShowsDecimalSeparator
}
set {
_reset()
_alwaysShowsDecimalSeparator = newValue
}
}
internal var _currencyDecimalSeparator: String!
open var currencyDecimalSeparator: String! {
get {
return _currencyDecimalSeparator
}
set {
_reset()
_currencyDecimalSeparator = newValue
}
}
internal var _usesGroupingSeparator: Bool = false
open var usesGroupingSeparator: Bool {
get {
return _usesGroupingSeparator
}
set {
_reset()
_usesGroupingSeparator = newValue
}
}
internal var _groupingSeparator: String!
open var groupingSeparator: String! {
get {
return _groupingSeparator
}
set {
_reset()
_groupingSeparator = newValue
}
}
//
internal var _zeroSymbol: String?
open var zeroSymbol: String? {
get {
return _zeroSymbol
}
set {
_reset()
_zeroSymbol = newValue
}
}
internal var _textAttributesForZero: [String : Any]?
open var textAttributesForZero: [String : Any]? {
get {
return _textAttributesForZero
}
set {
_reset()
_textAttributesForZero = newValue
}
}
internal var _nilSymbol: String = ""
open var nilSymbol: String {
get {
return _nilSymbol
}
set {
_reset()
_nilSymbol = newValue
}
}
internal var _textAttributesForNil: [String : Any]?
open var textAttributesForNil: [String : Any]? {
get {
return _textAttributesForNil
}
set {
_reset()
_textAttributesForNil = newValue
}
}
internal var _notANumberSymbol: String!
open var notANumberSymbol: String! {
get {
return _notANumberSymbol
}
set {
_reset()
_notANumberSymbol = newValue
}
}
internal var _textAttributesForNotANumber: [String : Any]?
open var textAttributesForNotANumber: [String : Any]? {
get {
return _textAttributesForNotANumber
}
set {
_reset()
_textAttributesForNotANumber = newValue
}
}
internal var _positiveInfinitySymbol: String = "+∞"
open var positiveInfinitySymbol: String {
get {
return _positiveInfinitySymbol
}
set {
_reset()
_positiveInfinitySymbol = newValue
}
}
internal var _textAttributesForPositiveInfinity: [String : Any]?
open var textAttributesForPositiveInfinity: [String : Any]? {
get {
return _textAttributesForPositiveInfinity
}
set {
_reset()
_textAttributesForPositiveInfinity = newValue
}
}
internal var _negativeInfinitySymbol: String = "-∞"
open var negativeInfinitySymbol: String {
get {
return _negativeInfinitySymbol
}
set {
_reset()
_negativeInfinitySymbol = newValue
}
}
internal var _textAttributesForNegativeInfinity: [String : Any]?
open var textAttributesForNegativeInfinity: [String : Any]? {
get {
return _textAttributesForNegativeInfinity
}
set {
_reset()
_textAttributesForNegativeInfinity = newValue
}
}
//
internal var _positivePrefix: String!
open var positivePrefix: String! {
get {
return _positivePrefix
}
set {
_reset()
_positivePrefix = newValue
}
}
internal var _positiveSuffix: String!
open var positiveSuffix: String! {
get {
return _positiveSuffix
}
set {
_reset()
_positiveSuffix = newValue
}
}
internal var _negativePrefix: String!
open var negativePrefix: String! {
get {
return _negativePrefix
}
set {
_reset()
_negativePrefix = newValue
}
}
internal var _negativeSuffix: String!
open var negativeSuffix: String! {
get {
return _negativeSuffix
}
set {
_reset()
_negativeSuffix = newValue
}
}
internal var _currencyCode: String!
open var currencyCode: String! {
get {
return _currencyCode
}
set {
_reset()
_currencyCode = newValue
}
}
internal var _currencySymbol: String!
open var currencySymbol: String! {
get {
return _currencySymbol
}
set {
_reset()
_currencySymbol = newValue
}
}
internal var _internationalCurrencySymbol: String!
open var internationalCurrencySymbol: String! {
get {
return _internationalCurrencySymbol
}
set {
_reset()
_internationalCurrencySymbol = newValue
}
}
internal var _percentSymbol: String!
open var percentSymbol: String! {
get {
return _percentSymbol
}
set {
_reset()
_percentSymbol = newValue
}
}
internal var _perMillSymbol: String!
open var perMillSymbol: String! {
get {
return _perMillSymbol
}
set {
_reset()
_perMillSymbol = newValue
}
}
internal var _minusSign: String!
open var minusSign: String! {
get {
return _minusSign
}
set {
_reset()
_minusSign = newValue
}
}
internal var _plusSign: String!
open var plusSign: String! {
get {
return _plusSign
}
set {
_reset()
_plusSign = newValue
}
}
internal var _exponentSymbol: String!
open var exponentSymbol: String! {
get {
return _exponentSymbol
}
set {
_reset()
_exponentSymbol = newValue
}
}
//
internal var _groupingSize: Int = 3
open var groupingSize: Int {
get {
return _groupingSize
}
set {
_reset()
_groupingSize = newValue
}
}
internal var _secondaryGroupingSize: Int = 0
open var secondaryGroupingSize: Int {
get {
return _secondaryGroupingSize
}
set {
_reset()
_secondaryGroupingSize = newValue
}
}
internal var _multiplier: NSNumber?
/*@NSCopying*/ open var multiplier: NSNumber? {
get {
return _multiplier
}
set {
_reset()
_multiplier = newValue
}
}
internal var _formatWidth: Int = 0
open var formatWidth: Int {
get {
return _formatWidth
}
set {
_reset()
_formatWidth = newValue
}
}
internal var _paddingCharacter: String!
open var paddingCharacter: String! {
get {
return _paddingCharacter
}
set {
_reset()
_paddingCharacter = newValue
}
}
//
internal var _paddingPosition: PadPosition = .beforePrefix
open var paddingPosition: PadPosition {
get {
return _paddingPosition
}
set {
_reset()
_paddingPosition = newValue
}
}
internal var _roundingMode: RoundingMode = .halfEven
open var roundingMode: RoundingMode {
get {
return _roundingMode
}
set {
_reset()
_roundingMode = newValue
}
}
internal var _roundingIncrement: NSNumber! = 0
/*@NSCopying*/ open var roundingIncrement: NSNumber! {
get {
return _roundingIncrement
}
set {
_reset()
_roundingIncrement = newValue
}
}
internal var _minimumIntegerDigits: Int = 0
open var minimumIntegerDigits: Int {
get {
return _minimumIntegerDigits
}
set {
_reset()
_minimumIntegerDigits = newValue
}
}
internal var _maximumIntegerDigits: Int = 42
open var maximumIntegerDigits: Int {
get {
return _maximumIntegerDigits
}
set {
_reset()
_maximumIntegerDigits = newValue
}
}
internal var _minimumFractionDigits: Int = 0
open var minimumFractionDigits: Int {
get {
return _minimumFractionDigits
}
set {
_reset()
_minimumFractionDigits = newValue
}
}
internal var _maximumFractionDigits: Int = 0
open var maximumFractionDigits: Int {
get {
return _maximumFractionDigits
}
set {
_reset()
_maximumFractionDigits = newValue
}
}
internal var _minimum: NSNumber?
/*@NSCopying*/ open var minimum: NSNumber? {
get {
return _minimum
}
set {
_reset()
_minimum = newValue
}
}
internal var _maximum: NSNumber?
/*@NSCopying*/ open var maximum: NSNumber? {
get {
return _maximum
}
set {
_reset()
_maximum = newValue
}
}
internal var _currencyGroupingSeparator: String!
open var currencyGroupingSeparator: String! {
get {
return _currencyGroupingSeparator
}
set {
_reset()
_currencyGroupingSeparator = newValue
}
}
internal var _lenient: Bool = false
open var isLenient: Bool {
get {
return _lenient
}
set {
_reset()
_lenient = newValue
}
}
internal var _usesSignificantDigits: Bool = false
open var usesSignificantDigits: Bool {
get {
return _usesSignificantDigits
}
set {
_reset()
_usesSignificantDigits = newValue
}
}
internal var _minimumSignificantDigits: Int = 1
open var minimumSignificantDigits: Int {
get {
return _minimumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_minimumSignificantDigits = newValue
}
}
internal var _maximumSignificantDigits: Int = 6
open var maximumSignificantDigits: Int {
get {
return _maximumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_maximumSignificantDigits = newValue
}
}
internal var _partialStringValidationEnabled: Bool = false
open var isPartialStringValidationEnabled: Bool {
get {
return _partialStringValidationEnabled
}
set {
_reset()
_partialStringValidationEnabled = newValue
}
}
//
internal var _hasThousandSeparators: Bool = false
open var hasThousandSeparators: Bool {
get {
return _hasThousandSeparators
}
set {
_reset()
_hasThousandSeparators = newValue
}
}
internal var _thousandSeparator: String!
open var thousandSeparator: String! {
get {
return _thousandSeparator
}
set {
_reset()
_thousandSeparator = newValue
}
}
//
internal var _localizesFormat: Bool = true
open var localizesFormat: Bool {
get {
return _localizesFormat
}
set {
_reset()
_localizesFormat = newValue
}
}
//
internal var _format: String?
open var format: String {
get {
return _format ?? "#;0;#"
}
set {
_reset()
_format = newValue
}
}
//
internal var _attributedStringForZero: NSAttributedString = NSAttributedString(string: "0")
/*@NSCopying*/ open var attributedStringForZero: NSAttributedString {
get {
return _attributedStringForZero
}
set {
_reset()
_attributedStringForZero = newValue
}
}
internal var _attributedStringForNil: NSAttributedString = NSAttributedString(string: "")
/*@NSCopying*/ open var attributedStringForNil: NSAttributedString {
get {
return _attributedStringForNil
}
set {
_reset()
_attributedStringForNil = newValue
}
}
internal var _attributedStringForNotANumber: NSAttributedString = NSAttributedString(string: "NaN")
/*@NSCopying*/ open var attributedStringForNotANumber: NSAttributedString {
get {
return _attributedStringForNotANumber
}
set {
_reset()
_attributedStringForNotANumber = newValue
}
}
internal var _roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.default
/*@NSCopying*/ open var roundingBehavior: NSDecimalNumberHandler {
get {
return _roundingBehavior
}
set {
_reset()
_roundingBehavior = newValue
}
}
}
|
apache-2.0
|
0452a09c81460779f17fc00966a613e9
| 29.580396 | 166 | 0.599921 | 5.942007 | false | false | false | false |
imzyf/99-projects-of-swift
|
027-custom-transition/027-custom-transition/Transition/CustomPushTransition.swift
|
1
|
2047
|
//
// CustomPushTransition.swift
// 027-custom-transition
//
// Created by moma on 2018/3/13.
// Copyright © 2018年 yifans. All rights reserved.
//
import UIKit
class CustomPushTransition: NSObject, UIViewControllerAnimatedTransitioning {
// 转场时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewController(forKey: .from) as! ViewController
let toVC = transitionContext.viewController(forKey: .to) as! DetailViewController
let containerView = transitionContext.containerView
if let fromImageView = fromVC.selectedCell.viewWithTag(1001) as? UIImageView {
let snapshotView = fromImageView.snapshotView(afterScreenUpdates: false)
snapshotView?.frame = containerView.convert(fromImageView.frame, from: fromVC.selectedCell)
toVC.view.frame = transitionContext.finalFrame(for: toVC)
toVC.view.alpha = 0
toVC.imageView.isHidden = true
fromImageView.isHidden = true
containerView.addSubview(toVC.view)
containerView.addSubview(snapshotView!)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: UIViewAnimationOptions(), animations: {
snapshotView?.frame = toVC.imageView.frame
fromVC.view.alpha = 0
toVC.view.alpha = 1
}) { (finish) in
toVC.imageView.isHidden = false
fromImageView.isHidden = false
snapshotView?.removeFromSuperview()
// 告诉系统你的动画过程已经结束,这是非常重要的方法,必须调用。
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
}
|
mit
|
69ea5273acb9efee0ad578c843ac4d27
| 40.166667 | 145 | 0.655364 | 5.550562 | false | false | false | false |
thomasvl/swift-protobuf
|
Sources/protoc-gen-swift/OneofGenerator.swift
|
2
|
16405
|
// Sources/protoc-gen-swift/OneofGenerator.swift - Oneof handling
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This class represents a single Oneof in the proto and generates an efficient
/// algebraic enum to store it in memory.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
class OneofGenerator {
/// Custom FieldGenerator that caches come calculated strings, and bridges
/// all methods over to the OneofGenerator.
class MemberFieldGenerator: FieldGeneratorBase, FieldGenerator {
private weak var oneof: OneofGenerator!
private(set) var group: Int
let swiftName: String
let dottedSwiftName: String
let swiftType: String
let swiftDefaultValue: String
let protoGenericType: String
let comments: String
var isGroupOrMessage: Bool {
switch fieldDescriptor.type {
case .group, .message:
return true
default:
return false
}
}
// Only valid on message fields.
var messageType: Descriptor? { return fieldDescriptor.messageType }
init(descriptor: FieldDescriptor, namer: SwiftProtobufNamer) {
precondition(descriptor.oneofIndex != nil)
// Set after creation.
oneof = nil
group = -1
let names = namer.messagePropertyNames(field: descriptor,
prefixed: ".",
includeHasAndClear: false)
swiftName = names.name
dottedSwiftName = names.prefixed
swiftType = descriptor.swiftType(namer: namer)
swiftDefaultValue = descriptor.swiftDefaultValue(namer: namer)
protoGenericType = descriptor.protoGenericType
comments = descriptor.protoSourceComments()
super.init(descriptor: descriptor)
}
func setParent(_ oneof: OneofGenerator, group: Int) {
self.oneof = oneof
self.group = group
}
// MARK: Forward all the FieldGenerator methods to the OneofGenerator
func generateInterface(printer p: inout CodePrinter) {
oneof.generateInterface(printer: &p, field: self)
}
func generateStorage(printer p: inout CodePrinter) {
oneof.generateStorage(printer: &p, field: self)
}
func generateStorageClassClone(printer p: inout CodePrinter) {
oneof.generateStorageClassClone(printer: &p, field: self)
}
func generateDecodeFieldCase(printer p: inout CodePrinter) {
oneof.generateDecodeFieldCase(printer: &p, field: self)
}
func generateFieldComparison(printer p: inout CodePrinter) {
oneof.generateFieldComparison(printer: &p, field: self)
}
func generateRequiredFieldCheck(printer p: inout CodePrinter) {
// Oneof members are all optional, so no need to forward this.
}
func generateIsInitializedCheck(printer p: inout CodePrinter) {
oneof.generateIsInitializedCheck(printer: &p, field: self)
}
var generateTraverseUsesLocals: Bool {
return oneof.generateTraverseUsesLocals
}
func generateTraverse(printer p: inout CodePrinter) {
oneof.generateTraverse(printer: &p, field: self)
}
}
private let oneofDescriptor: OneofDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
private let usesHeapStorage: Bool
private let fields: [MemberFieldGenerator]
private let fieldsSortedByNumber: [MemberFieldGenerator]
// The fields in number order and group into ranges as they are grouped in the parent.
private let fieldSortedGrouped: [[MemberFieldGenerator]]
private let swiftRelativeName: String
private let swiftFullName: String
private let comments: String
private let swiftFieldName: String
private let underscoreSwiftFieldName: String
private let storedProperty: String
init(descriptor: OneofDescriptor, generatorOptions: GeneratorOptions, namer: SwiftProtobufNamer, usesHeapStorage: Bool) {
precondition(!descriptor.isSynthetic)
self.oneofDescriptor = descriptor
self.generatorOptions = generatorOptions
self.namer = namer
self.usesHeapStorage = usesHeapStorage
comments = descriptor.protoSourceComments()
swiftRelativeName = namer.relativeName(oneof: descriptor)
swiftFullName = namer.fullName(oneof: descriptor)
let names = namer.messagePropertyName(oneof: descriptor)
swiftFieldName = names.name
underscoreSwiftFieldName = names.prefixed
if usesHeapStorage {
storedProperty = "_storage.\(underscoreSwiftFieldName)"
} else {
storedProperty = "self.\(swiftFieldName)"
}
fields = descriptor.fields.map {
return MemberFieldGenerator(descriptor: $0, namer: namer)
}
fieldsSortedByNumber = fields.sorted {$0.number < $1.number}
// Bucked these fields in continuous chunks based on the other fields
// in the parent and the parent's extension ranges. Insert the `start`
// from each extension range as an easy way to check for them being
// mixed in between the fields.
var parentNumbers = descriptor.containingType.fields.map { Int($0.number) }
parentNumbers.append(contentsOf: descriptor.containingType.normalizedExtensionRanges.map { Int($0.lowerBound) })
var parentNumbersIterator = parentNumbers.sorted(by: { $0 < $1 }).makeIterator()
var nextParentFieldNumber = parentNumbersIterator.next()
var grouped = [[MemberFieldGenerator]]()
var currentGroup = [MemberFieldGenerator]()
for f in fieldsSortedByNumber {
let nextFieldNumber = f.number
if nextParentFieldNumber != nextFieldNumber {
if !currentGroup.isEmpty {
grouped.append(currentGroup)
currentGroup.removeAll()
}
while nextParentFieldNumber != nextFieldNumber {
nextParentFieldNumber = parentNumbersIterator.next()
}
}
currentGroup.append(f)
nextParentFieldNumber = parentNumbersIterator.next()
}
if !currentGroup.isEmpty {
grouped.append(currentGroup)
}
self.fieldSortedGrouped = grouped
// Now that self is fully initialized, set the parent references.
var group = 0
for g in fieldSortedGrouped {
for f in g {
f.setParent(self, group: group)
}
group += 1
}
}
func fieldGenerator(forFieldNumber fieldNumber: Int) -> FieldGenerator {
for f in fields {
if f.number == fieldNumber {
return f
}
}
fatalError("Can't happen")
}
func generateMainEnum(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
// Repeat the comment from the oneof to provide some context
// to this enum we generated.
p.print(
"",
"\(comments)\(visibility)enum \(swiftRelativeName): Equatable {")
p.withIndentation { p in
// Oneof case for each ivar
for f in fields {
p.print("\(f.comments)case \(f.swiftName)(\(f.swiftType))")
}
// A helper for isInitialized
let fieldsToCheck = fields.filter {
$0.isGroupOrMessage && $0.messageType!.containsRequiredFields()
}
if !fieldsToCheck.isEmpty {
p.print(
"",
"fileprivate var isInitialized: Bool {")
p.withIndentation { p in
if fieldsToCheck.count == 1 {
let f = fieldsToCheck.first!
p.print(
"guard case \(f.dottedSwiftName)(let v) = self else {return true}",
"return v.isInitialized")
} else if fieldsToCheck.count > 1 {
p.print("""
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch self {
""")
for f in fieldsToCheck {
p.print("case \(f.dottedSwiftName): return {")
p.printIndented(
"guard case \(f.dottedSwiftName)(let v) = self else { preconditionFailure() }",
"return v.isInitialized")
p.print("}()")
}
// If there were other cases, add a default.
if fieldsToCheck.count != fields.count {
p.print("default: return true")
}
p.print("}")
}
}
p.print("}")
}
p.print()
}
p.print("}")
}
func generateSendable(printer p: inout CodePrinter) {
// Once our minimum supported version has Data be Sendable, @unchecked could be removed.
p.print("extension \(swiftFullName): @unchecked Sendable {}")
}
private func gerenateOneofEnumProperty(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
p.print()
if usesHeapStorage {
p.print(
"\(comments)\(visibility)var \(swiftFieldName): \(swiftRelativeName)? {")
p.printIndented(
"get {return _storage.\(underscoreSwiftFieldName)}",
"set {_uniqueStorage().\(underscoreSwiftFieldName) = newValue}")
p.print("}")
} else {
p.print(
"\(comments)\(visibility)var \(swiftFieldName): \(swiftFullName)? = nil")
}
}
// MARK: Things brindged from MemberFieldGenerator
func generateInterface(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field causes the oneof enum to get generated.
if field === fields.first {
gerenateOneofEnumProperty(printer: &p)
}
let getter = usesHeapStorage ? "_storage.\(underscoreSwiftFieldName)" : swiftFieldName
// Within `set` below, if the oneof name was "newValue" then it has to
// be qualified with `self.` to avoid the collision with the setter
// parameter.
let setter = usesHeapStorage ? "_uniqueStorage().\(underscoreSwiftFieldName)" : (swiftFieldName == "newValue" ? "self.newValue" : swiftFieldName)
let visibility = generatorOptions.visibilitySourceSnippet
p.print(
"",
"\(field.comments)\(visibility)var \(field.swiftName): \(field.swiftType) {")
p.withIndentation { p in
p.print("get {")
p.printIndented(
"if case \(field.dottedSwiftName)(let v)? = \(getter) {return v}",
"return \(field.swiftDefaultValue)")
p.print(
"}",
"set {\(setter) = \(field.dottedSwiftName)(newValue)}")
}
p.print("}")
}
func generateStorage(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field causes the output.
guard field === fields.first else { return }
if usesHeapStorage {
p.print("var \(underscoreSwiftFieldName): \(swiftFullName)?")
} else {
// When not using heap stroage, no extra storage is needed because
// the public property for the oneof is the storage.
}
}
func generateStorageClassClone(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field causes the output.
guard field === fields.first else { return }
p.print("\(underscoreSwiftFieldName) = source.\(underscoreSwiftFieldName)")
}
func generateDecodeFieldCase(printer p: inout CodePrinter, field: MemberFieldGenerator) {
p.print("case \(field.number): try {")
p.withIndentation { p in
let hadValueTest: String
if field.isGroupOrMessage {
// Messages need to fetch the current value so new fields are merged into the existing
// value
p.print(
"var v: \(field.swiftType)?",
"var hadOneofValue = false",
"if let current = \(storedProperty) {")
p.printIndented(
"hadOneofValue = true",
"if case \(field.dottedSwiftName)(let m) = current {v = m}")
p.print("}")
hadValueTest = "hadOneofValue"
} else {
p.print("var v: \(field.swiftType)?")
hadValueTest = "\(storedProperty) != nil"
}
p.print(
"try decoder.decodeSingular\(field.protoGenericType)Field(value: &v)",
"if let v = v {")
p.printIndented(
"if \(hadValueTest) {try decoder.handleConflictingOneOf()}",
"\(storedProperty) = \(field.dottedSwiftName)(v)")
p.print("}")
}
p.print("}()")
}
var generateTraverseUsesLocals: Bool { return true }
func generateTraverse(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field in the group causes the output.
let group = fieldSortedGrouped[field.group]
guard field === group.first else { return }
if group.count == 1 {
p.print("try { if case \(field.dottedSwiftName)(let v)? = \(storedProperty) {")
p.printIndented("try visitor.visitSingular\(field.protoGenericType)Field(value: v, fieldNumber: \(field.number))")
p.print("} }()")
} else {
p.print("switch \(storedProperty) {")
for f in group {
p.print("case \(f.dottedSwiftName)?: try {")
p.printIndented(
"guard case \(f.dottedSwiftName)(let v)? = \(storedProperty) else { preconditionFailure() }",
"try visitor.visitSingular\(f.protoGenericType)Field(value: v, fieldNumber: \(f.number))")
p.print("}()")
}
if fieldSortedGrouped.count == 1 {
// Cover not being set.
p.print("case nil: break")
} else {
// Multiple groups, cover other cases (or not being set).
p.print("default: break")
}
p.print("}")
}
}
func generateFieldComparison(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field causes the output.
guard field === fields.first else { return }
let lhsProperty: String
let otherStoredProperty: String
if usesHeapStorage {
lhsProperty = "_storage.\(underscoreSwiftFieldName)"
otherStoredProperty = "rhs_storage.\(underscoreSwiftFieldName)"
} else {
lhsProperty = "lhs.\(swiftFieldName)"
otherStoredProperty = "rhs.\(swiftFieldName)"
}
p.print("if \(lhsProperty) != \(otherStoredProperty) {return false}")
}
func generateIsInitializedCheck(printer p: inout CodePrinter, field: MemberFieldGenerator) {
// First field causes the output.
guard field === fields.first else { return }
// Confirm there is message field with required fields.
let firstRequired = fields.first {
$0.isGroupOrMessage && $0.messageType!.containsRequiredFields()
}
guard firstRequired != nil else { return }
p.print("if let v = \(storedProperty), !v.isInitialized {return false}")
}
}
|
apache-2.0
|
1ef9693d4bb9c919692017017096b431
| 38.152745 | 153 | 0.586528 | 5.047692 | false | false | false | false |
wupingzj/YangRepoApple
|
QiuTuiJian/QiuTuiJianTests/DataServiceTest.swift
|
1
|
6207
|
//
// DataServiceTest.swift
// QiuTuiJian
//
// Created by Ping on 25/07/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import XCTest
import QiutuiJian
import CoreData
class DataServiceTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func xtestGetDataServiceSingleton() {
// let dataService:QiutuiJian.DataService = QiutuiJian.DataService.sharedInstance
// XCTAssertNotNil(dataService, "DataService is nil")
// XCTAssert(true, "This is FAILURE message")
// }
//
// func XtestCreateTestData() {
// println("********** testCreateTestData starting... ***********")
//
// let dataService: DataService = DataService.sharedInstance
// let ctx: NSManagedObjectContext = dataService.ctx
// XCTAssertNotNil(ctx, "ManagedObjectContext ctx is nil")
//
// //self.insertNewObject(ctx)
// }
// func insertNewObject(ctx: NSManagedObjectContext) {
// let MobileED: NSEntityDescription = NSEntityDescription.entityForName("Mobile", inManagedObjectContext: ctx)
//// let aMobile = NSEntityDescription.insertNewObjectForEntityForName(MobileED.name, inManagedObjectContext: ctx) as NSManagedObject
//// println("MobileED.name is \(MobileED.name)")
//// println("MobileED.managedObjectClassName is \(MobileED.managedObjectClassName)")
//
// let newMobile = Mobile(entity: MobileED, insertIntoManagedObjectContext: ctx)
//
// // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
// //newMobile.setValue("65", forKey: "countryCode")
// newMobile.initData()
// //newMobile.countryCode = "64"
// //newMobile.areaCode="4"
// newMobile.number="00000002"
// newMobile.phoneModel="iPhone 4S"
//// println("************* Mobile =\(newMobile.entity)")
// println("************* Mobile =\(newMobile)")
//
// // Save the context.
// var error: NSError? = nil
// if !ctx.save(&error) {
// // Replace this implementation with code to handle the error appropriately.
// // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
// println("Unresolved error \(error), \(error!.description)")
// //abort()
//
// XCTAssertNotNil(false, "Failed to save managed object context")
// } else {
// println("********** SUCCESSFULLY SAVED the managed object context")
// }
// }
// func XtestGetMobile() {
// let dataService: DataService = DataService.sharedInstance
// let ctx: NSManagedObjectContext = dataService.ctx
// XCTAssertNotNil(ctx, "ManagedObjectContext ctx is nil")
//
// let fetchRequest = NSFetchRequest(entityName: "Mobile")
// //let fetchRequest = NSFetchRequest()
// //let MobileED: NSEntityDescription = NSEntityDescription.entityForName("Mobile", inManagedObjectContext: ctx)
// //fetchRequest.entity = MobileED
//
//
// // disable faulting
// // otherwise, you would see data = {fault} if you don't access the fields
// fetchRequest.returnsObjectsAsFaults = false
// //fetchRequest.includesPropertyValues = true
//
// // Set the batch size
// fetchRequest.fetchBatchSize = 20
//
// // Set the sort key
// let sortDescriptor = NSSortDescriptor(key: "number", ascending: false)
// let sortDescriptors = [sortDescriptor]
// fetchRequest.sortDescriptors = [sortDescriptor]
//
//// let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: ctx, sectionNameKeyPath: nil, cacheName: "Master")
////
// var error: NSError? = nil
// // To make the class downcast possible, the Mobile entity must be mapped to QiuTuiJianTests.Mobile in the data model
// // I.E., the model class in Test Target
// var Mobiles: [Mobile] = ctx.executeFetchRequest(fetchRequest, error: &error) as [Mobile]
// //var Mobiles: AnyObject[] = ctx.executeFetchRequest(fetchRequest, error: &error)
//
// println("************** error= \(error)")
// if (error != nil) {
// println("Unresolved error \(error), \(error!.description)")
//
// XCTAssertNotNil(false, "Failed to save managed object context")
// } else {
// println("There are totally \(Mobiles.count) mobile phones in store.")
//
// var Mobile: Mobile? = nil
// for Mobile in Mobiles {
// println("mobile phone: \(Mobile) ")
// }
// }
//
//
//
// // narrow the fetch to these two properties
//// fetchRequest.propertiesToFetch = [NSArray arrayWithObjects:@"location", @"date", nil];
//// [fetchRequest setResultType:NSDictionaryResultType];
////
// // before adding the earthquake, first check if there's a duplicate in the backing store
//// NSError *error = nil;
//// Earthquake *earthquake = nil;
//// for (earthquake in earthquakes) {
//// fetchRequest.predicate = [NSPredicate predicateWithFormat:@"location = %@ AND date = %@", earthquake.location, earthquake.date];
////
//// NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//// if (fetchedItems.count == 0) {
//// // we found no duplicate earthquakes, so insert this new one
//// [self.managedObjectContext insertObject:earthquake];
//// }
//// }
// }
}
|
gpl-2.0
|
a2390c6a097c8e2068036fe50fb79627
| 43.654676 | 192 | 0.609634 | 4.608018 | false | true | false | false |
tsolomko/SWCompression
|
Sources/BZip2/BZip2+Compress.swift
|
1
|
11936
|
// Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import BitByteData
extension BZip2: CompressionAlgorithm {
/**
Compresses `data` with BZip2 algortihm.
- Parameter data: Data to compress.
- Note: Input data will be split into blocks of size 100 KB. Use `BZip2.compress(data:blockSize:)` function to
specify the size of a block.
*/
public static func compress(data: Data) -> Data {
return compress(data: data, blockSize: .one)
}
private static let blockMarker: [UInt8] = [
0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0,
0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1
]
private static let eosMarker: [UInt8] = [
0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0,
0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0
]
/**
Compresses `data` with BZip2 algortihm, splitting data into blocks of specified `blockSize`.
- Parameter data: Data to compress.
- Parameter blockSize: Size of blocks in which `data` will be split.
*/
public static func compress(data: Data, blockSize: BlockSize) -> Data {
let bitWriter = MsbBitWriter()
// We intentionally use smaller block size for compression to account for potential data size expansion
// after intial RLE, which seems to be not being expected by original BZip2 implementation.
let rawBlockSize = blockSize.sizeInKilobytes * 800
// BZip2 Header.
bitWriter.write(number: 0x425a, bitsCount: 16) // Magic number = 'BZ'.
bitWriter.write(number: 0x68, bitsCount: 8) // Version = 'h'.
bitWriter.write(number: blockSize.headerByte, bitsCount: 8) // Block size.
var totalCRC: UInt32 = 0
for i in stride(from: data.startIndex, to: data.endIndex, by: rawBlockSize) {
let blockData = data[i..<min(data.endIndex, i + rawBlockSize)]
let blockCRC = CheckSums.bzip2crc32(blockData)
totalCRC = (totalCRC << 1) | (totalCRC >> 31)
totalCRC ^= blockCRC
// Start block header.
bitWriter.write(bits: blockMarker) // Block magic number.
bitWriter.write(number: blockCRC.toInt(), bitsCount: 32) // Block crc32.
process(block: blockData, bitWriter)
}
// EOS magic number.
bitWriter.write(bits: eosMarker)
// Total crc32.
bitWriter.write(number: totalCRC.toInt(), bitsCount: 32)
bitWriter.align()
return bitWriter.data
}
private static func process(block data: Data, _ bitWriter: MsbBitWriter) {
var out = initialRle(data)
var pointer = 0
(out, pointer) = BurrowsWheeler.transform(bytes: out)
let usedBytes = Set(out).sorted()
var maxSymbol = 0
(out, maxSymbol) = mtfRle(out, characters: usedBytes)
// First, we analyze data and create Huffman trees and selectors.
// Then we will perform encoding itself.
// These are separate stages because all information about trees is stored at the beginning of the block,
// and it is hard to modify it later.
var processed = 50
var tables = [EncodingTree]()
var tablesLengths = [[Int]]()
var selectors = [Int]()
// Algorithm for code lengths calculations skips any symbol with frequency equal to 0.
// Unfortunately, we need such unused symbols in tree creation, so we cannot skip them.
// To prevent skipping, we set default value of 1 for every symbol's frequency.
var stats = Array(repeating: 1, count: maxSymbol + 2)
for i in 0..<out.count {
let symbol = out[i]
stats[symbol] += 1
processed -= 1
if processed <= 0 || i == out.count - 1 {
processed = 50
// Let's find minimum possible sizes for our stats using existing tables.
var minimumSize = Int.max
var minimumSelector = -1
for tableIndex in 0..<tables.count {
let bitSize = tables[tableIndex].bitSize(for: stats)
if bitSize < minimumSize {
minimumSize = bitSize
minimumSelector = tableIndex
}
}
// If we already have 6 tables, we cannot create more, thus we choose one of the existing tables.
if tables.count == 6 {
selectors.append(minimumSelector)
} else {
// Otherwise, let's create a new table and check if it gives us better results.
// First, we calculate code lengths and codes for our current stats.
let lengths = BZip2.lengths(from: stats)
let codes = Code.huffmanCodes(from: lengths)
// Then, using these codes, we create a new Huffman tree.
let table = EncodingTree(codes: codes.codes, bitWriter)
if table.bitSize(for: stats) < minimumSize {
tables.append(table)
tablesLengths.append(lengths.sorted { $0.symbol < $1.symbol }.map { $0.codeLength })
selectors.append(tables.count - 1)
} else {
selectors.append(minimumSelector)
}
}
// Clear stats.
stats = Array(repeating: 1, count: maxSymbol + 2)
}
}
// Format requires at least two tables to be present.
// If we have only one, we add a duplicate of it.
if tables.count == 1 {
tables.append(tables[0])
tablesLengths.append(tablesLengths[0])
}
// Now, we perform encoding itself.
// But first, we need to finish block header.
bitWriter.write(number: 0, bitsCount: 1) // "Randomized".
bitWriter.write(number: pointer, bitsCount: 24) // Original pointer (from BWT).
var usedMap = Array(repeating: UInt8(0), count: 16)
for usedByte in usedBytes {
guard usedByte <= 255
else { fatalError("Incorrect used byte.") }
usedMap[usedByte / 16] = 1
}
bitWriter.write(bits: usedMap)
var usedBytesIndex = 0
for i in 0..<16 {
guard usedMap[i] == 1 else { continue }
for j in 0..<16 {
if usedBytesIndex < usedBytes.count && i * 16 + j == usedBytes[usedBytesIndex] {
bitWriter.write(bit: 1)
usedBytesIndex += 1
} else {
bitWriter.write(bit: 0)
}
}
}
bitWriter.write(number: tables.count, bitsCount: 3)
bitWriter.write(number: selectors.count, bitsCount: 15)
let mtfSelectors = mtf(selectors, characters: Array(0..<selectors.count))
for selector in mtfSelectors {
guard selector <= 5
else { fatalError("Incorrect selector.") }
bitWriter.write(bits: Array(repeating: 1, count: selector))
bitWriter.write(bit: 0)
}
// Delta bit lengths.
for lengths in tablesLengths {
// Starting length.
var currentLength = lengths[0]
bitWriter.write(number: currentLength, bitsCount: 5)
for length in lengths {
while currentLength != length {
bitWriter.write(bit: 1) // Alter length.
if currentLength > length {
bitWriter.write(bit: 1) // Decrement length.
currentLength -= 1
} else {
bitWriter.write(bit: 0) // Increment length.
currentLength += 1
}
}
bitWriter.write(bit: 0)
}
}
// Contents.
var encoded = 0
var selectorPointer = 0
var t: EncodingTree?
for symbol in out {
encoded -= 1
if encoded <= 0 {
encoded = 50
if selectorPointer == selectors.count {
fatalError("Incorrect selector.")
} else if selectorPointer < selectors.count {
t = tables[selectors[selectorPointer]]
selectorPointer += 1
}
}
t?.code(symbol: symbol)
}
}
/// Initial Run Length Encoding.
private static func initialRle(_ data: Data) -> [Int] {
var out = [Int]()
var index = data.startIndex
while index < data.endIndex {
var runLength = 1
while index + 1 < data.endIndex && data[index] == data[index + 1] && runLength < 255 {
runLength += 1
index += 1
}
let byte = data[index].toInt()
for _ in 0..<min(4, runLength) {
out.append(byte)
}
if runLength >= 4 {
out.append(runLength - 4)
}
index += 1
}
return out
}
private static func mtf(_ array: [Int], characters: [Int]) -> [Int] {
var out = [Int]()
/// Mutable copy of `characters`.
var dictionary = characters
for i in 0..<array.count {
let index = dictionary.firstIndex(of: array[i])!
out.append(index)
let old = dictionary.remove(at: index)
dictionary.insert(old, at: 0)
}
return out
}
private static func mtfRle(_ array: [Int], characters: [Int]) -> ([Int], Int) {
var out = [Int]()
/// Mutable copy of `characters`.
var dictionary = characters
var lengthOfZerosRun = 0
var maxSymbol = 1
for i in 0..<array.count {
let byte = dictionary.firstIndex(of: array[i])!
// Run length encoding of zeros.
if byte == 0 {
lengthOfZerosRun += 1
}
if (byte == 0 && i == array.count - 1) || byte != 0 {
// Runs of zeros are represented using a modified binary system with two "digits", RUNA and RUNB, where
// RUNA represents 1 and RUNB represents 2 (whereas in the usual base-2 system the digits are 0 and 1).
// (We don't need a digit for zero since we can't get a run of length 0 by definition.)
if lengthOfZerosRun > 0 {
let digitsNumber = Int(floor(log2(Double(lengthOfZerosRun) + 1)))
var remainder = lengthOfZerosRun
for _ in 0..<digitsNumber {
let quotient = Int(ceil(Double(remainder) / 2) - 1)
let digit = remainder - quotient * 2
if digit == 1 {
out.append(0)
} else {
out.append(1)
}
remainder = quotient
}
lengthOfZerosRun = 0
}
}
if byte != 0 {
// We add one, because 1 is used as RUNB.
let newSymbol = byte + 1
out.append(newSymbol)
if newSymbol > maxSymbol {
maxSymbol = newSymbol
}
}
// Move to the front.
let old = dictionary.remove(at: byte)
dictionary.insert(old, at: 0)
}
// Add the 'end of stream' symbol.
out.append(maxSymbol + 1)
return (out, maxSymbol)
}
}
|
mit
|
5ba3bf6e58b1214be8499c9a3922c976
| 37.503226 | 120 | 0.518851 | 4.430586 | false | false | false | false |
gottesmm/swift
|
test/IRGen/dllimport.swift
|
3
|
3506
|
// RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -parse-stdlib -module-name dllimport %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT
// RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -parse-stdlib -module-name dllimport -primary-file %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT
// REQUIRES: CODEGENERATOR=ARM
import dllexport
public func get_ci() -> dllexport.c {
return dllexport.ci
}
public func get_c_type() -> dllexport.c.Type {
return dllexport.c
}
public class d : c {
override init() {
super.init()
}
@inline(never)
func f(_ : dllexport.c) { }
}
struct s : p {
func f() { }
}
func f(di : d) {
di.f(get_ci())
}
func blackhole<F>(_ : F) { }
public func g() {
blackhole({ () -> () in })
}
// CHECK-NO-OPT-DAG: @_swift_allocObject = external dllimport global %swift.refcounted* (%swift.type*, i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_deallocObject = external dllimport global void (%swift.refcounted*, i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_release = external dllimport global void (%swift.refcounted*)
// CHECK-NO-OPT-DAG: @_swift_retain = external dllimport global void (%swift.refcounted*)
// CHECK-NO-OPT-DAG: @_swift_slowAlloc = external dllimport global i8* (i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_slowDealloc = external dllimport global void (i8*, i32, i32)*
// CHECK-NO-OPT-DAG: @_TMC9dllexport1c = external dllimport global %swift.type
// CHECK-NO-OPT-DAG: @_TMp9dllexport1p = external dllimport global %swift.protocol
// CHECK-NO-OPT-DAG: @_TMT_ = external dllimport global %swift.full_type
// CHECK-NO-OPT-DAG: @_TWVBo = external dllimport global i8*
// CHECK-NO-OPT-DAG: declare dllimport i8* @_TF9dllexportau2ciCS_1c()
// CHECK-NO-OPT-DAG: declare dllimport %swift.refcounted* @_TFC9dllexport1cd(%C9dllexport1c*)
// CHECK-NO-OPT-DAG: declare dllimport %swift.type* @_TMaC9dllexport1c()
// CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden i8* @swift_rt_swift_slowAlloc(i32, i32)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_release(%swift.refcounted*)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_retain(%swift.refcounted*)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_slowDealloc(i8*, i32, i32)
// CHECK-OPT-DAG: @_swift_retain = external dllimport local_unnamed_addr global void (%swift.refcounted*)
// CHECK-OPT-DAG: @_TWVBo = external dllimport global i8*
// CHECK-OPT-DAG: @_TMC9dllexport1c = external dllimport global %swift.type
// CHECK-OPT-DAG: @_TMp9dllexport1p = external dllimport global %swift.protocol
// CHECK-OPT-DAG: @_swift_slowAlloc = external dllimport local_unnamed_addr global i8* (i32, i32)*
// CHECK-OPT-DAG: @_swift_slowDealloc = external dllimport local_unnamed_addr global void (i8*, i32, i32)*
// CHECK-OPT-DAG: declare dllimport i8* @_TF9dllexportau2ciCS_1c()
// CHECK-OPT-DAG: declare dllimport %swift.type* @_TMaC9dllexport1c()
// CHECK-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32)
// CHECK-OPT-DAG: declare dllimport %swift.refcounted* @_TFC9dllexport1cd(%C9dllexport1c*)
// CHECK-OPT-DAG: define linkonce_odr hidden i8* @swift_rt_swift_slowAlloc(i32, i32)
// CHECK-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_slowDealloc(i8*, i32, i32)
|
apache-2.0
|
176bfae566a09945656c89a1ce3d3a37
| 49.085714 | 224 | 0.719338 | 3.099912 | false | false | false | false |
leoru/Brainstorage
|
Brainstorage-iOS/Classes/Controllers/JobFilter/JobsFilterViewController.swift
|
1
|
3698
|
//
// JobsFilterViewController.swift
// Brainstorage-iOS
//
// Created by Kirill Kunst on 04.02.15.
// Copyright (c) 2015 Kirill Kunst. All rights reserved.
//
import UIKit
protocol JobsFilterProtocol : NSObjectProtocol {
func filterDidUpdated()
}
class JobsFilterViewController: UITableViewController {
@IBOutlet weak var fieildQuery: UITextField!
@IBOutlet weak var fieldCategories: UITextField!
@IBOutlet weak var switchFulltime: UISwitch!
@IBOutlet weak var switchContract: UISwitch!
@IBOutlet weak var switchFreelance: UISwitch!
weak var delegate : JobsFilterProtocol?
var filter : JobFilter = JobFilter.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.updateFilter()
}
func setup() {
self.navigationItem.title = "Фильтр"
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Bordered, target: nil, action: nil)
self.fieildQuery.addTarget(self, action: Selector("queryFieldChanged"), forControlEvents: UIControlEvents.EditingChanged)
var closeButtonItem = UIBarButtonItem(title: "Готово", style: UIBarButtonItemStyle.Done, target: self, action: Selector("actionCloseFilter"))
self.navigationItem.rightBarButtonItem = closeButtonItem
}
func updateFilter() {
// if (self.filter.query != "") {
self.fieildQuery.text = self.filter.query
// }
var selectedCategories = self.filter.selectedCategories()
if (selectedCategories.count > 0) {
self.fieldCategories.text = "Выбрано \(selectedCategories.count) из 9"
} else {
self.fieldCategories.text = "Выберите раздел"
}
self.switchFulltime.on = self.filter.fulltime
self.switchContract.on = self.filter.contract
self.switchFreelance.on = self.filter.freelance
}
func actionCloseFilter() {
self.dismissViewControllerAnimated(true, completion: nil)
if ((self.delegate) != nil) {
self.delegate?.filterDidUpdated()
}
}
// Actions
@IBAction func changeSwitchFreelance(sender: AnyObject) {
self.filter.freelance = self.switchFreelance.on
}
@IBAction func changeSwitchContract(sender: AnyObject) {
self.filter.contract = self.switchContract.on
}
@IBAction func changeSwitchFulltime(sender: AnyObject) {
self.filter.fulltime = self.switchFulltime.on
}
@IBAction func clearFilter(sender: AnyObject) {
self.filter.freelance = false
self.filter.contract = false
self.filter.fulltime = false;
self.filter.query = "";
for item in self.filter.selectedCategories(){
item.selected=false;
}
self.updateFilter();
}
// UITextField Text Changed Event
func queryFieldChanged() {
self.filter.query = self.fieildQuery.text
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 2) {
tableView.deselectRowAtIndexPath(indexPath, animated:false)
var vc : JobCategoriesViewController = self.storyboard?.instantiateViewControllerWithIdentifier("JobCategoriesViewController") as! JobCategoriesViewController
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
mit
|
4de79cc7a8f0ea9a696a3d5309004b4a
| 31.131579 | 170 | 0.65602 | 4.690141 | false | false | false | false |
mayongl/MyNews
|
MyNews/MyNews/ImageCollectionViewController.swift
|
1
|
8015
|
//
// ImageCollectionViewController.swift
// MyNews
//
// Created by Yonglin Ma on 4/24/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import SDWebImage
private let reuseIdentifier = "ImageCell"
var images : [NSDictionary] = []
class ImageCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
//self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getData() {
let tag1 = "美女"
let tag2 = "性感"
let urlstr = "http://image.baidu.com/wisebrowse/data?tag1=" + "\(tag1)" + "&tag2=" + "\(tag2)"+"&pn=1&rn=60"
//let urlstrEncoded = "http://image.baidu.com/wisebrowse/data?tag1=%E7%BE%8E%E5%A5%B3&tag2=%E6%80%A7%E6%84%9F&pn=0&rn=6"
//let urlstrEncoded = urlstr.addingPercentEscapes(using: String.Encoding.utf8)
//let urlstrEncoded = urlstr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)
let urlstrEncoded = urlstr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
Alamofire.request(urlstrEncoded!).responseJSON { response in
print(response.result) // result of response serialization
// var propertyListResponse: PropertyList?
// propertyListResponse = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments)
if let dictionary = response.result.value as? NSDictionary {
print(dictionary[ImageResponseKey.msg]!)
images = dictionary[ImageResponseKey.imgs] as! [NSDictionary]
}
self.collectionView?.reloadData()
}
}
// [[BaseEngine shareEngine] runRequestWithPara:dic path:urlstr success:^(id responseObject) {
//
// NSArray *dataarray = [Photo objectArrayWithKeyValuesArray:responseObject[@"imgs"]];
// NSMutableArray *statusFrameArray = [NSMutableArray array];
// for (Photo *photo in dataarray) {
// [statusFrameArray addObject:photo];
// }
//
// if (block_self.photoArray.count > 0) {
// [block_self.photoArray removeAllObjects];
// }
// block_self.photoArray = statusFrameArray;
//
// block_self.pn += 60;
// block_self.collectionView.footer.hidden = block_self.photoArray.count < 60;
// [block_self.collectionView reloadData];
// [block_self.collectionView.header endRefreshing];
// [block_self.collectionView.footer endRefreshing];
// + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray
// {
// // 1.判断真实性
// NSString *desc = [NSString stringWithFormat:@"keyValuesArray is not a keyValuesArray - keyValuesArray不是一个数组, keyValuesArray is a %@ - keyValuesArray参数是一个%@", keyValuesArray.class, keyValuesArray.class];
// MJAssert2([keyValuesArray isKindOfClass:[NSArray class]], desc, nil);
//
// // 2.创建数组
// NSMutableArray *modelArray = [NSMutableArray array];
//
// // 3.遍历
// for (NSDictionary *keyValues in keyValuesArray) {
// if (![keyValues isKindOfClass:[NSDictionary class]]) continue;
//
// id model = [self objectWithKeyValues:keyValues];
// [modelArray addObject:model];
// }
//
// return modelArray;
// }
// private func fetchImage() {
// if let url = imageURL {
// spinner.startAnimating()
// DispatchQueue.global(qos: .userInitiated).async { [weak self] in
// let urlContents = try? Data(contentsOf: url)
// if let imageData = urlContents, url == self?.imageURL {
// DispatchQueue.main.async {
// self?.image = UIImage(data: imageData)
// }
// }
// }
// }
// }
//
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
// override func numberOfSections(in collectionView: UICollectionView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 0
// }
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
print(images.count)
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageBrowseCollectionViewCell
// Configure the cell
let dic = images[indexPath.row]
cell.label.text = dic[ImgsKey.title] as? String
let url = URL(string: (dic[ImgsKey.image_url] as? String)!)
print(url)
cell.image.sd_setImage(with: url)
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
struct ImageResponseKey {
static let errno = "errno"
static let imgs = "imgs"
static let msg = "msg"
static let returnNumber = "returnNumber"
static let startIndex = "startIndex"
static let tag1 = "tag1"
static let tag2 = "tag2"
static let tag3 = "tag3"
static let totalNum = "totalNum"
}
struct ImgsKey {
static let albumNum = "albumNum"
static let content_sign = "content_sign"
static let dataId = "dataId"
static let fromurl = "fromurl"
static let image_height = "image_height"
static let image_url = "image_url"
static let image_width = "image_width"
static let mid_height = "mid_height"
static let mid_url = "mid_url"
static let set_id = "set_id"
static let small_height = "small_height"
static let small_url = "small_url"
static let small_width = "small_width"
static let title = "title"
}
}
|
mit
|
2411d4da02288eb46feb4fa733e4f437
| 35.356164 | 208 | 0.652223 | 4.591696 | false | false | false | false |
aliceatlas/daybreak
|
Classes/SBGoogleSuggestParser.swift
|
1
|
2223
|
/*
SBGoogleSuggestParser.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
private let kSBGSToplevelTagName = "toplevel"
private let kSBGSCompleteSuggestionTagName = "CompleteSuggestion"
private let kSBGSSuggestionTagName = "suggestion"
private let kSBGSNum_queriesTagName = "num_queries"
private let kSBGSSuggestionAttributeDataArgumentName = "data"
func SBParseGoogleSuggestData(data: NSData) throws -> [SBURLFieldItem] {
let document = try NSXMLDocument(data: data, options: 0)
var items: [SBURLFieldItem] = []
let element = document.rootElement()!
for suggestion in element.elementsForName(kSBGSCompleteSuggestionTagName) {
let item = suggestion.elementsForName(kSBGSSuggestionTagName)[0]
let string = item.attributeForName(kSBGSSuggestionAttributeDataArgumentName)!.stringValue!
items.append(.GoogleSuggest(title: string, URL: string.searchURLString))
}
return items
}
|
bsd-2-clause
|
36b461566a57ac7bcb8779053c9991bc
| 46.319149 | 98 | 0.79937 | 4.555328 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.